【问题标题】:Input Shape Error in Second-layer (but not first) of Keras LSTMKeras LSTM 第二层(但不是第一层)的输入形状错误
【发布时间】:2017-07-08 22:55:27
【问题描述】:

我正在尝试构建一个 LSTM 模型,处理 https://keras.io/layers/recurrent/ 的文档示例

from keras.models import Sequential
from keras.layers import LSTM

以下三行代码(加注释)直接取自上面的文档链接:

model = Sequential()
model.add(LSTM(32, input_dim=64, input_length=10))

# for subsequent layers, not need to specify the input size:
model.add(LSTM(16))

ValueError:输入 0 与层 lstm_2 不兼容:预期 ndim=3,发现 ndim=2

在执行第二个 model.add() 语句之后,但在将模型暴露给我的数据之前,甚至在编译它之前,我得到了上面的错误。

我在这里做错了什么?我正在使用 Keras 1.2.1。

编辑

刚刚升级到当前的 1.2.2,仍然有同样的问题。

【问题讨论】:

    标签: python tensorflow keras lstm recurrent-neural-network


    【解决方案1】:

    感谢 patyork 在Github 上回答这个问题:

    第二个 LSTM 层没有得到它所期望的 3D 输入(形状为 (batch_size, timesteps, features)。这是因为第一个 LSTM 层有(由于默认值的幸运)return_sequences=False,这意味着它只输出时间 t-1 的最后一个特征集,其形状为 (batch_size, 32),或不包含时间的 2 个维度。

    所以要提供一个代码示例,说明如何使用堆叠 LSTM 实现多对一 (return_sequences=False) 序列分类,只需确保在中间层上使用 return_sequences=True,如下所示:

    model = Sequential()
    model.add(LSTM(32, input_dim=64, input_length=10, return_sequences=True))
    model.add(LSTM(24, return_sequences=True))
    model.add(LSTM(16, return_sequences=True))
    model.add(LSTM(1,  return_sequences=False))
    
    model.compile(optimizer = 'RMSprop', loss = 'categorical_crossentropy')
    

    (没有错误)

    【讨论】:

      猜你喜欢
      • 2018-02-27
      • 2019-02-18
      • 2021-05-20
      • 2021-12-04
      • 2019-01-22
      • 2019-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多