Python之torch.no_grad()函數(shù)使用和示例
torch.no_grad()函數(shù)使用和示例
torch.no_grad() 是 PyTorch 中的一個上下文管理器,用于在進(jìn)入該上下文時禁用梯度計算。
這在你只關(guān)心評估模型,而不是訓(xùn)練模型時非常有用,因為它可以顯著減少內(nèi)存使用并加速計算。
當(dāng)你在 torch.no_grad() 上下文管理器中執(zhí)行張量操作時,PyTorch 不會為這些操作計算梯度。
這意味著不會在 .grad 屬性中累積梯度,并且操作會更快地執(zhí)行。
使用torch.no_grad()
import torch
# 創(chuàng)建一個需要梯度的張量
x = torch.tensor([1.0], requires_grad=True)
# 使用 no_grad() 上下文管理器
with torch.no_grad():
y = x * 2
y.backward()
print(x.grad)
輸出:
RuntimeError Traceback (most recent call last)
Cell In[52], line 11
7 with torch.no_grad():
8 y = x * 2
---> 11 y.backward()
13 print(x.grad)File E:\anaconda\lib\site-packages\torch\_tensor.py:396, in Tensor.backward(self, gradient, retain_graph, create_graph, inputs)
387 if has_torch_function_unary(self):
388 return handle_torch_function(
389 Tensor.backward,
390 (self,),
(...)
394 create_graph=create_graph,
395 inputs=inputs)
--> 396 torch.autograd.backward(self, gradient, retain_graph, create_graph, inputs=inputs)File E:\anaconda\lib\site-packages\torch\autograd\__init__.py:173, in backward(tensors, grad_tensors, retain_graph, create_graph, grad_variables, inputs)
168 retain_graph = create_graph
170 # The reason we repeat same the comment below is that
171 # some Python versions print out the first line of a multi-line function
172 # calls in the traceback and some print out the last line
--> 173 Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass
174 tensors, grad_tensors_, retain_graph, create_graph, inputs,
175 allow_unreachable=True, accumulate_grad=True)RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
輸出錯誤,因為使用了with torch.no_grad():。
不使用torch.no_grad()
import torch # 創(chuàng)建一個需要梯度的張量 x = torch.tensor([1.0], requires_grad=True) # 使用 no_grad() 上下文管理器 y = x * 2 y.backward() print(x.grad)
輸出:
tensor([2.])
@torch.no_grad()
with torch.no_grad()或者@torch.no_grad()中的數(shù)據(jù)不需要計算梯度,也不會進(jìn)行反向傳播
model.eval() with torch.no_grad(): ...
等價于
@torch.no_grad()
def eval():
...總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
解決python寫的windows服務(wù)不能啟動的問題
使用py2exe生成windows服務(wù)在win7下可以正常運(yùn)行,但是到了xp下面可以安裝,但是無法啟動2014-04-04
深入理解Python虛擬機(jī)中浮點數(shù)(float)的實現(xiàn)原理及源碼
在本篇文章當(dāng)中主要分析在 cpython 虛擬機(jī)當(dāng)中 float 類型的實現(xiàn)原理以及與他相關(guān)的一些源代碼,文中的示例代碼講解詳細(xì),感興趣的可以了解一下2023-03-03
python 列表遞歸求和、計數(shù)、求最大元素的實例
今天小編就為大家分享一篇python 列表遞歸求和、計數(shù)、求最大元素的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-11-11
python中pyplot基礎(chǔ)圖標(biāo)函數(shù)整理
在本篇文章里小編給大家整理的是一篇關(guān)于python中pyplot基礎(chǔ)圖標(biāo)函數(shù)整理的相關(guān)知識點,有興趣的朋友們可以參考下。2020-11-11

