【搭建PyTorch神经网络进行气温预测】

这篇具有很好参考价值的文章主要介绍了【搭建PyTorch神经网络进行气温预测】。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

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

数据表中

  • year,moth,day,week分别表示的具体的时间
  • temp_2:前天的最高温度值
  • temp_1:昨天的最高温度值
  • average:在历史中,每年这一天的平均最高温度值
  • actual:这就是我们的标签值了,当天的真实最高温度
  • friend:这一列可能是凑热闹的,你的朋友猜测的可能值,咱们不管它就好了
print('数据维度:', features.shape)
数据维度: (348, 9)
# 处理时间数据
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]
[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)]
# 准备画图
# 指定默认风格
plt.style.use('fivethirtyeight')

# 设置布局
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2, figsize = (10,10))
fig.autofmt_xdate(rotation = 45) #x标签倾斜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)

【搭建PyTorch神经网络进行气温预测】,# 人工智能pytorch框架,pytorch,神经网络,人工智能

# 独热编码
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
# 标签
labels = np.array(features['actual'])

# 在特征中去掉标签
features= features.drop('actual', axis = 1)

# 名字单独保存一下,以备后患
feature_list = list(features.columns)

# 转换成合适的格式
features = np.array(features)
features.shape
(348, 14)
from sklearn import preprocessing
input_features = preprocessing.StandardScaler().fit_transform(features)
input_features[0]
array([ 0.        , -1.5678393 , -1.65682171, -1.48452388, -1.49443549,
       -1.3470703 , -1.98891668,  2.44131112, -0.40482045, -0.40961596,
       -0.40482045, -0.40482045, -0.41913682, -0.40482045])

构建网络模型

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-I9ez3tyG-1691437809583)(attachment:image.png)]

#将数据转化为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(4238.8822, dtype=torch.float64, grad_fn=<MeanBackward0>)
loss: tensor(155.8961, dtype=torch.float64, grad_fn=<MeanBackward0>)
loss: tensor(146.9377, dtype=torch.float64, grad_fn=<MeanBackward0>)
loss: tensor(144.1912, dtype=torch.float64, grad_fn=<MeanBackward0>)
loss: tensor(142.8590, dtype=torch.float64, grad_fn=<MeanBackward0>)
loss: tensor(142.0588, dtype=torch.float64, grad_fn=<MeanBackward0>)
loss: tensor(141.5304, dtype=torch.float64, grad_fn=<MeanBackward0>)
loss: tensor(141.1626, dtype=torch.float64, grad_fn=<MeanBackward0>)
loss: tensor(140.8778, dtype=torch.float64, grad_fn=<MeanBackward0>)
loss: tensor(140.6519, dtype=torch.float64, grad_fn=<MeanBackward0>)
predictions.shape
torch.Size([348, 1])

更简单的构建网络模型

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 = []
    # 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)
        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 3947.049
100 37.844784
200 35.660378
300 35.282845
400 35.11639
500 34.988346
600 34.87178
700 34.753754
800 34.62929
900 34.49678

预测训练结果

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})

# 同理,再创建一个来存日期和其对应的模型预测值
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');

【搭建PyTorch神经网络进行气温预测】,# 人工智能pytorch框架,pytorch,神经网络,人工智能文章来源地址https://www.toymoban.com/news/detail-632067.html

