pytorch中使用torch.no_grad()和torch.enable_grad()控制梯度计算的方法

一、 torch.no_grad()

方法1:使用with torch.no_grad()控制requires_grad属性的作用域。

import torch 

x = torch.ones(2,2,requires_grad=True)

y = x**2
print(x.requires_grad)

with torch.no_grad():
    z = x**2
    print(z.requires_grad)

b = x**2
print(b.requires_grad)

输出:
True
False
True

方法2:使用 @ 装饰器和 torch.no_grad()控制requires_grad作用域,限制函数级别的运算梯度,使张量的requires_grad失效

import torch 

@torch.no_grad()        # 装饰器,无梯度
def doubler(x):
    return x*2

x = torch.ones(2,2,requires_grad=True)

y = doubler(x)
print(y.requires_grad)

def doubler2(x):        # 不带装饰器,有梯度
    return x*2

z = doubler2(x)
print(z.requires_grad)

输出:
False
True

二、torch.enable_grad()

方法1:使用with torch.enable_grad()控制requires_grad作用域

import torch 

x = torch.ones(2,2,requires_grad=True)

with torch.no_grad():
    with torch.enable_grad():
        z = x**2
print(z.requires_grad)

方法2: 使用装饰器 @torch.enable_grad()装饰函数后,该函数不再受with torch.no_grad()的影响

import torch 

@torch.enable_grad()        
def doubler(x):
    return x*2

x = torch.ones(2,2,requires_grad=True)
with torch.no_grad():
    y = doubler(x)
print(y.requires_grad)

输出:
True

翻译自:李金洪老师的基于Bert的语言处理实战

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值