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

神经网络气温预测

#引用所需要的库
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

features=pd.read_csv(‘temps.csv’)
features.head()

year 	month 	day 	week 	temp_2 	temp_1 	average 	actual 	friend

0 2016 1 1 Fri 45 45 45.6 45 29
1 2016 1 2 Sat 44 45 45.7 44 61
2 2016 1 3 Sun 45 44 45.8 41 56
3 2016 1 4 Mon 44 41 45.9 40 53
4 2016 1 5 Tues 41 40 46.0 44 41

#把列转为时间处理数据
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]

features.shape

(348, 9)

dates[:5]

[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)]

#小展示,看看数据集长什么样

#独热编码
features=pd.get_dummies(features)
features.head(5)

year 	month 	day 	temp_2 	temp_1 	average 	actual 	friend 	week_Fri 	week_Mon 	week_Sat 	week_Sun 	week_Thurs 	week_Tues 	week_Wed

0 2016 1 1 45 45 45.6 45 29 1 0 0 0 0 0 0
1 2016 1 2 44 45 45.7 44 61 0 0 1 0 0 0 0
2 2016 1 3 45 44 45.8 41 56 0 0 0 1 0 0 0
3 2016 1 4 44 41 45.9 40 53 0 1 0 0 0 0 0
4 2016 1 5 41 40 46.0 44 41 0 0 0 0 0 1 0

features.shape

(348, 15)

#标签(Y)
labels=np.array(features[‘actual’])
#在特征集中剔除标签,剩下x
features=features.drop(‘actual’,axis=1)
#单独保存名字,以备后患
feature_list=list(features.columns)
#转成数组格式->后续还需要转换成tensor张量
features=np.array(features)

features.shape

(348, 14)

#因为数据有大有小,归一化(数值浮动范围小)
from sklearn import preprocessing
input_features=preprocessing.StandardScaler().fit_transform(features)

#构建网络模型(复杂版)
#转为tensor
x = torch.tensor(input_features, 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_()

loss: tensor(8652.8872, dtype=torch.float64, grad_fn=)
loss: tensor(155.4351, dtype=torch.float64, grad_fn=)
loss: tensor(147.5643, dtype=torch.float64, grad_fn=)
loss: tensor(144.6621, dtype=torch.float64, grad_fn=)
loss: tensor(143.1741, dtype=torch.float64, grad_fn=)
loss: tensor(142.2740, dtype=torch.float64, grad_fn=)
loss: tensor(141.6748, dtype=torch.float64, grad_fn=)
loss: tensor(141.2530, dtype=torch.float64, grad_fn=)
loss: tensor(140.9336, dtype=torch.float64, grad_fn=)
loss: tensor(140.6799, dtype=torch.float64, grad_fn=)

简化实现

指定规模

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(1000):
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))

0 4015.5623
100 38.040577
200 35.64831
300 35.261333
400 35.099106
500 34.968235
600 34.84836
700 34.728233
800 34.605637
900 34.48074

#评估模型
x = torch.tensor(input_features,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})

同理,在创建一个来存日期和其对应的模型预测值

mouths = 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’)

plt.show()
ValueError: rotation must be ‘vertical’, ‘horizontal’ or a number, not 60

相关文章:

神经网络气温预测

#引用所需要的库 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 featurespd.read_csv(‘temps.csv’) feat…...

体验SOLIDWORKS钣金切口工具增强 硕迪科技

在工业生产制造中&#xff0c;钣金加工是一种常用的加工方式&#xff0c;在SOLIDWORKS2024新版本中&#xff0c;钣金切口工具再次增强了&#xff0c;从SOLIDWORKS 2024 开始&#xff0c; 您可以使用切口工具在空心或薄壁圆柱体和圆锥体中生成切口。 只需在现有空心或薄壁圆柱体…...

(八)Flask之app.route装饰器函数的参数

app.route参数 app.route()是Flask框架中用于定义路由的装饰器函数&#xff0c;它接受一些参数来指定路由的URL规则、请求方法等。 app.route()参数如下&#xff1a; rule&#xff08;必选&#xff09;&#xff1a;定义URL规则的字符串&#xff0c;表示要匹配的URL路径。可以…...

ES6.8集群配置注意点

x-pack配置 当启用xpack.security.enabled时&#xff0c;确保集群中的所有节点都配置了此项&#xff0c;并确保所有节点都已重启。如果只有部分节点启用安全性&#xff0c;那么集群可能会遇到问题。 设置密码 使用elasticsearch-setup-passwords工具设置密码时&#xff0c;确保…...

Powercli批量修改分布式交换机端口组

背景 需求&#xff1a; 批量修改虚拟机的分布式端口组 解决方式一&#xff1a; 三条命令解决&#xff1a;先获取目标虚拟机、获取目标端口组、修改虚拟机端口组、检查虚拟机状态。 $vm Get-VM -Name <虚拟机名称> $portGroup Get-VirtualPortGroup -Name <端口…...

ZKP10.2 Efficient Recursion via Statement Folding (Nova)

