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)