keras lstm回归 - 期望dense_1具有形状(batch_size,1)

时间:2017-11-14 17:41:46

标签: python tensorflow keras

我正在尝试使用Keras创建基于LSTM的回归模型,但我遇到了麻烦。我从GitHub上阅读博客文章和代码示例,感觉我正在以正确的方式使用Keras API,但它仍然会崩溃错误。

这是代码

from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM

import data_utils

seq_len = 10
n_epochs = 100
batch_size = 32
hdim = 4

train, valid = data_utils.load_dataset(10, 5, features=['trade_sign'])
datasets = {'train': train, 'valid': valid}

input_dim = data_utils.infer_input_dim(train)
batch_input_shape = (batch_size, seq_len, input_dim)
print('input_dim = {}'.format(input_dim))
print('batch_input_shape = {}'.format(batch_input_shape))

# reshape datasets to (n_samples, seq_len, input_dim)
# also make sure that n_samples is a multiple of batch_size
for dataset in datasets.values():
  data_utils.create_sequential_dataset(dataset, seq_len, batch_size)

model = Sequential()
model.add(LSTM(hdim, stateful=True, return_sequences=False,
               batch_input_shape=batch_input_shape))
model.add(Dense(1, activation='linear'))
model.compile(loss='mean_squared_error', optimizer='rmsprop')

print(model.summary())

for e in range(n_epochs):
  for i, (datestr, (x, y)) in enumerate(train.items()):
    model.reset_states()
    model.fit(x, y, epochs=1, batch_size=batch_size,
              verbose=999, shuffle=False)

代码在ValueError步骤提出model.fit

以下是运行此代码时得到的输出:

(hello)~ $ python /mnt/tmp/tmp7d/minimal_lstm_keras.py
Using TensorFlow backend.
input_dim = 1
batch_input_shape = (32, 10, 1)
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
lstm_1 (LSTM)                (32, 4)                   96
_________________________________________________________________
dense_1 (Dense)              (32, 1)                   5
=================================================================
Total params: 101
Trainable params: 101
Non-trainable params: 0
_________________________________________________________________
None
Traceback (most recent call last):
  File "minimal_lstm_keras.py", line 43, in <module>
verbose=999, shuffle=False, callbacks=[tb_cb])
  File "python2.7/site-packages/keras/models.py"
, line 867, in fit initial_epoch=initial_epoch)
  File "python2.7/site-packages/keras/engine/tra
ining.py", line 1522, in fit batch_size=batch_size)
  File "python2.7/site-packages/keras/engine/tra
ining.py", line 1382, in _standardize_user_data
    exception_prefix='target')
  File "python2.7/site-packages/keras/engine/tra
ining.py", line 144, in _standardize_input_data
    str(array.shape))
ValueError: Error when checking target:
expected dense_1 to have shape (32, 1)
but got array with shape (218816, 10)

我传递给x的{​​{1}}形状model.fit,应该如此。 (batch_size, seq_len, input_dim)形状y:也应如此。

我在这里做错了什么?

0 个答案:

没有答案