2025年3月27日 星期四 甲辰(龙)年 月廿六 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

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

时间:03-27来源:作者:点击数:45

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:
  • ...
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门