欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PyTorch一小時(shí)掌握之神經(jīng)網(wǎng)絡(luò)氣溫預(yù)測(cè)篇

 更新時(shí)間:2021年09月07日 16:14:24   作者:我是小白呀  
這篇文章主要介紹了PyTorch一小時(shí)掌握之神經(jīng)網(wǎng)絡(luò)氣溫預(yù)測(cè)篇,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

概述

具體的案例描述在此就不多贅述. 同一數(shù)據(jù)集我們?cè)跈C(jī)器學(xué)習(xí)里的隨機(jī)森林模型中已經(jīng)討論過(guò).

導(dǎo)包

import numpy as np
import pandas as pd
import datetime
import matplotlib.pyplot as plt
from pandas.plotting import register_matplotlib_converters
from sklearn.preprocessing import StandardScaler
import torch

數(shù)據(jù)讀取

# ------------------1. 數(shù)據(jù)讀取------------------

# 讀取數(shù)據(jù)
data = pd.read_csv("temps.csv")

# 看看數(shù)據(jù)長(zhǎng)什么樣子
print(data.head())

# 查看數(shù)據(jù)維度
print("數(shù)據(jù)維度:", data.shape)

# 產(chǎn)看數(shù)據(jù)類(lèi)型
print("數(shù)據(jù)類(lèi)型:", type(data))

輸出結(jié)果:
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
數(shù)據(jù)維度: (348, 9)
數(shù)據(jù)類(lèi)型: <class 'pandas.core.frame.DataFrame'>

數(shù)據(jù)預(yù)處理

# ------------------2. 數(shù)據(jù)預(yù)處理------------------

# datetime 格式
dates = pd.PeriodIndex(year=data["year"], month=data["month"], day=data["day"], freq="D").astype(str)
dates = [datetime.datetime.strptime(date, "%Y-%m-%d") for date in dates]
print(dates[:5])

# 編碼轉(zhuǎn)換
data = pd.get_dummies(data)
print(data.head())

# 畫(huà)圖
plt.style.use("fivethirtyeight")
register_matplotlib_converters()

# 標(biāo)簽
labels = np.array(data["actual"])

# 取消標(biāo)簽
data = data.drop(["actual"], axis= 1)
print(data.head())

# 保存一下列名
feature_list = list(data.columns)

# 格式轉(zhuǎn)換
data_new = np.array(data)

data_new  = StandardScaler().fit_transform(data_new)
print(data_new[:5])

輸出結(jié)果:
[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)]
year month day temp_2 ... week_Sun week_Thurs week_Tues week_Wed
0 2016 1 1 45 ... 0 0 0 0
1 2016 1 2 44 ... 0 0 0 0
2 2016 1 3 45 ... 1 0 0 0
3 2016 1 4 44 ... 0 0 0 0
4 2016 1 5 41 ... 0 0 1 0

[5 rows x 15 columns]
year month day temp_2 ... week_Sun week_Thurs week_Tues week_Wed
0 2016 1 1 45 ... 0 0 0 0
1 2016 1 2 44 ... 0 0 0 0
2 2016 1 3 45 ... 1 0 0 0
3 2016 1 4 44 ... 0 0 0 0
4 2016 1 5 41 ... 0 0 1 0

[5 rows x 14 columns]
[[ 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]
[ 0. -1.5678393 -1.54267126 -1.56929813 -1.49443549 -1.33755752
0.06187741 -0.40961596 -0.40482045 2.44131112 -0.40482045 -0.40482045
-0.41913682 -0.40482045]
[ 0. -1.5678393 -1.4285208 -1.48452388 -1.57953835 -1.32804474
-0.25855917 -0.40961596 -0.40482045 -0.40961596 2.47023092 -0.40482045
-0.41913682 -0.40482045]
[ 0. -1.5678393 -1.31437034 -1.56929813 -1.83484692 -1.31853195
-0.45082111 -0.40961596 2.47023092 -0.40961596 -0.40482045 -0.40482045
-0.41913682 -0.40482045]
[ 0. -1.5678393 -1.20021989 -1.8236209 -1.91994977 -1.30901917
-1.2198689 -0.40961596 -0.40482045 -0.40961596 -0.40482045 -0.40482045
2.38585576 -0.40482045]]

