【问题标题】:input_shape parameter mismatch error in Convolution1D in keraskeras中Convolution1D中的input_shape参数不匹配错误
【发布时间】:2017-05-10 07:28:44
【问题描述】:

我想在 keras 中使用 Convul​​ation1D 对数据集进行分类。

数据集描述

训练数据集大小 = [340,30] ;样本数 = 340 ,样本维度 = 30

测试数据集大小 = [230,30] ;样本数 = 230 ,样本维度 = 30

标签大小 = 2

拳头我使用来自 keras 网站https://keras.io/layers/convolutional/ 的信息通过以下代码尝试

batch_size=1
nb_epoch = 10
sizeX=340
sizeY=30
model = Sequential()
model.add(Convolution1D(64, 3, border_mode='same', input_shape=(sizeX,sizeY)))
model.add(Convolution1D(32, 3, border_mode='same'))
model.add(Convolution1D(16, 3, border_mode='same'))
model.add(Dense(1))
model.add(Activation('sigmoid'))

model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

print('Train...')
model.fit(X_train_transformed, y_train, batch_size=batch_size, nb_epoch=nb_epoch,
          validation_data=(X_test, y_test))
score, acc = model.evaluate(X_test_transformed, y_test, batch_size=batch_size)
print('Test score:', score)
print('Test accuracy:', acc)

它给出了以下错误, ValueError: 检查模型输入时出错:预期的 convolution1d_input_1 有 3 个维度,但得到的数组形状为 (340, 30)

然后我使用以下代码将训练和测试数据从二维转换为 3 维,

X_train = np.reshape(X_train_transformed, (X_train_transformed.shape[0], X_train_transformed.shape[1], 1))
X_test = np.reshape(X_test_transformed, (X_test_transformed.shape[0], X_test_transformed.shape[1], 1))

然后我运行修改后的以下代码,

batch_size=1
nb_epoch = 10
sizeX=340
sizeY=30

model = Sequential()
model.add(Convolution1D(64, 3, border_mode='same', input_shape=(sizeX,sizeY)))
model.add(Convolution1D(32, 3, border_mode='same'))
model.add(Convolution1D(16, 3, border_mode='same'))
model.add(Dense(1))
model.add(Activation('sigmoid'))

model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

print('Train...')
model.fit(X_train, y_train, batch_size=batch_size, nb_epoch=nb_epoch,
          validation_data=(X_test, y_test))
score, acc = model.evaluate(X_test, y_test, batch_size=batch_size)
print('Test score:', score)
print('Test accuracy:', acc)

但它显示错误, ValueError:检查模型输入时出错:预期的 convolution1d_input_1 的形状为 (None, 340, 30) 但得到的数组的形状为 (340, 30, 1)

我无法在此处找到尺寸不匹配错误。

【问题讨论】:

    标签: tensorflow deep-learning theano keras


    【解决方案1】:

    随着 TF 2.0 和 tf.keras 的发布,您可以相当轻松地更新模型以使用这些新版本。这可以通过以下代码完成:

    # import tensorflow 2.0
    # keras doesn't need to be imported because it is built into tensorflow
    from __future__ import absolute_import, division, print_function, unicode_literals
    
    try:
      %tensorflow_version 2.x
    except Exception:
      pass
    
    import tensorflow as tf
    
    
    batch_size = 1
    nb_epoch = 10
    # the model only needs the size of the sample as input, explained further below
    size = 30
    
    # reshape as you had before
    X_train = np.reshape(X_train_transformed, (X_train_transformed.shape[0],                        
        X_train_transformed.shape[1], 1))
    X_test = np.reshape(X_test_transformed, (X_test_transformed.shape[0], 
        X_test_transformed.shape[1], 1))
    
    # define the sequential model using tf.keras
    model = tf.keras.Sequential([
    
          # the 1d convolution layers can be defined as shown with the same
          # number of filters and kernel size
          # instead of border_mode, the parameter is padding
          # the input_shape is (the size of each sample, 1), explained below
          tf.keras.layers.Conv1D(64, 3, padding='same', input_shape=(size, 1)),
          tf.keras.layers.Conv1D(32, 3, padding='same'),
          tf.keras.layers.Conv1D(16, 3, padding='same'),
    
          # Dense and Activation can be combined into one layer
          # where the dense layer has 1 neuron and a sigmoid activation
          tf.keras.layers.Dense(1, activation='sigmoid')
    ])
    
    # the model can be compiled, fit, and evaluated in the same way
    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
    
    print('Train...')
    model.fit(X_train, y_train, batch_size=batch_size, nb_epoch=nb_epoch,
              validation_data=(X_test, y_test))
    
    score, acc = model.evaluate(X_test, y_test, batch_size=batch_size)
    print('Test score:', score)
    print('Test accuracy:', acc)
    

    您遇到的问题来自模型的输入形状。根据keras documentation,模型的输入形状必须是(批次、步骤、通道)。这意味着第一个维度是您拥有的实例数。第二个维度是每个样本的大小。第三个维度是通道数,在您的情况下只有一个。总体而言,您的输入形状将是 (340, 30, 1)。当您实际在模型中定义输入形状时,您只需要指定第二维和第三维,这意味着您的输入形状将是 (size, 1)。该模型已经将第一个维度(您拥有的实例数)作为输入,因此您无需指定该维度。

    【讨论】:

      【解决方案2】:

      你可以试试这个吗?

      X_train = np.reshape(X_train_transformed, (1, X_train_transformed.shape[0], X_train_transformed.shape[1]))
      X_test = np.reshape(X_test_transformed, (1, X_test_transformed.shape[0], X_test_transformed.shape[1]))
      

      【讨论】:

      • 当我尝试使用它时,它会给出以下错误 ValueError: Error when checks model target: expected activation_1 to have 3 dimensions, but got array with shape (340, 1)
      • 你明白了吗?有的话请贴出答案,我也有同样的问题
      猜你喜欢
      • 2023-01-12
      • 1970-01-01
      • 1970-01-01
      • 2018-11-21
      • 2014-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多