PyTorch的Variable已经不需要用了!!!


转载自:https://blog.csdn.net/rambo_csdn_123/article/details/119056123

Pytorch的torch.autograd.Variable
今天在看《莫凡Python》的PyTorch教程的时候发现他的代码还在使用Variable,并且我记得过去读一些GitHub上面的代码的时候也发现了Variable这个东西,根据教程中所说的,想要计算tensor的梯度等等,就必须将tensor放入Variable中并指定required_grad的值为True,通过这个Variable的容器才能进行梯度求导等等操作,代码如下:

import torch
from torch.autograd import Variable

tensor = torch.FloatTensor([[1, 2], [3, 4]])
variable = Variable(tensor, requires_grad=True)
v_out = torch.mean(variable * variable)
v_out.backward()
print(variable.grad)

  在我查阅PyTorch的官方文档之后,发现Variable已经被放弃使用了,因为tensor自己已经支持自动求导的功能了,只要把requires_grad属性设置成True就可以了,所以下次见到Variable可以大胆地更改代码

 例如之前的代码可以改成

import torch

tensor = torch.FloatTensor([[1, 2], [3, 4]])
tensor.requires_grad = True  # 这个尤其重要!!!
t_out = torch.mean(tensor * tensor)
t_out.backward()
print(tensor.grad)