構(gòu)建網(wǎng)絡(luò)模型

# ------------------3. 構(gòu)建網(wǎng)絡(luò)模型------------------

x = torch.tensor(data_new)
y = torch.tensor(labels)

# 權(quán)重參數(shù)初始化
weights1 = torch.randn((14,128), dtype=float, requires_grad= True)
biases1 = 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):
    # 計(jì)算隱層
    hidden = x.mm(weights1) + biases1
    # 加入激活函數(shù)
    hidden = torch.relu(hidden)
    # 預(yù)測(cè)結(jié)果
    predictions = hidden.mm(weights2) + biases2
    # 計(jì)算損失
    loss = torch.mean((predictions - y) ** 2)

    # 打印損失值
    if i % 100 == 0:
        print("loss:", loss)
    # 反向傳播計(jì)算
    loss.backward()

    # 更新參數(shù)
    weights1.data.add_(-learning_rate * weights1.grad.data)
    biases1.data.add_(-learning_rate * biases1.grad.data)
    weights2.data.add_(-learning_rate * weights2.grad.data)
    biases2.data.add_(-learning_rate * biases2.grad.data)

    # 每次迭代清空
    weights1.grad.data.zero_()
    biases1.grad.data.zero_()
    weights2.grad.data.zero_()
    biases2.grad.data.zero_()

輸出結(jié)果:
loss: tensor(4746.8598, dtype=torch.float64, grad_fn=<MeanBackward0>)
loss: tensor(156.5691, dtype=torch.float64, grad_fn=<MeanBackward0>)
loss: tensor(148.9419, dtype=torch.float64, grad_fn=<MeanBackward0>)
loss: tensor(146.1035, dtype=torch.float64, grad_fn=<MeanBackward0>)
loss: tensor(144.5652, dtype=torch.float64, grad_fn=<MeanBackward0>)
loss: tensor(143.5376, dtype=torch.float64, grad_fn=<MeanBackward0>)
loss: tensor(142.7823, dtype=torch.float64, grad_fn=<MeanBackward0>)
loss: tensor(142.2151, dtype=torch.float64, grad_fn=<MeanBackward0>)
loss: tensor(141.7770, dtype=torch.float64, grad_fn=<MeanBackward0>)
loss: tensor(141.4294, dtype=torch.float64, grad_fn=<MeanBackward0>)

數(shù)據(jù)可視化

# ------------------4. 數(shù)據(jù)可視化------------------

def graph1():
    # 創(chuàng)建子圖
    f, ax = plt.subplots(2, 2, figsize=(10, 10))

    # 標(biāo)簽值
    ax[0, 0].plot(dates, labels, color="#ADD8E6")
    ax[0, 0].set_xticks([""])
    ax[0, 0].set_ylabel("Temperature")
    ax[0, 0].set_title("Max Temp")

    # 昨天
    ax[0, 1].plot(dates, data["temp_1"], color="#87CEFA")
    ax[0, 1].set_xticks([""])
    ax[0, 1].set_ylabel("Temperature")
    ax[0, 1].set_title("Previous Max Temp")

    # 前天
    ax[1, 0].plot(dates, data["temp_2"], color="#00BFFF")
    ax[1, 0].set_xticks([""])
    ax[1, 0].set_xlabel("Date")
    ax[1, 0].set_ylabel("Temperature")
    ax[1, 0].set_title("Two Days Prior Max Temp")

    # 朋友
    ax[1, 1].plot(dates, data["friend"], color="#1E90FF")
    ax[1, 1].set_xticks([""])
    ax[1, 1].set_xlabel("Date")
    ax[1, 1].set_ylabel("Temperature")
    ax[1, 1].set_title("Friend Estimate")

    plt.show()

輸出結(jié)果:

在這里插入圖片描述

完整代碼

