Pytorch 自动求梯度 2

From 60 Minute Blitz
这一节学习Pytorch求梯度。

Variable

autograd.Variable是核心包,打包一个张量,定义几乎所有的张量操作。计算完后,调用.backward()可以自动求导.
.data属性可以查看张量,.grad查看导数。

Variable

另一个重要且可以自动计算导数的实现函数是Function
VariableFunction相互配合,组成一个无向图,用于编码一次计算。每个变量有一个.creator属性,用于记录参考函数(用户创造的变量除外)。
计算导数调用.backward()。如果它是标量,则不需要指定backward(),但需要额外指定grad_output,用于匹配张量的形状。

from torch.autograd import Variable
x = Variable(torch.ones(2,2), requires_grad=True)
print x
Variable containing:
 1  1
 1  1
[torch.FloatTensor of size 2x2]
y = x + 2
print y
Variable containing:
 3  3
 3  3
[torch.FloatTensor of size 2x2]
print y.grad_fn
<torch.autograd._functions.basic_ops.AddConstant object at 0x7f4910ac7220>
>>> z = y * y * 3
>>> out = z.mean()
>>> print (z,out)
(Variable containing:
 27  27
 27  27
[torch.FloatTensor of size 2x2]
, Variable containing:
 27
[torch.FloatTensor of size 1]
)

这个求导也很简单,
[图片上传失败...(image-90e567-1512569250845)]
[图片上传失败...(image-654be4-1512569250845)]^2)
[图片上传失败...(image-ac2257-1512569250845)]

梯度

使用out.backward()out.backward(torch.Tensor([1.0]))等价

out.backward()
print x.grad
Variable containing:
 4.5000  4.5000
 4.5000  4.5000
[torch.FloatTensor of size 2x2]
x = torch.randn(3)
x = Variable(x, requires_grad=True)
y = x * 2
while y.data.norm() < 1000:
     y = y * 2
print x 
print y
Variable containing:
 0.2498
-0.2275
-0.0349
[torch.FloatTensor of size 3]

Variable containing:
 1023.3572
 -931.9229
 -142.9044
[torch.FloatTensor of size 3]

输出 x.grad()

gradient = torch.FloatTensor([0.1, 1., 0.0001])
y.backward(gradient)
print x.grad
Variable containing:
  409.6000
 4096.0000
    0.4096
[torch.FloatTensor of size 3]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容