用pytorch写一个天气预测的代码,用LSTM或CNN,读取天气中的csv文件,由时间和气温两列数据,区分训练集和测试集,用gpu训练,输入为60天的天气,输出为某一天的天气,并画出60天的实际曲线和预测曲线图,注意维度要一致
时间: 2023-09-30 07:06:03 浏览: 101
好的,以下是天气预测的PyTorch代码,使用了LSTM模型:
```python
import torch
import torch.nn as nn
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 读取天气数据
data = pd.read_csv('weather.csv')
# 选取需要的时间和气温数据
data = data[['Time', 'Temperature']]
# 归一化数据
max_temp = data['Temperature'].max()
min_temp = data['Temperature'].min()
data['Temperature'] = (data['Temperature'] - min_temp) / (max_temp - min_temp)
# 划分训练集和测试集
train_data = data.iloc[:-30, :]
test_data = data.iloc[-30:, :]
# 定义函数,将数据集转换为LSTM模型的输入格式
def create_dataset(data, seq_len):
X = []
y = []
for i in range(len(data)-seq_len-1):
X.append(data[i:i+seq_len])
y.append(data[i+seq_len])
return np.array(X), np.array(y)
# 定义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, input):
lstm_out, _ = self.lstm(input.view(len(input), 1, -1))
output = self.fc(lstm_out.view(len(input), -1))
return output[-1]
# 定义超参数
seq_len = 60
input_size = 1
hidden_size = 64
output_size = 1
lr = 0.001
epochs = 200
# 转换数据集为LSTM模型的输入格式
train_X, train_y = create_dataset(train_data['Temperature'].values, seq_len)
test_X, test_y = create_dataset(test_data['Temperature'].values, seq_len)
# 将数据集转换为PyTorch张量
train_X = torch.from_numpy(train_X).float()
train_y = torch.from_numpy(train_y).float()
test_X = torch.from_numpy(test_X).float()
test_y = torch.from_numpy(test_y).float()
# 定义模型和优化器
model = LSTM(input_size, hidden_size, output_size)
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
# 将模型和数据移动到GPU上
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.to(device)
train_X = train_X.to(device)
train_y = train_y.to(device)
test_X = test_X.to(device)
test_y = test_y.to(device)
# 训练模型
for epoch in range(epochs):
loss = 0
for i in range(len(train_X)):
optimizer.zero_grad()
output = model(train_X[i])
loss = loss + nn.MSELoss()(output, train_y[i])
loss.backward()
optimizer.step()
if epoch % 10 == 0:
print('Epoch {}/{} Loss {:.6f}'.format(epoch+1, epochs, loss))
# 测试模型
model.eval()
test_predict = []
with torch.no_grad():
for i in range(len(test_X)):
output = model(test_X[i])
test_predict.append(output.item())
# 将预测结果还原为原始数据范围
test_predict = np.array(test_predict) * (max_temp - min_temp) + min_temp
test_y = np.array(test_y) * (max_temp - min_temp) + min_temp
# 绘制实际曲线和预测曲线图
plt.plot(range(len(test_y)), test_y, color='blue', label='Actual')
plt.plot(range(len(test_predict)), test_predict, color='red', label='Predict')
plt.legend()
plt.show()
```
这段代码读取名为`weather.csv`的天气数据文件,选取其中的时间和气温数据,并进行归一化处理。然后将数据集划分为训练集和测试集,使用`create_dataset`函数将数据集转换为LSTM模型的输入格式。接着定义LSTM模型和优化器,将模型和数据移动到GPU上,训练模型并测试模型。最后将预测结果还原为原始数据范围,并绘制实际曲线和预测曲线图。
阅读全文