阅读说明: 保留原笔记的编号与章节顺序;代码只供查看,没有在本站运行。历史输出不代表当前版本的复现结果。截图/外链图以独立整理的公式、表格、示意或文字替换;纠错与必要补充均作说明。
1. Tensor
import torchx = torch.ones(2, 4, requires_grad=True)
xtensor([[1., 1., 1., 1.],
[1., 1., 1., 1.]], requires_grad=True)
y = x + 2
ytensor([[3., 3., 3., 3.],
[3., 3., 3., 3.]], grad_fn=<AddBackward0>)
y.requires_gradTrue
We can change the property with tensor.requires_grad_() method.
x.requires_grad_(False)tensor([[1., 1., 1., 1.],
[1., 1., 1., 1.]])
x.gradprint(x.requires_grad, y.requires_grad)False True
2. Gradients
Note: x should be float in order to use autograd.
计算图独立重写: ,,,。这里平方是逐元素运算,输出j是标量。
x = torch.tensor([[1., 2., 3.], [4., 5., 6.]], requires_grad=True)
y = x + 1
z = 2 * y * y
j = torch.mean(z)Compute gradient
j.backward()x.gradtensor([[1.3333, 2.0000, 2.6667],
[3.3333, 4.0000, 4.6667]])
链式求导:
对x的六个元素1到6,梯度依次为4/3、2、8/3、10/3、4、14/3,与原输出相符。
Note:
一个计算图只能backward一次,在计算图backward之后,这个计算图就销毁了(节省内存)。
再次求导会报错。
整理注: backward通常释放反向计算需要的中间缓存,不是所有图结构都销毁;需要复用时可retain_graph=True,或重新做前向。梯度默认会累积。
在下面的计算图中,如果先对p求导(backward),求导之后,无法再对q进行求导。
共享中间节点: 若p与q都依赖同一前向中间量,先对p反向后,计算q可能还需已释放的缓存;可以首次backward保留图,或重新前向。求导的目标、累积梯度和释放缓存是三个不同概念。
实际计算需要保留计算图,添加retain_graph=True到backward。
You can stop autograd from tracking history on tensors by wrapping the conde block in with torch.no_grad().
x.requires_gradTrue
(x ** 2).requires_gradTrue
with torch.no_grad():
print((x ** 2).requires_grad)False
Or by using .detach() to get a new Tensor with the same content but that does not require gradients.
y = x.detach()
y.requires_gradFalse
x.eq(y).all()tensor(True)
教程出处
本篇部分示例对应PyTorch入门教程,整理时保留章节与代码,修正说明已标注。原许可见PyTorch tutorials BSD-3-Clause。