下面的代码是关于pytorch的,它是关于派生的,我认为输出是18,但它是4.5,我不知道为什么:
import torch
x = torch.ones(2, 2, requires_grad=True)
y = x + 2
z = y * y * 3
out = z.mean()
out.backward()
print(x.grad)
输出:张量([[4.5000,4.5000],[4.5000,4.5000]])
I think the derivative is 2*3*(1+2), so it should be:
tensor([[18, 18],
[18, 18]])
为什么输出为4.5?有人认为使导数为/ 4的方法是平均值,但是当我执行代码“ print(out)”时,输出为“ tensor(27。,grad_fn =)”,而不是(4.5。,grad_fn =),我是pytorch的新手,所以我不知道它对“ tensor.mean()”的作用,但是由于“ print(out)”的输出为27,所以我认为没有“ tensor.mean()”中的“ / 4”过程,所以我不认为它应该在导数计算中包括“ / 4”过程,对吗?(请帮帮我〜)
这是我的看法:
y = x + 2
并且z = y * y * 3
,因此z为3 * (x+2)^2
接下来,out = z.mean()
或者sigma z / n
这是sigma z/4
因为我们在Z A共4个号码的了。
因此,(3 * (x + 2)^2)/4
在x = 1处找到sigma的导数。在x = 1处得出(3/4) * 2(x + 2)
4.5
因此,我认为您已经解决了所有问题,但是在最后一步中,您错过了除以4的操作,这是必需的,因为其中有一个mean()函数。
编辑:由于您对mean()如何影响输出感到困惑,所以让我们做一个张量[1,2,3,4]的张量,而不是torch.ones()
看效果。
x = torch.tensor([1.0,2.0,3.0,4.0], requires_grad=True)
y = x + 2
z = y * y * 3
out = z.mean()
out.backward()
print(x.grad)
这将输出
tensor([4.5000, 6.0000, 7.5000, 9.0000])
怎么样?请记住,我们导出的导数方程为:(3/4) * 2(x + 2)
现在,将x代入1,得到4.500。
然后对于x = 2,您将获得6.000,对于x = 3,您将获得7.500,依此类推。
在前面的示例中,您有四个x = 1的实例,这就是为什么x.grad为[[4.5,4.5],[4.5,4.5]]的原因
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句