import numpy as np
import pandas as pd
import datetime
import matplotlib.pyplot as plt
from pandas.plotting import register_matplotlib_converters
from sklearn.preprocessing import StandardScaler
import torch


# ------------------1. 數(shù)據(jù)讀取------------------

# 讀取數(shù)據(jù)
data = pd.read_csv("temps.csv")

# 看看數(shù)據(jù)長(zhǎng)什么樣子
print(data.head())

# 查看數(shù)據(jù)維度
print("數(shù)據(jù)維度:", data.shape)

# 產(chǎn)看數(shù)據(jù)類(lèi)型
print("數(shù)據(jù)類(lèi)型:", type(data))

# ------------------2. 數(shù)據(jù)預(yù)處理------------------

# datetime 格式
dates = pd.PeriodIndex(year=data["year"], month=data["month"], day=data["day"], freq="D").astype(str)
dates = [datetime.datetime.strptime(date, "%Y-%m-%d") for date in dates]
print(dates[:5])

# 編碼轉(zhuǎn)換
data = pd.get_dummies(data)
print(data.head())

# 畫(huà)圖
plt.style.use("fivethirtyeight")
register_matplotlib_converters()

# 標(biāo)簽
labels = np.array(data["actual"])

# 取消標(biāo)簽
data = data.drop(["actual"], axis= 1)
print(data.head())

# 保存一下列名
feature_list = list(data.columns)

# 格式轉(zhuǎn)換
data_new = np.array(data)

data_new  = StandardScaler().fit_transform(data_new)
print(data_new[:5])

# ------------------3. 構(gòu)建網(wǎng)絡(luò)模型------------------

x = torch.tensor(data_new)
y = torch.tensor(labels)

# 權(quán)重參數(shù)初始化
weights1 = torch.randn((14,128), dtype=float, requires_grad= True)
biases1 = 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):
    # 計(jì)算隱層
    hidden = x.mm(weights1) + biases1
    # 加入激活函數(shù)
    hidden = torch.relu(hidden)
    # 預(yù)測(cè)結(jié)果
    predictions = hidden.mm(weights2) + biases2
    # 計(jì)算損失
    loss = torch.mean((predictions - y) ** 2)

    # 打印損失值
    if i % 100 == 0:
        print("loss:", loss)
    # 反向傳播計(jì)算
    loss.backward()

    # 更新參數(shù)
    weights1.data.add_(-learning_rate * weights1.grad.data)
    biases1.data.add_(-learning_rate * biases1.grad.data)
    weights2.data.add_(-learning_rate * weights2.grad.data)
    biases2.data.add_(-learning_rate * biases2.grad.data)

    # 每次迭代清空
    weights1.grad.data.zero_()
    biases1.grad.data.zero_()
    weights2.grad.data.zero_()
    biases2.grad.data.zero_()

# ------------------4. 數(shù)據(jù)可視化------------------

def graph1():
    # 創(chuàng)建子圖
    f, ax = plt.subplots(2, 2, figsize=(10, 10))

    # 標(biāo)簽值
    ax[0, 0].plot(dates, labels, color="#ADD8E6")
    ax[0, 0].set_xticks([""])
    ax[0, 0].set_ylabel("Temperature")
    ax[0, 0].set_title("Max Temp")

    # 昨天
    ax[0, 1].plot(dates, data["temp_1"], color="#87CEFA")
    ax[0, 1].set_xticks([""])
    ax[0, 1].set_ylabel("Temperature")
    ax[0, 1].set_title("Previous Max Temp")

    # 前天
    ax[1, 0].plot(dates, data["temp_2"], color="#00BFFF")
    ax[1, 0].set_xticks([""])
    ax[1, 0].set_xlabel("Date")
    ax[1, 0].set_ylabel("Temperature")
    ax[1, 0].set_title("Two Days Prior Max Temp")

    # 朋友
    ax[1, 1].plot(dates, data["friend"], color="#1E90FF")
    ax[1, 1].set_xticks([""])
    ax[1, 1].set_xlabel("Date")
    ax[1, 1].set_ylabel("Temperature")
    ax[1, 1].set_title("Friend Estimate")

    plt.show()


