Pytorch中torch.autograd ---backward函數的使用方法詳細解析,具體例子分析


 backward函數

官方定義:

torch.autograd.backward(tensorsgrad_tensors=Noneretain_graph=Nonecreate_graph=Falsegrad_variables=None)

Computes the sum of gradients of given tensors w.r.t. graph leaves.The graph is differentiated using the chain rule. If any of tensors are non-scalar (i.e. their data has more than one element) and require gradient, the function additionally requires specifying grad_tensors. It should be a sequence of matching length, that contains gradient of the differentiated function w.r.t. corresponding tensors (None is an acceptable value for all tensors that don’t need gradient tensors). This function accumulates gradients in the leaves - you might need to zero them before calling it.

翻譯和解釋:參數tensors如果是標量,函數backward計算參數tensors對於給定圖葉子節點的梯度( graph leaves,即為設置requires_grad=True的變量)。 

 參數tensors如果不是標量,需要另外指定參數grad_tensors參數grad_tensors必須和參數tensors的長度相同。在這一種情況下,backward實際上實現的是代價函數(loss = torch.sum(tensors*grad_tensors); 注:torch中向量*向量實際上是點積,因此tensors和grad_tensors的維度必須一致 )關於葉子節點的梯度計算,而不是參數tensors對於給定圖葉子節點的梯度。如果指定參數grad_tensors=torch.ones((size(tensors))),顯而易見,代價函數關於葉子節點的梯度,也就等於參數tensors對於給定圖葉子節點的梯度。

每次backward之前,需要注意葉子梯度節點是否清零,如果沒有清零,第二次backward會累計上一次的梯度。

 下面給出具體的例子:

1 import torch 2 x=torch.randn((3),dtype=torch.float32,requires_grad=True) 3 y = torch.randn((3),dtype=torch.float32,requires_grad=True) 4 z = torch.randn((3),dtype=torch.float32,requires_grad=True) 5 t = x + y 6 loss = t.dot(z)  #求向量的內積

在調用 backward 之前,可以先手動求一下導數,應該是: 

用代碼實現求導:

1 loss.backward(retain_graph=True) 2 print(z,x.grad,y.grad)  #預期打印出的結果都一樣
3 print(t,z.grad)    #預期打印出的結果都一樣
4 print(t.grad)    #在這個例子中,x,y,z就是葉子節點,而t不是,t的導數在backward的過程中求出來回傳之后就會被釋放,因而預期結果是None

結果和預期一致:

tensor([-2.6752,  0.2306, -0.8356], requires_grad=True) tensor([-2.6752,  0.2306, -0.8356]) tensor([-2.6752,  0.2306, -0.8356]) tensor([-1.1916, -0.0156,  0.8952], grad_fn=<AddBackward0>) tensor([-1.1916, -0.0156,  0.8952]) None

 敲重點:注意到前面函數的解釋中,在參數tensors不是標量的情況下,tensor.backward(grad_tensors)實現的是代價函數torch.sum(tensors*grad_tensors))關於葉子節點的導數。在上面例子中,loss = t.dot(z),因此用t.backward(z),實現的就是loss對於所有葉子結點的求導,實際運算結果和預期吻合。 

1 t.backward(z,retain_graph=True) 2 print(z,x.grad,y.grad) 3 print(t,z.grad)

運行結果如下:

tensor([-0.7830,  1.4468,  1.2440], requires_grad=True) tensor([-0.7830,  1.4468,  1.2440]) tensor([-0.7830,  1.4468,  1.2440]) tensor([-0.7145, -0.7598,  2.0756], grad_fn=<AddBackward0>) None

上面的結果中,出現了一個問題,雖然loss關於x和y的導數正確,但是z不再是葉子節點了。

問題1:當使用t.backward(z,retain_graph=True)的時候, print(z.grad)結果是None,這意味着z不再是葉子節點,這是為什么呢?

另外一個嘗試,loss = t.dot(z)=z.dot(t),但是如果用z.backward(t)替換t.backward(z,retain_graph=True),結果卻不同。

1 z.backward(t) 2 print(z,x.grad,y.grad) 3 print(t,z.grad)

運行結果:

tensor([-1.0716, -1.3643, -0.0016], requires_grad=True) None None tensor([-0.7324,  0.9763, -0.4036], grad_fn=<AddBackward0>) tensor([-0.7324,  0.9763, -0.4036])

問題2:上面的結果中可以看到,使用z.backward(t),x和y都不再是葉子節點了,z仍然是葉子節點,且得到的loss相對於z的導數正確。

 

上述仿真出現的兩個問題,我還不能解釋,希望和大家交流,我的郵箱yangyuwen_yang@126.com,歡迎來信討論。

問題1:當使用t.backward(z,retain_graph=True)的時候, print(z.grad)結果是None,這意味着z不再是葉子節點,這是為什么呢?

問題2:上面的結果中可以看到,使用z.backward(t),x和y都不再是葉子節點了,z仍然是葉子節點,且得到的loss相對於z的導數正確。

 
        
另外強調一下,每次backward之前,需要注意葉子梯度節點是否清零,如果沒有清零,第二次backward會累計上一次的梯度。
簡單的代碼可以看出:
1 #測試1,:對比上兩次單獨執行backward,此處連續執行兩次backward
2 t.backward(z,retain_graph=True)
3 print(z,x.grad,y.grad)
4 print(t,z.grad)
5 z.backward(t)
6 print(z,x.grad,y.grad)
7 print(t,z.grad)
8 # 結果x.grad,y.grad本應該是None,因為保留了第一次backward的結果而打印出上一次梯度的結果

tensor([-0.5590, -1.4094, -1.5367], requires_grad=True) tensor([-0.5590, -1.4094, -1.5367]) tensor([-0.5590, -1.4094, -1.5367])
tensor([-1.7914, 0.8761, -0.3462], grad_fn=<AddBackward0>) None
tensor([-0.5590, -1.4094, -1.5367], requires_grad=True) tensor([-0.5590, -1.4094, -1.5367]) tensor([-0.5590, -1.4094, -1.5367])
tensor([-1.7914, 0.8761, -0.3462], grad_fn=<AddBackward0>) tensor([-1.7914, 0.8761, -0.3462])

 1 #測試2,:連續執行兩次backward,並且清零,可以驗證第二次backward沒有計算x和y的梯度
 2 t.backward(z,retain_graph=True)
 3 print(z,x.grad,y.grad)
 4 print(t,z.grad)
 5 x.grad.data.zero_()
 6 y.grad.data.zero_()
 7 z.backward(t)
 8 print(z,x.grad,y.grad)
 9 print(t,z.grad)

tensor([ 0.8671, 0.6503, -1.6643], requires_grad=True) tensor([ 0.8671, 0.6503, -1.6643]) tensor([ 0.8671, 0.6503, -1.6643])
tensor([1.6231e+00, 1.3842e+00, 4.6492e-06], grad_fn=<AddBackward0>) None
tensor([ 0.8671, 0.6503, -1.6643], requires_grad=True) tensor([0., 0., 0.]) tensor([0., 0., 0.])
tensor([1.6231e+00, 1.3842e+00, 4.6492e-06], grad_fn=<AddBackward0>) tensor([1.6231e+00, 1.3842e+00, 4.6492e-06])


附參考學習的鏈接如下,並對作者表示感謝:

PyTorch 的 backward 為什么有一個 grad_variables 參數?
該話題在我的知乎專欄里同時轉載,歡迎更多討論交流,參見鏈接


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM