自动求导属性
import torch
#设置自动求导
a = torch.rand((2,4), requires_grad=True)
print (a)
#查看自动求导属性
print (a.requires_grad)
#改变自动求导属性
a.requires_grad_(False)
print (a.requires_grad)
tensor([[0.9605, 0.0482, 0.1256, 0.1872],
[0.2282, 0.2772, 0.7683, 0.7361]], requires_grad=True)
True
False
自动反向求导
x = torch.tensor([[1., 2., 3.],
[4., 5., 6.]], requires_grad=True)
y = x + 1
z = 2 * y * y
J = torch.mean(z)
#进行反向求导
J.backward()
#查看梯度
x.grad
tensor([[1.3333, 2.0000, 2.6667],
[3.3333, 4.0000, 4.6667]])
grad can be implicitly created only for scalar outputs
张量反向求导时,backward函数需要传入相同大小的权重张量
x = torch.tensor([[1., 2., 3.],
[4., 5., 6.]], requires_grad=True)
y = x + 1
z = 2 * y * y
J = torch.mean(z)
#报错 grad can be implicitly created only for scalar outputs
#z.backward()
#传入相同尺度的权重张量
z.backward(torch.ones_like(z))
x.grad
tensor([[ 8., 12., 16.],
[20., 24., 28.]])
计算图
- 如果某一Tensor的requires_grad属性设置为True,则依赖其的Tensor的requires_grad属性也为True
- 在计算图中,只有叶节点会保存其grad值,其他节点的grad值,会在叶节点的grad值计算完后,释放。
x = torch.tensor([[1., 2., 3.],
[4., 5., 6.]], requires_grad=True)
y = x + 1
z = 2 * y * y
J = torch.mean(z)
#y, z, J都未设置requires_grad, 但他们由x计算得出,
#所以requires_grad均为True
print (x.requires_grad)
print (y.requires_grad)
print (z.requires_grad)
print (J.requires_grad)
J.backward()
#非叶节点的梯度,会在叶节点梯度计算完后释放
print (x.grad)
print (y.grad)
print (z.grad)
print (J.grad)
True
True
True
True
tensor([[1.3333, 2.0000, 2.6667],
[3.3333, 4.0000, 4.6667]])
None
None
None