ValueError: Input 0 of layer sequential is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: (57, 1)

Issue

I am working with the LSTM model and getting this error.

ValueError: Input 0 of layer sequential is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: (57, 1)

Here is my code:

model = tf.keras.Sequential()
model.add(tf.keras.layers.LSTM(64, input_shape = (700, 57), return_sequences=True))
model.add(tf.keras.layers.LSTM(64))
model.add(tf.keras.layers.Dense(64, activation='relu'))
model.add(tf.keras.layers.Dense(10, activation='softmax'))

optimizer = tf.keras.optimizers.Adam(lr=0.001)

model.compile(optimizer=optimizer,
             loss='sparse_categorical_crossentropy',
             metrics=['accuracy'])

model.summary()
history = model.fit(train_data, batch_size=32, epochs=60, verbose=2, validation_data=valid_data)
model.save("LSTM.h5")

The shape of my training data is:

input_shape = (x_train.shape, y_train.shape)
print(input_shape)

((700, 57), (700,))

The training dataset contains 700 rows (samples) and 57 columns (features) and the test dataset contains labels for 700 samples.

Solution

LSTM expects an input of three dimensions, namely (batch, timestep, features). Is each sample of yours a length-1 sequence? In that case, you’ll need to set input_shape = (1,57) and reshape your data as x_train = x_train[:, None, :] and x_validation = x_validation[:, None, :]

Answered By – Muhammad Faizan

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published