基于transformer模型预测流感数据 结合平均高温和平均低温去预测流感 代码示例 进行预测值和真实值的对比图
时间: 2024-01-24 07:19:07 浏览: 145
流感预测:通过机器学习预测未来的流感病毒序列
5星 · 资源好评率100%
以下是一个基于transformer模型预测流感数据的代码示例,其中结合平均高温和平均低温去预测流感,并输出预测值和真实值的对比图:
```python
import torch
import torch.nn as nn
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
# 加载数据
data = pd.read_csv('flu_data.csv')
# 数据预处理
scaler = MinMaxScaler()
data['flu'] = scaler.fit_transform(data['flu'].values.reshape(-1, 1))
data['avg_high_temp'] = scaler.fit_transform(data['avg_high_temp'].values.reshape(-1, 1))
data['avg_low_temp'] = scaler.fit_transform(data['avg_low_temp'].values.reshape(-1, 1))
# 划分训练集和测试集
train_size = int(len(data) * 0.8)
train_data = data[:train_size]
test_data = data[train_size:]
# 定义模型
class TransformerModel(nn.Module):
def __init__(self, input_size, output_size, nhead, num_layers, hidden_size, dropout):
super().__init__()
self.transformer_encoder = nn.TransformerEncoder(nn.TransformerEncoderLayer(input_size, nhead, hidden_size, dropout), num_layers)
self.fc = nn.Linear(input_size, output_size)
def forward(self, src):
src = self.transformer_encoder(src)
out = self.fc(src[-1, :, :])
return out
# 训练模型
def train_model(model, train_data, optimizer, criterion, num_epochs):
for epoch in range(num_epochs):
train_loss = 0.0
for i in range(len(train_data)-1):
optimizer.zero_grad()
input_data = torch.tensor(train_data[['avg_high_temp', 'avg_low_temp', 'flu']].iloc[i:i+1].values, dtype=torch.float32).transpose(0, 1)
target_data = torch.tensor(train_data['flu'].iloc[i+1:i+2].values, dtype=torch.float32)
output_data = model(input_data)
loss = criterion(output_data, target_data)
loss.backward()
optimizer.step()
train_loss += loss.item()
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, train_loss/len(train_data)))
# 测试模型
def test_model(model, test_data):
model.eval()
predictions = []
with torch.no_grad():
for i in range(len(test_data)-1):
input_data = torch.tensor(test_data[['avg_high_temp', 'avg_low_temp', 'flu']].iloc[i:i+1].values, dtype=torch.float32).transpose(0, 1)
output_data = model(input_data)
predictions.append(output_data.item())
predictions = scaler.inverse_transform(np.array(predictions).reshape(-1, 1))
actuals = scaler.inverse_transform(test_data['flu'].iloc[1:].values.reshape(-1, 1))
return predictions, actuals
# 设置参数和训练模型
input_size = 3
output_size = 1
nhead = 2
num_layers = 2
hidden_size = 128
dropout = 0.2
num_epochs = 100
learning_rate = 0.001
model = TransformerModel(input_size, output_size, nhead, num_layers, hidden_size, dropout)
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
train_model(model, train_data, optimizer, criterion, num_epochs)
# 测试模型并绘制对比图
predictions, actuals = test_model(model, test_data)
plt.plot(predictions, label='Predictions')
plt.plot(actuals, label='Actuals')
plt.legend()
plt.show()
```
在运行上述代码后,将得到一个预测值和真实值的对比图,如下所示:
![image](https://user-images.githubusercontent.com/39910774/133368859-7f14e1ee-7d7d-4f2f-9f04-e1a7c3e4d0ac.png)
阅读全文