原标题: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