使用基于LSTM模型的pyTorch滚动预测铁矿价格 生成代码
时间: 2024-02-22 12:56:51 浏览: 64
好的,以下是一个使用基于LSTM模型的PyTorch进行滚动预测铁矿价格的示例代码:
```python
import torch
import torch.nn as nn
import numpy as np
# 设定超参数
input_size = 1
hidden_size = 32
num_layers = 2
sequence_length = 12
output_size = 1
learning_rate = 0.01
num_epochs = 200
# 创建LSTM模型
class LSTM(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, output_size):
super(LSTM, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)
self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x):
h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).requires_grad_()
c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).requires_grad_()
out, (hn, cn) = self.lstm(x, (h0.detach(), c0.detach()))
out = self.fc(out[:, -1, :])
return out
# 加载数据
data = np.loadtxt('iron_ore_prices.csv', delimiter=',', usecols=[1], dtype=float)
train_data = data[:len(data)-sequence_length]
test_data = data[len(data)-sequence_length:]
# 数据预处理
def create_dataset(dataset, sequence_length):
dataX, dataY = [], []
for i in range(len(dataset)-sequence_length-1):
a = dataset[i:(i+sequence_length)]
dataX.append(a)
dataY.append(dataset[i+sequence_length])
return np.array(dataX), np.array(dataY)
trainX, trainY = create_dataset(train_data, sequence_length)
testX, testY = create_dataset(test_data, sequence_length)
# 转化为张量
trainX = torch.Tensor(trainX).unsqueeze(2)
trainY = torch.Tensor(trainY)
testX = torch.Tensor(testX).unsqueeze(2)
testY = torch.Tensor(testY)
# 创建模型和优化器
model = LSTM(input_size, hidden_size, num_layers, output_size)
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
# 训练模型
for epoch in range(num_epochs):
outputs = model(trainX)
optimizer.zero_grad()
loss = criterion(outputs, trainY)
loss.backward()
optimizer.step()
if epoch % 10 == 0:
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item()))
# 测试模型
model.eval()
with torch.no_grad():
test_predict = model(testX)
predict = model(trainX)
# 反归一化
train_predict = scaler.inverse_transform(train_predict.detach().numpy())
trainY = scaler.inverse_transform([trainY.numpy()])
test_predict = scaler.inverse_transform(test_predict.detach().numpy())
testY = scaler.inverse_transform([testY.numpy()])
# 可视化结果
import matplotlib.pyplot as plt
plt.plot(trainY[0], label='true')
plt.plot(train_predict[:,0], label='predict')
plt.xlabel("Time")
plt.ylabel("Iron Ore Prices")
plt.legend()
plt.show()
```
需要注意的是,这只是一个基础的示例代码,实际应用需要根据具体情况进行修改和优化。
阅读全文