为什么我们需要重塑LSTM的输入?

2024-04-25 23:33:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我读了这篇关于LSTM的文章:

https://machinelearningmastery.com/how-to-develop-lstm-models-for-time-series-forecasting/

第一个基本示例是关于“香草LSTM”:预测下一个时间序列

其中输入=[10, 20, 30, 40, 50, 60, 70, 80, 90]

在本文中,作者将输入(序列)拆分为矩阵:

X,              y
10, 20, 30      40
20, 30, 40      50
30, 40, 50      60
...

我不明白为什么输入需要改变形状:

reshape from [samples, timesteps] into [samples, timesteps, features]

1。我们为什么需要这个?

此外,如果我的输入类似(基本示例+ID列):

ID    X,                y
1     10, 20, 30        40
1     20, 30, 40        50
2     30, 40, 50        60
2     40, 50, 60,       70
...

2。我们如何重塑它?我们将成为什么样的新维度?


Tags: tohttpscomid示例models文章序列
2条回答

不确定ID来自何处,但对于Keras中的LSTM网络,您需要三维输入

最初,您将二维矩阵作为输入,其中每行是一个时间戳,因此
[samples, timesteps]

但是,由于预期输入是三维的,所以您将其重新塑造为[samples, timesteps, 1]。这里1表示数据中的特征或变量的数量。由于这是一个单变量时间序列(只有一个变量的序列),n_特征为1

这可以通过np_array.reshape(np_array.shape[0], np_array.shape[1], 1)轻松完成

我认为this链接将帮助您了解原因

You always have to give a three-dimensional array as an input to your LSTM network. Where the first dimension represents the batch size, the second dimension represents the number of time-steps you are feeding a sequence. And the third dimension represents the number of units in one input sequence. For example, input shape looks like (batch_size, time_steps, seq_len)

让我们以您的序列为例:[10,20,30,40,50,60,70,80,90]

一旦我们按照你的文章所述分割了_序列,我们就得到了形状为(6,3)的二维特征向量X。其中6是样本数,3是步骤数

但考虑到模型只接受三维向量,我们必须将二维向量重塑为三维向量

因此,从(6,3)开始>;(6, 3, 1).

要回答第二个问题,只需通过执行以下操作重塑二维特征向量X:

# Given that X is a numpy array
samples = X.shape[0]
steps = X.shape[1]
X = X.reshape(samples, steps, 1)

相关问题 更多 >