需要帮助理解 pytorch 中的梯度函数
Need help understanding the gradient function in 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)
由于 gradient
函数中的张量参数是输入张量形状的全一张量,我的理解是
w.grad
表示y
w.r.tw
的导数,产生b
、
x.grad
表示 y
w.r.t x
的导数,并产生 b
和
b.grad
表示y
w.r.tb
的导数,产生全1。
其中,只有第 3 点的答案符合我的预期结果。有人可以帮助我理解前两个答案。我想我理解积累部分,但我不认为这是在这里发生的。
为了在这个例子中找到正确的导数,我们需要考虑和和产品规则。
求和规则:
产品规则:
这意味着你的方程的导数计算如下。
相对于x:
相对于w:
相对于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
下面的代码
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
函数中的张量参数是输入张量形状的全一张量,我的理解是
w.grad
表示y
w.r.tw
的导数,产生b
、x.grad
表示y
w.r.tx
的导数,并产生b
和b.grad
表示y
w.r.tb
的导数,产生全1。
其中,只有第 3 点的答案符合我的预期结果。有人可以帮助我理解前两个答案。我想我理解积累部分,但我不认为这是在这里发生的。
为了在这个例子中找到正确的导数,我们需要考虑和和产品规则。
求和规则:
产品规则:
这意味着你的方程的导数计算如下。
相对于x:
相对于w:
相对于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