0

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 项?),或者我不明白autogradTorch。

任何指针?

4

1 回答 1

2
do/dz = 1 / 4
dz/dy = 6y = 6 * 3 = 18
dy/dx = 1

因此,do/dx = 9/2

于 2020-01-11T08:05:50.767 回答