到了这里,关于【搭建PyTorch神经网络进行气温预测】的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 神经网络气温预测

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

    2024年02月05日
    浏览(27)
  • 【深度学习】——循环神经网络RNN及实例气温预测、单层lstm股票预测

           密集连接网络和卷积神经网络都有主要的特点,那就是它们没有记忆。它们单独处理每个输入,在输入和输入之间没有保存任何状态。举个例子:当你在阅读一个句子的时候,你需要记住之前的内容,我们才能动态的了解这个句子想表达的含义。生物智能已渐进的方

    2023年04月24日
    浏览(35)
  • 基于PyTorch神经网络进行温度预测——基于jupyter实现

    导入环境 读取文件 其中 数据表中 year,moth,day,week分别表示的具体的时间 temp_2:前天的最高温度值 temp_1:昨天的最高温度值 average:在历史中,每年这一天的平均最高温度值 actual:这就是我们的标签值了,当天的真实最高温度 friend:据说凑热闹 查阅数据维度 时间维度数据进

    2024年04月14日
    浏览(24)
  • 【复杂网络建模】——使用PyTorch和DGL库实现图神经网络进行链路预测

    🤵‍♂️ 个人主页:@Lingxw_w的个人主页 ✍🏻作者简介:计算机科学与技术研究生在读 🐋 希望大家多多支持,我们一起进步!😄 如果文章对你有帮助的话, 欢迎评论 💬点赞👍🏻 收藏 📂加关注+  目录 1、常见的链路预测方法 2、图神经网络上的链路预测 3、使用PyTorc

    2024年02月09日
    浏览(29)
  • 深度学习图像分类实战——pytorch搭建卷积神经网络(AlexNet, LeNet, ResNet50)进行场景图像分类(详细)

    目录 1  一、实验过程 1.1  实验目的 1.2  实验简介 1.3  数据集的介绍 1.4  一、LeNet5网络模型 1.5  二、AlexNet网络模型 1.6  三、ResNet50(残差网络)网络模型  二、实验代码 导入实验所需要的库  参数配置 数据预处理 重新DataSet 加载数据转为DataLoader函数 可视化一批训练

    2024年02月05日
    浏览(48)
  • 循环神经网络-单变量序列预测详解(pytorch)

    参考博客 (1)导入所需要的包 (2)读取数据并展示 (3)数据预处理 缺失值,转化成numpy.ndarray类型,转化成float类型,归一化处理 (4)划分训练集和测试集 用30个预测一个 1-30:31 2-31:32 … 94-143:144 需要注意 a = [dataset[i: (i + look_back)]] ,而不是 a = dataset[i: (i + look_back)] 对于

    2024年01月17日
    浏览(49)
  • 使用python里的神经网络进行数据分类预测

    在Python中使用神经网络进行数据分类预测,可以使用深度学习库如TensorFlow、Keras或PyTorch来实现。以下是使用Keras库的示例代码: Step 1: 准备数据 首先,准备用于训练和测试神经网络的数据集。将数据集分为输入特征和相应的目标类别。确保对数据进行适当处理和归一化。 S

    2024年02月16日
    浏览(28)
  • 使用python里的神经网络进行数据回归预测

    在Python中使用神经网络进行数据回归预测,你可以使用深度学习库如TensorFlow、Keras或PyTorch来实现。以下是使用Keras库的示例代码: Step 1: 准备数据 首先,准备用于训练和测试神经网络的数据集。将数据集分为输入特征和相应的目标值。确保对数据进行适当处理和归一化。 S

    2024年02月17日
    浏览(29)
  • 使用matlab里的神经网络进行数据分类预测

    在MATLAB中使用神经网络进行数据分类预测,你可以按照以下步骤进行: Step 1: 准备数据 首先,准备用于训练和测试神经网络的数据。将数据集分为输入特征和相应的目标类别。确保数据已经进行了适当的预处理和标准化。 Step 2: 创建并训练神经网络模型 使用MATLAB的Neural Net

    2024年02月16日
    浏览(32)
  • 【Pytorch】神经网络搭建

    在之前我们学习了如何用Pytorch去导入我们的数据和数据集,并且对数据进行预处理。接下来我们就需要学习如何利用Pytorch去构建我们的神经网络了。 目录 基本网络框架Module搭建 卷积层 从conv2d方法了解原理 从Conv2d方法了解使用 池化层 填充层 非线性层 线性层 Pytorch里面有一

    2023年04月17日
    浏览(26)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包