栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python编程细节: 模型的训练与测试模式+网络冻结+自动优化算法(自动化)+变量管理AverageMeter()

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python编程细节: 模型的训练与测试模式+网络冻结+自动优化算法(自动化)+变量管理AverageMeter()

inplace=False1

多使用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).

对paramer迭代转为list
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)
    更多方法的详解
变量管理AverageMeter()(初始化,get/set方法)

在train函数中采用自定义的AverageMeter类来管理一些变量的更新
在初始化的时候就调用的重置方法reset。当调用该类对象的update方法的时候就会进行变量更新,当要读取某个变量的时候,可以通过对象.属性的方式来读取,比如在train函数中的top1.val读取top1准确率。


  1. ↩︎

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/724989.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号