我正在训练一个模型来预测股票价格,输入数据是收盘价。我使用 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/