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

用Pytorch實(shí)現(xiàn)線性回歸模型的步驟

 更新時(shí)間:2024年01月16日 11:19:18   作者:chairon  
線性關(guān)系是一種非常簡單的變量之間的關(guān)系,因變量和自變量在線性關(guān)系的情況下,可以使用線性回歸算法對一個(gè)或多個(gè)因變量和自變量間的線性關(guān)系進(jìn)行建模,本文主要介紹了如何利用Pytorch實(shí)現(xiàn)線性模型,需要的朋友可以參考下

Pytorch實(shí)現(xiàn)

步驟

  • 準(zhǔn)備數(shù)據(jù)集
  • 設(shè)計(jì)模型(計(jì)算預(yù)測值y_hat):從nn.Module模塊繼承
  • 構(gòu)造損失函數(shù)和優(yōu)化器:使用PytorchAPI
  • 訓(xùn)練過程:Forward、Backward、update

1. 準(zhǔn)備數(shù)據(jù)

在PyTorch中計(jì)算圖是通過mini-batch形式進(jìn)行,所以X、Y都是多維的Tensor。

在這里插入圖片描述

import torch
x_data = torch.Tensor([[1.0], [2.0], [3.0]])
y_data = torch.Tensor([[2.0], [4.0], [6.0]])

2. 設(shè)計(jì)模型

在之前講解梯度下降算法時(shí),我們需要自己計(jì)算出梯度,然后更新權(quán)重。

在這里插入圖片描述

而使用Pytorch構(gòu)造模型,重點(diǎn)時(shí)在構(gòu)建計(jì)算圖和損失函數(shù)上。

在這里插入圖片描述

class LinearModel

通過構(gòu)造一個(gè) class LinearModel類來實(shí)現(xiàn),所有的模型類都需要繼承nn.Module,這是所有神經(jīng)忘了模塊的基礎(chǔ)類。
class LinearModel這種定義的模型類必須包含兩個(gè)部分:

  • init():構(gòu)造函數(shù),進(jìn)行初始化。
    def __init__(self):
        super(LinearModel, self).__init__()#調(diào)用父類構(gòu)造函數(shù),不用管,照著寫。
        # torch.nn.Linear(in_featuers, in_featuers)構(gòu)造Linear類的對象,其實(shí)就是實(shí)現(xiàn)了一個(gè)線性單元
        self.linear = torch.nn.Linear(1, 1)

在這里插入圖片描述

  • forward():進(jìn)行前饋計(jì)算(backward沒有被寫,是因?yàn)樵谶@種模型類里面會(huì)自動(dòng)實(shí)現(xiàn))

Class nn.Linear 實(shí)現(xiàn)了magic method call():它使類的實(shí)例可以像函數(shù)一樣被調(diào)用。通常會(huì)調(diào)用forward()。

    def forward(self, x):
        y_pred = self.linear(x)#調(diào)用linear對象,輸入x進(jìn)行預(yù)測
        return y_pred

代碼

class LinearModel(torch.nn.Module):
    def __init__(self):
        super(LinearModel, self).__init__()#調(diào)用父類構(gòu)造函數(shù),不用管,照著寫。
        # torch.nn.Linear(in_featuers, in_featuers)構(gòu)造Linear類的對象,其實(shí)就是實(shí)現(xiàn)了一個(gè)線性單元
        self.linear = torch.nn.Linear(1, 1)
    def forward(self, x):
        y_pred = self.linear(x)#調(diào)用linear對象,輸入x進(jìn)行預(yù)測
        return y_pred

model = LinearModel()#實(shí)例化LinearModel()

3. 構(gòu)造損失函數(shù)和優(yōu)化器

采用MSE作為損失函數(shù)

torch.nn.MSELoss(size_average,reduce)

  • size_average:是否求mini-batch的平均loss。
  • reduce:降維,不用管。

在這里插入圖片描述

SGD作為優(yōu)化器torch.optim.SGD(params, lr):

  • params:參數(shù)
  • lr:學(xué)習(xí)率

在這里插入圖片描述

criterion = torch.nn.MSELoss(size_average=False)#size_average:the losses are averaged over each loss element in the batch.
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)#params:model.parameters(): w、b

4. 訓(xùn)練過程

  • 預(yù)測
  • 計(jì)算loss
  • 梯度清零
  • Backward
  • 參數(shù)更新
    簡化:Forward–>Backward–>更新
