【问题标题】:LSTM: Understand timesteps, samples and features and especially the use in reshape and input_shapeLSTM:了解时间步长、样本和特征,尤其是在 reshape 和 input_shape 中的使用
【发布时间】:2018-01-08 03:45:58
【问题描述】:

我正在尝试学习 LSTM。参加过这个网络课程,读过这本书(https://machinelearningmastery.com/lstms-with-python/)和很多博客......但是,我完全被困住了。我的兴趣是多元 LSTM,我已经阅读了所有我能找到但仍然无法理解的内容。不知道是我傻还是怎么回事……

如果这个确切的问题和一个好的答案已经存在,那么我很抱歉重复发布,但我已经查看并没有找到它......

因为我想真正了解基础知识,所以我在 excel 中创建了一个虚拟数据集,其中每个“y”取决于每个输入 x1 和 x2 的总和,但也取决于时间。据我了解,这是一个多对一的场景。 伪代码:

x1(t) = sin(A(t))
x2(t) = cos(A(t))
tmp(t) = x1(t) + x2(t)         (dummy variable)
y(t) = tmp(t) + tmp(t-1) + tmp(t-2)     (i.e. sum over the last three steps)

(基本上我想在三个时间步长给定 x1 和 x2 的情况下预测 y(t))

然后将其导出到包含 x1、x2、y 列的 csv 文件

我已经尝试在下面对其进行编码,但显然它不起作用。

我读取数据并将其拆分为 80/20 测试和训练集,分别为 X_train、y_train、X_test、y_test,尺寸为 (217,2)、(217,1)、(54,2)、(54/ 1)

我真正还没有掌握的是时间步长和样本到底是什么,以及在 reshape 和 input_shape 中的使用。在我看过的许多代码示例中,它们只是使用数字而不是定义的变量,这使得很难理解正在发生的事情,特别是如果你想改变一些东西。例如,在我参加的其中一门课程中,重塑的编码是这样的......

X_train = np.reshape(X_train, (1257, 1, 1))

这并没有提供太多信息...

无论如何,当我运行下面的代码时,它会说

ValueError: 无法将大小为 434 的数组重新整形为 (217,3,2)

所以,我知道导致错误的原因,但不知道我需要做什么来修复它。如果我设置 look_back=1 它可以工作,但这不是我想要的。

import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import LSTM
from keras.layers import Dense

# Load data
data_set = pd.read_csv('../Data/LSTM_test.csv',';')
"""
data loaded have three columns:
    col 0, col 1: features (x)
    col 2: y
"""

# Train/test and variable split
split = 0.8 # 80% train, 20% test
split_idx = int(data_set.shape[0]*split)

# ...train
X_train = data_set.values[0:split_idx,0:2]
y_train = data_set.values[0:split_idx,2]

# ...test
X_test = data_set.values[split_idx:-1,0:2]
y_test = data_set.values[split_idx:-1,2]

# Model setup
look_back = 3 # as that is how y was generated (i.e. sum last three steps)
num_features = 2 # in this case: 2 features x1, x2
output_dim = 1 # want to predict 1 y value

nb_hidden_neurons = 32 # assume something to start with
nb_epoch = 2 # assume something to start with

# Reshaping
nb_samples = len(X_train) # in this case 217 samples in the training set
X_train_reshaped = np.reshape(X_train,(nb_samples, look_back, num_features))

# Create model
model = Sequential()
model.add(LSTM(nb_hidden_neurons, input_shape=(look_back,num_features)))
model.add(Dense(units=output_dim))
model.compile(optimizer = 'adam', loss = 'mean_squared_error')

model.fit(X_train_reshaped, y_train, batch_size = 32, epochs = nb_epoch)
print(model.summary())

谁能解释一下我做错了什么?

正如我所说,我已经阅读了很多博客、问题、教程等,但如果有人有特别好的信息来源,我也很乐意查看。

【问题讨论】:

    标签: python keras lstm


    【解决方案1】:

    我之前也有这个问题。在更高的层次上,在(samples, time steps, features)

    1. samples 是数据的数量,或者说你的数据集中有多少行
    2. time step 是模型馈送的次数或@​​987654326@
    3. features是每个样本的列数

    对我来说,我认为一个更好理解的例子是在NLP,假设你有一个句子要处理,那么这里的样本是1,表示要读1个句子,time step是字数在那个句子中,您在模型读取所有单词之前逐字输入句子并获得该句子的整个上下文,features 这里是每个单词的维度,因为在像word2vec 或@987654332 这样的词嵌入中@,每个单词都被一个多维向量解释。

    Keras中的input_shape参数只有(time_steps, num_features), 更多可以参考this

    而你的问题是,当你重塑数据时,每个维度的乘积应该等于原始数据集维度的乘积,其中434不等于217*3*2。

    当你实现LSTM时,你应该非常清楚你希望模型在每个时间步读取的特征和元素是什么。有一个非常相似的案例here 肯定可以帮助你。例如,如果您尝试使用t-1t-2 预测时间t 的值,您可以选择输入两个值作为一个元素来预测t,其中(time_step, num_features)=(1, 2),或者您可以在 2 个时间步内输入每个值,其中(time_step, num_features)=(2, 1)

    我基本上是这么理解的,希望你能说清楚。

    【讨论】:

      【解决方案2】:

      您似乎对 LSTM 的期望有一个不错的了解,并且正在努力将您的数据转换为正确的格式。您从形状为(217, 2)X_train 开始,并且您希望对其进行重塑,使其形状为(nb_samples, look_back, num_features)。你已经定义了look_backnum_features,剩下的工作就是用你原来的X_train 生成长度为look_backnb_samples 块。 Numpy 的 reshape 并不是真正的工具,而是您必须编写一些代码。

      import numpy as np
      
      nb_samples = X_train.shape[0] - look_back
      
      x_train_reshaped = np.zeros((nb_samples, look_back, num_features))
      y_train_reshaped = np.zeros((nb_samples))
      
      for i in range(nb_samples):
          y_position = i + look_back
          x_train_reshaped[i] = X_train[i:y_position]
          y_train_reshaped[i] = y_train[y_position]
      
      model.fit(x_train_reshaped, y_train_reshaped, ...)
      

      现在的形状是:

      x_train_reshaped.shape
      # (214, 3, 2)
      
      y_train_reshaped.shape
      # (214,)
      

      您必须对 X_testy_test 执行相同的操作。

      【讨论】:

      • 太棒了!谢谢你,妮可。有效!拟合和预测,结果表明 LSTM 完成了我希望的工作。知道如何围绕模型工作可以让我开始建模更有用的东西。
      • @ nicole白色:好的解决方案!所以,在选择y_train[y_position]时,你将拥有y_reshaped[0] = y[3], y_reshaped[1] = y[4] ...。所以,您要删除 y_train 数组的第一个值,对吧?
      【解决方案3】:

      这个https://github.com/fchollet/keras/issues/2045 帮助了我。

      但很快,您的问题的答案: 您想将具有 434 元素的列表重塑为形状 (217,3,2),但这是不可能的,让我告诉你原因:

      一个新形状有 217*3*2 = 1302 个元素,但您在原始列表中有 434 个元素。因此,解决方案是改变重塑的尺寸。

      【讨论】:

        猜你喜欢
        • 2022-01-24
        • 2018-08-28
        • 1970-01-01
        • 2020-04-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多