使用pytorch(LSTM)预测未来60天

2024-04-19 12:43:28 发布

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

我正在尝试使用pytorch对时间序列数据集进行预测。你知道吗

1-首先,我将数据集分为训练和测试。你知道吗

Dataset

然后,我创建了模型。你知道吗

import torch.nn as nn
import torch.nn.functional as F


class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()

        self.rnn = nn.LSTM(input_size=1,hidden_size=50,num_layers=3,batch_first=True,dropout=0.2)
        self.out = nn.Linear(50, 1)

    def forward(self, x):

        r_out, (h_n, h_c) = self.rnn(x, None)
        x = r_out[:,-1,:]                    #last hidden output!
        x = self.out(x)
        return x

model = Model()

if cuda:
    model.cuda()

在训练模型之后,我做了验证步骤。你知道吗

mse = mean_squared_error(dataset['y'].iloc[60:].values,predicted)
print("RMSE:", np.sqrt(mse))

# RMSE: 0.10680269716212222

问题:我想知道,如何使用此模型预测未来60天?你知道吗

我读到有必要:从我的预测中取最后一个预测值(即predicted[-1]),并将其添加到total_x的最后一个数组中,不包括第一个timestep。

所以,我试过这个:

#array --> List
today = total_x[-1].reshape(-1).tolist()

# scaling last price
last_price = scaler.transform(infered['y_pred'][-1].reshape(-1, 1))

# adding last price to list.
today.append(last_price[0])

# Exclude first(0th index) element
today = today[1:]

#reshape
today = np.array(today).reshape(-1,60,1)

today = torch.Tensor(list(today))

#predict!
tomorrow = predict_with_pytorch(model, today)

#inverse transform.
tomorrow = scaler.inverse_transform(tomorrow)[0]

这个变量tomorrow是我明天的预测,然而,如何做到这一点,在未来60天?你知道吗


Tags: 数据模型selftodaymodeltransformnntorch