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