在Python中使用PyTorch使用LSTM进行时间序列预测的数据预处理,比如金融数据,天气预报数据,飞机航班出行数据
我们将探讨如何使用PyTorch库和长短期记忆网络(LSTM)对时间序列数据进行预测。时间序列数据是按时间顺序排列的数据点集合,例如气温记录、产品价格或股票价格等。LSTM是一种特殊的循环神经网络(RNN),它能够学习时间序列数据中的长期依赖关系,因此非常适合进行时间序列预测。https://s2.51cto.com/images/blog/202205/12110009_627c78396e17572727.webp?x-oss-process=image/watermark,size_14,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_30,g_se,x_10,y_10,shadow_20,type_ZmFuZ3poZW5naGVpdGk=/format,webp/resize,m_fixed,w_1184
以下是使用PyTorch进行时间序列预测的步骤:
1. **数据集和问题定义**:
我们将使用Seaborn库的内建数据集,例如“flights”数据集,它包含了12年的月度乘客数量。
2. **数据处理**:
数据预处理包括将数据转换为浮点数、划分训练集和测试集、数据标准化等。
3. **创建序列数据**:
为了训练LSTM模型,我们需要将时间序列数据转换为序列数据。这通常涉及到定义一个时间窗口(例如12个月),并创建输入序列和相应的标签。
4. **构建LSTM模型**:
我们将构建一个包含LSTM层和全连接层的神经网络模型。
5. **训练模型**:
使用训练数据对模型进行训练,并在测试集上评估模型的性能。
以下是实现这些步骤的示例代码:
```python
import torch
import torch.nn as nn
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from torch.utils.data import DataLoader, TensorDataset
# 导入数据集
flight_data = sns.load_dataset("flights")
all_data = flight_data['passengers'].values.astype(float)
# 数据标准化
scaler = MinMaxScaler(feature_range=(-1, 1))
train_data_normalized = scaler.fit_transform(all_data[:-12].reshape(-1, 1))
# 转换为PyTorch张量
train_data_normalized = torch.FloatTensor(train_data_normalized).view(-1)
# 定义序列长度
train_window = 12
# 创建序列数据
def create_inout_sequences(input_data, tw):
inout_seq = []
L = len(input_data)
for i in range(L-tw):
train_seq = input_data[i:i+tw]
train_label = input_data[i+tw:i+tw+1]
inout_seq.append((train_seq ,train_label))
return inout_seq
train_inout_seq = create_inout_sequences(train_data_normalized, train_window)
# 创建数据加载器
dataset = TensorDataset(torch.stack([i[0] for i in train_inout_seq]), torch.stack([i[1] for i in train_inout_seq]))
train_loader = DataLoader(dataset, batch_size=1, shuffle=True)
# 定义LSTM模型
class LSTMModel(nn.Module):
def __init__(self, input_size=1, hidden_layer_size=100, output_size=1):
super().__init__()
self.hidden_layer_size = hidden_layer_size
self.lstm = nn.LSTM(input_size, hidden_layer_size)
self.linear = nn.Linear(hidden_layer_size, output_size)
self.hidden_cell = (torch.zeros(1, 1, self.hidden_layer_size),
torch.zeros(1, 1, self.hidden_layer_size))
def forward(self, input_seq):
lstm_out, self.hidden_cell = self.lstm(input_seq.view(len(input_seq) ,1, -1), self.hidden_cell)
predictions = self.linear(lstm_out.view(len(input_seq), -1))
return predictions[-1]
# 实例化模型
model = LSTMModel()
loss_function = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
# 训练模型
epochs = 150
for i in range(epochs):
for seq, labels in train_loader:
optimizer.zero_grad()
model.hidden_cell = (torch.zeros(1, 1, model.hidden_layer_size),
torch.zeros(1, 1, model.hidden_layer_size))
y_pred = model(seq)
single_loss = loss_function(y_pred, labels)
single_loss.backward()
optimizer.step()
if i%25 == 1:
print(f'epoch: {i:3} loss: {single_loss.item():10.8f}')
print(f'epoch: {i:3} loss: {single_loss.item():10.10f}')
```
请注意,这个代码只是一个简单的示例,实际应用中可能需要更复杂的数据预处理、模型结构和训练策略。此外,为了获得更好的预测结果,可能还需要对模型进行调优和验证。、、
注意点是 训练集 需要数据规范化,而测试集不需要,也不能 会相互干扰
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)