当前位置: 首页 > news >正文

pytorch学习之第二课之预测温度

主要有以下几个步骤

第一:导入相应的工具包
第二:导入需要使用的数据集
第三:对导入的数据集输入进行预处理,找出特征与标签,查看数据特征的类型,判断是否需要标准化或者归一化处理
第四:构建神经网络的一些参数

在使用matplotlib时,需要加入

import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt

防止报错

实现如下:

import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
# 导入sklearn预处理模块
from sklearn import preprocessingimport torch
import torch.optim as optim
import datetime
import warnings
warnings.filterwarnings("ignore")
# matplotlib inline
features = pd.read_csv('C:\\Users\\Administrator\\Desktop\\temps.csv')
# 观看数据大致情况
print(features.head())
# 查看数据维度
print(features.shape)#对年月日进行格式转换
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]
print(dates[:2])# 准备画图
# 指定绘画的风格
plt.style.use('fivethirtyeight')#设置布局
# fig,((ax1,ax2),(ax3,ax4))=plt.subplots(nrows=2,ncols=2,figsize = (10,10))
# fig.autofmt_xdate(rotation=45)
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)plt.show(block = True)# 独热编码
features = pd.get_dummies(features)
print(features.head())# 标签
labels = np.array(features['actual'])# 在特征中去掉标签
features = features.drop('actual',axis=1)# 名字单独保存,以防后面需要
features_list = list(features.columns)# 转换成合适的格式
features = np.array(features)
print(features.shape)# 对数据进行预处理
# 由于数据差距太大所以需要进行标准化处理
input_features = preprocessing.StandardScaler().fit_transform(features)## 构建网络模型
x = torch.tensor(input_features, dtype=float)
y = torch.tensor(labels, dtype=float)# 权重参数初始化
weights = torch.randn((14, 128), dtype=float, requires_grad=True)
# 将14个特征转换成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.01
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_()

但是着这种构造太麻烦,因为导入的工具包都帮我们设置好了,我们只需要设置相应的参数即可
改版如下:

import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
# 导入sklearn预处理模块
from sklearn import preprocessingimport torch
import torch.optim as optim
import datetime
import warnings
warnings.filterwarnings("ignore")
# matplotlib inline
features = pd.read_csv('C:\\Users\\Administrator\\Desktop\\temps.csv')
# 观看数据大致情况
print(features.head())
# 查看数据维度
print(features.shape)#对年月日进行格式转换
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]
print(dates[:2])# 独热编码
features = pd.get_dummies(features)
print(features.head())# 标签
labels = np.array(features['actual'])# 在特征中去掉标签
features = features.drop('actual',axis=1)# 名字单独保存,以防后面需要
features_list = list(features.columns)# 转换成合适的格式
features = np.array(features)
print(features.shape)# 对数据进行预处理
# 由于数据差距太大所以需要进行标准化处理
input_features = preprocessing.StandardScaler().fit_transform(features)## 构建网络模型
x = torch.tensor(input_features, dtype=float)
y = torch.tensor(labels, dtype=float)# 权重参数初始化
weights = torch.randn((14, 128), dtype=float, requires_grad=True)
# 将14个特征转换成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)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.01)#动态调整学习率# 训练网络
losses = []for i in range(1000):batch_lose = []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()# 更新操作optimizer.step()batch_lose.append(loss.data.numpy())# 打印损失if i % 100 == 0:losses.append(np.mean(batch_lose))print(i,np.mean(batch_lose))# 预测训练模型
# 还是需要将数据转换成torchtensor格式
x = torch.tensor(input_features,dtype=torch.float)
# 要将预测的结果转换numpy格式更容易后续计算
pred = 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_date = pd.DataFrame(data={'date':dates,'actual':labels})# 创建一个存日期和其对应的模型预测值
months = features[:,features_list.index('month')]
days = features[:, features_list.index('day')]
years = features[:,features_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]pred_data = pd.DataFrame(data={'date':test_dates,'pred':pred.reshape(-1)})plt.plot(true_date['date'],true_date['actual'],'b-',label = 'actual')
plt.plot(pred_data['date'],pred_data['pred'],'ro',label = 'prediction')
plt.xticks(fontsize=15, rotation=45, ha='right')
plt.legend()

