I'm building an LSTM model for time series data, but I got this error:
ValueError: Input 0 of layer "lstm_121" is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: (None, 50)
My model:
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(X_train.shape[1], 1)))
model.add(LSTM(50, recurrent_dropout=0.3))
model.add(LSTM(50, recurrent_dropout=0.3))
model.add(LSTM(50, recurrent_dropout=0.3))
model.add(Dense(1))
The dimension of the X_train
is (1198, 60, 1)
and the one of y_train
is (1198,)
.
CodePudding user response:
The problem is that the LSTM layer expects a 3D input, while your 3rd and 4th LSTM layers are receiving a 2D input of shape (None, 50)
since return_sequences
is set to False
(the default) in the 2nd and 3rd LSTM layers, while it should be set to True
.
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense
X_train = np.random.normal(size=(1198, 60, 1))
y_train = np.mean(X_train, axis=1)
model = Sequential()
model.add(LSTM(50, return_sequences=True, input_shape=X_train.shape[1:]))
model.add(LSTM(50, return_sequences=True, recurrent_dropout=0.3))
model.add(LSTM(50, return_sequences=True, recurrent_dropout=0.3))
model.add(LSTM(50, recurrent_dropout=0.3))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mse')
model.fit(X_train, y_train, epochs=10, batch_size=128)