版权说明:本篇文章为本人原创内容,转载请注明出处,谢谢合作!
2018年4月25号,官方发布Pytorch0.4.0版本,此版本除了支持Windows外,与之前的Pytorch版本也有诸多不同,主要表现在编程方面。因此该指南主要用来介绍Pytorch0.4.0代码方面需要注意的地方:
之前版本,最终的输入数据必须转化为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’>” #能返回数据类型之前版本的volatitle=True 相当于requires_grad=False,一般用于测试的时候不需要进行梯度计算,这样做能减少内存使用。新版中使用torch.no_grad()代替。
如:device = torch.device(“cuda” if torch.cuda.is_available() else “cpu”),会依据你的计算机配置自动选择CPU还是GPU运算。
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: ...