一、数据集预处理
1,数据集介绍
训练数据集:temps.csv免费下载链接
数据集主要包括348条样本,共8个自变量,1个因变量
自变量 | 因变量 |
---|---|
year:年 | actual:当天的真实最高温度 |
month:月 | |
day:日 | |
week:星期 | |
temp_1:昨天的最高温度值 | |
temp_2:前天的最高温度值 | |
average:在历史中,每年这一天的平均最高温度值 | |
friend:朋友猜测的可能值,凑热闹的 |
2,数据集整理格式
Ⅰ 导包
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
import torch.optim as optim
import datetime
Ⅱ 读入数据集并查看前10条
dataset = pd.read_csv('temps.csv')
print(dataset.shape) # (348, 9)
dataset.head(10)
Ⅲ 获取年月日信息转换为datetime格式并查看前10条
dates存放预测气温的具体年月日信息
years = dataset['year'] # 获取数据集中的year列
months = dataset['month'] # 获取数据集中的month列
days = dataset['day'] # 获取数据集中的day列
# datetime格式
dates = [str(int(year)) + '-' + str(int(month)) + '-' + str(int(day)) for year, month, day in zip(years, months, days)]
dates[:10]
"""
['2016-1-1',
'2016-1-2',
'2016-1-3',
'2016-1-4',
'2016-1-5',
'2016-1-6',
'2016-1-7',
'2016-1-8',
'2016-1-9',
'2016-1-10']
"""
dates = [datetime.datetime.strptime(date, '%Y-%m-%d') for date in dates]
dates[:10]
"""
[datetime.datetime(2016, 1, 1, 0, 0),
datetime.datetime(2016, 1, 2, 0, 0),
datetime.datetime(2016, 1, 3, 0, 0),
datetime.datetime(2016, 1, 4, 0, 0),
datetime.datetime(2016, 1, 5, 0, 0),
datetime.datetime(2016, 1, 6, 0, 0),
datetime.datetime(2016, 1, 7, 0, 0),
datetime.datetime(2016, 1, 8, 0, 0),
datetime.datetime(2016, 1, 9, 0, 0),
datetime.datetime(2016, 1, 10, 0, 0)]
"""
Ⅳ X轴为dates,Y轴为不同天所预测的气温
plt.subplots(nrows=2, ncols=2, figsize = (20,20))
2行,2列,图像大小20*20
fig.autofmt_xdate(rotation = 0)
X轴的字体旋转角度,也就是dates所对应的年月日信息显示旋转角度,这里是0°,如:2016-01等,水平显示
ax1.plot(dates, dataset['actual'])
X轴为dates(年月日),Y轴为actual(实际的真实温度值)
ax1.set_xlabel(''); ax1.set_ylabel('Temperature'); ax1.set_title('Actual Max Temp')
X轴标签为空,Y轴标签为Temperature,整体标题为Actual Max Temp
其他的同理
plt.tight_layout(pad=1, h_pad=1, w_pad=1)
pad:图形边和子图的边之间进行填充
h_pad,w_pad:相邻子图的边之间的填充(高度/宽度)
# 准备画图
# 指定默认风格
plt.style.use('fivethirtyeight')
# 设置布局
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2, figsize = (20,20))# 2行 2列 画布大小为20*20
fig.autofmt_xdate(rotation = 0) # X轴的字体旋转角度,也就是dates所对应的信息显示旋转角度,这里是0°,水平显示
# 标签值
ax1.plot(dates, dataset['actual'])
ax1.set_xlabel(''); ax1.set_ylabel('Temperature'); ax1.set_title('Actual Max Temp')
# 昨天
ax2.plot(dates, dataset['temp_1'])
ax2.set_xlabel(''); ax2.set_ylabel('Temperature'); ax2.set_title('Previous Max Temp')
# 前天
ax3.plot(dates, dataset['temp_2'])
ax3.set_xlabel('Date'); ax3.set_ylabel('Temperature'); ax3.set_title('Two Days Prior Max Temp')
# 朋友预测
ax4.plot(dates, dataset['friend'])
ax4.set_xlabel('Date'); ax4.set_ylabel('Temperature'); ax4.set_title('Friend Estimate')
plt.tight_layout(pad=1, h_pad=1, w_pad=1)
Ⅴ 对非数字特征进行one-hot编码
数据集中的week特征,并不是数字,故通过one-hot编码进行转换
此时,labels为actual这一列特征,也就是最终的实际结果;dataset则将actual这一列特征给删除
最终再将dataset数据集转化为array格式
# 标签
labels = np.array(dataset['actual'])
# 在特征中去掉标签
dataset= dataset.drop('actual', axis = 1)
# 名字单独保存一下,以备后患
dataset_list = list(dataset.columns)
# 转换成合适的格式
dataset = np.array(dataset)
dataset.shape # (348, 14)
Ⅵ 标准化
因为数据集中month有的为1,而其他的像temp_1等特征为45之类的大小,相差很大,故需要通过标准进行处理一下,sklearn中有专门的预处理模块preprocessing
对数据集做完标准化可以使后续预测结果收敛速度更快一些,收敛的损失值也会相对更小一些。
StandardScaler会保证每个特征的平均值为0,方差为1
from sklearn import preprocessing
input_dataset = preprocessing.StandardScaler().fit_transform(dataset)
input_dataset[0]
"""
array([ 0. , -1.5678393 , -1.65682171, -1.48452388, -1.49443549,
-1.3470703 , -1.98891668, 2.44131112, -0.40482045, -0.40961596,
-0.40482045, -0.40482045, -0.41913682, -0.40482045])
"""
到此为止,数据集的预处理已经完成,接下来开始进行加载数据集、模型搭建以及后续的训练模型等操作。
最终处理完之后的数据集为input_dataset
Ⅶ 完整代码
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
import torch.optim as optim
import datetime
from sklearn import preprocessing
dataset = pd.read_csv('temps.csv')
#print(dataset.shape)
#dataset.head(10)
years = dataset['year']
months = dataset['month']
days = dataset['day']
# datetime格式
dates = [str(int(year)) + '-' + str(int(month)) + '-' + str(int(day)) for year, month, day in zip(years, months, days)]
#dates[:10]
dates = [datetime.datetime.strptime(date, '%Y-%m-%d') for date in dates]
#dates[:10]
# 准备画图
# 指定默认风格
plt.style.use('fivethirtyeight')
# 设置布局
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2, figsize = (20,20))# 2行 2列 画布大小为20*20
fig.autofmt_xdate(rotation = 0)
# 标签值
ax1.plot(dates, dataset['actual'])
ax1.set_xlabel(''); ax1.set_ylabel('Temperature'); ax1.set_title('Actual Max Temp')
# 昨天
ax2.plot(dates, dataset['temp_1'])
ax2.set_xlabel(''); ax2.set_ylabel('Temperature'); ax2.set_title('Previous Max Temp')
# 前天
ax3.plot(dates, dataset['temp_2'])
ax3.set_xlabel('Date'); ax3.set_ylabel('Temperature'); ax3.set_title('Two Days Prior Max Temp')
# 朋友预测
ax4.plot(dates, dataset['friend'])
ax4.set_xlabel('Date'); ax4.set_ylabel('Temperature'); ax4.set_title('Friend Estimate')
plt.tight_layout(pad=1, h_pad=1, w_pad=1)
#dataset
# 独热编码
dataset = pd.get_dummies(dataset)
#dataset.head(5)
# 标签
labels = np.array(dataset['actual'])
# 在特征中去掉标签
dataset= dataset.drop('actual', axis = 1)
# 名字单独保存一下,以备后患
dataset_list = list(dataset.columns)
# 转换成合适的格式
dataset = np.array(dataset)
#dataset.shape
input_dataset = preprocessing.StandardScaler().fit_transform(dataset)
#input_dataset[0]
二、搭建网络模型步骤
1,加载数据集
因为此时数据集input_dataset为array格式,而PyTorch训练所使用的数据类型为tensor,故需要进行转换
labels上述已经进行了定义,为actual实际的气温,也就是最终的正确结果y值
x = torch.tensor(input_dataset,dtype=float)
y = torch.tensor(labels,dtype=float)
2,网络模型搭建
2.1 常规方法
这里以一个具有两层隐藏层网络为例进行模型搭建
这里插入我自己的理解:
x = torch.tensor(input_dataset, dtype = float)
y = torch.tensor(labels, dtype = float)
# 权重参数初始化
weights = torch.randn((14, 128), dtype = float, requires_grad = True)
biases = torch.randn(128, dtype = float, requires_grad = True)
weights2 = torch.randn((128, 1), dtype = float, requires_grad = True)
biases2 = torch.randn(1, dtype = float, requires_grad = True)
learning_rate = 0.001
losses = []
for i in range(1000):
# 计算隐层
hidden = x.mm(weights) + biases
# 加入激活函数
hidden = torch.relu(hidden)
# 预测结果
predictions = hidden.mm(weights2) + biases2
# 通计算损失
loss = torch.mean((predictions - y) ** 2)
losses.append(loss.data.numpy())
# 打印损失值
if i % 100 == 0:
print('loss:', loss)
#返向传播计算
loss.backward()
#更新参数
weights.data.add_(- learning_rate * weights.grad.data)
biases.data.add_(- learning_rate * biases.grad.data)
weights2.data.add_(- learning_rate * weights2.grad.data)
biases2.data.add_(- learning_rate * biases2.grad.data)
# 每次迭代都得记得清空
weights.grad.data.zero_()
biases.grad.data.zero_()
weights2.grad.data.zero_()
biases2.grad.data.zero_()
#predictions.shape
2.2 简便方法
input_size = input_dataset.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(1000):
batch_loss = []
# MINI-Batch方法来进行训练
for start in range(0, len(input_dataset), batch_size):
end = start + batch_size if start + batch_size < len(input_dataset) else len(input_dataset)
xx = torch.tensor(input_dataset[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))
三、模型预测结果
x = torch.tensor(input_dataset, dtype = torch.float)
predict = 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})
# 同理,再创建一个来存日期和其对应的模型预测值
months = dataset[:, dataset_list .index('month')]
days = dataset[:, dataset_list .index('day')]
years = dataset[:, dataset_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)})
四、绘图展示
# 真实值
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 = 30);
plt.legend()
# 图名
plt.xlabel('Date'); plt.ylabel('Maximum Temperature (F)'); plt.title('Actual and Predicted Values');
五、完整代码
1,数据集预处理、网络模型搭建、模型训练
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
import torch.optim as optim
import datetime
from sklearn import preprocessing
dataset = pd.read_csv('temps.csv')
#print(dataset.shape)
#dataset.head(10)
years = dataset['year']
months = dataset['month']
days = dataset['day']
# datetime格式
dates = [str(int(year)) + '-' + str(int(month)) + '-' + str(int(day)) for year, month, day in zip(years, months, days)]
#dates[:10]
dates = [datetime.datetime.strptime(date, '%Y-%m-%d') for date in dates]
#dates[:10]
# 准备画图
# 指定默认风格
plt.style.use('fivethirtyeight')
# 设置布局
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2, figsize = (20,20))# 2行 2列 画布大小为20*20
fig.autofmt_xdate(rotation = 0)
# 标签值
ax1.plot(dates, dataset['actual'])
ax1.set_xlabel(''); ax1.set_ylabel('Temperature'); ax1.set_title('Actual Max Temp')
# 昨天
ax2.plot(dates, dataset['temp_1'])
ax2.set_xlabel(''); ax2.set_ylabel('Temperature'); ax2.set_title('Previous Max Temp')
# 前天
ax3.plot(dates, dataset['temp_2'])
ax3.set_xlabel('Date'); ax3.set_ylabel('Temperature'); ax3.set_title('Two Days Prior Max Temp')
# 朋友预测
ax4.plot(dates, dataset['friend'])
ax4.set_xlabel('Date'); ax4.set_ylabel('Temperature'); ax4.set_title('Friend Estimate')
plt.tight_layout(pad=1, h_pad=1, w_pad=1)
#dataset
# 独热编码
dataset = pd.get_dummies(dataset)
#dataset.head(5)
# 标签
labels = np.array(dataset['actual'])
# 在特征中去掉标签
dataset= dataset.drop('actual', axis = 1)
# 名字单独保存一下,以备后患
dataset_list = list(dataset.columns)
# 转换成合适的格式
dataset = np.array(dataset)
#dataset.shape
input_dataset = preprocessing.StandardScaler().fit_transform(dataset)
#input_dataset[0]
# 模型搭建
input_size = input_dataset.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(1000):
batch_loss = []
# MINI-Batch方法来进行训练
for start in range(0, len(input_dataset), batch_size):
end = start + batch_size if start + batch_size < len(input_dataset) else len(input_dataset)
xx = torch.tensor(input_dataset[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))
2,模型预测、预测结果展示
# 模型预测
x = torch.tensor(input_dataset, dtype = torch.float)
predict = 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})
# 同理,再创建一个来存日期和其对应的模型预测值
months = dataset[:, dataset_list .index('month')]
days = dataset[:, dataset_list .index('day')]
years = dataset[:, dataset_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)})
#绘图展示
# 真实值
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 = 30);
plt.legend()
# 图名
plt.xlabel('Date'); plt.ylabel('Maximum Temperature (F)'); plt.title('Actual and Predicted Values');