问题描述
我正在尝试构建一个 LSTM 模型,正在处理 https://keras.io 上的文档示例/layers/recurrent/
from keras.models import Sequential从 keras.layers 导入 LSTM
以下三行代码(加上注释)直接取自上面的文档链接:
model = Sequential()模型.add(LSTM(32, input_dim=64, input_length=10))# 对于后续层,不需要指定输入大小:模型.添加(LSTM(16))
ValueError:输入 0 与层 lstm_2 不兼容:预期ndim=3,找到 ndim=2
在执行第二个 model.add() 语句后,但在将模型暴露给我的数据之前,甚至编译它之前,我收到了上述错误.
我在这里做错了什么?我使用的是 Keras 1.2.1.
编辑
刚刚升级到当前的 1.2.2,仍然有同样的问题.
感谢 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))模型编译(优化器 = 'RMSprop',损失 = 'categorical_crossentropy')
(没有错误)
I am trying to build an LSTM model, working off the documentation example at https://keras.io/layers/recurrent/
from keras.models import Sequential
from keras.layers import LSTM
The following three lines of code (plus comment) are taken directly from the documentation link above:
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))
I get that error above after executing the second model.add() statement, but before exposing the model to my data, or even compiling it.
What am I doing wrong here? I'm using Keras 1.2.1.
Edit
Just upgraded to current 1.2.2, still having same issue.
Thanks to patyork for answering this on Github:
So to offer a code example of how to use a stacked LSTM to achieve many-to-one (return_sequences=False) sequence classification, just make sure to use return_sequences=True on the intermediate layers like this:
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')
(no errors)
这篇关于Keras LSTM 的第二层(但不是第一层)中的输入形状错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!