qiuzitao深度学习之PyTorch实战(六)
史上最简单、实际、通俗易懂的PyTorch实战系列教程!(新手友好、小白请进、建议收藏)
手把手教你搭建PyTorch神经网络进行气温预测
数据集:链接:https://pan.baidu.com/s/1BFGTUu19-TsUqxrJb9qqxA
提取码:seua
1、导入需要用到的库
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
2、导入、查看数据
features = pd.read_csv('temps.csv')#看看数据长什么样子
features.head()
print('数据维度:', features.shape)
一共有348天,每一天有9个特征。
3、数据可视化
# 准备画图
# 指定默认风格
plt.style.use('fivethirtyeight')# 设置布局
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2, figsize = (10,10))
fig.autofmt_xdate(rotation = 45)# 标签值
ax1.plot(dates, features['actual'])
ax1.set_xlabel(''); ax1.set_ylabel('Temperature'); ax1.set_title('Max Temp')# 昨天
ax2.plot(dates, features['temp_1'])
ax2.set_xlabel(''); ax2.set_ylabel('Temperature'); ax2.set_title('Previous Max Temp')# 前天
ax3.plot(dates, features['temp_2'])
ax3.set_xlabel('Date'); ax3.set_ylabel('Temperature'); ax3.set_title('Two Days Prior Max Temp')# 我的逗逼朋友
ax4.plot(dates, features['friend'])
ax4.set_xlabel('Date'); ax4.set_ylabel('Temperature'); ax4.set_title('Friend Estimate')plt.tight_layout(pad=2)
4、数据预处理
① 提取出标准的时间数据格式:
# 处理时间数据
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]
dates[:5]
② 特征数字化,用独热编码(One-Hot Encoding),把 week 这一列数据进行转换。
# 独热编码
features = pd.get_dummies(features)
features.head(5)
By the way ,这里顺便介绍一下独热编码(One-Hot Encoding)(哑变量):
One-Hot编码,又称为一位有效编码,主要是采用位状态寄存器来对个状态进行编码,每个状态都由他独立的寄存器位,并且在任意时候只有一位有效。
独热编码是利用0和1表示一些参数,使用N位状态寄存器来对N个状态进行编码。(几个特征就有几位)
例如:数字手写体识别中: 如数字字体识别 0~9 中,6 的独热编码为 0000001000 (10位数)
独热编码的优点:
- 能够处理非连续型数值特征。
- 在一定程度上也扩充了特征。比如性别本身是一个特征,经过one hot编码以后,就变成了男或女两个特征。
缺点:
- 当特征类别较多时,数据经过独热编码可能会变得过于稀疏。这时候一般要用PCA降维和它结合。
③ 数据标签处理:
# 标签
labels = np.array(features['actual'])# 在特征中去掉标签
features= features.drop('actual', axis = 1)# 名字单独保存一下,以备后患
feature_list = list(features.columns)# 转换成合适的格式
features = np.array(features)features.shape
④ 数据标准化:
from sklearn import preprocessing
input_features = preprocessing.StandardScaler().fit_transform(features)
input_features[0]
5、构建网络模型
① 第一种较为复杂的详细的方法(自己写自己搭):
x = torch.tensor(input_features, dtype = float)y = torch.tensor(labels, dtype = float)# 权重参数初始化
weights = torch.randn((14, 128), dtype = float, requires_grad = True) # 128个隐层特征
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 #矩阵乘法后加上偏置项b# 加入激活函数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
② 更简单的构建网络模型(调包):
input_size = input_features.shape[1]
hidden_size = 128
output_size = 1
batch_size = 16 #一次取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_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) #计算lossoptimizer.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))
6、预测结果
x = torch.tensor(input_features, dtype = torch.float)
predict = my_nn(x).data.numpy() # x传进去网络后输出预测值,改成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)})
# 真实值
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');
可以看到,这条红线就是我们训练出来的模型的回归曲线,还是较为拟合的,也就是准确率还是很不错的。
qiuzitao深度学习之PyTorch实战(六)相关推荐
- qiuzitao深度学习之PyTorch实战(十六)
史上最简单.实际.通俗易懂的PyTorch实战系列教程!(新手友好.小白请进.建议收藏) 基于3D卷积的视频分析与动作识别 一.3D卷积原理解读 视频就是一帧一帧的图像按照时间拼接组成的,3D卷积就是 ...
- 《深度学习之pytorch实战计算机视觉》第6章 PyTorch基础(代码可跑通)
上一篇文章<深度学习之pytorch实战计算机视觉>第5章 Python基础讲了Python基础.接下来看看第6章 PyTorch基础. 目录 6.1 PyTorch中的Tensor 6. ...
- 《深度学习之pytorch实战计算机视觉》第8章 图像风格迁移实战(代码可跑通)
上一章<深度学习之pytorch实战计算机视觉>第7章 迁移学习(代码可跑通)介绍了迁移学习.本章将完成一个有趣的应用,基于卷积神经网络实现图像风格迁移(Style Transfer).和 ...
- pytorch 预测手写体数字_深度学习之PyTorch实战(3)——实战手写数字识别
如果需要小编其他论文翻译,请移步小编的GitHub地址 传送门:请点击我 如果点击有误:https://github.com/LeBron-Jian/DeepLearningNote 上一节,我们已经 ...
- 深度学习--猫狗大战pytorch实战
文章目录 数据准备&处理 模型构建 训练 kaggle上的一个经典项目,拿来做做算是当CNN入门了,做的比较粗糙简单 我把整个项目分成了四块 config用来配置一些参数,Dataset用来构 ...
- 深度学习与PyTorch实战
- 视频教程-深度学习与PyTorch入门实战教程-深度学习
深度学习与PyTorch入门实战教程 新加坡国立大学研究员 龙良曲 ¥399.00 立即订阅 扫码下载「CSDN程序员学院APP」,1000+技术好课免费看 APP订阅课程,领取优惠,最少立减5元 ↓ ...
- tensorflow 语义slam_研究《视觉SLAM十四讲从理论到实践第2版》PDF代码+《OpenCV+TensorFlow深度学习与计算机视觉实战》PDF代码笔记...
我们知道随着人工神经网络和深度学习的发展,通过模拟视觉所构建的卷积神经网络模型在图像识别和分类上取得了非常好的效果,借助于深度学习技术的发展,使用人工智能去处理常规劳动,理解语音语义,帮助医学诊断和支 ...
- 深度学习框架PyTorch快速开发与实战
深度学习框架PyTorch快速开发与实战 邢梦来,王硕,孙洋洋 著 ISBN:9787121345647 包装:平装 开本:16开 用纸:胶版纸 正文语种:中文 出版社:电子工业出版社 出版时间:20 ...
最新文章
- hdu-3625 Examining the Rooms(斯特灵数第一类)
- http://www.myexception.cn/web/426486.html
- MyBatis之优化MyBatis配置文件中的配置
- 实时检索系统Zoie实现分析
- 用MobaXterm远程连接Centos系统_使用技巧---Linux工作笔记047
- git整合分支的两种方式 merge 和 rebase
- [算法] 循环有序数组查找递归实现
- 读程序员网游专题云风的文章有感
- JSPatch源码解读
- 基于注解的 Spring MVC 简单入门
- 解决IDEA中的Tomcat Localhost日志乱码问题
- 推荐一款调试工具:深蓝串口调试工具 2021秋季版(2.16.1.),一直使用这个,最近更新好快。
- threejs光源的使用
- 无线网460王者荣耀服务器,王者荣耀460ms解决方法:王者荣耀网速460ms怎么办?...
- 用python写银行叫号系统(这个是学校的实训题目,真的没什么技术含量)
- electron开发问题记录
- DBeaver小松鼠:数据库客户端界面工具DBeaver连接Hive
- 龙门架式焊接机器人_龙门架式焊接机器人系统设计
- 巴比伦没有春夏秋冬,哪来四季历法?
- python格式化字符串format函数
热门文章
- JavaSE基础篇 | super关键字
- JS获取input框用户输入信息作为数组存储传输给后台数据库操作存储方法
- 设置 Edge 阅读PDF文档时的背景颜色
- 科研经验003:获取指定期刊的Latex/word模板
- NSGA-II算法的学习笔记
- java调用r实例,Spring Boot中使用RSocket的示例代码
- 一篇从零开始、步骤完整的网站搭建教程(全篇7000字、102张截图说明,力求每一个人都能看懂,附源码)
- 信息生态学与语义信息论
- 【已解决】安装Gin出现:go get: module github.com/gin-gonic/gin: Get “https://proxy.golang.org/github.com/
- DNS服务,SSL原理