#本项目可在jupyternotebook中运行
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”)
%matplotlib inline
#读取csv文件,并打印出来
feature = pd.read_csv(‘temps.csv’)
feature.head()
#由于week列中是字符串,对其进行独热编码
features = pd.get_dummies(features)
features. head()
#处理时间数据为后续画图做准备
import datetime
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]
#构建标签
labels = np.array(features[‘actual’])
#去除actual这一列,axis=1为选定列
features = features.drop(‘actual’, axis=1)
feature_list = list(features.columns)
features = np.array(features)
#对数据进行标准化操作
from sklearn import preprocessing
input_features = preprocessing.StandardScaler().fit_transform(features)
#可以对比一下标准化前后数据的变化
#标准化后
#标准化前
下面将用两种方法构建网络
第一种:构建较繁琐,但能清楚的展现出计算过程,梯度下降及权重更新
#将输入和label转化为tensor
x = torch.tensor(input_features,dtype=float)
y = torch.tensor(labels,dtype=float)
#权重参数初始化
w1 = torch.randn((14, 128), dtype = float, requires_grad = True)
b1 = torch.randn(128, dtype = float , requires_grad = True)
w2 = torch.randn((128, 1),dtype = float, requires_grad = True)
b2 = torch.randn(1, dtype = float, requires_grad = True)
#下图为对选取权重及偏置并计算的过程的一些解释
#定义学习率,损失,训练轮次
learning_rate = 0.001
losses = []
epoch = 1000
#模型训练
for i in range(epoch):
#隐层计算
hidden = x.mm(w1) + b1
#激活函数
hidden = torch.relu(hidden)
#预测结果
predictions = hidden.mm(w2) + b2
#计算损失-方差均值
loss = torch.mean((predictions - y)**2)
#将损失添加到之前定义的losses列表中
losses.append(loss.data.numpy())
#每隔100个epoch打印出损失
if i%100 == 0 :
print(‘loss’, loss)
#反向传播
loss.backward()
#梯度下降.更新参数
w1.data.add_(-learning_rate*w1.grad.data)
b1.data.add_(- learning_rate * b1.grad.data)
w2.data.add_(- learning_rate * w2.grad.data)
b2.data.add_(- learning_rate * b2.grad.data)
#清空梯度.否则梯度会累加造成计算错误
w1.grad.data.zero_()
b1.grad.data.zero_()
w2.grad.data.zero_()
b2.grad.data.zero_()
#损失不断降低
第二种:较为简单,调用pytroch中的nn模块即可像搭积木般轻松构建网络
#输入的size就是数据的列数,即特征的个数
input_size = input_features.shape[1]
#定义隐层的size,输出的size,批次大小,训练轮次
hidden_size = 128
output_size = 1
batch_size = 16
eepoch = 1000
#构建网络架构
model = torch.nn.Sequential(
torch.nn.Linear(input_size, hidden_size),
torch.nn.Sigmoid(),
torch.nn.Linear(hidden_size, output_size),
)
#定义损失函数
loss_func = torch.nn.MSELoss(reduction=‘mean’)
#构建优化器
optimizer = torch.optim.Adam(model. Parameters(), lr=0.001)
#计算流程大致如下
#训练网络
losses = []
for i in range(eepoch):
batch_loss = []
#采用minibatch的方法,每批次训练16个数据
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)
x_train = torch.tensor(input_features[start:end], dtype = torch.float, requires_grad = True)
y_train = torch.tensor(labels[start:end], dtype = torch.float, requires_grad = True)
#前向传播
prediction = model(x_train)
#计算损失
loss = loss_func(prediction, y_train)
optimizer.zero_grad()
loss.backward(retain_graph=True)
optimizer.step()
batch_loss.append(loss.data.numpy())
#每100个epoch打印出loss
if i%100 ==0:
losses.append(np.mean(batch_loss))
print(i,np.mean(batch_loss))
#损失值
#将x输入到网络中,得出预测值
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]
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)})
#真实值
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’);
plt.legend()
plt.xlabel(‘Date’); plt.ylabel(‘Maximum Temperature (F)’); plt.title(‘Actual and Predicted Values’);
上图中红色部分为预测值,蓝色折线为真实值