GoBackess
GoBackess

Reputation: 414

how can i solve lstm dimension error in keras?

Here is my code

model = Sequential()
model.add(LSTM(512,  return_sequences=True))
model.add(Dropout(0.3))

model.add(LSTM(512,  return_sequences=True))
model.add(Dropout(0.3))
model.add(LSTM(1, return_sequences=True))

I got this error

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

if I set return_sequences=True then output shape is 3D array

So, why this error occur??

Upvotes: 0

Views: 82

Answers (1)

KrisR89
KrisR89

Reputation: 1541

The input and output of the keras LSTM layer should be 3 dimensional, and by default follows the shape,

(Batch_size, Time_steps, Features).

It seems like you are using only two dimensions (62796, 1) from you error message.

following is a minimal working example with synthetic data, which illustrate the input and output shape required by your LSTM network.

from keras.models import Sequential
from keras.layers import LSTM, Dropout
import numpy as np

numb_outputs = 1

batch_size = 10
timesteps = 5
features = 2

x_single_batch = np.random.rand(batch_size, timesteps, features)
y_single_batch = np.random.rand(batch_size, timesteps, numb_outputs)

model = Sequential()
model.add(LSTM(512,  return_sequences=True))
model.add(Dropout(0.3))

model.add(LSTM(512,  return_sequences=True))
model.add(Dropout(0.3))
model.add(LSTM(numb_outputs, return_sequences=True))

model.compile(optimizer='adam',loss='mse')
model.fit(x= x_single_batch, y=y_single_batch)

Upvotes: 1

Related Questions