Pytorch0.4.0迁移指南

最近遇到低版本的pytorch向0.4.0版本迁移,最终找到一个比较好的讲解

转自:https://blog.csdn.net/sunqiande88/article/details/80172391

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))
“<classtorch.Tensor’>”  #不再返回数据类型
>>>print(x.type())
“<classtorch.DoubleTensor’>”  #能返回数据类型
  • 1
  • 2
  • 3
  • 4
  • 5

2. 支持零维Tensors

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

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:
          ...
      ...
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

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:
          ...

猜你喜欢

转载自blog.csdn.net/suan2014/article/details/80598825
今日推荐