当前位置:首页 » 《随便一记》 » 正文

【Python】torch.no_grad()函数详解和示例

6 人参与  2024年03月12日 12:11  分类 : 《随便一记》  评论

点击全文阅读


torch.no_grad() 是 PyTorch 中的一个上下文管理器,用于在进入该上下文时禁用梯度计算。这在你只关心评估模型,而不是训练模型时非常有用,因为它可以显著减少内存使用并加速计算。

当你在 torch.no_grad() 上下文管理器中执行张量操作时,PyTorch 不会为这些操作计算梯度。这意味着不会在 .grad 属性中累积梯度,并且操作会更快地执行。

使用torch.no_grad()

import torch# 创建一个需要梯度的张量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# 创建一个需要梯度的张量x = torch.tensor([1.0], requires_grad=True)# 使用 no_grad() 上下文管理器y = x * 2y.backward()print(x.grad)

输出:

tensor([2.])

点击全文阅读


本文链接:http://www.zhangshiyu.com/post/78218.html

<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

最新文章

  • 丁榆:结局+番外看点十足(和渣男小叔叔的游戏日常)全书无套路阅读
  • 法医狂妃:王爷你命中缺我小说(苏七夜景辰)全本完整阅读最新章节(法医狂妃:王爷你命中缺我)_笔趣阁
  • (头条)洛甯陆乘渊小说(闪婚老公是卧底,消失三年回来了)整本免费版阅读无广告(洛甯陆乘渊)
  • 陆少今天又秀恩爱了吗后续(陆怀骁苏棠)(陆少今天又秀恩爱了吗)整本畅享在线+无广告结局
  • 独家江柏俊夏清恬无删减(重生之团长俊夫要离婚)(江柏俊夏清恬)TXT免费版阅读
  • 全网首发重生下乡嫁糙汉,渣男全家悔哭了彩蛋(师明凯颜惜雪)(重生下乡嫁糙汉,渣男全家悔哭了)全本完整阅读无弹窗
  • 我是让他不屑一顾,不愿多看一眼的路人小说(安喻意商晋深)(我是让他不屑一顾,不愿多看一眼的路人)在线畅读阅读连载中
  • 丁榆后续(和渣男小叔叔的游戏日常)全文在线下载在线+纯净版结局
  • 洛甯陆乘渊::结局+番外评价五颗星-闪婚老公是卧底,消失三年回来了:结局+番外新上热文
  • 前传孟流年周丽珍续集(孟流年周丽珍)终章阅读极简(孟流年周丽珍)
  • 夏语栀祁墨寒我们各归人海,此生,也不必再见彩蛋小说结尾+附加(我们各归人海,此生,也不必再见)清爽版阅读
  • 重生下乡嫁糙汉,渣男全家悔哭了小说完结篇(师明凯颜惜雪)(重生下乡嫁糙汉,渣男全家悔哭了)全书无套路阅读无广告小说大结局

    关于我们 | 我要投稿 | 免责申明

    Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1