if __name__ == "__main__":
    graph1()

到此這篇關(guān)于PyTorch一小時(shí)掌握之神經(jīng)網(wǎng)絡(luò)氣溫預(yù)測(cè)篇的文章就介紹到這了,更多相關(guān)PyTorch 神經(jīng)網(wǎng)絡(luò)氣溫預(yù)測(cè)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python裝飾器基礎(chǔ)概念與用法詳解

    Python裝飾器基礎(chǔ)概念與用法詳解

    這篇文章主要介紹了Python裝飾器基礎(chǔ)概念與用法,結(jié)合實(shí)例形式詳細(xì)分析了Python裝飾器的概念、功能、用法及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下
    2018-12-12
  • Python中的DateTime和TimeDelta詳解

    Python中的DateTime和TimeDelta詳解

    這篇文章主要介紹了Python中的DateTime和TimeDelta詳解,在Python中,date,time和datetime類(lèi)提供了許多函數(shù)來(lái)處理日期、時(shí)間和時(shí)間間隔,每當(dāng)您操縱日期或時(shí)間時(shí),都需要導(dǎo)入DateTime函數(shù),需要的朋友可以參考下
    2023-07-07
  • Python發(fā)起請(qǐng)求提示UnicodeEncodeError錯(cuò)誤代碼解決方法

    Python發(fā)起請(qǐng)求提示UnicodeEncodeError錯(cuò)誤代碼解決方法

    這篇文章主要介紹了Python發(fā)起請(qǐng)求提示UnicodeEncodeError錯(cuò)誤代碼解決方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-04-04
  • keras.layers.Conv2D()函數(shù)參數(shù)用法及說(shuō)明

    keras.layers.Conv2D()函數(shù)參數(shù)用法及說(shuō)明

    這篇文章主要介紹了keras.layers.Conv2D()函數(shù)參數(shù)用法及說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-02-02
  • Python生成九宮格圖片的示例代碼

    Python生成九宮格圖片的示例代碼

    這篇文章主要介紹了Python生成九宮格圖片的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-04-04
  • 利用Python制作動(dòng)態(tài)排名圖的實(shí)現(xiàn)代碼

    利用Python制作動(dòng)態(tài)排名圖的實(shí)現(xiàn)代碼

    這篇文章主要介紹了利用Python制作動(dòng)態(tài)排名圖的實(shí)現(xiàn)代碼,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-04-04
  • 將imagenet2012數(shù)據(jù)為tensorflow的tfrecords格式并跑驗(yàn)證的詳細(xì)過(guò)程

    將imagenet2012數(shù)據(jù)為tensorflow的tfrecords格式并跑驗(yàn)證的詳細(xì)過(guò)程

    這篇文章主要介紹了將imagenet2012數(shù)據(jù)為tensorflow的tfrecords格式并跑驗(yàn)證,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-09-09
  • Pyinstaller 打包exe教程及問(wèn)題解決

    Pyinstaller 打包exe教程及問(wèn)題解決

    這篇文章主要介紹了Pyinstaller 打包exe教程及問(wèn)題解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-08-08
  • 使用Python實(shí)現(xiàn)在Excel工作表中添加、修改及刪除超鏈接

    使用Python實(shí)現(xiàn)在Excel工作表中添加、修改及刪除超鏈接

    在創(chuàng)建Excel工作簿時(shí),內(nèi)部文檔的互鏈、報(bào)告自動(dòng)化生成或是創(chuàng)建外部資源快速訪問(wèn)路徑是比較常見(jiàn)的需求,本文將介紹如何使用Python實(shí)現(xiàn)在Excel工作表中對(duì)超鏈接進(jìn)行添加、修改及刪除的操作,需要的朋友可以參考下
    2024-10-10
  • 詳解python-opencv 常用函數(shù)

    詳解python-opencv 常用函數(shù)

    這篇文章主要介紹了python-opencv 常用函數(shù),主要包括讀取圖像保存圖像和縮放圖像的相關(guān)知識(shí),需要的朋友可以參考下
    2022-08-08

最新評(píng)論