ZKP学习笔记 ZK-Learning MOOC课程笔记 Lecture 10: Recursive SNARKs, Aggregation and Accumulation (Dan Boneh) 10.3 Efficient Recursion via Statement Folding: Nova, Supernova, and generalizations The difficulty with full recursion Prover P needs to build a…...

高浓度cod废水怎么处理

高浓度COD废水的处理方法主要有物理法、生物法和化学法。 物理法&#xff1a;一般通过加入絮凝剂&#xff0c;利用絮凝剂的吸附、电中和等作用将水中的颗粒物结团沉降下去&#xff0c;从而达到去除部分来自颗粒物的COD。此方法基本上只对浓度上万、上千的COD起作用&#xff0c…...

Docker学习——②

文章目录 1、Docker是什么1.1 Docker本质1.2 Docker的引擎迭代1.3 Docker和虚拟机的区别1.4 Docker 为什么比虚拟机资源利用率高&#xff0c;启动快&#xff1f;1.5 Docker 和 JVM 虚拟化的区别&#xff1f; 2、Docker架构3、Docker生态3.1 新时代软件诉求3.2 Docker 解决方案 …...

VSCode 设置平滑光标

1.点击左下角的设置按钮&#xff0c;再点击设置 2.点击文本编辑器&#xff0c;点击光标&#xff0c;勾选控制是否启用平滑插入动画。 3.随便打开一个文件&#xff0c;上下左右移动光标时&#xff0c;会发现非常的流畅。 原创作者&#xff1a;吴小糖 创作时间&#xff1a;2023…...

Spring、SpringMVC、Mybatis

一.Spring基础 1.Spring 框架是什么 Spring 是一款开源的轻量级 Java 开发框架&#xff0c;我们一般说 Spring 框架指的都是 Spring Framework&#xff0c;它是很多模块的集合&#xff0c;例如&#xff0c;Spring core、Spring JDBC、Spring MVC 等&#xff0c;使用这些模块可…...

Kubernetes 架构

Kubernetes 架构 Kubernetes 最初源于谷歌内部的 Borg,提供了面向应用的容器集群部署和管理系统。Kubernetes 的目标旨在消除编排物理 / 虚拟计算,网络和存储基础设施的负担,并使应用程序运营商和开发人员完全将重点放在以容器为中心的原语上进行自助运营。Kubernetes 也提…...

python---数据类型(列表)

组织列表 使用sort()方法对列表永久性排序 按照字母顺序排序&#xff1a; motorcycles [chunlan, yamaha, dayun, jianshe]motorcycles.sort()print(motorcycles) 字母倒序&#xff1a; motorcycles [chunlan, yamaha, dayun, jianshe]motorcycles.sort(reverseTrue)pri…...

CentOS 7升级gcc/G++版本

Centos 7默认gcc版本为4.8&#xff0c;有时需要更高版本&#xff0c;只需要执行几条命令&#xff0c;无需下载源码编译编译。 安装centos-release-scl sudo yum install centos-release-scl 安装devtoolset sudo yum install devtoolset-8-gcc* 注意&#xff0c;如果想安装…...

uni-app开发微信公众号 H5打开扫一扫功能

<!--引入微信sdk--> <script src"http://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>let url location.href.split(#)[0];newApi.getSignature({ url }).then(res > {if (res.code 0) {this.sdk.config({beta: true, // 必须这么写&a…...

k8s-服务网格实战-入门Istio

istio-01.png 背景 终于进入大家都比较感兴趣的服务网格系列了&#xff0c;在前面已经讲解了&#xff1a; 如何部署应用到 kubernetes服务之间如何调用如何通过域名访问我们的服务如何使用 kubernetes 自带的配置 ConfigMap 基本上已经够我们开发一般规模的 web 应用了&#xf…...

金属压铸件自动化3D全尺寸测量设备自动外观检测三维检测-CASAIM

铸造作为现代装备制造工业的基础共性技术之一&#xff0c;铸件产品既是工业制造产品&#xff0c;也是大型机械的重要组成部分&#xff0c;被广泛运用在航空航天、工业船舶、机械电子和交通运输等行业。 铸件形状复杂&#xff0c;一般的三坐标或者卡尺圆规等工具难以获取多特征…...

Android笔记(十):结合Navigation组件实现Compose界面的导航

在Android笔记&#xff08;七&#xff09;搭建Android JetPack Compose组件中Scaffold脚手架 一文中通过定义一个导航的函数来实现不同界面的切换。如果没有传递任何参数&#xff0c;这样的导航处理也是可以接受的&#xff0c;处理方式也非常简单。但是&#xff0c;如果考虑到不…...

linux内核tcp配置--断网后连接卡住

通过隐藏通信应用程序中的临时网络中断&#xff0c;TCP 可以在偶尔不可靠的网络上提供可靠的通信。在通知发件人任何问题之前&#xff0c;您的操作系统将多次重发丢失的消息。大多数 Linux 发行版默认将任何丢失的数据包重传 15 次。重新传输以指数方式回退&#xff0c;因此这 …...

Apache Pulsar 在腾讯云上的最佳实践

