不同时间步长的数据形状和LSTM输入

2024-09-29 02:22:06 发布

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

在我的硕士论文中,我想用LSTM模型来预测股票在未来一小时内的价格。My X数据包含30.000行,具有6个维度(=6个要素),My Y数据包含30.000行和1个维度(=目标变量)。对于我的第一个LSTM模型,我将X数据重塑为(30.000x1x6),将Y数据重塑为(30.000x1),并确定如下输入: input_nn=输入(形状=(1,6))

如果我想增加时间步长,我不知道如何重塑数据形状和确定模型的输入形状。我仍然想预测下一个小时的股价,但包括更多之前的时间步数。 我是否必须在第二个维度的X数据中添加以前时间步长的数据?在

你能解释一下LSTM的单位数到底是指什么吗?它应该和我的情况下的时间步数一样吗?在


Tags: 数据模型目标my时间价格股票要素
2条回答

你是在正确的轨道上,但混淆了单位数量与时间步长。units是一个超参数,它控制LSTM的输出维度。它是LSTM输出向量的维数,所以如果输入是(1,6),并且你有32个单位,你将得到(32,),因为在LSTM中,它将遍历单个时间步并产生一个大小为32的向量。在

时间步长指的是你可以考虑的历史的大小。所以它和单位根本不一样。Keras没有自己处理数据,而是提供了一个方便的TimeseriesGenerator,它可以像你的那样获取二维数据,并使用一个时间步长大小的滑动窗口来生成timeseries数据。根据文件:

from keras.preprocessing.sequence import TimeseriesGenerator
import numpy as np

data = np.array([[i] for i in range(50)])
targets = np.array([[i] for i in range(50)])

data_gen = TimeseriesGenerator(data, targets,
                               length=10, sampling_rate=2,
                               batch_size=2)
assert len(data_gen) == 20

batch_0 = data_gen[0]
x, y = batch_0
assert np.array_equal(x,
                      np.array([[[0], [2], [4], [6], [8]],
                                [[1], [3], [5], [7], [9]]]))
assert np.array_equal(y,
                      np.array([[10], [11]]))

你可以使用model.fit_generator(data_gen,...)中的目录,让你可以选择尝试不同的采样率、时间步长等。你可能应该研究一下这些参数以及它们是如何影响论文结果的。在

使用比上一个快5倍的代码进行更新:

x = np.load(nn_input + "/EOAN" + "/EOAN_X" + ".npy")
y = np.load(nn_input + "/EOAN" + "/EOAN_Y" + ".npy")
num_features = x.shape[1]
num_time_steps = 500

for train_index, test_index in tscv.split(x):
# Split into train and test set
print("Fold:", fold_counter, "\n" + "Train Index:", train_index, "Test Index:", test_index)
x_train_raw, y_train, x_test_raw, y_test = x[train_index], y[train_index], x[test_index], y[test_index]

# Scaling the data
scaler = StandardScaler()
scaler.fit(x_train_raw)
x_train_raw = scaler.transform(x_train_raw)
x_test_raw = scaler.transform(x_test_raw)

# Creating Input Data with variable timesteps
x_train = np.zeros((x_train_raw.shape[0] - num_time_steps + 1, num_time_steps, num_features), dtype="float32")
x_test = np.zeros((x_test_raw.shape[0] - num_time_steps + 1, num_time_steps, num_features), dtype="float32")

for row in range(len(x_train)):
    for timestep in range(num_time_steps):
        x_train[row][timestep] = x_train_raw[row + timestep]

for row in range(len(x_test)):
    for timestep in range(num_time_steps):
        x_test[row][timestep] = x_test_raw[row + timestep]

y_train = y_train[num_time_steps - 1:]
y_test = y_test[num_time_steps - 1:]

相关问题 更多 >