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

    搭建PyTorch神经网络进行气温预测,pytorch,神经网络,人工智能

  • # 独热编码
    features = pd.get_dummies(features)
    features.head(5)
    # 标签
    labels = np.array(features['actual'])
    
    # 在特征中去掉标签
    features= features.drop('actual', axis = 1)
    
    # 名字单独保存一下,以备后患
    feature_list = list(features.columns)
    
    # 转换成合适的格式
    features = np.array(features)
    from sklearn import preprocessing
    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) 
    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_()

    搭建PyTorch神经网络进行气温预测,pytorch,神经网络,人工智能

  • 更简单的构建网络模型

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

    预测训练结果

    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,神经网络,人工智能

  • https://gitee.com/code-wenjiahao/neural-network-practical-classification-and-regression-tasks文章来源地址https://www.toymoban.com/news/detail-699233.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日
    浏览(28)
  • 【深度学习】——循环神经网络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

领红包