【Pytorch项目实战】之回归分析:基于CNN的气温预测

文章目录

  • 回归分析
    • (一)实战:基于CNN的气温预测

回归分析

链接:https://pan.baidu.com/s/1W9-2yhpGBVETStoRZetTeg?pwd=3hnn
提取码:3hnn

(一)实战:基于CNN的气温预测

【Pytorch项目实战】之回归分析:基于CNN的气温预测_第1张图片

import pandas as pd
import datetime
from sklearn import preprocessing

import numpy as np
import matplotlib.pyplot as plt
import torch
############################################################
# (1)导入数据
features = pd.read_csv('temps.csv')
print('打印数据维度:', features.shape)
############################################################
# (2)数据提取,格式转换
years = features['year']        # 获取年(序列)
months = features['month']      # 获取月(序列)
days = features['day']          # 获取日(序列)

# 拼接字符串
dates = [str(int(year)) + '-' + str(int(month)) + '-' + str(int(day)) for year, month, day in zip(years, months, days)]
dates = [datetime.datetime.strptime(date, '%Y-%m-%d') for date in dates]        # list列表:序列格式转换为datetime格式

# 转换成合适的格式
features = pd.get_dummies(features)             # 独热编码
labels = np.array(features['actual'])           # 获取标签。Numpy格式
features = features.drop('actual', axis=1)      # 获取特征
feature_list = list(features.columns)           # 获取特征的名字(表头)

features = np.array(features)                   # 特征。转换Numpy格式
input_features = preprocessing.StandardScaler().fit_transform(features)     # 数据归一化
############################################################
# (3)超参数
input_size = input_features.shape[1]
hidden_size1 = 128
hidden_size2 = 64
output_size = 1
batch_size = 16
############################################################
# (4)构建网络模型
model = torch.nn.Sequential(
    torch.nn.Linear(input_size, hidden_size1),                  # 卷积层1
    torch.nn.ReLU(),                                            # 激活函数:Sigmoid、ReLU
    torch.nn.Linear(hidden_size1, hidden_size2),                # 卷积层2
    torch.nn.ReLU(),                                            # 激活函数:Sigmoid、ReLU
    torch.nn.Linear(hidden_size2, output_size))                 # 全连接层

cost = torch.nn.MSELoss()                                       # 损失函数:交叉熵
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)      # 优化器:Adam
############################################################
# (5)训练网络
losses = []
for i in range(1000):
    batch_loss = []
    for start in range(0, len(input_features), batch_size):
        end = start+batch_size if start+batch_size < len(input_features) else len(input_features)

        xx = torch.tensor(input_features[start:end], dtype=torch.float, requires_grad=True)     # 输入数据
        yy = torch.tensor(labels[start:end], dtype=torch.float, requires_grad=True)             # 真实值

        prediction = model(xx)                  # 前向传播
        prediction = torch.squeeze(prediction)  # 压缩一个维度

        loss = cost(prediction, yy)             # 损失函数
        optimizer.zero_grad()                   # 梯度清零
        loss.backward(retain_graph=True)        # 梯度下降
        optimizer.step()                        # 参数更新
        batch_loss.append(loss.data.numpy())

    # 打印损失
    if i % 100 == 0:
        losses.append(np.mean(batch_loss))
        print('迭代:{}, Train_loss={}' .format(i, np.mean(batch_loss)))

############################################################
# (6)预测训练结果
x = torch.tensor(input_features, dtype=torch.float)
predict = model(x).data.numpy()

# 转换(真实数据)日期格式
dates = [str(int(year)) + '-' + str(int(month)) + '-' + str(int(day)) for year, month, day in zip(years, months, days)]
dates = [datetime.datetime.strptime(date, '%Y-%m-%d') for date in dates]
true_data = pd.DataFrame(data={'date': dates, 'actual': labels})        # 创建一个表格:存日期和其对应的标签数值

months = features[:, feature_list.index('month')]       # 创建一个表格:存日期和其对应的模型预测值
days = features[:, feature_list.index('day')]           # 创建一个表格:存日期和其对应的模型预测值
years = features[:, feature_list.index('year')]         # 创建一个表格:存日期和其对应的模型预测值

# 转换(预测数据)日期格式
test_dates = [str(int(year)) + '-' + str(int(month)) + '-' + str(int(day)) for year, month, day in zip(years, months, days)]
test_dates = [datetime.datetime.strptime(date, '%Y-%m-%d') for date in test_dates]
predictions_data = pd.DataFrame(data={'date': test_dates, 'prediction': predict.reshape(-1)})
############################################################
# (7)绘制图形
plt.plot(true_data['date'], true_data['actual'], 'b-', label='actual')                              # 真实值
plt.plot(predictions_data['date'], predictions_data['prediction'], 'ro', label='prediction')        # 预测值

plt.xticks(rotation='60')       # x坐标:旋转60度显示
plt.legend()
plt.xlabel('Date')
plt.ylabel('Maximum Temperature (F)')
plt.title('Actual and Predicted Values')
plt.show()

你可能感兴趣的:(Pytorch项目实战,深度学习,pytorch,回归,cnn,python,深度学习)