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的容器才能进行梯度求导等等操作,代码如下:

1
2
3
4
5
6
7
8
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可以大胆地更改代码

 

 例如之前的代码可以改成

1
2
3
4
5
6
7
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)

  

posted on   lmqljt  阅读(320)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
历史上的今天:
2020-05-07 99乘法表

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示