pytorch Variable與Tensor合并后 requires_grad()默認與修改方式
pytorch更新完后合并了Variable與Tensor
torch.Tensor()能像Variable一樣進行反向傳播的更新,返回值為Tensor
Variable自動創(chuàng)建tensor,且返回值為Tensor,(所以以后不需要再用Variable)
Tensor創(chuàng)建后,默認requires_grad=Flase
可以通過xxx.requires_grad_()將默認的Flase修改為True
下面附代碼及官方文檔代碼:
import torch from torch.autograd import Variable #使用Variabl必須調(diào)用庫 lis=torch.range(1,6).reshape((-1,3))#創(chuàng)建1~6 形狀 #行不指定(-1意為由計算機自己計算)列為3的floattensor矩陣 print(lis) print(lis.requires_grad) #查看默認的requires_grad是否是Flase lis.requires_grad_() #使用.requires_grad_()修改默認requires_grad為true print(lis.requires_grad)
結(jié)果如下:
tensor([[1., 2., 3.],
[4., 5., 6.]])
False
True
創(chuàng)建一個Variable,Variable必須接收Tensor數(shù)據(jù) 不能直接寫為 a=Variable(range(6)).reshape((-1,3))
否則報錯 Variable data has to be a tensor, but got range
正確如下:
import torch from torch.autograd import Variable tensor=torch.FloatTensor(range(8)).reshape((-1,4)) my_ten=Variable(tensor) print(my_ten) print(my_ten.requires_grad) my_ten.requires_grad_() print(my_ten.requires_grad)
結(jié)果:
tensor([[0., 1., 2., 3.],
[4., 5., 6., 7.]])
False
True
由上面可以看出,Tensor完全可以取代Variable。
下面給出官方文檔:
# 默認創(chuàng)建requires_grad = False的Tensor x = torch . ones ( 1 ) # create a tensor with requires_grad=False (default) x . requires_grad # out: False # 創(chuàng)建另一個Tensor,同樣requires_grad = False y = torch . ones ( 1 ) # another tensor with requires_grad=False # both inputs have requires_grad=False. so does the output z = x + y # 因為兩個Tensor x,y,requires_grad=False.都無法實現(xiàn)自動微分, # 所以操作(operation)z=x+y后的z也是無法自動微分,requires_grad=False z . requires_grad # out: False # then autograd won't track this computation. let's verify! # 因而無法autograd,程序報錯 z . backward ( ) # out:程序報錯:RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn # now create a tensor with requires_grad=True w = torch . ones ( 1 , requires_grad = True ) w . requires_grad # out: True # add to the previous result that has require_grad=False # 因為total的操作中輸入Tensor w的requires_grad=True,因而操作可以進行反向傳播和自動求導(dǎo)。 total = w + z # the total sum now requires grad! total . requires_grad # out: True # autograd can compute the gradients as well total . backward ( ) w . grad #out: tensor([ 1.]) # and no computation is wasted to compute gradients for x, y and z, which don't require grad # 由于z,x,y的requires_grad=False,所以并沒有計算三者的梯度 z . grad == x . grad == y . grad == None # True existing_tensor . requires_grad_ ( ) existing_tensor . requires_grad # out:True
或者直接用Tensor創(chuàng)建時給定requires_grad=True
my_tensor = torch.zeros(3,4,requires_grad = True) my_tensor.requires_grad # out: True
lis=torch.range(1,6,requires_grad=True).reshape((-1,3)) print(lis) print(lis.requires_grad) lis.requires_grad_() print(lis.requires_grad)
結(jié)果
tensor([[1., 2., 3.],
[4., 5., 6.]], requires_grad=True)
True
True
補充:volatile 和 requires_grad在pytorch中的意思
Backward過程中排除子圖
pytorch的BP過程是由一個函數(shù)決定的,loss.backward(), 可以看到backward()函數(shù)里并沒有傳要求誰的梯度。那么我們可以大膽猜測,在BP的過程中,pytorch是將所有影響loss的Variable都求了一次梯度。
但是有時候,我們并不想求所有Variable的梯度。那就要考慮如何在Backward過程中排除子圖(ie.排除沒必要的梯度計算)。
如何BP過程中排除子圖? Variable的兩個參數(shù)(requires_grad和volatile)
requires_grad=True 要求梯度
requires_grad=False 不要求梯度
volatile=True相當于requires_grad=False。反之則反之。。。。。。。ok
注意:如果a是requires_grad=True,b是requires_grad=False。則c=a+b是requires_grad=True。同樣的道理應(yīng)用于volatile
為什么要排除子圖
也許有人會問,梯度全部計算,不更新的話不就得了。
這樣就涉及了效率的問題了,計算很多沒用的梯度是浪費了很多資源的(時間,計算機內(nèi)存)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
Python基礎(chǔ)數(shù)據(jù)類型tuple元組的概念與用法
元組(tuple)是 Python 中另一個重要的序列結(jié)構(gòu),和列表類似,元組也是由一系列按特定順序排序的元素組成,這篇文章主要給大家介紹了關(guān)于Python基礎(chǔ)數(shù)據(jù)類型tuple元組的概念與使用方法,需要的朋友可以參考下2021-07-07VS2019+python3.7+opencv4.1+tensorflow1.13配置詳解
這篇文章主要介紹了VS2019+python3.7+opencv4.1+tensorflow1.13配置詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04在keras中對單一輸入圖像進行預(yù)測并返回預(yù)測結(jié)果操作
這篇文章主要介紹了在keras中對單一輸入圖像進行預(yù)測并返回預(yù)測結(jié)果操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07PID原理與python的簡單實現(xiàn)和調(diào)參
這篇文章主要介紹了PID原理與python的簡單實現(xiàn)和調(diào)參文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值。感興趣的小伙伴可以參考一下2022-08-08