Pytorch學習(一)—— 自動求導機制


  現在對 CNN 有了一定的了解,同時在 GitHub 上找了幾個 examples 來學習,對網絡的搭建有了籠統地認識,但是發現有好多基礎 pytorch 的知識需要補習,所以慢慢從官網 API 進行學習吧。

AUTOGRAD MECHANICS(自動求導機制)

  這一部分做了解處理,不需要完全理解的明明白白的。

Excluding subgraphs from backward

  每一個 Tensor 變量都可以設置一個屬性:requires_grad(默認參數 False),可以設置此參數排除向后梯度求導時排除子圖,提高運行效率。

 1 import torch
 2 x = torch.randn(3, 3) # requires_grad=False by default
 3 y = torch.randn(3, 3)
 4 z = torch.randn(3, 3, requires_grad= True)
 5 
 6 a = x + y
 7 print(a.requires_grad) # False
 8 
 9 b = z + a
10 print(b.requires_grad) # True

  這個設置在如下情況很好用:你提前知道你不需要某個參數的梯度。例如,你需要微調網絡的時候,你只需要在最后一層將變量的 requires_grad 屬性切換一下,因為仿射裝換需要使用通過梯度調整的權重,而且輸出結果也需要它。

1 model = torchvision.models.resnet18(pretrained=True)
2 for param in model.parameters():
3     param.requires_grad = False  # 切換模式
4 # Replace the last fully-connected layer
5 # Parameters of newly constructed modules have requires_grad=True by default
6 model.fc = nn.Linear(512, 100)
7 
8 # Optimize only the classifier
9 optimizer = optim.SGD(model.fc.parameters(), lr=1e-2, momentum=0.9)

How autograd encodes the history(自動求導如何編碼歷史信息)

  Autograd is reverse automatic (反向自動) differentiation system.....(這段話有點難翻譯)。

  個人覺得關鍵是:When computing the forwards pass, autograd simultaneously performs the requested computations and builds up a graph representing the function that computes the gradient (the .grad_fn attribute of each torch.Tensor is an entry point into this graph)

  

In-place operations with autograd(自動求導中使用 in-place)

  在自動求導中支持 in-place 是件困難的事,在多數場合下我們並不鼓勵你使用。

In-place correctness checks(in-place 的正確性檢擦)

  每一個 tensor 變量都擁有版本計數器,每次被調用都會加一,當一個 Function 保留 tensor 用來向后計算時,也會保存這個版本計數器。當你訪問 self.saved_tensors 的時候,就會檢查版本計數器的值,如果大於計數器的值,就會報錯。

 

  


免責聲明!

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



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