



为了让广大读者更好地理解和认识深度学习以及PyTorch框架的实施,本节先介绍一个每日最高温度预测的例子,供后续学习参考。
本实例利用PyTorch中的神经网络模型,对北京市2021年6月份的气温进行建模,并将数据存储在temps.csv文件中,主要字段如表1-2所示。
表1-2 数据集字段
具体的实现步骤如下:
导入Python中相关的第三方库,代码如下:
import torch import numpy as np import pandas as pd import datetime import matplotlib import matplotlib.pyplot as plt from matplotlib.pyplot import MultipleLocator from sklearn import preprocessing
读取本地离线文件数据源数据,代码如下:
features = pd.read_csv('./temps.csv')
labels = np.array(features['actual'])
features = features.drop('actual', axis=1)
feature_list = list(features.columns)
为了提升模型的准确率,首先需要对数据进行格式转换与标准化处理,代码如下:
features = np.array(features)
input_features =
preprocessing.StandardScaler().fit_transform(features)
设置神经网络模型的网络结构,代码如下:
input_size = input_features.shape[1]
hidden_size = 128
output_size = 1
batch_size = 16
my_nn = torch.nn.Sequential(
torch.nn.Linear(input_size, hidden_size),
torch.nn.Sigmoid(),
torch.nn.Linear(hidden_size, output_size),
)
定义神经网络模型的损失函数与优化器,代码如下:
cost = torch.nn.MSELoss(reduction='mean') optimizer = torch.optim.Adam(my_nn.parameters(), lr=0.001)
训练神经网络模型,代码如下:
losses = []
for i in range(500):
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 = my_nn(xx)
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(i, np.mean(batch_loss), batch_loss)
x = torch.tensor(input_features, dtype=torch.float)
predict = my_nn(x).data.numpy()
转换数据集中的日期格式,代码如下:
months = features[:, feature_list.index('month')]
days = features[:, feature_list.index('day')]
years = features[:, feature_list.index('year')]
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})
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)})
使用Matplotlib库绘制日最高温度的散点图,代码如下:
matplotlib.rc("font", family='SimHei')
plt.figure(figsize=(12, 7), dpi=160)
plt.plot(true_data['date'], true_data['actual'], 'b+', label='真实值')
plt.plot(predictions_data['date'], predictions_data['prediction'],
'r+', label='预测值',marker='o')
plt.xticks(rotation='30',size=15)
plt.ylim(0,50)
plt.yticks(size=15)
x_major_locator=MultipleLocator(3)
y_major_locator=MultipleLocator(5)
ax=plt.gca()
ax.xaxis.set_major_locator(x_major_locator)
ax.yaxis.set_major_locator(y_major_locator)
plt.legend(fontsize=15)
plt.ylabel('日最高温度',size=15)
plt.show()
本实例使用PyTorch中的神经网络模型,通过绘制散点图的方式对2021年6月份北京市的日最高温度进行预测。
运行上述每日温度预测模型的代码,输出真实值和预测值的散点图,如图1-19所示。
图1-19 气温真实值和预测值的散点图