pytorch autograd模块

pytorch autograd模块

pytorch中张量分为可导张量和不可导张量,即requires_grad参数是否为TRUE,默认是False。注意,可导张量计算得出的新张量也是可导的,不可导张量计算的出的新张量也是不可导的。

本质上就是两个模块,一个是backward()函数,一个是grad参数。

import torch

a = torch.tensor(23,requires_grad=True, dtype=torch.float32)
# a是可导的,b也是可导的。
b = a * 2
b.backward()
a.grad
'''
tensor(2.)
'''

其中requires_grad参数表示张量是否需要进行微分,如果对某段代码中所有的变量都设置成不需要微分,那么有三种方式。

方式一:with torch.no_grad():在with范围内,所有由可导张量计算得出新张量都不可导。

import torchimport torch

a = torch.tensor(10, requires_grad=True, dtype=torch.float32)
with torch.no_grad():
    b = a * 2
c = a * 2
print(a.requires_grad, b.requires_grad, c.requires_grad)
'''
True False True
'''

方式二:@torch.no_grad():在函数范围内

@torch.no_grad()
def test(x):
    b = x * 2
    # b不可导。
    print(b.requires_grad)
    return x ** 2
# 返回的新张量也不可导。
print(test(a).requires_grad)
'''
False
False
'''

方式三:torch.set_grad_enabled(False),除了声明可导张量以外,所有新生成的张量均不可导。torch.set_grad_enabled(True),恢复成默认状态。

torch.set_grad_enabled(False)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值