相关文章:

pytorch学习之第二课之预测温度

主要有以下几个步骤 第一&#xff1a;导入相应的工具包 第二&#xff1a;导入需要使用的数据集 第三&#xff1a;对导入的数据集输入进行预处理&#xff0c;找出特征与标签&#xff0c;查看数据特征的类型&#xff0c;判断是否需要标准化或者归一化处理 第四&#xff1a;构建神…...

基于Mahony互补滤波的IMU数据优化_学习笔记整理

这周自己被安排进行优化软件 IMU 姿态解算项目&#xff0c;之前自己只简单了解四元数&#xff0c;对IMU数据处理从未接触&#xff0c;通过这一周的学习感觉收获颇丰&#xff0c;在今天光棍节之际&#xff0c;&#xff0c;&#xff0c;用大半天的时间对这一周的收获进行整理&…...

c语言实现哈夫曼编码

要实现哈夫曼编码&#xff0c;需要以下步骤&#xff1a; 统计字符出现的频率构建哈夫曼树遍历哈夫曼树&#xff0c;给不同的字符赋予不同的编码将编码后的字符写入文件中 下面是一个简单的 C 语言实现&#xff1a; #include <stdio.h> #include <stdlib.h> #inc…...

Vuex:模块化Module :VCA模式

VCA中不支持辅助函数&#xff0c;因为辅助函数中是用this.$store&#xff0c;而VCA中没有绑定this的 由于使用单一状态树&#xff0c;应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时&#xff0c;store 对象就有可能变得相当臃肿。 这句话的意思是&#xff0c;…...

【uni-app + uView】CountryCodePicker 国家区号组件

1. 效果图 2. 组件完整代码 <template><u-popup class="country-code-picker-container" v-if="show" :show...

思科对路由器的配置

②对路由器R2进行配置 对路由器R2进行配置&#xff0c;先对各接口配置基本IP地址&#xff0c;然后配置动态路由协议。&#xff08;对实验步骤进行文字描述&#xff09; Router>enable //用户模式进入特权…...

实战Leetcode(三)

Practice makes perfect&#xff01; 实战一&#xff1a; 带环问题其实我们小学时就接触过&#xff0c;就比如在操场上比赛跑步的追击问题&#xff0c;这里也是一样&#xff0c;如果我们定义两个指针&#xff0c;一个快指针&#xff0c;一个慢指针&#xff0c;快指针走的快&…...

【PTE-day05 宽字节注入】

1、函数 过滤输入的函数: addslashes mysql_real_escape_string mysql_escape_string当字符的大小为一个字节时,称之为窄字节 例如ascii编码 当字符的大小为两个字节时,称之为宽字节 例如GB2312、GBK、GB8030 mysql使用GBK编码时,默认的会认为两个字符为一个汉字,前一个字…...

计算机网络期末复习-Part3

1、rdt1.0&#xff0c;rdt2.0&#xff0c;rdt3.0的底层信道模型 RDT 1.0: 完全可靠的底层信道&#xff0c;没有比特差错&#xff0c;也没有分组丢失。 RDT 2.0: 具有比特差错的底层信道&#xff0c;有比特差错&#xff0c;但没有分组丢失。 RDT 3.0: 具有差错和丢包的底层信道…...

docker在虚拟机中的应用

文章目录 Docker的基础概念与入门docker与docker镜像的理解虚拟机下[ubantu系统下]Docker的安装Docker-engine 的常用命令Docker 的 Example配置Docker的国内源虚拟机安装Postgresql的Docker物理机访问Postgresql数据库利用Docker-engine容器化前端项目工程1. 编写项目电器2. 构…...

小程序样式淡入淡出效果

