Pytorch反向求導更新網(wǎng)絡參數(shù)的方法
更新時間:2019年08月17日 17:57:56 作者:tsq292978891
今天小編就為大家分享一篇Pytorch反向求導更新網(wǎng)絡參數(shù)的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
方法一:手動計算變量的梯度,然后更新梯度
import torch from torch.autograd import Variable # 定義參數(shù) w1 = Variable(torch.FloatTensor([1,2,3]),requires_grad = True) # 定義輸出 d = torch.mean(w1) # 反向求導 d.backward() # 定義學習率等參數(shù) lr = 0.001 # 手動更新參數(shù) w1.data.zero_() # BP求導更新參數(shù)之前,需先對導數(shù)置0 w1.data.sub_(lr*w1.grad.data)
一個網(wǎng)絡中通常有很多變量,如果按照上述的方法手動求導,然后更新參數(shù),是很麻煩的,這個時候可以調用torch.optim
方法二:使用torch.optim
import torch from torch.autograd import Variable import torch.nn as nn import torch.optim as optim # 這里假設我們定義了一個網(wǎng)絡,為net steps = 10000 # 定義一個optim對象 optimizer = optim.SGD(net.parameters(), lr = 0.01) # 在for循環(huán)中更新參數(shù) for i in range(steps): optimizer.zero_grad() # 對網(wǎng)絡中參數(shù)當前的導數(shù)置0 output = net(input) # 網(wǎng)絡前向計算 loss = criterion(output, target) # 計算損失 loss.backward() # 得到模型中參數(shù)對當前輸入的梯度 optimizer.step() # 更新參數(shù)
注意:torch.optim只用于參數(shù)更新和對參數(shù)的梯度置0,不能計算參數(shù)的梯度,在使用torch.optim進行參數(shù)更新之前,需要寫前向與反向傳播求導的代碼
以上這篇Pytorch反向求導更新網(wǎng)絡參數(shù)的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Python實現(xiàn)常見網(wǎng)絡通信的示例詳解
這篇文章主要為大家詳細介紹了Python實現(xiàn)常見網(wǎng)絡通信的相關方法,文中的示例代碼講解詳細,感興趣的小伙伴就跟隨小編一起學習一下吧2025-04-04

