Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

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

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: 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)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

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)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...