用pytorch帮我写一个气温神经网络,从csv文件中读取温度数据,输入为前60天的平均气温,输出为某天的平均气温,画出实际气温变化与预测气温变化的对比图,計算在所有测试数据上的均方誤差。
时间: 2024-05-07 10:19:53 浏览: 75
搭建PyTorch神经网络进行气温预测.ipynb
好的,以下是一个简单的气温神经网络的代码示例:
```python
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 读取csv文件
data = pd.read_csv('temp.csv')
# 提取温度数据
temp = data['temperature'].values
# 归一化数据
temp_max = np.max(temp)
temp_min = np.min(temp)
temp = (temp - temp_min) / (temp_max - temp_min)
# 定义模型
class TemperatureNet(nn.Module):
def __init__(self):
super(TemperatureNet, self).__init__()
self.fc1 = nn.Linear(60, 10)
self.fc2 = nn.Linear(10, 1)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = self.fc2(x)
return x
# 初始化模型
model = TemperatureNet()
# 定义损失函数和优化器
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=0.01)
# 划分训练集和测试集
train_data = temp[:3000]
test_data = temp[3000:]
# 构建训练数据
def create_dataset(dataset, look_back=60):
dataX, dataY = [], []
for i in range(len(dataset)-look_back-1):
a = dataset[i:(i+look_back)]
dataX.append(a)
dataY.append(dataset[i + look_back])
return np.array(dataX), np.array(dataY)
train_X, train_Y = create_dataset(train_data)
test_X, test_Y = create_dataset(test_data)
# 训练模型
for epoch in range(100):
inputs = torch.Tensor(train_X)
labels = torch.Tensor(train_Y)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels.view(-1, 1))
loss.backward()
optimizer.step()
print('Epoch {}, Loss {}'.format(epoch, loss.item()))
# 测试模型
model.eval()
test_inputs = torch.Tensor(test_X)
test_outputs = model(test_inputs)
test_outputs = test_outputs.detach().numpy()
test_Y = test_Y.reshape(-1, 1)
test_outputs = test_outputs * (temp_max - temp_min) + temp_min
test_Y = test_Y * (temp_max - temp_min) + temp_min
# 绘制实际气温变化与预测气温变化的对比图
plt.plot(test_outputs, label='Predicted temperature')
plt.plot(test_Y, label='Actual temperature')
plt.legend()
plt.show()
# 计算在所有测试数据上的均方误差
mse = np.mean((test_outputs - test_Y)**2)
print('Mean Squared Error:', mse)
```
需要注意的是,这个代码示例只是一个简单的气温神经网络,可能需要根据实际情况进行调整和优化。
阅读全文