检查目标时出错:预期dense_1 有3 个维度,但得到形状为(118, 1) 的数组 [英] Error when checking target: expected dense_1 to have 3 dimensions, but got array with shape (118, 1)

查看:28
本文介绍了检查目标时出错:预期dense_1 有3 个维度,但得到形状为(118, 1) 的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm training a model to predict the stock price and input data is close price. I use 45 days data to predict the 46th day's close price and a economic Indicator to be second feature, here is the model:

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: 检查目标时出错:预期密集_1 有 3维度,但得到了形状为 (118, 1) 的数组

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

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

However, I print the shape of data and they are:

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

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

I have no idea why the model is expecting a 3 dimensional output when y_train is (118, 1). Where am I wrong and what should I do?

推荐答案

你的第二个 LSTM 层也返回序列,并且 Dense 层默认将内核应用到每个时间步也产生一个序列:

Your second LSTM layer also returns sequences and Dense layers by default apply the kernel to every timestep also producing a sequence:

# (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 来压缩序列:

So your output is shape (bs, 45, 1). To solve the problem you need to set return_sequences=False in your second LSTM layer which will compress sequence:

# (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 是批量大小.

And you'll get the desired output. Note bs is the batch size.

这篇关于检查目标时出错:预期dense_1 有3 个维度,但得到形状为(118, 1) 的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