Lstm多变量时间序列预测框架|pytorch

这是目前我看国内总结时序预测对小白很友好的博客教程,先推荐一下

PyTorch搭建CNN实现时间序列预测(风速预测)_Cyril_KI的博客-CSDN博客_cnn回归预测pytorch 

代码:单步预测

## 如果在初始化LSTM时令batch_first=True,那么input和output的shape将由:

## input(seq_len, batch_size, input_size)

## output(seq_len, batch_size, num_directions * hidden_size)

## 变为

## input(batch_size, seq_len, input_size)

## output(batch_size, seq_len, num_directions * hidden_size)

## self.num_directions = 1 # 单向LSTM 2为双向LSTM

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
class LSTM(nn.Module):
    def __init__(self, input_size, hidden_size, num_layers, output_size, batch_size):
        super().__init__()
        self.input_size = input_size #channel
        self.hidden_size = hidden_size #输出维度 也就是输出通道
        self.num_layers = num_layers
        self.output_size = output_size #输出个数
        self.num_directions = 1 # 单向LSTM
        self.batch_size = batch_size
        self.lstm = nn.LSTM(self.input_size, self.hidden_size, self.num_layers, batch_first=True)
        self.linear = nn.Linear(self.hidden_size, self.output_size)
        # self.linear = nn.Linear()


    def forward(self, input_seq):
        batch_size, seq_len = input_seq.shape[0], input_seq.shape[1]
        h_0 = torch.randn(self.num_directions * self.num_layers, self.batch_size, self.hidden_size).to(device)
        c_0 = torch.randn(self.num_directions * self.num_layers, self.batch_size, self.hidden_size).to(device)
        # output(batch_size, seq_len, num_directions * hidden_size)
        output, _ = self.lstm(input_seq, (h_0, c_0)) # output(5, 30, 64)
        pred = self.linear(output)  # (5, 30, 1)
        pred = pred[:, -1, :]  # (5, 1)
        return pred
lstm = LSTM(input_size=7,hidden_size=64, output_size=1,batch_size=5,num_layers=5).to(device)
tensor = torch.rand(5, 30, 7).to(device)
result = lstm(tensor)
print("result.shape:",result.shape)

参考资料

深入理解PyTorch中LSTM的输入和输出(从input输入到Linear输出)_Cyril_KI的博客-CSDN博客_lstm输入

//写的非常得好 

多步预测的讨论

我的意见如下:首先,要理清楚两个概念:一是多变量一般是指你在预测时考虑了主变量以外的其他变量,而不是说你要预测多个变量,预测多个变量当然是可以的,但效果特别差,这个我之前还和清华一个搞新能源预测的PhD讨论过,所以我们一般是多变量预测单变量,如果要预测多变量那就训练多个LSTM;二是步长的问题,我这里预测了4步,所以是多步。你所纠结的无非是预测的是下一时刻,然而我却直接经过转换变成了预测四个时刻,但这种写法其实是合理的。多步长预测一般有以下几种方法:第一种就是我这种,直接取最后一步,然后接一个MLP来转换成多步,这种优点是简单,可以直接输入多个预测值,这种相当于是把最后的时间序列预测变成了一个纯粹的神经网络非线性预测,也就是这种最后的预测结果要看你MLP的性能了,所以这种我们一般会多加几个线性层;第二种是滚动预测,也就是预测单步然后把预测值加入继续滚动预测多次,这种可能会把误差传递,效果也一般;第三种是多个单步预测,也就是你要预测接下来n步,那么就训练n个模型分别来预测每一步,这种比较耗时。所以用哪种看你自己,你想要理解我这种想法,你可以就把最后这个转换看成是一个简单的MLP转换,仅此而已。

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43332715/article/details/127741022