我试图了解如何在Keras上编写Conv1D模型,但我一直遇到维数不匹配错误。现在x_train = [1000,294](1000个项目和294个特征)和y_train = [1000,9](1000个项目和9个标签)。我不断收到预期的错误消息3维,但有2维。但是我尝试修复它,它再次出现。 github上的一些问题建议使用Flatten()
,但是它已经存在并且没有运气。知道我缺少什么吗?谢谢
我得到的错误
ValueError:输入0与层conv1d_1不兼容:预期
ndim = 3,找到的ndim = 2
代码包含在下面
tb = [keras.callbacks.TensorBoard(log_dir='./dllogs')]
main_input = Input(shape=(294, ), dtype='float32')
x_train = np.array(x_train)
y_train = np.array(y_train)
x_dev = np.array(x_dev)
y_dev = np.array(y_dev)
x = Conv1D(128, 5, activation='relu')(main_input)
x = MaxPooling1D(5)(x)
x = Conv1D(128, 5, activation='relu')(x)
x = MaxPooling1D(5)(x)
x = Conv1D(128, 5, activation='relu')(x)
x = MaxPooling1D(35)(x)
x = Flatten()(x)
x = Dropout(0.25)(x)
x = Dense(128, activation='relu')(x)
preds = Dense(pred_dim, activation='softmax')(x)
model = Model(inputs=main_input, outputs=preds)
model.compile(optimizer='adam', loss='kullback_leibler_divergence', metrics=['accuracy'])
print(model.summary())
history_NN = model.fit(x_train, y_train, batch_size=BATCHSIZE, epochs=EPOCHS, callbacks=tb, validation_data=(x_dev, y_dev))
回答
尺寸是一个引起麻烦的问题,今天的评论已解决了这一问题。
接下来是池的尺寸,这是池化后减小的尺寸,所以在整个事情之后,当我进行更改时,最终的池化没有35张幻灯片。固定。
结果代码,
tb = [keras.callbacks.TensorBoard(log_dir='./dllogs')]
main_input = Input(shape=(294, 1))#changed
x_train = np.array(x_train)
y_train = np.array(y_train)
x_dev = np.array(x_dev)
y_dev = np.array(y_dev)
x_train = np.expand_dims(x_train, axis=-1) #changed
x_dev = np.expand_dims(x_dev, axis=-1) #changed
x = Conv1D(128, 5, activation='relu')(main_input)
x = MaxPooling1D(5)(x)
x = Conv1D(128, 5, activation='relu')(x)
x = MaxPooling1D(5)(x)
x = Conv1D(128, 5, activation='relu')(x)
x = MaxPooling1D(11)(x)
x = Flatten()(x)
x = Dropout(0.25)(x)
x = Dense(128, activation='relu')(x)
preds = Dense(pred_dim, activation='softmax')(x)
model = Model(inputs=main_input, outputs=preds)
model.compile(optimizer='adam', loss='kullback_leibler_divergence', metrics=['accuracy'])
print(model.summary())
history_NN = model.fit(x_train, y_train, batch_size=BATCHSIZE, epochs=EPOCHS, callbacks=tb, validation_data=(x_dev, y_dev))
最佳答案
Conv1D
层需要形状为(sequence_length, num_features)
的序列输入。似乎您有一个长度为294且具有一个特征的序列;因此,每个输入样本都必须具有(294,1)
的形状(而不是(294,)
)。要解决此问题,可以使用np.expand_dims
将大小为1的第三维添加到输入数据:
x_train = np.expand_dims(x_train, axis=-1)
x_dev = np.expand_dims(x_dev, axis=-1)
main_input = Input(shape=(294, 1)) # fix the input shape here as well