基于pytorch搭建多特征LSTM时间序列预测代码详细解读(附完整代码)

时间: 2023-07-29 10:09:30 浏览: 83
好的,我会尽力为您解答。以下是基于PyTorch搭建多特征LSTM时间序列预测代码的详细解读和完整代码。 首先,我们需要导入相应的库和模块: ```python import torch import torch.nn as nn import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error ``` 其中,`torch`和`torch.nn`是PyTorch中的主要模块,用于搭建神经网络。`pandas`和`numpy`用于数据处理,`matplotlib`用于可视化。`seaborn`是一个用于美化可视化图形的库。`MinMaxScaler`用于对数据进行归一化处理,`mean_squared_error`用于计算均方误差。 接下来,我们需要加载并预处理数据。我们使用的是一个包含多个特征的时间序列数据集,其中包括日期、销售额、促销和竞争对手等特征。我们将使用Pandas库来读取并处理数据,然后将其转换为NumPy数组。 ```python df = pd.read_csv('sales_data.csv') df['date'] = pd.to_datetime(df['date']) df.set_index('date', inplace=True) df.sort_index(inplace=True) df.head() ``` 读取后的数据集前五行如下所示: ``` sales holidays competition_distance promotion date 2013-01-01 13 1 1270.0 0 2013-01-02 11 0 1270.0 0 2013-01-03 14 0 1270.0 0 2013-01-04 13 0 1270.0 0 2013-01-05 10 0 1270.0 0 ``` 我们可以看到,数据集中包含四个特征:销售额、假期、竞争对手距离和促销。我们还可以看到,时间序列按日期排序。 接下来,我们使用`MinMaxScaler`对数据进行归一化处理: ```python scaler = MinMaxScaler() df = scaler.fit_transform(df) ``` 然后,我们需要将数据集分成训练集和测试集。在这里,我们将使用前80%的数据作为训练集,剩余20%的数据作为测试集: ```python train_size = int(len(df) * 0.8) test_size = len(df) - train_size train_data, test_data = df[0:train_size,:], df[train_size:len(df),:] ``` 接下来,我们需要创建一个函数来将数据转换为适合LSTM模型使用的格式。我们将使用时间步长为1的滑动窗口方法来创建输入序列和输出序列: ```python def create_dataset(dataset, look_back=1): dataX, dataY = [], [] for i in range(len(dataset)-look_back-1): a = dataset[i:(i+look_back), :] dataX.append(a) dataY.append(dataset[i + look_back, 0]) return np.array(dataX), np.array(dataY) ``` 其中,`look_back`参数用于指定滑动窗口的大小。在这里,我们将使用默认值1,也就是使用前一个时间步的数据来预测当前时间步的销售额。 接下来,我们需要使用上面的函数来创建训练集和测试集的输入序列和输出序列: ```python look_back = 1 trainX, trainY = create_dataset(train_data, look_back) testX, testY = create_dataset(test_data, look_back) ``` 接下来,我们需要将数据转换为PyTorch张量: ```python trainX = torch.from_numpy(trainX).type(torch.Tensor) trainY = torch.from_numpy(trainY).type(torch.Tensor) testX = torch.from_numpy(testX).type(torch.Tensor) testY = torch.from_numpy(testY).type(torch.Tensor) ``` 然后,我们需要定义LSTM模型。在这里,我们将使用一个包含两个LSTM层和一个全连接层的模型: ```python class LSTM(nn.Module): def __init__(self, input_dim, hidden_dim, output_dim): super(LSTM, self).__init__() self.hidden_dim = hidden_dim self.lstm1 = nn.LSTM(input_dim, hidden_dim, batch_first=True) self.lstm2 = nn.LSTM(hidden_dim, hidden_dim, batch_first=True) self.fc = nn.Linear(hidden_dim, output_dim) def forward(self, x): h0 = torch.zeros(1, x.size(0), self.hidden_dim).requires_grad_() c0 = torch.zeros(1, x.size(0), self.hidden_dim).requires_grad_() out, (hn, cn) = self.lstm1(x, (h0.detach(), c0.detach())) out, (hn, cn) = self.lstm2(out, (hn.detach(), cn.detach())) out = self.fc(out[:, -1, :]) return out ``` 其中,`input_dim`参数用于指定输入特征的数量,`hidden_dim`参数用于指定LSTM层中隐藏神经元的数量,`output_dim`参数用于指定输出特征的数量。 接下来,我们需要定义模型的超参数: ```python input_dim = 4 hidden_dim = 32 output_dim = 1 learning_rate = 0.01 num_epochs = 1000 ``` 然后,我们需要初始化模型并定义损失函数和优化器: ```python model = LSTM(input_dim, hidden_dim, output_dim) criterion = nn.MSELoss() optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) ``` 接下来,我们需要训练模型。在每个epoch中,我们将使用训练集来更新模型参数,并计算训练集和测试集的损失值: ```python train_loss = [] test_loss = [] for epoch in range(num_epochs): # 训练集 model.train() optimizer.zero_grad() output = model(trainX) loss = criterion(output, trainY) loss.backward() optimizer.step() train_loss.append(loss.item()) # 测试集 model.eval() test_output = model(testX) loss = criterion(test_output, testY) test_loss.append(loss.item()) if epoch % 100 == 0: print(f'Epoch {epoch}, Train Loss: {train_loss[-1]:.4f}, Test Loss: {test_loss[-1]:.4f}') ``` 最后,我们可以使用训练好的模型来对测试集进行预测,然后计算均方误差和可视化预测结果: ```python # 测试集预测 model.eval() test_predict = model(testX) # 反归一化 test_predict = scaler.inverse_transform(test_predict.detach().numpy()) testY = scaler.inverse_transform(testY.detach().numpy().reshape(-1, 1)) # 计算均方误差 test_score = mean_squared_error(testY, test_predict) print(f'Test MSE: {test_score:.4f}') # 可视化预测结果 plt.figure(figsize=(10, 6)) plt.plot(testY, label='True') plt.plot(test_predict, label='Predicted') plt.legend() plt.show() ``` 这就是完整的基于PyTorch搭建多特征LSTM时间序列预测代码,希望对您有所帮助!

相关推荐

最新推荐

recommend-type

基于pytorch的lstm参数使用详解

今天小编就为大家分享一篇基于pytorch的lstm参数使用详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
recommend-type

pytorch下使用LSTM神经网络写诗实例

今天小编就为大家分享一篇pytorch下使用LSTM神经网络写诗实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
recommend-type

华为OD机试D卷 - 用连续自然数之和来表达整数 - 免费看解析和代码.html

私信博主免费获取真题解析以及代码
recommend-type

Screenshot_2024-05-10-20-21-01-857_com.chaoxing.mobile.jpg

Screenshot_2024-05-10-20-21-01-857_com.chaoxing.mobile.jpg
recommend-type

数字图像处理|Matlab-频域增强实验-彩色图像的频域滤波.zip

数字图像处理|Matlab-频域增强实验-彩色图像的频域滤波.zip
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

spring添加xml配置文件

1. 创建一个新的Spring配置文件,例如"applicationContext.xml"。 2. 在文件头部添加XML命名空间和schema定义,如下所示: ``` <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。