以下代码
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)
由于gradient
函数中的张量参数是一个与输入张量形状相同的全1张量,我的理解是
-
w.grad
表示y
对w
的导数,结果是b
, -
x.grad
表示y
对x
的导数,结果是b
, -
b.grad
表示y
对b
的导数,结果是全1。
在这三点中,只有第三点的答案与我的预期结果相符。有人能帮我理解前两个答案吗?我认为我理解了累积部分,但在这里似乎没有发生这种情况。
回答:
要在本例中找到正确的导数,我们需要考虑求和规则和乘积规则。
求和规则:
乘积规则:
这意味着你的方程的导数计算如下。
关于x的导数:
关于w的导数:
关于b的导数:
梯度完全反映了这些结果:
torch.equal(w.grad, x) # => Truetorch.equal(x.grad, w) # => Truetorch.equal(b.grad, torch.tensor([[1, 1], [1, 1]], dtype=torch.float64)) # => True