导语 由 StreamNative 主办的 Pulsar Meetup Beijing 2023 在2023年10月14日完美落幕&#xff0c;本次活动大咖云集&#xff0c;来自腾讯、滴滴、华为、智联招聘、RisingWave 和 StreamNative 的行业专家们一起&#xff0c;深入探讨 Pulsar 在生产环境中的最佳应用实践&#x…...

VMware 虚拟机安装 CentOS 7

CentOS 7 1. 下载CentOS 7 iso镜像 Index of /centos/7.9.2009/isos/x86_64/ 2. Vmware安装CentOS 7 安装教程&#xff1a; 超详细VMware CentOS7(最小安装)安装教程_虚拟机最小化安装-CSDN博客 【精选】VMware 安装 Centos7 详细过程_vm虚拟机安装centos7_expectation Fu…...

Vue记事本应用实现教程

文章目录 1. 项目介绍2. 开发环境准备3. 设计应用界面4. 创建Vue实例和数据模型5. 实现记事本功能5.1 添加新记事项5.2 删除记事项5.3 清空所有记事 6. 添加样式7. 功能扩展&#xff1a;显示创建时间8. 功能扩展&#xff1a;记事项搜索9. 完整代码10. Vue知识点解析10.1 数据绑…...

【HarmonyOS 5.0】DevEco Testing:鸿蒙应用质量保障的终极武器

——全方位测试解决方案与代码实战 一、工具定位与核心能力 DevEco Testing是HarmonyOS官方推出的​​一体化测试平台​​&#xff0c;覆盖应用全生命周期测试需求&#xff0c;主要提供五大核心能力&#xff1a; ​​测试类型​​​​检测目标​​​​关键指标​​功能体验基…...

高频面试之3Zookeeper

高频面试之3Zookeeper 文章目录 高频面试之3Zookeeper3.1 常用命令3.2 选举机制3.3 Zookeeper符合法则中哪两个&#xff1f;3.4 Zookeeper脑裂3.5 Zookeeper用来干嘛了 3.1 常用命令 ls、get、create、delete、deleteall3.2 选举机制 半数机制&#xff08;过半机制&#xff0…...

macOS多出来了:Google云端硬盘、YouTube、表格、幻灯片、Gmail、Google文档等应用

文章目录 问题现象问题原因解决办法 问题现象 macOS启动台&#xff08;Launchpad&#xff09;多出来了&#xff1a;Google云端硬盘、YouTube、表格、幻灯片、Gmail、Google文档等应用。 问题原因 很明显&#xff0c;都是Google家的办公全家桶。这些应用并不是通过独立安装的…...

是否存在路径(FIFOBB算法)

题目描述 一个具有 n 个顶点e条边的无向图&#xff0c;该图顶点的编号依次为0到n-1且不存在顶点与自身相连的边。请使用FIFOBB算法编写程序&#xff0c;确定是否存在从顶点 source到顶点 destination的路径。 输入 第一行两个整数&#xff0c;分别表示n 和 e 的值&#xff08;1…...

人工智能(大型语言模型 LLMs)对不同学科的影响以及由此产生的新学习方式

今天是关于AI如何在教学中增强学生的学习体验&#xff0c;我把重要信息标红了。人文学科的价值被低估了 ⬇️ 转型与必要性 人工智能正在深刻地改变教育&#xff0c;这并非炒作&#xff0c;而是已经发生的巨大变革。教育机构和教育者不能忽视它&#xff0c;试图简单地禁止学生使…...

淘宝扭蛋机小程序系统开发:打造互动性强的购物平台

淘宝扭蛋机小程序系统的开发&#xff0c;旨在打造一个互动性强的购物平台&#xff0c;让用户在购物的同时&#xff0c;能够享受到更多的乐趣和惊喜。 淘宝扭蛋机小程序系统拥有丰富的互动功能。用户可以通过虚拟摇杆操作扭蛋机&#xff0c;实现旋转、抽拉等动作&#xff0c;增…...

毫米波雷达基础理论(3D+4D)

3D、4D毫米波雷达基础知识及厂商选型 PreView : https://mp.weixin.qq.com/s/bQkju4r6med7I3TBGJI_bQ 1. FMCW毫米波雷达基础知识 主要参考博文&#xff1a; 一文入门汽车毫米波雷达基本原理 &#xff1a;https://mp.weixin.qq.com/s/_EN7A5lKcz2Eh8dLnjE19w 毫米波雷达基础…...

Ubuntu Cursor升级成v1.0

0. 当前版本低 使用当前 Cursor v0.50时 GitHub Copilot Chat 打不开&#xff0c;快捷键也不好用&#xff0c;当看到 Cursor 升级后&#xff0c;还是蛮高兴的 1. 下载 Cursor 下载地址&#xff1a;https://www.cursor.com/cn/downloads 点击下载 Linux (x64) &#xff0c;…...

LangFlow技术架构分析

&#x1f527; LangFlow 的可视化技术栈 前端节点编辑器 底层框架&#xff1a;基于 &#xff08;一个现代化的 React 节点绘图库&#xff09; 功能&#xff1a; 拖拽式构建 LangGraph 状态机 实时连线定义节点依赖关系 可视化调试循环和分支逻辑 与 LangGraph 的深…...