pytorch實現(xiàn)梯度下降和反向傳播圖文詳細講解
反向傳播
這里說一下我的理解,反向傳播是相對于前向計算的,以公式J(a,b,c)=3(a+bc)為例,前向計算相當于向右計算J(a,b,c)的值,反向傳播相當于反過來通過y求變量a,b,c的導數(shù),如下圖
手動完成線性回歸
import torch import numpy as np from matplotlib import pyplot as plt """ 假設模型為y=w*x+b 我們給出的訓練數(shù)據(jù)是通過y=3*x+1,得到的,其中w=3,b=1 通過訓練y=w*x+b觀察訓練結(jié)果是否接近于w=3,b=1 """ # 設置學習率 learning_rate=0.01 #準備數(shù)據(jù) x=torch.rand(500,1) #隨機生成500個x作為訓練數(shù)據(jù) y_true=x*3+1 #根據(jù)模型得到x對應的y的實際值 #初始化參數(shù) w=torch.rand([1,1],requires_grad=True) #初始化w b=torch.rand(1,requires_grad=True,dtype=torch.float32) #初始化b #通過循環(huán),反向傳播,更新參數(shù) for i in range(2000): # 通過模型計算y_predict y_predict=torch.matmul(x,w)+b #根據(jù)模型得到預測值 #計算loss loss=(y_true-y_predict).pow(2).mean() #防止梯度累加,每次計算梯度前都將其置為0 if w.grad is not None: w.grad.data.zero_() if b.grad is not None: b.grad.data.zero_() #通過反向傳播,記錄梯度 loss.backward() #更新參數(shù) w.data=w.data-learning_rate*w.grad b.data=b.data-learning_rate*b.grad # 這里打印部分值看一看變化 if i%50==0: print("w,b,loss:",w.item(),b.item(),loss.item()) #設置圖像的大小 plt.figure(figsize=(20,8)) #將真實值用散點表示出來 plt.scatter(x.numpy().reshape(-1),y_true.numpy().reshape(-1)) #將預測值用直線表示出來 y_predict=torch.matmul(x,w)+b plt.plot(x.numpy().reshape(-1),y_predict.detach().numpy().reshape(-1),c="r") #顯示圖像 plt.show()
pytorch API完成線性回歸
優(yōu)化器類
優(yōu)化器(optimizer),可以理解為torch為我們封裝的用來進行更新參數(shù)的方法,比如常見的隨機梯度下降(stochastic gradient descent,SGD)
優(yōu)化器類都是由torch.optim提供的,例如
- torch.optim.SGD(參數(shù),學習率)
- torch.optim.Adam(參數(shù),學習率)
注意:
- 參數(shù)可以使用model.parameters()來獲取,獲取模型中所有requires_grad=True的參數(shù)
- 優(yōu)化類的使用方法
①實例化
②所有參數(shù)的梯度,將其置為0
③反向傳播計算梯度
④更新參數(shù)值
實現(xiàn)
import torch from torch import nn from torch import optim from matplotlib import pyplot as plt import numpy as np # 1.定義數(shù)據(jù),給出x x=torch.rand(50,1) # 假定模型為y=w*x+b,根據(jù)模型給出真實值y=x*3+0.8 y=x*3+0.8 # print(x) #2.定義模型 class Lr(torch.nn.Module): def __init__(self): super(Lr, self).__init__() self.linear = torch.nn.Linear(1, 1) def forward(self, x): out = self.linear(x) return out # 3.實例化模型、loss、優(yōu)化器 model=Lr() criterion=nn.MSELoss() # print(list(model.parameters())) optimizer=optim.SGD(model.parameters(),lr=1e-3) # 4.訓練模型 for i in range(30000): out=model(x) #獲取預測值 loss=criterion(y,out) #計算損失 optimizer.zero_grad() #梯度歸零 loss.backward() #計算梯度 optimizer.step() #更新梯度 if (i+1)%100 ==0: print('Epoch[{}/{}],loss:{:.6f}'.format(i,30000,loss.data)) # 5.模型評估 model.eval() #設置模型為評估模式,即預測模式 predict=model(x) predict=predict.data.numpy() plt.scatter(x.data.numpy(),y.data.numpy(),c="r") plt.plot(x.data.numpy(),predict) plt.show()
到此這篇關于pytorch實現(xiàn)梯度下降和反向傳播圖文詳細講解的文章就介紹到這了,更多相關pytorch梯度下降和反向傳播內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python通過socket搭建極簡web服務器的實現(xiàn)代碼
python的web框架眾多,常見的如django、flask、tornado等,其底層是什么還是有些許的疑問,所以查找相關資料,實現(xiàn)瀏覽器訪問,并返回相關信息,本文將給大家介紹python通過socket搭建極簡web服務器,需要的朋友可以參考下2023-10-10python?操作?mongodb?數(shù)據(jù)庫詳情
這篇文章主要介紹了python?操作?mongodb?數(shù)據(jù)庫詳情,通過鏈接數(shù)據(jù)庫,創(chuàng)建數(shù)據(jù)庫展開內(nèi)容詳細,具有一定的參考價值,需要的的小伙伴可以參考一下2022-04-04如何通過神經(jīng)網(wǎng)絡實現(xiàn)線性回歸的擬合
這篇文章主要介紹了如何通過神經(jīng)網(wǎng)絡實現(xiàn)線性回歸的擬合問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05python如何通過twisted實現(xiàn)數(shù)據(jù)庫異步插入
這篇文章主要為大家詳細介紹了python如何通過twisted實現(xiàn)數(shù)據(jù)庫異步插入,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-03-03