ValueError: Input 0 of layer lstm_17 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: [None, 128]

ValueError: Input 0 of layer lstm_17 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: [None, 128]

代码如下:

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Embedding, LSTM, RepeatVector, Dense, Reshape

Model = Sequential([
          Embedding(vocab_size, 256, input_length=49),
          LSTM(256, return_sequences=True),
          LSTM(128, return_sequences=False),
          LSTM(128),
          Reshape((128, 1)),
          Dense(vocab_size, activation='softmax')
])

这是错误信息:

ValueError: Input 0 of layer lstm_11 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: [None, 128]

我在 Google Colab 上使用 tensorflow 1.15.0 和 运行 它。我该如何解决它。

正如 Marco 在评论中所说,解码器期望 3d 但它得到 2d,因此在解码器工作之前应用 RepeatVector 层。修正后的型号:

Model = Sequential([
      Embedding(vocab_size, 256, input_length=49),
      LSTM(256, return_sequences=True),
      LSTM(128, return_sequences=False),
      RepeatVector(1),
      LSTM(128),
      Dense(vocab_size, activation='softmax')
])

我添加了 RepeatVector 层以使输出形状为 3D,并删除了 Reshape 层,因为现在它没有用了。

感谢 Marco 的帮助!