【PyTorch】PyTorch入门教程二
·
Variable
众所周知,PyTorch和TensorFlow最牛逼的地方就是自动求导术,而在PyTorch中运用这一“玄学”的就是Variable。一旦我们将网络结构,loss算法,优化策略等计算构建好之后,调用.backward()就可以自动求网络参数的导数。
Variable是对Tensor的一种封装,可以调用.data属性获取Tensor数据,导数也可以调用.grad获得。如果Variable是标量的话,就不需要求导。只有对变量进行某种操作或者函数定义,这个Variable才有求导行为,可以用.grad_fn获取求导行为。
import torch
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]
由于y是通过函数获得的,因此y是有.grad_fn属性的
print(y.grad_fn)
输出为
<torch.autograd.function.AddConstantBackward object at 0x7fd60e508148>
对y做更多的操作
z = y * y * 3
#对z求均值
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]
Gradients
out.backward()
print(x.grad)
输出为
Variable containing:
4.5000 4.5000
4.5000 4.5000
[torch.FloatTensor of size 2x2]
求导过程如下
更多推荐



所有评论(0)