pytorch之with torch.no_grad
生活随笔
收集整理的這篇文章主要介紹了
pytorch之with torch.no_grad
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
在使用pytorch時,并不是所有的操作都需要進行計算圖的生成(計算過程的構(gòu)建,以便梯度反向傳播等操作)。而對于tensor的計算操作,默認是要進行計算圖的構(gòu)建的,在這種情況下,可以使用 with torch.no_grad():,強制之后的內(nèi)容不進行計算圖構(gòu)建。
下面針對是否使用torch.no_grad()做個實驗。
1. 不使用torch.no_grad()
2. 使用torch.no_grad()
import torchx = torch.arange(4.0) x.requires_grad_(True) # 強制之后的內(nèi)容不進行計算圖構(gòu)建 with torch.no_grad y = 2 * torch.dot(x, x)y.backward() # 報錯 RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn參考資料
總結(jié)
以上是生活随笔為你收集整理的pytorch之with torch.no_grad的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python算法基础教程_python算
- 下一篇: 多表操作查询 一对一