李沐大神 动手学深度学习 课程笔记
简单学习笔记,详情请阅读 https://zh-v2.d2l.ai/
import torch
矩阵求导 shape
pytorch 隐式构造图
x = torch.arange(4.0, requires_grad = True) #注意4.0,不能为4,需为tensor。
x
tensor([0., 1., 2., 3.], requires_grad=True)
y = 2* torch.dot(x, x)#x向量,y标量,同时记录y是从x计算过来( grad_fn=<MulBackward0> )
print(y)
tensor(28., grad_fn=<MulBackward0>)
y.backward() # 反向求导
x.grad == 4 * x
tensor([True, True, True, True])
# 默认情况 pytorch 会累积梯度,需清除之前的值
x.grad.zero_() #下划线为重写内容,把0写入; 若不清零,梯度会在原来基础上累加
y = x.sum()
y.backward()
x.grad
tensor([1., 1., 1., 1.])
# y 为向量时, 对非标量调用“backward”需要传入一个“gradient”参数,该参数指定微分函数
# 目的:计算batch中每个样本单独计算的偏导数之和。
x.grad.zero_()
y = x * x
y.sum().backward() #通过求和变为标量,等价于.backward(torch.ones(len(x)))
x.grad
tensor([0., 2., 4., 6.])
# 某些计算移到记录的计算图之外,把某些参数固定住
x.grad.zero_()
y = x * x
u = y.detach()
z = u * x
z.sum().backward()
x.grad == u
tensor([True, True, True, True])
# python控制流(条件,循环,任意函数调用)时,仍可求导.
# 在这一点上,隐式构造图比显式做的更好一些。快。
def f(a):
b = a * 2
while b.norm() < 1000:
b = b * 2
if b.sum() > 0:
c = b
else:
c = 100 * b
return c
a = torch.randn(size=(),requires_grad=True) #标量
d = f(a)
d.backward()
a.grad == d / a
tensor(True)