pytorch 换版本_PyTorch 4.0版本迁移指南

PyTorch 0.4.0版本将Tensor和Variable合并,张量的type()改为使用isinstance()或x.type()检查,autograd的追踪由requires_grad标记控制。此外,支持0维张量,弃用了volatile标记,引入了dtypes、devices和Numpy风格的创建函数。推荐使用Tensor的device属性和to方法处理设备定位。
摘要由CSDN通过智能技术生成

原标题:PyTorch 4.0版本迁移指南

PyTorch昨天(4月25日)发布了PyTorch 0.4.0版本。这个版本伴随着很多重大的更新,包括正式开始支持windows。以下为PyTorch官方为让大家使用新版PyTorch而发布的代码迁移指南。

欢迎阅读PyTorch 0.4.0的迁移指南。在此版本中,我们引入了许多振奋人心的新功能和重要的bug修复,旨在为用户提供更好,更清晰的接口。在这个指南中,我们将介绍从以前版本迁移现有代码时最重要的变化:

Tensor与Variable合并支持0维(标量)Tensor弃用volatile标记dtypes,devices和Numpy风格的Tensor创建函数编写不限制设备的代码

合并Tensor和Variable类

torch.Tensor和torch.autograd.Variable现在是相同的类。更确切地说,torch.Tensor能够像旧版Variable一样追踪历史; Variable封装还像过去那样工作,但返回一个torch.Tensor类型的对象。这意味着你不再需要在代码中到处使用Variable封装器。

在type()的Tensor更改

还要注意,张量的type()不再反映数据类型。而是使用isinstance()或x.type()替代:

1>>> x=torch.DoubleTensor([1,1,1])

2>>>print(type(x)) # was torch.DoubleTensor

3""

4>>>print(x.type()) # OK: 'torch.DoubleTensor'

5'torch.DoubleTensor'

6>>>print(isinstance(x, torch.DoubleTensor)) # OK: True

7True

autograd什么时候开始追踪历史记录?

requires_grad,autograd的主要标记,现在归属于Tensor。过去适用于Variables的规则同样适用于Tensor; 当一个操作的任何输入Tensor有requires_grad=True时,autograd开始跟踪历史记录。例如:

01>>> x=torch.ones(1) # create a tensor with requires_grad=False (default)

02>>> x.requires_grad

03False

04>>> y=torch.ones(1) # another tensor with requires_grad=False

05>>> z=x+y

06>>># both inputs have requires_grad=False. so does the output

07>>> z.requires_grad

08False

09>>># then autograd won't track this computation. let's verify!

10>>> z.backward()

11RuntimeError: element0of tensors doesnotrequire gradanddoesnothave a grad_fn

12>>>

13>>># now create a tensor with requires_grad=True

14>>> w=torch.ones(1, requires_grad=True)

15>>> w.requires_grad

16True

17>>># add to the previous result that has require_grad=False

18>>> total=w+z

19>>># the total sum now requires grad!

20>>> total.requires_grad

21True

22>>># autograd can compute the gradients as

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值