当前位置: 首页 > 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…...

云原生核心技术 (7/12): K8s 核心概念白话解读(上):Pod 和 Deployment 究竟是什么?

大家好&#xff0c;欢迎来到《云原生核心技术》系列的第七篇&#xff01; 在上一篇&#xff0c;我们成功地使用 Minikube 或 kind 在自己的电脑上搭建起了一个迷你但功能完备的 Kubernetes 集群。现在&#xff0c;我们就像一个拥有了一块崭新数字土地的农场主&#xff0c;是时…...

.Net框架,除了EF还有很多很多......

文章目录 1. 引言2. Dapper2.1 概述与设计原理2.2 核心功能与代码示例基本查询多映射查询存储过程调用 2.3 性能优化原理2.4 适用场景 3. NHibernate3.1 概述与架构设计3.2 映射配置示例Fluent映射XML映射 3.3 查询示例HQL查询Criteria APILINQ提供程序 3.4 高级特性3.5 适用场…...

【快手拥抱开源】通过快手团队开源的 KwaiCoder-AutoThink-preview 解锁大语言模型的潜力

引言&#xff1a; 在人工智能快速发展的浪潮中&#xff0c;快手Kwaipilot团队推出的 KwaiCoder-AutoThink-preview 具有里程碑意义——这是首个公开的AutoThink大语言模型&#xff08;LLM&#xff09;。该模型代表着该领域的重大突破&#xff0c;通过独特方式融合思考与非思考…...

C++八股 —— 单例模式

文章目录 1. 基本概念2. 设计要点3. 实现方式4. 详解懒汉模式 1. 基本概念 线程安全&#xff08;Thread Safety&#xff09; 线程安全是指在多线程环境下&#xff0c;某个函数、类或代码片段能够被多个线程同时调用时&#xff0c;仍能保证数据的一致性和逻辑的正确性&#xf…...

CMake控制VS2022项目文件分组

我们可以通过 CMake 控制源文件的组织结构,使它们在 VS 解决方案资源管理器中以“组”(Filter)的形式进行分类展示。 🎯 目标 通过 CMake 脚本将 .cpp、.h 等源文件分组显示在 Visual Studio 2022 的解决方案资源管理器中。 ✅ 支持的方法汇总(共4种) 方法描述是否推荐…...

精益数据分析(97/126):邮件营销与用户参与度的关键指标优化指南

精益数据分析&#xff08;97/126&#xff09;&#xff1a;邮件营销与用户参与度的关键指标优化指南 在数字化营销时代&#xff0c;邮件列表效度、用户参与度和网站性能等指标往往决定着创业公司的增长成败。今天&#xff0c;我们将深入解析邮件打开率、网站可用性、页面参与时…...

微软PowerBI考试 PL300-在 Power BI 中清理、转换和加载数据

微软PowerBI考试 PL300-在 Power BI 中清理、转换和加载数据 Power Query 具有大量专门帮助您清理和准备数据以供分析的功能。 您将了解如何简化复杂模型、更改数据类型、重命名对象和透视数据。 您还将了解如何分析列&#xff0c;以便知晓哪些列包含有价值的数据&#xff0c;…...

Selenium常用函数介绍

目录 一&#xff0c;元素定位 1.1 cssSeector 1.2 xpath 二&#xff0c;操作测试对象 三&#xff0c;窗口 3.1 案例 3.2 窗口切换 3.3 窗口大小 3.4 屏幕截图 3.5 关闭窗口 四&#xff0c;弹窗 五&#xff0c;等待 六&#xff0c;导航 七&#xff0c;文件上传 …...

macOS 终端智能代理检测

&#x1f9e0; 终端智能代理检测&#xff1a;自动判断是否需要设置代理访问 GitHub 在开发中&#xff0c;使用 GitHub 是非常常见的需求。但有时候我们会发现某些命令失败、插件无法更新&#xff0c;例如&#xff1a; fatal: unable to access https://github.com/ohmyzsh/oh…...

前端高频面试题2:浏览器/计算机网络

本专栏相关链接 前端高频面试题1&#xff1a;HTML/CSS 前端高频面试题2&#xff1a;浏览器/计算机网络 前端高频面试题3&#xff1a;JavaScript 1.什么是强缓存、协商缓存&#xff1f; 强缓存&#xff1a; 当浏览器请求资源时&#xff0c;首先检查本地缓存是否命中。如果命…...