ValueError:输入0与层lstm_15不兼容:预期ndim = 3,找到ndim = 2

时间:2020-10-10 12:52:18

标签: python keras lstm text-classification cnn

我想将CNN层的输出馈送到LSTM层,但是出现错误ValueError: Input 0 is incompatible with layer lstm_15: expected ndim=3, found ndim=2,其代码如下:

inp = Input(shape = (max_length,))
xe = Embedding(vocabulary_size, 300, weights = [embedding_matrix], trainable = False)(inp)
x = Conv1D(512,kernel_size = 2, activation='relu',kernel_initializer = "he_uniform")(xe)
x = GlobalMaxPooling1D()(x)
x = LSTM(128)(x)
x = Dense(11, activation = "sigmoid")(x)

输入形状:

embedding_matrix: (26441, 300)
inp : TensorShape([Dimension(None), Dimension(3146)])
X_train :(1432, 3146)
Y_train: (1432, 11)
vocabulary_size: 26441
max_length: 3146

有人可以帮助我

1 个答案:

答案 0 :(得分:0)

这是因为当您应用GlobalMaxPooling1D时,它将返回形状为(batch_size, 512)的张量。如docs中所述,该层通过采用时间维度上的最大值来对输入表示进行降采样。您有两个选择或者不使用GlobalMaxPool1D(可以使用MaxPool1D之类的本地池层),也可以使用RepeatVector来更改GlobalMaxPool1D的输出形状从(batch_size, 512)(batch_size, n, 512),其中nRepeatVector定义的参数,您希望序列重复多少次。