需要帮助理解pytorch中的梯度函数

use*_*142 2 python gradient machine-learning pytorch

以下代码


w = np.array([[2., 2.],[2., 2.]])
x = np.array([[3., 3.],[3., 3.]])
b = np.array([[4., 4.],[4., 4.]])
w = torch.tensor(w, requires_grad=True)
x = torch.tensor(x, requires_grad=True)
b = torch.tensor(b, requires_grad=True)


y = w*x + b 
print(y)
# tensor([[10., 10.],
#         [10., 10.]], dtype=torch.float64, grad_fn=<AddBackward0>)

y.backward(torch.FloatTensor([[1, 1],[ 1, 1]]))

print(w.grad)
# tensor([[3., 3.],
#         [3., 3.]], dtype=torch.float64)

print(x.grad)
# tensor([[2., 2.],
#         [2., 2.]], dtype=torch.float64)

print(b.grad)
# tensor([[1., 1.],
#         [1., 1.]], dtype=torch.float64)

Run Code Online (Sandbox Code Playgroud)

由于函数内的张量参数gradient是输入张量形状的全一张量,我的理解是

  1. w.grad表示ywrt 的导数w,并产生b,

  2. x.grad表示ywrt 的衍生物x,并产生b

  3. b.grad表示ywrt 的衍生物b,并产生所有的。

其中,只有第 3 点的答案符合我的预期结果。有人可以帮助我理解前两个答案。我想我理解积累部分,但不要认为这在这里发生。

Mic*_*ngo 5

为了在这个例子中找到正确的导数,我们需要考虑总和和乘积规则。

总和规则:

求和规则

产品规则:

产品规则

这意味着方程的导数计算如下。

关于x

关于 x 的导数

关于w

关于 w 的导数

关于b

关于 b 的导数

渐变正好反映了这一点:

torch.equal(w.grad, x) # => True

torch.equal(x.grad, w) # => True

torch.equal(b.grad, torch.tensor([[1, 1], [1, 1]], dtype=torch.float64)) # => True
Run Code Online (Sandbox Code Playgroud)