用pytorch写一个天气预测的代码,用RNN模型,读取天气数据csv文件中的时间和气温两列数据,区分训练集和测试集,用gpu训练,输入为60天的天气,输出为某一天的天气
时间: 2023-09-13 09:10:42 浏览: 85
使用pytorch进行气温的预测 里面包含数据集和代码!
好的,以下是一个简单的天气预测代码,使用了PyTorch和RNN模型:
```python
import torch
import torch.nn as nn
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
# 读取数据
data = pd.read_csv('weather.csv')
# 选择需要的特征,即时间和气温
data = data[['time', 'temperature']]
# 将时间转换为时间戳并排序
data['time'] = pd.to_datetime(data['time'])
data = data.sort_values('time')
# 将气温归一化
scaler = MinMaxScaler()
data['temperature'] = scaler.fit_transform(data['temperature'].values.reshape(-1,1))
# 划分训练集和测试集
training_data = data.iloc[:len(data)-60]
testing_data = data.iloc[len(data)-60:]
# 定义数据预处理函数
def create_dataset(dataset, look_back=1):
dataX, dataY = [], []
for i in range(len(dataset)-look_back):
x = dataset[i:(i+look_back), 0]
y = dataset[i+look_back, 0]
dataX.append(x)
dataY.append(y)
return np.array(dataX), np.array(dataY)
# 准备训练数据
trainX, trainY = create_dataset(training_data['temperature'].values.reshape(-1,1), look_back=60)
trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
# 定义RNN模型
class RNN(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(RNN, self).__init__()
self.hidden_size = hidden_size
self.rnn = nn.RNN(input_size, hidden_size, batch_first=True)
self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x):
h0 = torch.zeros(1, x.size(0), self.hidden_size).cuda()
out, _ = self.rnn(x, h0)
out = self.fc(out[:, -1, :])
return out
# 定义模型参数
input_size = 1
hidden_size = 64
output_size = 1
# 创建模型并将其移动到GPU上
model = RNN(input_size, hidden_size, output_size).cuda()
# 定义损失函数和优化器
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
# 训练模型
num_epochs = 1000
for epoch in range(num_epochs):
inputs = torch.autograd.Variable(torch.Tensor(trainX).cuda())
labels = torch.autograd.Variable(torch.Tensor(trainY).cuda())
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
if epoch % 100 == 0:
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item()))
# 使用模型进行预测
model.eval()
test_inputs = torch.autograd.Variable(torch.Tensor(testing_data['temperature'].values.reshape(-1,1)).cuda())
testX, testY = create_dataset(testing_data['temperature'].values.reshape(-1,1), look_back=60)
testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))
test_inputs = torch.autograd.Variable(torch.Tensor(testX).cuda())
predicted_temperature = model(test_inputs).cpu().detach().numpy()
predicted_temperature = scaler.inverse_transform(predicted_temperature)
# 打印预测结果
print(predicted_temperature)
```
注:该代码假设CSV文件中仅包含两列数据:时间和气温。您需要根据您的CSV文件结构进行相应的修改。此外,您需要安装PyTorch和Scikit-learn库,并且需要一台带有GPU的计算机来运行此代码。
阅读全文