利用pytorch实现lstm代码
时间: 2023-10-26 20:28:12 浏览: 116
好的,以下是一个利用PyTorch实现LSTM的代码示例:
```python
import torch
import torch.nn as nn
import numpy as np
import pandas as pd
import os
# 定义函数读取数据
def read_data(path):
data_list = []
for folder in os.listdir(path):
folder_path = os.path.join(path, folder)
folder_data = []
for file in os.listdir(folder_path):
file_path = os.path.join(folder_path, file)
df = pd.read_excel(file_path)
folder_data.append(df.values)
data_list.append(np.array(folder_data))
return np.array(data_list)
# 读取数据
data_path = "/path/to/data" # 修改为你的数据所在路径
data = read_data(data_path)
# 将数据随机分为训练集和测试集
train_size = int(len(data) * 0.8)
train_data = data[:train_size]
test_data = data[train_size:]
# 定义模型
class LSTM(nn.Module):
def __init__(self, input_dim, hidden_dim, batch_size, output_dim=1, num_layers=2):
super(LSTM, self).__init__()
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.batch_size = batch_size
self.num_layers = num_layers
self.lstm = nn.LSTM(self.input_dim, self.hidden_dim, self.num_layers)
self.linear = nn.Linear(self.hidden_dim, output_dim)
def init_hidden(self):
# 初始化隐层状态
return (torch.zeros(self.num_layers, self.batch_size, self.hidden_dim),
torch.zeros(self.num_layers, self.batch_size, self.hidden_dim))
def forward(self, input):
lstm_out, self.hidden = self.lstm(input.view(len(input), self.batch_size, -1), self.hidden)
y_pred = self.linear(lstm_out[-1].view(self.batch_size, -1))
return y_pred
input_dim = train_data.shape[2]
hidden_dim = 50
batch_size = 1
num_layers = 2
output_dim = 1
model = LSTM(input_dim, hidden_dim, batch_size, output_dim, num_layers)
# 定义损失函数和优化器
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
# 将数据转换为Torch张量
train_data = torch.from_numpy(train_data).float()
test_data = torch.from_numpy(test_data).float()
# 训练模型
num_epochs = 100
for epoch in range(num_epochs):
# 初始化隐层状态
model.hidden = model.init_hidden()
# 前向传播
output = model(train_data)
loss = criterion(output, train_data)
# 反向传播和优化
optimizer.zero_grad()
loss.backward()
optimizer.step()
if epoch % 10 == 0:
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item()))
# 预测结果
model.eval()
train_predict = model(train_data)
test_predict = model(test_data)
# 可以根据需要对预测结果进行后处理,如去除负数等
```
需要注意的是,上述代码为一个简单的示例,对于真实的数据还需要进行数据预处理、特征工程等步骤,以获得更好的预测效果。另外,上述代码中使用了PyTorch的自动求导功能,可以大大简化反向传播的代码实现。
阅读全文