小程序切换下一个文章或者页面&#xff0c;淡入淡出效果 // detail.js getArticleData: function(articleId) {// 开始淡出效果this.animate(.detail-page, [{ opacity: 1.0, ease: ease-out },{ opacity: 0.0, ease: ease-out }], 500, () > {// 在淡出动画完成后请求文章…...

虚幻5 删除C盘缓存及修改缓存路径

一.修改C盘缓存 C盘缓存路径为&#xff1a; C:\Users\xx(这里是你的用户名)\AppData\Local\UnrealEngine\Common\DerivedDataCache 注意&#xff0c;如果没有AppData文件夹&#xff0c;请依次点击查看-勾选显示隐藏的项目&#xff0c;即可 可删除里面的所有文件即可 二.修改…...

手写C++ 实现链表的反转、删除、合并

目录 一、手写List成员方法 1.1 打印链表 1.2 删除链表节点 1.3 链表中倒数第k个节点 1.4 反转链表 1.5 合并两个排序链表 二、完整代码 一、C实现链表成员方法 在上一篇博客《手写链表C》&#xff0c;实现了基本的List类。在面试中&#xff0c;经常被问到List如何反转、…...

虚幻C++基础 day4

虚幻中的UI 虚幻中的比较常用的UI&#xff1a;Widget Blueprint又称UMG虚幻中的两种布局&#xff1a; 网格布局锚布局 创建Widget Blueprint 网格布局 有点类似Qt中的网格布局&#xff0c;将UI面板进行行列切分Horizontal Box&#xff1a;水平分布Vertical Box&#xff1a;…...

【Vue】【uni-app】工单管理页面实现

用的是uni-app的uni-ui拓展组件实现的 功能是对工单进行一个展示&#xff0c;并对工单根据一些筛选条件进行搜索 目前是实现了除了日期之外的搜索功能&#xff0c;测试数据是下面这个tableData.js&#xff0c;都是我自己手写的&#xff0c;后端请求也稍微写了一些&#xff0c;…...

【系统架构设计】架构核心知识: 2.1 软件过程模型

目录 一 软件过程模型 1 瀑布模型 2 V模型 3 喷泉模型 4 增量模型 5 原型模型...

数据管理系统-week1-文件系统、数据库和数据库管理系统

文章目录 前言一、 文件系统文件系统的限制 二、 数据库系统三、 数据库管理系统参考文献 前言 一、 文件系统 对于更高级的数据处理应用程序来说&#xff0c;基于数据块的持久存储逻辑模型过于简单数据块序列被划分为称为文件的数据块的可变子序列&#xff0c;与文件相关的名…...

探索OpenCV中直方图的神奇之处:应用与实现

文章目录 导言&#xff1a;直方图概述&#xff1a;函数原型参数说明&#xff1a;代码示例 应用场景&#xff1a;结语&#xff1a; 导言&#xff1a; 直方图是数字图像处理中一个强大而重要的工具&#xff0c;它通过可视化数据的分布情况&#xff0c;帮助我们更好地理解图像的特…...

MapReduce编程——矩阵乘法(Python版本)

数据格式 对于矩阵元素 A i j A_{ij} Aij​&#xff0c;将其处理为 < i , j , M a t r i x N a m e , v a l u e > <i,j,MatrixName,value> <i,j,MatrixName,value>的四元组格式&#xff0c;例如矩阵[[2, 1, 3, 4], [10, -8, 7, 2], [9, 1, 6, -2]]可被转化…...

nature日报:为什么印度德里现在的空气污染如此严重?

为什么印度德里现在的空气污染如此严重&#xff1f; 后季风季节为印度大城市的空气污染积累创造了理想的条件。 本文整理扩展自2023年11月10日nature杂志的NEWS EXPLAINER——Why is Delhi’s air pollution so bad right now? (nature.com) Highlights 季风期间&#xff0…...

使用docker在3台服务器上搭建基于redis 6.x的一主两从三台均是哨兵模式

