本文主要是介绍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 = 0for input, target in train_loader:input, target = Variable(input), Variable(target) #需转化为Variablehidden = Variable(torch.zeros(*h_shape)) # 定义是否使用GPUif 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还是CPUmodel = CNN().to(device)# 训练total_loss = 0for input, target in train_loader:#不需要转化为Variable,直接用Tensors作为输入,用.to(device)来决定使用GPU还是CPUinput, 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:...
这篇关于Pytorch 0.4.0迁移指南(与之前版本编程上的不同点)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!