用pytorch写一个天气预测的代码,用LSTM,读取天气中的csv文件中时间和气温两列数据,区分训练集和测试集,用gpu训练,输入为60天的天气,输出为某一天的天气,并画出60天的实际曲线和预测曲线图,横坐标为时间,纵坐标为温度,注意维度要一致
时间: 2023-10-07 20:07:39 浏览: 103
lstm 多输入 多输出 负荷预测 pytorch 直接可跑 内含数据集
好的,下面是一个使用PyTorch框架实现天气预测的LSTM模型代码,包括读取CSV文件、数据预处理、模型定义、训练和预测:
```python
import torch
import torch.nn as nn
import pandas as pd
import matplotlib.pyplot as plt
# 读取csv文件
data = pd.read_csv('weather.csv')
# 取时间和气温两列数据
temp = data.iloc[:, [0, 1]].values
# 将数据规范化到[-1, 1]之间
from sklearn.preprocessing import MinMaxScaler
sc = MinMaxScaler(feature_range=(-1, 1))
temp = sc.fit_transform(temp)
# 将数据集分为训练集和测试集
training_size = int(len(temp) * 0.75)
test_size = len(temp) - training_size
train_data, test_data = temp[0:training_size, :], temp[training_size:len(temp), :]
# 创建函数,生成输入和输出序列
def create_dataset(dataset, look_back=60):
X, Y = [], []
for i in range(len(dataset)-look_back-1):
a = dataset[i:(i+look_back), 0]
X.append(a)
Y.append(dataset[i + look_back, 0])
return torch.tensor(X), torch.tensor(Y)
# 生成训练集和测试集的输入和输出序列
look_back = 60
X_train, Y_train = create_dataset(train_data, look_back)
X_test, Y_test = create_dataset(test_data, look_back)
# 将数据转换为PyTorch张量
X_train = torch.reshape(X_train, (X_train.shape[0], 1, X_train.shape[1]))
Y_train = torch.reshape(Y_train, (Y_train.shape[0], 1, 1))
X_test = torch.reshape(X_test, (X_test.shape[0], 1, X_test.shape[1]))
Y_test = torch.reshape(Y_test, (Y_test.shape[0], 1, 1))
# 定义LSTM模型
class LSTM(nn.Module):
def __init__(self, input_size=1, hidden_size=100, output_size=1, num_layers=1):
super().__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.lstm = nn.LSTM(input_size, hidden_size, num_layers)
self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x):
h0 = torch.zeros(self.num_layers, x.size(1), self.hidden_size).to(device)
c0 = torch.zeros(self.num_layers, x.size(1), self.hidden_size).to(device)
out, _ = self.lstm(x, (h0, c0))
out = self.fc(out[:, -1, :])
return out
# 设置设备
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# 定义模型、损失函数和优化器
model = LSTM().to(device)
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
# 训练模型
num_epochs = 100
for epoch in range(num_epochs):
outputs = model(X_train.to(device))
loss = criterion(outputs, Y_train.to(device))
optimizer.zero_grad()
loss.backward()
optimizer.step()
if epoch % 10 == 0:
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item()))
# 测试模型
model.eval()
Y_train_pred = model(X_train.to(device)).cpu().detach().numpy()
Y_test_pred = model(X_test.to(device)).cpu().detach().numpy()
# 将数据转换为原始形式
Y_train = sc.inverse_transform(Y_train.reshape(-1, 1))
Y_train_pred = sc.inverse_transform(Y_train_pred.reshape(-1, 1))
Y_test = sc.inverse_transform(Y_test.reshape(-1, 1))
Y_test_pred = sc.inverse_transform(Y_test_pred.reshape(-1, 1))
# 绘制实际曲线和预测曲线图
plt.plot(Y_train, label='Actual')
plt.plot(Y_train_pred, label='Predicted')
plt.legend()
plt.show()
plt.plot(Y_test, label='Actual')
plt.plot(Y_test_pred, label='Predicted')
plt.legend()
plt.show()
```
运行上面的代码后,会输出训练过程中的损失值,并绘制出训练集和测试集的实际曲线和预测曲线图。
阅读全文