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

查看:53
本文介绍了检查目标时出错:预期density_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)

运行此命令时,出现以下错误:

When I run this I get the following error:

ValueError:检查目标时出错:预期density_1具有3 尺寸,但数组的形状为(118,1)

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

但是,我print数据的形状是:

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.

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

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