一、环境及版本说明 如果服务器已经安装了docker,则忽略此步骤,如果没有安装,则可以按照一下方式安装: 1. 在线安装(有互联网环境): 请看我这篇文章 传送阵>> 点我查看 2. 离线安装(内网环境):请看我这篇文章 传送阵>> 点我查看 说明&#xff1a;假设每台服务器已…...

装饰模式(Decorator Pattern)重构java邮件发奖系统实战

前言 现在我们有个如下的需求&#xff0c;设计一个邮件发奖的小系统&#xff0c; 需求 1.数据验证 → 2. 敏感信息加密 → 3. 日志记录 → 4. 实际发送邮件 装饰器模式&#xff08;Decorator Pattern&#xff09;允许向一个现有的对象添加新的功能&#xff0c;同时又不改变其…...

RocketMQ延迟消息机制

两种延迟消息 RocketMQ中提供了两种延迟消息机制 指定固定的延迟级别 通过在Message中设定一个MessageDelayLevel参数&#xff0c;对应18个预设的延迟级别指定时间点的延迟级别 通过在Message中设定一个DeliverTimeMS指定一个Long类型表示的具体时间点。到了时间点后&#xf…...

工业安全零事故的智能守护者:一体化AI智能安防平台

前言&#xff1a; 通过AI视觉技术&#xff0c;为船厂提供全面的安全监控解决方案&#xff0c;涵盖交通违规检测、起重机轨道安全、非法入侵检测、盗窃防范、安全规范执行监控等多个方面&#xff0c;能够实现对应负责人反馈机制&#xff0c;并最终实现数据的统计报表。提升船厂…...

Oracle查询表空间大小

1 查询数据库中所有的表空间以及表空间所占空间的大小 SELECTtablespace_name,sum( bytes ) / 1024 / 1024 FROMdba_data_files GROUP BYtablespace_name; 2 Oracle查询表空间大小及每个表所占空间的大小 SELECTtablespace_name,file_id,file_name,round( bytes / ( 1024 …...

STM32+rt-thread判断是否联网

一、根据NETDEV_FLAG_INTERNET_UP位判断 static bool is_conncected(void) {struct netdev *dev RT_NULL;dev netdev_get_first_by_flags(NETDEV_FLAG_INTERNET_UP);if (dev RT_NULL){printf("wait netdev internet up...");return false;}else{printf("loc…...

Opencv中的addweighted函数

一.addweighted函数作用 addweighted&#xff08;&#xff09;是OpenCV库中用于图像处理的函数&#xff0c;主要功能是将两个输入图像&#xff08;尺寸和类型相同&#xff09;按照指定的权重进行加权叠加&#xff08;图像融合&#xff09;&#xff0c;并添加一个标量值&#x…...

Keil 中设置 STM32 Flash 和 RAM 地址详解

文章目录 Keil 中设置 STM32 Flash 和 RAM 地址详解一、Flash 和 RAM 配置界面(Target 选项卡)1. IROM1(用于配置 Flash)2. IRAM1(用于配置 RAM)二、链接器设置界面(Linker 选项卡)1. 勾选“Use Memory Layout from Target Dialog”2. 查看链接器参数(如果没有勾选上面…...

DBAPI如何优雅的获取单条数据

API如何优雅的获取单条数据 案例一 对于查询类API&#xff0c;查询的是单条数据&#xff0c;比如根据主键ID查询用户信息&#xff0c;sql如下&#xff1a; select id, name, age from user where id #{id}API默认返回的数据格式是多条的&#xff0c;如下&#xff1a; {&qu…...

ElasticSearch搜索引擎之倒排索引及其底层算法

文章目录 一、搜索引擎1、什么是搜索引擎?2、搜索引擎的分类3、常用的搜索引擎4、搜索引擎的特点二、倒排索引1、简介2、为什么倒排索引不用B+树1.创建时间长,文件大。2.其次,树深,IO次数可怕。3.索引可能会失效。4.精准度差。三. 倒排索引四、算法1、Term Index的算法2、 …...