Keras lstm model fit function reports an error

-sharp build model


model = Sequential()
model.add(LSTM(20, return_sequences=True,
               input_shape=(max_len, data_dim)))
model.add(Dropout(0.5))
model.add(Dense(1, activation="sigmoid"))

model.compile(loss="binary_crossentropy",
              optimizer="rmsprop",
              metrics=["accuracy"])

model.fit(train_x, train_y, batch_size=16, epochs=10)
score = model.evaluate(test_x, test_y, batch_size=16)

print(score)

Dimension information of input data:
shape of train_x: (40960,30)
shape of test_x: (103,60,30)
shape of train_y: (409,1)
shape of test_y: (103,1)

Why the error is reported as follows:

F:\Anaconda\envs\tensorflow\lib\site-packages\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs)
   1591             class_weight=class_weight,
   1592             check_batch_axis=False,
-> 1593             batch_size=batch_size)
   1594         -sharp Prepare validation data.
   1595         do_validation = False

F:\Anaconda\envs\tensorflow\lib\site-packages\keras\engine\training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_batch_axis, batch_size)
   1428                                     output_shapes,
   1429                                     check_batch_axis=False,
-> 1430                                     exception_prefix="target")
   1431         sample_weights = _standardize_sample_weights(sample_weight,
   1432                                                      self._feed_output_names)

F:\Anaconda\envs\tensorflow\lib\site-packages\keras\engine\training.py in _standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
    108                         ": expected " + names[i] + " to have " +
    109                         str(len(shape)) + " dimensions, but got array "
--> 110                         "with shape " + str(data_shape))
    111                 if not check_batch_axis:
    112                     data_shape = data_shape[1:]

ValueError: Error when checking target: expected dense_8 to have 3 dimensions, but got array with shape (409, 1)
May.05,2021

change the return_sequences of the LSTM layer to False to run correctly

Menu