Pytorch 0.4.0迁移指南(与之前版本编程上的不同点)

版权说明:本篇文章为本人原创内容,转载请注明出处,谢谢合作!

2018年4月25号,官方发布Pytorch0.4.0版本,此版本除了支持Windows外,与之前的Pytorch版本也有诸多不同,主要表现在编程方面。因此该指南主要用来介绍Pytorch0.4.0代码方面需要注意的地方:
####1. 弃用Variables并与Tensors合并
之前版本,最终的输入数据必须转化为Variable的形式,而在Pytorch0.4.0版中,torch.Tensor包括了torch.autograd.Variable,已经不需要转化为Variable的形式。
type()的功能也变了,它不会再返回数据的类型,需要用x.type()代替。

>>>x = torch.DoubleTensor([1, 1, 1])
>>>print(type(x))<class ‘torch.Tensor’>#不再返回数据类型
>>>print(x.type())<class ‘torch.DoubleTensor’>#能返回数据类型

####2. 支持零维Tensors

>>>torch.tensor(3.1416).size()
Torch.Size([])  #零维张量

####3. 弃用volatile
之前版本的volatitle=True 相当于requires_grad=False,一般用于测试的时候不需要进行梯度计算,这样做能减少内存使用。新版中使用torch.no_grad()代替。
####4.新增dtypes、devices和numpy风格的Tensor
如:device = torch.device(“cuda” if torch.cuda.is_available() else “cpu”),会依据你的计算机配置自动选择CPU还是GPU运算。
####用一个例子来对比Pytorch 0.4.0代码上需要注意的地方:
0.3.1(老版本):

model = CNN()
  if use_cuda:
      model = model.cuda()
      
  # 训练
  total_loss = 0
  for input, target in train_loader:
      input, target = Variable(input), Variable(target) #需转化为Variable
      hidden = Variable(torch.zeros(*h_shape))  
      # 定义是否使用GPU
      if use_cuda:
          input, target, hidden = input.cuda(), target.cuda(), hidden.cuda()
      ...  
      # 获得loss的值
      total_loss += loss.data[0]

  # 测试
  for input, target in test_loader:
      input = Variable(input, volatile=True)
      if use_cuda:
          ...
      ...

0.4.0(新版本):

  # 定义device,是否使用GPU,依据计算机配置自动会选择
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
  #用.to(device)来决定模型使用GPU还是CPU
  model = CNN().to(device)

  # 训练
  total_loss = 0
  for input, target in train_loader:
      #不需要转化为Variable,直接用Tensors作为输入,用.to(device)来决定使用GPU还是CPU
      input, target = input.to(device), target.to(device)
      hidden = input.new_zeros(*h_shape)  
      ...  # 获得loss值,也与老版本不同
      total_loss += loss.item()          

  # 测试
  with torch.no_grad():      # 测试时不会进行梯度计算,节约内存
      for input, target in test_loader:
          ...
  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

魔法战胜魔法

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值