Python之torch.no_grad()函數(shù)使用和示例
torch.no_grad()函數(shù)使用和示例
torch.no_grad() 是 PyTorch 中的一個(gè)上下文管理器,用于在進(jìn)入該上下文時(shí)禁用梯度計(jì)算。
這在你只關(guān)心評(píng)估模型,而不是訓(xùn)練模型時(shí)非常有用,因?yàn)樗梢燥@著減少內(nèi)存使用并加速計(jì)算。
當(dāng)你在 torch.no_grad() 上下文管理器中執(zhí)行張量操作時(shí),PyTorch 不會(huì)為這些操作計(jì)算梯度。
這意味著不會(huì)在 .grad 屬性中累積梯度,并且操作會(huì)更快地執(zhí)行。
使用torch.no_grad()
import torch # 創(chuàng)建一個(gè)需要梯度的張量 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
輸出錯(cuò)誤,因?yàn)槭褂昧藈ith torch.no_grad():。
不使用torch.no_grad()
import torch # 創(chuàng)建一個(gè)需要梯度的張量 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ì)算梯度,也不會(huì)進(jìn)行反向傳播
model.eval() with torch.no_grad(): ...
等價(jià)于
@torch.no_grad() def eval(): ...
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
在Python的Flask框架下使用sqlalchemy庫的簡單教程
這篇文章主要介紹了在Python的Flask框架下使用sqlalchemy庫的簡單教程,用來簡潔地連接與操作數(shù)據(jù)庫,需要的朋友可以參考下2015-04-04Python抓新型冠狀病毒肺炎疫情數(shù)據(jù)并繪制全國疫情分布的代碼實(shí)例
在本篇文章里小編給大家整理了一篇關(guān)于Python抓新型冠狀病毒肺炎疫情數(shù)據(jù)并繪制全國疫情分布的代碼實(shí)例,有興趣的朋友們可以學(xué)習(xí)下。2020-02-02利用Python將每日一句定時(shí)推送至微信的實(shí)現(xiàn)方法
這篇文章主要給大家介紹了關(guān)于利用Python將每日一句定時(shí)推送至微信的實(shí)現(xiàn)方法,文中通過示例代碼將實(shí)現(xiàn)的步驟一步步介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-08-08Django報(bào)錯(cuò)TemplateDoesNotExist的問題及解決
這篇文章主要介紹了Django報(bào)錯(cuò)TemplateDoesNotExist的問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08python爬取網(wǎng)頁轉(zhuǎn)換為PDF文件
這篇文章主要為大家詳細(xì)介紹了python爬取網(wǎng)頁轉(zhuǎn)換為PDF文件,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-06-06Python使用SQLAlchemy操作Mysql數(shù)據(jù)庫的操作示例
SQLAlchemy是Python的SQL工具包和對(duì)象關(guān)系映射(ORM)庫,它提供了全套的企業(yè)級(jí)持久性模型,用于高效、靈活且優(yōu)雅地與關(guān)系型數(shù)據(jù)庫進(jìn)行交互,這篇文章主要介紹了Python使用SQLAlchemy操作Mysql數(shù)據(jù)庫,需要的朋友可以參考下2024-08-08TensorFlow人工智能學(xué)習(xí)張量及高階操作示例詳解
這篇文章主要為大家介紹了TensorFlow人工智能學(xué)習(xí)張量及高階操作的示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-11-11PyQT5 QTDesigner窗口及組成的實(shí)現(xiàn)
這篇文章主要介紹了PyQT5 QTDesigner窗口及組成的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04