如何使用Keras创建具有许多输入和许多输出的LSTM时间序列模型

时间:2019-02-16 18:46:15

标签: keras time-series many-to-many lstm

我有这样的训练数据:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
train_x = np.random.randint(1, 20, (5, 4))
train_x
array([[ 4, 19,  5,  4],
       [ 5,  2,  2,  8],
       [11,  9, 17, 16],
       [18, 18,  7, 10],
       [ 2,  1,  1,  4]])
train_y = np.random.randint(1, 10, (5, 2))
train_y

还有这样的验证数据集:

array([[2, 7],
       [2, 9],
       [4, 5],
       [7, 8],
       [2, 8]])

对于train_x,它表示:

validation_x = np.random.randint(1, 20, (5, 4))
validation_y = np.random.randint(1, 10, (5, 2))

对于train_y,它表示:

                Jan  Feb   Mrch  April
 project_1      4     19    5    4
 project_2      5     2     2    8
 project_3      11    9     17   16
 project_4      18    18    7    10
 project_5      2     1     1    4

也就是说,我有5个样本。每个样本具有过去4个月的时间步长作为输入数据,未来2个月作为输出数据。 但是对于输出数据y,我需要预测与输入数据相比不同时间长度的数据:

                May    June
 project_1      2        7
 project_2      2        9
 project_3      4        5
 project_4      7        8
 project_5      2        8
  1. 我知道如何为多对多模型创建模型。就像使用过去4个月的输入来预测未来4个月的输出一样。
  2. 我的问题是,当输入月份与输出月份不同时,如何使用KERAS来预测未来月份的数据?

打击是我的错误代码:

               May    June
 project      ?        ?
train_x = train_x[:,:,np.newaxis]
train_y = train_y[:,:,np.newaxis]
validation_x = validation_x[:,:,np.newaxis]
validation_y = validation_y[:,:,np.newaxis]
def buildModel(shape):
    model = Sequential()
    model.add(LSTM(5, input_shape=(shape[1], shape[2]), return_sequences=True))
    model.add(TimeDistributed(Dense(1)))
    model.compile(loss="mse", optimizer="adam", metrics=['accuracy'])
    model.summary()
    return model
model = buildModel(train_x.shape)
callback = EarlyStopping(monitor="loss", patience=2, verbose=1, mode="auto")
history = model.fit(train_x, train_y, epochs=2, batch_size=10, validation_data=(validation_x, validation_y), callbacks=[callback])

谢谢。

0 个答案:

没有答案