python - 检查目标 : expected dense_1 to have 3 dimensions, 时出错,但得到形状为 (118, 1) 的数组

标签 python keras output lstm

我正在训练一个模型来预测股票价格,输入数据是收盘价。我使用 45 天的数据来预测第 46 天的收盘价和经济指标作为第二个特征,这是模型:

model = Sequential()
model.add( LSTM( 512, input_shape=(45, 2), return_sequences=True))
model.add( LSTM( 512, return_sequences=True))
model.add( (Dense(1)))
model.compile(loss='mse', optimizer='adam')
history = model.fit( X_train, y_train, batch_size = batchSize, epochs=epochs, shuffle = False)

当我运行它时,出现以下错误:

ValueError: Error when checking target: expected dense_1 to have 3 dimensions, but got array with shape (118, 1)

但是,我打印数据的形状,它们是:

X_train:(118, 45, 2)
y_train:(118, 1)

我不知道为什么当 y_train 为 (118, 1) 时模型需要 3 维输出。我哪里错了,我该怎么办?

最佳答案

您的第二个 LSTM 层也返回序列,默认情况下,密集层将内核应用于每个时间步,同时生成一个序列:

# (bs, 45, 2)
model.add( LSTM( 512, input_shape=(45, 2), return_sequences=True))
# (bs, 45, 512)
model.add( LSTM( 512, return_sequences=True))
# (bs, 45, 512)
model.add( (Dense(1)))
# (bs, 45, 1)

所以你的输出是形状 (bs, 45, 1)。要解决此问题,您需要在将压缩序列的第二个 LSTM 层中设置 return_sequences=False:

# (bs, 45, 2)
model.add( LSTM( 512, input_shape=(45, 2), return_sequences=True))
# (bs, 45, 512)
model.add( LSTM( 512, return_sequences=False)) # SET HERE
# (bs, 512)
model.add( (Dense(1)))
# (bs, 1)

您将获得所需的输出。注意 bs 是批量大小。

关于python - 检查目标 : expected dense_1 to have 3 dimensions, 时出错,但得到形状为 (118, 1) 的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51763983/

相关文章:

python - keras LSTM 层训练时间太长

unix - 如何在使用查找时不显示无法访问的文件夹

linux - 从 Bash 输出中隐藏 "Directory and Bash Directory"

python - Outlook/Python : Open specific message at screen

machine-learning - 在 Keras 中为序列到序列自动编码器制作解码器模型

Python 递归行为

keras - 如何在 Keras 中计算 F1 宏?

c++ - WriteConsoleOutputCharacter 使控制台应用程序崩溃

python - 使用 joinload 的 sqlalchemy 查询对于每个新的过滤子句会呈指数减慢

Python Egg 与 package_dir .. 似乎打破了要求