以下代码
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
wrt的导数w
,并产生b
,
x.grad
表示y
wrt的导数x
,并产生b
和
b.grad
表示y
wrt的导数b
,并产生所有的。
其中,只有第3点答案与我的预期结果相符。有人可以帮助我理解前两个答案吗?我想我了解积累部分,但是不要认为这里正在发生。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句