【问题标题】:Keras LSTM - Input shape for time series predictionKeras LSTM - 时间序列预测的输入形状
【发布时间】:2019-08-06 09:45:10
【问题描述】:

我正在尝试预测函数的输出。 (最终它将是多输入多输出)但现在只是为了让机制正确,我试图预测 sin 函数的输出。我的数据集如下,

    t0          t1
0   0.000000    0.125333
1   0.125333    0.248690
2   0.248690    0.368125
3   0.368125    0.481754
4   0.481754    0.587785
5   0.587785    0.684547
6   0.684547    0.770513
7   0.770513    0.844328
8   0.844328    0.904827
9   0.904827    0.951057
.....

总共 100 个值。 t0 是当前输入 t1 是我要预测的下一个输出。然后通过 scikit 将数据拆分为训练/测试,

x_train, x_test, y_train, y_test = train_test_split(wave["t0"].values, wave["t1"].values, test_size=0.20)

问题发生在合适的位置,我收到一个错误,提示输入错误的尺寸。

model = Sequential()
model.add(LSTM(128, input_shape=??? ,stateful=True))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')

model.fit(x_train, y_train, 
          batch_size=10, epochs=100,
          validation_data=(x_test, y_test))

我已经尝试过网站上的其他问题来解决问题,但无论我尝试什么,我都无法让 keras 识别正确的输入。

【问题讨论】:

  • x_trainy_train的形状是什么?
  • @thushv89,x_train 是 t0 列,y_train 是 t1 列
  • @thushv89 numpy 单个值数组
  • 认为这就是您的问题所在。 LSTM 层接受 [batch_size, sequence_length, num_features] 输入。因此,您需要将输入重塑为 [1,100,1] 数组。
  • @thushv89,我从其他问题中理解了那部分,但是如何做以及重塑后的样子我无法理解。

标签: python tensorflow keras deep-learning lstm


【解决方案1】:

LSTM 期望输入数据具有一定的形状(batch_size、time_steps、num_features)。在正弦波预测中,num_features 为 1,time_steps 是 LSTM 应该使用多少之前的时间点进行预测。在下面的示例中,batch size 为 1,time_steps 为 2,num_features 为 1。

x_train = np.ones((1,2,1)) 
y_train = np.ones((1,1))

x_test = np.ones((1,2,1))
y_test = np.ones((1,1))

model = Sequential()
model.add(LSTM(128, input_shape=(2,1)))
#for stateful
#model.add(LSTM(128, batch_input_shape=(1,2,1), stateful=True))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')

model.fit(x_train, y_train,
          batch_size=1, epochs=100,
          validation_data=(x_test, y_test))

【讨论】:

  • 你的数据集很好。当我尝试重塑我的数据时,x_train = x_train.reshape((1, x_train.shape[0], 1)) 我仍然会遇到同样的错误。原始 x_train 是 (80,) 并且重新整形是 (1, 80, 1)。 Error when checking input: expected lstm_7_input to have shape (2, 1) but got array with shape (80, 1)
  • 你需要改变 input_shape,适当地像这样:model.add(LSTM(128, input_shape=(80,1)))。
猜你喜欢
  • 2017-12-30
  • 2018-02-27
  • 2019-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多