keras lstm模型 fit函数报错

# 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)

输入数据的维度信息:
shape of train_x: (409, 60, 30)
shape of test_x: (103, 60, 30)
shape of train_y: (409, 1)
shape of test_y: (103, 1)

为什么会报错如下:

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         # 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)
阅读 5k
1 个回答

把LSTM层的return_sequences改为False即可正确运行

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题