多使用inplace=False,否则可能报错:
RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.cuda.FloatTensor [1, 32, 22, 256, 256]], which is output 0 of ReluBackward1, is at version 3; expected version 2 instead. Hint: enable anomaly detection to find the operation that failed to compute its gradient, with torch.autograd.set_detect_anomaly(True).
params = cof TypeError: params argument given to the optimizer should be an iterable of Tensors or dicts, but got torch.FloatTensor
import torch cof = torch.eye(512) params = list(cof) # list(model.encoder.parameters()) optimizer = torch.optim.Adam(params, 1e-4)Pytorch遇到的坑——训练模式和测试模式切换
Pytorch的训练模式和测试模式切换 由于训练的时候Dropout和BN层起作用,每个batch BN层的参数不一样,dropout在训练时随机失效点具有随机性,所以训练和测试要区分开来。 使用时切记要根据实际情况切换: model.train() model.eval()
train:如果model是train的状态,intermediate varaible和computation graph会被保留,这些将来都会在backprop的时候用来计算gradient。因此,速度会比eval慢。eval:如果model是eval的状态,intermediate variable和computation graph不会被保留。因此速度会比train快。
pytorch中关于网络的反向传播操作是基于Variable对象,Variable中有一个参数requires_grad,将requires_grad=False,网络就不会对该层计算梯度。
在用户手动定义Variable时,参数requires_grad默认值是False。而在Module中的层在定义时,相关Variable的requires_grad参数默认是True。
自动调整batchsize以适应内存,当然batchsize为相当重要的参数,谨慎修改。
cudnn.benchmark=True自动寻找最适合当前配置的高效算法,以增加运行效率
自动调整学习率1.自定义根据 epoch 改变学习率
def adjust_learning_rate(optimizer, epoch):
"""Sets the learning rate to the initial LR divided by 5 at 60th, 120th and 160th epochs"""
lr = args.lr * ((0.2 ** int(epoch >= 60)) * (0.2 ** int(epoch >= 120))* (0.2 ** int(epoch >= 160)))
# log to TensorBoard
if args.tensorboard:
log_value('learning_rate', lr, epoch)
for param_group in optimizer.param_groups:
param_group['lr'] = lr
- 余弦退火方法
scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.epochs)
- 更多方法的详解
在train函数中采用自定义的AverageMeter类来管理一些变量的更新
在初始化的时候就调用的重置方法reset。当调用该类对象的update方法的时候就会进行变量更新,当要读取某个变量的时候,可以通过对象.属性的方式来读取,比如在train函数中的top1.val读取top1准确率。
↩︎



