【问题标题】:ValueError: Input 0 of layer lstm_17 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: [None, 128]ValueError: 层 lstm_17 的输入 0 与层不兼容:预期 ndim=3,发现 ndim=2。收到的完整形状:[无,128]
【发布时间】:2021-01-21 03:44:38
【问题描述】:

代码如下:

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]

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

【问题讨论】:

  • return_sequences=True 在第二个 lstm 层
  • @MarcoCerliani 我认为 LSTM 层很好,因为前 2 个 lstm 层是编码器,最后一个 lstm 层是解码器
  • 您的“解码器”在您传递 2D 时需要 3D...错误正是如此

标签: python keras runtime-error google-colaboratory tf.keras


【解决方案1】:

正如 Marco 在 cmets 中所说,解码器需要 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层,因为现在它没有用了。

感谢马可的帮助!

【讨论】:

    猜你喜欢
    • 2021-01-24
    • 2020-08-01
    • 2021-08-25
    • 2021-05-19
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    相关资源
    最近更新 更多