用pytorch写一个天气预测的代码,用LSTM,读取天气中的csv文件中时间和气温两列数据,区分训练集和测试集,用gpu训练,输入为60天的天气,输出为某一天的天气,并画出60天的实际曲线和预测曲线图,横坐标为时间,纵坐标为温度,注意维度要一致
时间: 2023-10-07 16:07:39 浏览: 134
以下是用PyTorch实现天气预测的代码,使用LSTM模型进行训练和预测:
```python
import torch
import torch.nn as nn
import pandas as pd
import matplotlib.pyplot as plt
# 读取数据
data = pd.read_csv('weather.csv')
time = data['time'].values
temperature = data['temperature'].values
# 数据归一化
temperature = (temperature - temperature.mean()) / temperature.std()
# 划分训练集和测试集
train_data = temperature[:500]
test_data = temperature[500:]
# 定义参数
input_size = 1
hidden_size = 32
num_layers = 2
output_size = 1
batch_size = 60
seq_len = 60
learning_rate = 0.001
num_epochs = 1000
# 将数据转换成序列数据
def create_sequences(data, seq_len):
xs = []
ys = []
for i in range(len(data)-seq_len-1):
x = data[i:(i+seq_len)]
y = data[i+seq_len]
xs.append(x)
ys.append(y)
return torch.Tensor(xs), torch.Tensor(ys)
# 创建训练集和测试集的序列数据
train_x, train_y = create_sequences(train_data, seq_len)
test_x, test_y = create_sequences(test_data, seq_len)
# 定义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).to(device)
c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)
out, _ = self.lstm(x, (h0, c0))
out = out[:, -1, :]
out = self.fc(out)
return out
# 实例化模型和优化器
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = LSTM(input_size, hidden_size, num_layers, output_size).to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
# 定义损失函数
criterion = nn.MSELoss()
# 训练模型
train_losses = []
test_losses = []
for epoch in range(num_epochs):
# 训练集
model.train()
for i in range(0, train_x.size(0), batch_size):
x_batch = train_x[i:i+batch_size].unsqueeze(-1).to(device)
y_batch = train_y[i:i+batch_size].unsqueeze(-1).to(device)
outputs = model(x_batch)
loss = criterion(outputs, y_batch)
optimizer.zero_grad()
loss.backward()
optimizer.step()
train_losses.append(loss.item())
# 测试集
model.eval()
with torch.no_grad():
for i in range(0, test_x.size(0), batch_size):
x_batch = test_x[i:i+batch_size].unsqueeze(-1).to(device)
y_batch = test_y[i:i+batch_size].unsqueeze(-1).to(device)
outputs = model(x_batch)
loss = criterion(outputs, y_batch)
test_losses.append(loss.item())
# 打印损失值
if epoch % 100 == 0:
print(f'Epoch {epoch}, Train Loss: {train_losses[-1]}, Test Loss: {test_losses[-1]}')
# 预测数据
model.eval()
with torch.no_grad():
train_predict = model(train_x.unsqueeze(-1).to(device))
test_predict = model(test_x.unsqueeze(-1).to(device))
# 反归一化
train_data = train_data * temperature.std() + temperature.mean()
test_data = test_data * temperature.std() + temperature.mean()
train_predict = train_predict.cpu().numpy() * temperature.std() + temperature.mean()
test_predict = test_predict.cpu().numpy() * temperature.std() + temperature.mean()
# 绘制实际曲线和预测曲线图
plt.figure(figsize=(10, 6))
plt.plot(time[:500], train_data, label='Actual')
plt.plot(time[:500], train_predict, label='Predicted')
plt.plot(time[500:], test_data, label='Actual')
plt.plot(time[500:], test_predict, label='Predicted')
plt.xlabel('Time')
plt.ylabel('Temperature')
plt.legend()
plt.show()
```
注:代码中`weather.csv`文件中的数据应该至少包含两列,一列是时间,一列是气温。
阅读全文