#4. Training Cycle
for epoch in range(100):
    y_pred = model(x_data)#Forward:預(yù)測
    loss = criterion(y_pred, y_data)#Forward:計(jì)算loss
    print(epoch, loss)
    optimizer.zero_grad()#梯度清零
    loss.backward()#backward:計(jì)算梯度
    optimizer.step()#通過step()函數(shù)進(jìn)行參數(shù)更新

5. 輸出和測試

# Output weight and bias
print('w = ', model.linear.weight.item())
print('b = ', model.linear.bias.item())

# Test Model
x_test = torch.Tensor([[4.0]])
y_test = model(x_test)
print('y_pred = ', y_test.data)

完整代碼

import torch
#1. Prepare dataset
x_data = torch.Tensor([[1.0], [2.0], [3.0]])
y_data = torch.Tensor([[2.0], [4.0], [6.0]])

#2. Design Model
class LinearModel(torch.nn.Module):
    def __init__(self):
        super(LinearModel, self).__init__()#調(diào)用父類構(gòu)造函數(shù),不用管,照著寫。
        # torch.nn.Linear(in_featuers, in_featuers)構(gòu)造Linear類的對象,其實(shí)就是實(shí)現(xiàn)了一個(gè)線性單元
        self.linear = torch.nn.Linear(1, 1)
    def forward(self, x):
        y_pred = self.linear(x)#調(diào)用linear對象,輸入x進(jìn)行預(yù)測
        return y_pred

model = LinearModel()#實(shí)例化LinearModel()

# 3. Construct Loss and Optimize
criterion = torch.nn.MSELoss(size_average=False)#size_average:the losses are averaged over each loss element in the batch.
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)#params:model.parameters(): w、b

#4. Training Cycle
for epoch in range(100):
    y_pred = model(x_data)#Forward:預(yù)測
    loss = criterion(y_pred, y_data)#Forward:計(jì)算loss
    print(epoch, loss)
    optimizer.zero_grad()#梯度清零
    loss.backward()#backward:計(jì)算梯度
    optimizer.step()#通過step()函數(shù)進(jìn)行參數(shù)更新

# Output weight and bias
print('w = ', model.linear.weight.item())
print('b = ', model.linear.bias.item())

# Test Model
x_test = torch.Tensor([[4.0]])
y_test = model(x_test)
print('y_pred = ', y_test.data)

輸出結(jié)果:

85 tensor(0.2294, grad_fn=)
86 tensor(0.2261, grad_fn=)
87 tensor(0.2228, grad_fn=)
88 tensor(0.2196, grad_fn=)
89 tensor(0.2165, grad_fn=)
90 tensor(0.2134, grad_fn=)
91 tensor(0.2103, grad_fn=)
92 tensor(0.2073, grad_fn=)
93 tensor(0.2043, grad_fn=)
94 tensor(0.2014, grad_fn=)
95 tensor(0.1985, grad_fn=)
96 tensor(0.1956, grad_fn=)
97 tensor(0.1928, grad_fn=)
98 tensor(0.1900, grad_fn=)
99 tensor(0.1873, grad_fn=)
w = 1.711882472038269
b = 0.654958963394165
y_pred = tensor([[7.5025]])

可以看到誤差還比較大,可以增加訓(xùn)練輪次,訓(xùn)練1000次后的結(jié)果:

980 tensor(2.1981e-07, grad_fn=)
981 tensor(2.1671e-07, grad_fn=)
982 tensor(2.1329e-07, grad_fn=)
983 tensor(2.1032e-07, grad_fn=)
984 tensor(2.0737e-07, grad_fn=)
985 tensor(2.0420e-07, grad_fn=)
986 tensor(2.0143e-07, grad_fn=)
987 tensor(1.9854e-07, grad_fn=)
988 tensor(1.9565e-07, grad_fn=)
989 tensor(1.9260e-07, grad_fn=)
990 tensor(1.8995e-07, grad_fn=)
991 tensor(1.8728e-07, grad_fn=)
992 tensor(1.8464e-07, grad_fn=)
993 tensor(1.8188e-07, grad_fn=)
994 tensor(1.7924e-07, grad_fn=)
995 tensor(1.7669e-07, grad_fn=)
996 tensor(1.7435e-07, grad_fn=)
997 tensor(1.7181e-07, grad_fn=)
998 tensor(1.6931e-07, grad_fn=)
999 tensor(1.6700e-07, grad_fn=)
w = 1.9997280836105347
b = 0.0006181497010402381
y_pred = tensor([[7.9995]])

