Home > database >  how to make a stacked keras LSTM
how to make a stacked keras LSTM

Time:01-29

My Tensorflow non-stacked LSTM model code works well for this:

# reshape input to be [samples, time steps, features]
trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))

# create and fit the LSTM network
model = Sequential()
model.add(LSTM(4, input_shape=(1, LOOK_BACK)))

model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(trainX, trainY, epochs=EPOCHS, batch_size=1, verbose=2)

# make predictions
trainPredict = model.predict(trainX)
testPredict = model.predict(testX)

If I try to sequentially add more layers with using this:

# create and fit the LSTM network
model = Sequential()
batch_size = 1
model.add(LSTM(4, batch_input_shape=(batch_size, LOOK_BACK, 1), stateful=True, return_sequences=True))
model.add(LSTM(4, batch_input_shape=(batch_size, LOOK_BACK, 1), stateful=True))

This will error out:

ValueError: Input 0 of layer "lstm_6" is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: (None, 4)

Another similar SO post any tips appreciated not alot of wisdom here.

CodePudding user response:

The LSTM layer's input (layer "lstm 6") has an incompatible form, according to this error notice. The input shape obtained is 2-dimensional (ndim=2) with shape dimensions (batch size, sequence length, and feature dim), as opposed to the 3-dimensional (ndim=3) form that was anticipated (None, 4). This indicates that either the sequence length or feature dim dimension is missing from the input. To resolve this problem, you must make sure that the input to the LSTM layer has the proper form. You may do this by reshaping the input or by altering the data preparation pipeline.

  • Related