gpt4 book ai didi

python - Keras LSTM 第二层(但不是第一层)的输入形状错误

转载 作者:太空宇宙 更新时间:2023-11-03 14:07:27 24 4
gpt4 key购买 nike

我正在尝试构建一个 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: Input 0 is incompatible with layer lstm_2: expected ndim=3, found ndim=2

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

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

编辑

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

最佳答案

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

the second LSTM layer is not getting a 3D input that it expects (with a shape of (batch_size, timesteps, features). This is because the first LSTM layer has (by fortune of default values) return_sequences=False, meaning it only output the last feature set at time t-1 which is of shape (batch_size, 32), or 2 dimensions that doesn't include time.

因此,为了提供如何使用堆叠 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')

(没有错误)

关于python - Keras LSTM 第二层(但不是第一层)的输入形状错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42331396/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com