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


    1. import numpy as np
    2. import pandas as pd
    3. import matplotlib.pyplot as plt
    4. import torch
    5. import torch.optim as optim
    6. import warnings
    7. warnings.filterwarnings("ignore")
    8. %matplotlib inline
    1. features = pd.read_csv('temps.csv')
    2. #看看数据长什么样子
    3. features.head()

    数据表

    • year,moth,day,week分别表示的具体的时间
    • temp_2:前天的最高温度值
    • temp_1:昨天的最高温度值
    • average:在历史中,每年这一天的平均最高温度值
    • actual:这就是我们的标签值了,当天的真实最高温度
    • friend:这一列可能是凑热闹的,你的朋友猜测的可能值,咱们不管它就好了
      1. # 处理时间数据
      2. import datetime
      3. # 分别得到年,月,日
      4. years = features['year']
      5. months = features['month']
      6. days = features['day']
      7. # datetime格式
      8. dates = [str(int(year)) + '-' + str(int(month)) + '-' + str(int(day)) for year, month, day in zip(years, months, days)]
      9. dates = [datetime.datetime.strptime(date, '%Y-%m-%d') for date in dates]
      1. # 准备画图
      2. # 指定默认风格
      3. plt.style.use('fivethirtyeight')
      4. # 设置布局
      5. fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2, figsize = (10,10))
      6. fig.autofmt_xdate(rotation = 45)
      7. # 标签值
      8. ax1.plot(dates, features['actual'])
      9. ax1.set_xlabel(''); ax1.set_ylabel('Temperature'); ax1.set_title('Max Temp')
      10. # 昨天
      11. ax2.plot(dates, features['temp_1'])
      12. ax2.set_xlabel(''); ax2.set_ylabel('Temperature'); ax2.set_title('Previous Max Temp')
      13. # 前天
      14. ax3.plot(dates, features['temp_2'])
      15. ax3.set_xlabel('Date'); ax3.set_ylabel('Temperature'); ax3.set_title('Two Days Prior Max Temp')
      16. # 我的逗逼朋友
      17. ax4.plot(dates, features['friend'])
      18. ax4.set_xlabel('Date'); ax4.set_ylabel('Temperature'); ax4.set_title('Friend Estimate')
      19. plt.tight_layout(pad=2)

      1. # 独热编码
      2. features = pd.get_dummies(features)
      3. features.head(5)
      1. # 标签
      2. labels = np.array(features['actual'])
      3. # 在特征中去掉标签
      4. features= features.drop('actual', axis = 1)
      5. # 名字单独保存一下,以备后患
      6. feature_list = list(features.columns)
      7. # 转换成合适的格式
      8. features = np.array(features)
      1. from sklearn import preprocessing
      2. input_features = preprocessing.StandardScaler().fit_transform(features)

      构建网络模型

      1. x = torch.tensor(input_features, dtype = float)
      2. y = torch.tensor(labels, dtype = float)
      3. # 权重参数初始化
      4. weights = torch.randn((14, 128), dtype = float, requires_grad = True)
      5. biases = torch.randn(128, dtype = float, requires_grad = True)
      6. weights2 = torch.randn((128, 1), dtype = float, requires_grad = True)
      7. biases2 = torch.randn(1, dtype = float, requires_grad = True)
      8. learning_rate = 0.001
      9. losses = []
      10. for i in range(1000):
      11. # 计算隐层
      12. hidden = x.mm(weights) + biases
      13. # 加入激活函数
      14. hidden = torch.relu(hidden)
      15. # 预测结果
      16. predictions = hidden.mm(weights2) + biases2
      17. # 通计算损失
      18. loss = torch.mean((predictions - y) ** 2)
      19. losses.append(loss.data.numpy())
      20. # 打印损失值
      21. if i % 100 == 0:
      22. print('loss:', loss)
      23. #返向传播计算
      24. loss.backward()
      25. #更新参数
      26. weights.data.add_(- learning_rate * weights.grad.data)
      27. biases.data.add_(- learning_rate * biases.grad.data)
      28. weights2.data.add_(- learning_rate * weights2.grad.data)
      29. biases2.data.add_(- learning_rate * biases2.grad.data)
      30. # 每次迭代都得记得清空
      31. weights.grad.data.zero_()
      32. biases.grad.data.zero_()
      33. weights2.grad.data.zero_()
      34. biases2.grad.data.zero_()

    • 更简单的构建网络模型

      1. input_size = input_features.shape[1]
      2. hidden_size = 128
      3. output_size = 1
      4. batch_size = 16
      5. my_nn = torch.nn.Sequential(
      6. torch.nn.Linear(input_size, hidden_size),
      7. torch.nn.Sigmoid(),
      8. torch.nn.Linear(hidden_size, output_size),
      9. )
      10. cost = torch.nn.MSELoss(reduction='mean')
      11. optimizer = torch.optim.Adam(my_nn.parameters(), lr = 0.001)
      1. # 训练网络
      2. losses = []
      3. for i in range(1000):
      4. batch_loss = []
      5. # MINI-Batch方法来进行训练
      6. for start in range(0, len(input_features), batch_size):
      7. end = start + batch_size if start + batch_size < len(input_features) else len(input_features)
      8. xx = torch.tensor(input_features[start:end], dtype = torch.float, requires_grad = True)
      9. yy = torch.tensor(labels[start:end], dtype = torch.float, requires_grad = True)
      10. prediction = my_nn(xx)
      11. loss = cost(prediction, yy)
      12. optimizer.zero_grad()
      13. loss.backward(retain_graph=True)
      14. optimizer.step()
      15. batch_loss.append(loss.data.numpy())
      16. # 打印损失
      17. if i % 100==0:
      18. losses.append(np.mean(batch_loss))
      19. print(i, np.mean(batch_loss))

      预测训练结果

      1. x = torch.tensor(input_features, dtype = torch.float)
      2. predict = my_nn(x).data.numpy()
      3. # 转换日期格式
      4. dates = [str(int(year)) + '-' + str(int(month)) + '-' + str(int(day)) for year, month, day in zip(years, months, days)]
      5. dates = [datetime.datetime.strptime(date, '%Y-%m-%d') for date in dates]
      6. # 创建一个表格来存日期和其对应的标签数值
      7. true_data = pd.DataFrame(data = {'date': dates, 'actual': labels})
      8. # 同理,再创建一个来存日期和其对应的模型预测值
      9. months = features[:, feature_list.index('month')]
      10. days = features[:, feature_list.index('day')]
      11. years = features[:, feature_list.index('year')]
      12. test_dates = [str(int(year)) + '-' + str(int(month)) + '-' + str(int(day)) for year, month, day in zip(years, months, days)]
      13. test_dates = [datetime.datetime.strptime(date, '%Y-%m-%d') for date in test_dates]
      14. predictions_data = pd.DataFrame(data = {'date': test_dates, 'prediction': predict.reshape(-1)})
      15. # 真实值
      16. plt.plot(true_data['date'], true_data['actual'], 'b-', label = 'actual')
      17. # 预测值
      18. plt.plot(predictions_data['date'], predictions_data['prediction'], 'ro', label = 'prediction')
      19. plt.xticks(rotation = '60');
      20. plt.legend()
      21. # 图名
      22. plt.xlabel('Date'); plt.ylabel('Maximum Temperature (F)'); plt.title('Actual and Predicted Values');

    • https://gitee.com/code-wenjiahao/neural-network-practical-classification-and-regression-tasks

  • 相关阅读:
    中断机制-中断协商机制、中断方法
    vue集成海康h5player实现播放
    照片+制作照片书神器,效果太棒了!
    计算机公共课面试常见问题:线性代数篇
    堆--数组中第K大元素
    React state(及组件) 的保留与重置
    CenterNet算法by bilibili
    Vue学习笔记-配置代理服务器
    NewStarCTF2023week2-Unserialize?
    零基础学Java(3)运算符
  • 原文地址:https://blog.csdn.net/qq_65838372/article/details/132724524