Pytorch学习(一)—— 自动求导机制
現(xiàn)在對 CNN 有了一定的了解,同時在 GitHub 上找了幾個 examples 來學(xué)習(xí),對網(wǎng)絡(luò)的搭建有了籠統(tǒng)地認(rèn)識,但是發(fā)現(xiàn)有好多基礎(chǔ) pytorch 的知識需要補習(xí),所以慢慢從官網(wǎng) API 進(jìn)行學(xué)習(xí)吧。
AUTOGRAD MECHANICS(自動求導(dǎo)機制)
這一部分做了解處理,不需要完全理解的明明白白的。
Excluding subgraphs from backward
每一個 Tensor 變量都可以設(shè)置一個屬性:requires_grad(默認(rèn)參數(shù) False),可以設(shè)置此參數(shù)排除向后梯度求導(dǎo)時排除子圖,提高運行效率。
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這個設(shè)置在如下情況很好用:你提前知道你不需要某個參數(shù)的梯度。例如,你需要微調(diào)網(wǎng)絡(luò)的時候,你只需要在最后一層將變量的?requires_grad 屬性切換一下,因為仿射裝換需要使用通過梯度調(diào)整的權(quán)重,而且輸出結(jié)果也需要它。
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(自動求導(dǎo)如何編碼歷史信息)
Autograd is?reverse?automatic (反向自動)?differentiation system.....(這段話有點難翻譯)。
個人覺得關(guān)鍵是: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(自動求導(dǎo)中使用 in-place)
在自動求導(dǎo)中支持 in-place 是件困難的事,在多數(shù)場合下我們并不鼓勵你使用。
In-place correctness checks(in-place 的正確性檢擦)
每一個 tensor 變量都擁有版本計數(shù)器,每次被調(diào)用都會加一,當(dāng)一個 Function 保留 tensor 用來向后計算時,也會保存這個版本計數(shù)器。當(dāng)你訪問 self.saved_tensors 的時候,就會檢查版本計數(shù)器的值,如果大于計數(shù)器的值,就會報錯。
?
轉(zhuǎn)載于:https://www.cnblogs.com/KongHuZi/p/10960998.html
總結(jié)
以上是生活随笔為你收集整理的Pytorch学习(一)—— 自动求导机制的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: angular学习笔记之父子传值
- 下一篇: python学习之函数的参数类型