Variable与Tensor合并后,关于训练、验证的相关变化

Variable与Tensor合并后,关于训练、验证的相关变化


原本是打算自己写一下的,但后来发现有篇文章写的很全,这里给出合并前与合并后的代码对比,并在结尾处给出文章的链接

0.4.0 版本以前

 model = Net()
 if use_cuda:
     model = model.cuda()
     
 # train
 total_loss = 0
 for input, target in train_loader:
     input, target = Variable(input), Variable(target)
     if use_cuda:
         input, target = input.cuda(), target.cuda()
         outputs= model(input)
         loss = criterion(outputs,target)
     total_loss += loss.data[0]
     
 # evaluate
 for input, target in test_loader:
     input = Variable(input, volatile=True)
     if use_cuda:
         ...
     ...

0.4.0 版本及以后:

 device = torch.device("cuda" if use_cuda else "cpu")
 model = Net().to(device)
 
 # train
 total_loss = 0
 for input, target in train_loader:
     input, target = input.to(device), target.to(device)
     outputs= model(input)
     loss = criterion(outputs,target)
     total_loss += loss.item()           

 # evaluate
 with torch.no_grad():                  
     for input, target in test_loader:
         ...

简单来说就是去掉了Variable操作和.data.
Variable和Tensor合并后,PyTorch的代码要怎么改?
.data在pytorch中仍然有用吗?

你可能感兴趣的:(神经网络基础及相关处理,神经网络,pytorch,深度学习)