新版本torch中Variable和Tensor合并
Variable和Tensor
import torch from torch.autograd import Variable # torch 中 Variable 模块 tensor = torch.FloatTensor([[1,2],[3,4]]) variable = Variable(tensor) print(tensor) print(variable)
结果如下:
tensor([[1., 2.], [3., 4.]]) tensor([[1., 2.], [3., 4.]])
发现tensor和variable输出的形式是一样的,在新版本的torch中可以直接使用tensor而不需要使用variable。
在旧版本中variable和tensor的区别在于,variable可以进行误差的反向传播,而tensor不可以。
接下来看一下,合并Tensor和Variable之后autograd
是如何实现历史追踪和反向传播的
作为能否autograd
的标签,requires_grad
现在是Tensor的属性,所以,只要当一个操作(operation)的任何输入Tensor
具有requires_grad = True
的属性,autograd
就可以自动追踪历史和反向传播了。
官方给出的具体例子如下:
# 默认创建requires_grad = False的Tensor x = torch.ones(1) # create a tensor with requires_grad=False (default) x.requires_grad # out: False # 创建另一个Tensor,同样requires_grad = False y = torch.ones(1) # another tensor with requires_grad=False # both inputs have requires_grad=False. so does the output z = x + y # 因为两个Tensor x,y,requires_grad=False.都无法实现自动微分, # 所以操作(operation)z=x+y后的z也是无法自动微分,requires_grad=False z.requires_grad # out: False # then autograd won't track this computation. let's verify! # 因而无法autograd,程序报错 z.backward() # out:程序报错:RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn # now create a tensor with requires_grad=True w = torch.ones(1, requires_grad=True) w.requires_grad # out: True # add to the previous result that has require_grad=False # 因为total的操作中输入Tensor w的requires_grad=True,因而操作可以进行反向传播和自动求导。 total = w + z # the total sum now requires grad! total.requires_grad # out: True # autograd can compute the gradients as well total.backward() w.grad #out: tensor([ 1.]) # and no computation is wasted to compute gradients for x, y and z, which don't require grad # 由于z,x,y的requires_grad=False,所以并没有计算三者的梯度 z.grad == x.grad == y.grad == None # True