添加Conv1D图层时,错误“输入0与conv1d_48层不兼容:预期ndim = 3,找到ndim = 2”

时间:2018-10-18 09:20:53

标签: python machine-learning keras conv-neural-network lstm

我正在尝试构建以下模型:

model = Sequential()
model.add(Embedding(input_dim = num_top_words, output_dim = 64, input_length = input_length))
model.add(LSTM(100, activation = 'relu'))
model.add(Conv1D(64, kernel_size = 5, activation = 'relu'))
model.add(MaxPooling1D())
model.add(Dense(5, activation = 'softmax'))
model.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['accuracy'])

但是运行它时出现以下错误:

Input 0 is incompatible with layer conv1d_48: expected ndim=3, found ndim=2

指出以下一行存在错误:

model.add(Conv1D(64, kernel_size = 5, activation = 'relu'))

可能是什么问题?

1 个答案:

答案 0 :(得分:1)

问题在于,当前LSTM层的输出形状为(None, 100),但是,正如错误所暗示的那样,Conv1D层(例如LSTM层)的3D输入为形状为(None, n_steps, n_features)。因此,解决此问题的一种方法是将return_sequences=True传递到LSTM层以获取每个时间步的输出,因此其输出将为3D:

model.add(LSTM(100, activation = 'relu', return_sequences=True))

或者,您可以在Conv1D层之前放置MaxPooling1DLSTM层(这可能比当前体系结构更好,因为一种用法是Conv1D加上池层是为了减少LSTM层的输入维,从而降低计算复杂度):

model.add(Conv1D(64, kernel_size = 5, activation = 'relu'))
model.add(MaxPooling1D())
model.add(LSTM(100, activation = 'relu'))