pytorch p12 简化版本气温预测

Posted bohu83

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了pytorch p12 简化版本气温预测相关的知识,希望对你有一定的参考价值。

数据准备工作跟之前的 一样, 主要是构建 神经网络 模块 变得更简化了,使用 了torch.nn模块。

包括构建模型,使用torch.nn.MseLoss作为损失值, 使用torch.optim.Adam构造优化器 。

完整 的代码 如下:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
import torch.optim as optim
import warnings
warnings.filterwarnings('ignore')

features = pd.read_csv('temps.csv')

# 可视化图形
print(features.head(5))

print("数据维度:", features.shape)
print("数据类型:", type(features))

# 处理时间数据
import datetime

# 分别得到年/月/日
years = features['year']
months = features['month']
days = features['day']

# 处理成datetime格式
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]



#  编码转换
features = pd.get_dummies(features)
print(features.head())

# 标签
labels = np.array(features['actual'])

# 去掉便签后的数据
features = features.drop('actual',axis=1)

features_list = list(features.columns)

# 将train转成合适的格式
features = np.array(features)

# 对特征进行标准化操作
from sklearn import preprocessing

input_feature = preprocessing.StandardScaler().fit_transform(features)


import torch
import torch.nn as nn

input_size = input_feature.shape[1]
hidden_size = 128
output_size = 1
batch_size = 16
epochs = 1000

my_nn = nn.Sequential(
    torch.nn.Linear(input_size, hidden_size),
    torch.nn.Sigmoid(),
    torch.nn.Linear(hidden_size, output_size)
)

x = torch.tensor(input_feature, dtype=torch.float)
y = torch.tensor(labels, dtype=torch.float)

cost = torch.nn.MSELoss(reduction="mean")
optimizer = torch.optim.Adam(my_nn.parameters(), lr=0.001)
#训练网络
for i in range(epochs):
    batch_mean = []
    for start in range(0, len(input_feature), batch_size):
        end = start + batch_size if start + batch_size < len(input_feature) else len(input_feature)
        xx = x[start:end]
        yy = y[start:end]
        predict = my_nn(xx)
        loss = cost(yy, predict)
        optimizer.zero_grad()
        loss.backward(retain_graph=True)
        optimizer.step()
        batch_mean.append(loss.data.numpy())
    if i % 100 == 0:
        print(np.mean(batch_mean))


for i in my_nn.parameters():
    print(i.data.numpy())

x = torch.tensor(input_feature, dtype=torch.float)
predict = np.squeeze(my_nn(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)

predict_data = pd.DataFrame(data= "date":dates, "predict":predict)

plt.plot(true_data["date"], true_data["actual"], "b-", label='actual')
plt.plot(predict_data['date'], predict_data['predict'], 'ro', label='predict')
plt.xticks(rotation=60)
plt.title("Temperature Predict")
plt.xlabel("Date")
plt.ylabel("Temperature")
plt.show()



 

以上是关于pytorch p12 简化版本气温预测的主要内容,如果未能解决你的问题,请参考以下文章

PyTorch 之 强大的 hub 模块和搭建神经网络进行气温预测

PyTorch搭建全连接网络训练MNIST数据集分类任务和气温预测回归任务及全连接网络过拟合和欠拟合的调参方式

Pytorch 入门

搭建神经网络进行气温预测

《动手学深度学习》线性回归(PyTorch版)

数值预测案例 LSTM 时间序列气温数据预测,附TensorFlow完整代码