用pytorch写一个天气预测的代码,用LSTM,读取天气中的csv文件中时间和气温两列数据,区分训练集和测试集,用gpu训练,输入为60天的天气,输出为某一天的天气,并画出60天的实际曲线和预测曲线图,横坐标为时间,纵坐标为温度,注意维度要一致
时间: 2023-10-07 18:07:39 浏览: 92
以下是使用PyTorch编写的天气预测代码,使用LSTM模型。这个代码假设您的CSV文件中的第一列是日期,第二列是温度。
```
import torch
import torch.nn as nn
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt
# 读取CSV文件
data = pd.read_csv('weather.csv')
# 取出温度列
data = data['temperature']
# 将数据转换为numpy数组
data = np.array(data)
# 将数据的形状更改为一列和多行
data = data.reshape(-1, 1)
# 将数据缩放到0到1的范围内
scaler = MinMaxScaler(feature_range=(0, 1))
data = scaler.fit_transform(data)
# 创建训练集和测试集
train_size = int(len(data) * 0.7)
test_size = len(data) - train_size
train_data, test_data = data[0:train_size,:], data[train_size:len(data),:]
# 创建时间步长为60的数据集
def create_dataset(dataset, look_back=60):
dataX, dataY = [], []
for i in range(len(dataset)-look_back-1):
a = dataset[i:(i+look_back), 0]
dataX.append(a)
dataY.append(dataset[i + look_back, 0])
return np.array(dataX), np.array(dataY)
trainX, trainY = create_dataset(train_data)
testX, testY = create_dataset(test_data)
# 将数据转换为张量
trainX = torch.Tensor(trainX).unsqueeze(2)
trainY = torch.Tensor(trainY).unsqueeze(1)
testX = torch.Tensor(testX).unsqueeze(2)
testY = torch.Tensor(testY).unsqueeze(1)
# 定义LSTM模型
class LSTM(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(LSTM, self).__init__()
self.hidden_size = hidden_size
self.lstm = nn.LSTM(input_size, hidden_size)
self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x):
h0 = torch.zeros(1, x.size(1), self.hidden_size).to(device)
c0 = torch.zeros(1, x.size(1), self.hidden_size).to(device)
out, _ = self.lstm(x, (h0, c0))
out = self.fc(out[-1, :, :])
return out
# 定义超参数
input_size = 1
hidden_size = 32
output_size = 1
lr = 0.001
num_epochs = 1000
# 创建模型并将其移动到GPU上
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model = LSTM(input_size, hidden_size, output_size).to(device)
# 定义损失函数和优化器
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
# 训练模型
for epoch in range(num_epochs):
# 将数据移动到GPU上
inputs = trainX.to(device)
labels = trainY.to(device)
# 前向传递
outputs = model(inputs)
# 计算损失函数
loss = criterion(outputs, labels)
# 反向传播和优化
optimizer.zero_grad()
loss.backward()
optimizer.step()
# 每100个epoch打印一次损失
if (epoch+1) % 100 == 0:
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item()))
# 测试模型
model.eval()
with torch.no_grad():
# 将测试数据移动到GPU上
inputs = testX.to(device)
# 前向传递
outputs = model(inputs)
# 计算测试损失
test_loss = criterion(outputs, testY.to(device))
print('Test Loss: {:.4f}'.format(test_loss.item()))
# 反缩放预测值和真实值
predicted = scaler.inverse_transform(outputs.cpu().numpy())
actual = scaler.inverse_transform(testY.cpu().numpy())
# 绘制实际曲线和预测曲线
plt.plot(actual, label='Actual')
plt.plot(predicted, label='Predicted')
plt.legend()
plt.show()
```
这个代码将数据集拆分为训练集和测试集,使用LSTM模型进行预测,并将预测值和真实值反缩放到原始范围,然后绘制实际曲线和预测曲线。请根据自己的实际需求进行调整。
阅读全文