練習(xí)

用以下這些優(yōu)化器替換SGD,得到訓(xùn)練結(jié)果并畫出損失曲線圖。

在這里插入圖片描述

比如說:Adam的loss圖:

在這里插入圖片描述

以上就是用Pytorch實(shí)現(xiàn)線性回歸模型的步驟的詳細(xì)內(nèi)容,更多關(guān)于Pytorch線性回歸模型的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Python多進(jìn)程使用及進(jìn)程池詳解

    Python多進(jìn)程使用及進(jìn)程池詳解

    這篇文章主要為大家介紹了Python多進(jìn)程使用及進(jìn)程池詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-06-06
  • Python編程中flask的簡介與簡單使用

    Python編程中flask的簡介與簡單使用

    今天小編就為大家分享一篇關(guān)于Python編程中flask的簡介與簡單使用,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧
    2018-12-12
  • 利用Python編寫一個(gè)簡單的緩存系統(tǒng)

    利用Python編寫一個(gè)簡單的緩存系統(tǒng)

    今天來做一個(gè)最簡單的例子,利用寫一個(gè)最簡單的緩存系統(tǒng),以key``value的方式保持?jǐn)?shù)據(jù),并且需要將內(nèi)容中的數(shù)據(jù)落地到文件,以便下次啟動(dòng)的時(shí)候,將文件的內(nèi)容加載進(jìn)內(nèi)存中來,感興趣的可以了解一下
    2023-04-04
  • opencv python 傅里葉變換的使用

    opencv python 傅里葉變換的使用

    這篇文章主要介紹了opencv python 傅里葉變換的使用,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-07-07
  • python使用socket實(shí)現(xiàn)的傳輸demo示例【基于TCP協(xié)議】

    python使用socket實(shí)現(xiàn)的傳輸demo示例【基于TCP協(xié)議】

    這篇文章主要介紹了python使用socket實(shí)現(xiàn)的傳輸demo,結(jié)合實(shí)例形式分析了Python使用socket庫基于TCP協(xié)議實(shí)現(xiàn)的客戶端與服務(wù)器端相關(guān)操作技巧,需要的朋友可以參考下
    2019-09-09
  • Matplotlib學(xué)習(xí)筆記之plt.xticks()用法

    Matplotlib學(xué)習(xí)筆記之plt.xticks()用法

    在matplotlib中ticks表示的是刻度,而刻度有兩層意思,一個(gè)是刻標(biāo)(locs),一個(gè)是刻度標(biāo)簽(tick?labels),下面這篇文章主要給大家介紹了關(guān)于Matplotlib學(xué)習(xí)筆記之plt.xticks()用法的相關(guān)資料,需要的朋友可以參考下
    2022-09-09
  • 微信跳一跳游戲python腳本

    微信跳一跳游戲python腳本

    這篇文章主要為大家詳細(xì)介紹了微信跳一跳游戲python腳本,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-01-01
  • Pytorch關(guān)于Dataset?的數(shù)據(jù)處理

    Pytorch關(guān)于Dataset?的數(shù)據(jù)處理

    這篇文章主要介紹了Pytorch關(guān)于Dataset?的數(shù)據(jù)處理,學(xué)習(xí)如何對卷積神經(jīng)網(wǎng)絡(luò)編程;首先,需要了解Pytorch對數(shù)據(jù)的使用,也是在我們模型流程中對數(shù)據(jù)的預(yù)處理部分,下面我們就一起進(jìn)入文章查看具體處理過程吧
    2021-12-12
  • 詳解Python判定IP地址合法性的三種方法

    詳解Python判定IP地址合法性的三種方法

    這篇文章主要介紹了詳解Python判定IP地址合法性的三種方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-03-03
  • 給ubuntu18安裝python3.7的詳細(xì)教程

    給ubuntu18安裝python3.7的詳細(xì)教程

    這篇文章主要介紹了給ubuntu18安裝python3.7的詳細(xì)教程,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-06-06

最新評(píng)論