张量自动微分及vector-Jacobian
实例代码及注释如下
import torch
#初始化张量并为其设置操作跟踪
#完成计算后可以调用.backward()并自动计算所有渐变
#该张量的梯度将累积到.grad属性中。
#要阻止张量跟踪历史记录可以调用.detach()它将其从计算历史记录中分离出来
x = torch.ones(2, 2, requires_grad=True)
print(x)
#打印张量操作记录
y = x + 2
print(y)
print(y.grad_fn)
#操作案例
z = y * y * 3
out = z.mean()
print(z)
print(out)
#设置.requires_grad,默认为False
a = torch.randn(2, 2)
a = ((a * 3) / (a - 1))
print(a.requires_grad)
a.requires_grad_(True)
print(a.requires_grad)
b = (a * a).sum()
print(b.grad_fn)
#out.backward()相当于out.backward(torch.tensor(1.))
#输出梯度
out.backward()
print(x)
print(x.grad)
#vector-Jacobian计算
x = torch.randn(3, requires_grad=True)
y = x * 2
while y.data.norm() < 1000:
y = y * 2
print(y)
#torch.autograd无法在非标量上直接计算完整vector-Jacobian
#但如果只想要vector-Jacobian,只需将向量传递给backward参数
v = torch.tensor([0.1, 1.0, 0.0001], dtype=torch.float)
y.backward(v)
print(x.grad)
#停止在Tensors上跟踪历史记录
print(x.requires_grad)
print((x ** 2).requires_grad)
with torch.no_grad():
print((x ** 2).requires_grad)
vector-Jacobian部分详解如下所示:
vector-Jacobian