1. 程式人生 > 實用技巧 >Autograd與計算圖-04

Autograd與計算圖-04

  基本資料Tensor可以保證完成前向傳播, 想要完成神經網路的訓練, 接下來還需要進行反向傳播與梯度更新, 而PyTorch提供了自動求導機制autograd, 將前向傳播的計算記錄成計算圖, 自動完成求導。在PyTorch 0.4版本之前, Tensor僅僅是對多維陣列的抽象, 使用自動求導機制需要將Tensor封裝成torch.autograd.Variable型別, 才能構建計算圖。 PyTorch 0.4版本則將TensorVariable進行了整合, 以前Variable的使用情景都可以直接使用Tensor, 變得更簡單實用。

本節首先介紹Tensor的自動求導屬性, 然後對計算圖進行簡要的講解。

1. Tensor的自動求導: Autograd
 自動求導機制記錄了Tensor的操作, 以便自動求導與反向傳播。 可以通過requires_grad引數來建立支援自動求導機制的Tensor
 require_grad引數表示是否需要對該Tensor進行求導, 預設為False;設定為True則需要求導, 並且依賴於該Tensor的之後的所有節點都需要求導。 值得注意的是, 在PyTorch 0.4對於Tensor的自動求導中, volatile引數已經被其他torch.no_grad()等函式取代了。
 Tensor有兩個重要的屬性, 分別記錄了該Tensor的梯度與經歷的操作。
   grad: 該Tensor對應的梯度, 型別為Tensor, 並與Tensor同維度。

grad_fn: 指向function物件, 即該Tensor經過了什麼樣的操作, 用作反向傳播的梯度計算, 如果該Tensor由使用者自己建立, 則該grad_fnNone

 具體的引數使用示例如下:

 1 import torch
 2 
 3 a = torch.randn(2, 2, requires_grad=True)
 4 b = torch.randn(2, 2)
 5 
 6 # 可以看到預設的Tensor是不需要求導的, 設定requires_grad為True後則需要求導
 7 print(a.requires_grad)
 8 >> True
9 print(b.requires_grad) 10 >> False 11 12 # 也可以通過內建函式requires_grad_()將Tensor變為需要求導 13 print(b.requires_grad_()) 14 >> tensor([[ 1.3655, -1.5378], 15 [-0.2241, -1.4778]], requires_grad=True) 16 print(b.requires_grad) 17 >> True 18 19 # 通過計算生成的Tensor, 由於依賴的Tensor需要求導, 因此c也需要求導 20 c = a + b 21 print(c.requires_grad) 22 >> True 23 24 # a與b是自己建立的, grad_fn為None, 而c的grad_fn則是一個Add函式操作 25 print(a.grad_fn, b.grad_fn, c.grad_fn) 26 >> None None <AddBackward0 object at 0x7f5ae5a45390> 27 # detach就是截斷反向傳播的梯度流 28 d = c.detach() 29 print(d.requires_grad) 30 >> False
View Code

注意: 早些版本使用.data屬性來獲取資料, PyTorch 0.4中建議使用Tensor.detach()函式, 因為.data屬性在某些情況下不安全, 原因在於對.data生成的資料進行修改不會被autograd追蹤。 Tensor.detach()函式生成的資料預設requires_gradFalse