在Python 的 Torch 教程示例中,他们使用下图:
x = [[1, 1], [1, 1]]
y = x + 2
z = 3y^2
o = mean( z ) # 1/4 * x.sum()
因此,前向传球让我们知道:
x_i = 1, y_i = 3, z_i = 27, o = 27
在代码中,这看起来像:
import torch
# define graph
x = torch.ones(2, 2, requires_grad=True)
y = x + 2
z = y * y * 3
out = z.mean()
# if we don't do this, torch will only retain gradients for leaf nodes, ie: x
y.retain_grad()
z.retain_grad()
# does a forward pass
print(z, out)
但是,我对计算出的梯度感到困惑:
# now let's run our backward prop & get gradients
out.backward()
print(f'do/dz = {z.grad[0,0]}')
输出:
do/dx = 4.5
根据链式法则,do/dx = do/dz * dz/dy * dy/dx
,其中:
dy/dx = 1
dz/dy = 9/2 given x_i=1
do/dz = 1/4 given x_i=1
意思是:
do/dx = 1/4 * 9/2 * 1 = 9/8
但是,这与 Torch 返回的梯度 (9/2 = 4.5) 不匹配。也许我有一个数学错误(do/dz = 1/4 项?),或者我不明白autograd
Torch。
任何指针?