TransWikia.com

[Keras][LSTM] error due to shape mismatch

Data Science Asked by Malintha on March 7, 2021

I have following data. Where I have 2 samples. Each sample I have 3 time steps each with 2 features. I intend to have 2 batches (to updates weights after every sample)

X=np.array([[[0.54, 0.3], [0.11, 0.2], [0.37, 0.81]],[[0.55, 0.4], [0.12, 0.3], [0.38, 0.9]]])
X=X.reshape(2,3,2)
y = np.array([[[0.2],[0.3],[0.4]],[[0.3],[0.4],[0.5]]])
y = y.reshape(2,3)

Following is my Keras LSTM code

model = Sequential()
model.add(LSTM(50, activation='relu', batch_input_shape=(2, 3, 2)))
# model.add(LSTM(50, activation='relu', batch_input_shape=(1, n_steps, n_features)))
# model.add(LSTM(50, activation='relu', input_shape=(n_steps, n_features)))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mse')

model.fit(X, y, epochs=10000, verbose=0)

Which gives me following error. According to my understanding it is due to the size mismatch but cannot figure out the issue in my sizes. Appreciate your input

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

One Answer

LSTM gives 2 outputs:-

  1. Sequences
  2. States.

LSTM

Now as you are working with Keras, by default the LSTM layer is designed to return states over Sequence (Which can to altered by turning return_sequence argument to True in keras layer).

Looking at the shape of your output, (2,3) is incorrect for the states and is actually looks like it should be for the sequence. This is the reason why your code is throwing an error.

Answered by thanatoz on March 7, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP