【AI】Pytorch_LearningRate
From: https://liudongdong1.github.io/
a. 有序调整:等间隔调整(Step),按需调整学习率(MultiStep),指数衰减调整(Exponential)和 余弦退火CosineAnnealing。
b. 自适应调整:自适应调整学习率 ReduceLROnPlateau。
c. 自定义调整:自定义调整学习率 LambdaLR。
#得到当前学习率
lr = next(iter(optimizer.param_groups))['lr']
#multiple learning rates for different layers.
all_lr = []
for param_group in optimizer.param_groups:
all_lr.append(param_group['lr'])
#学习率衰减
#Reduce learning rate when validation accuarcy plateau.
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='max', patience=5, verbose=True)
for t in range(0, 80):
train(...); val(...)
scheduler.step(val_acc)
#Cosine annealing learning rate.
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=80)
#Reduce learning rate by 10 at given epochs.
scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[50, 70], gamma=0.1)
for t in range(0, 80):
scheduler.step()
train(...); val(...)
#Learning rate warmup by 10 epochs.
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda t: t / 10)
for t in range(0, 10):
scheduler.step()
train(...); val(...)
1. 针对不同的层
model = torchvision.models.resnet101(pretrained=True)
large_lr_layers = list(map(id,model.fc.parameters()))
small_lr_layers = filter(lambda p:id(p) not in large_lr_layers,model.parameters())
optimizer = torch.optim.SGD([
{"params":large_lr_layers},
{"params":small_lr_layers,"lr":1e-4}
],lr = 1e-2,momenum=0.9)
2. 等间隔调整学习率 StepLR
torch.optim.lr_scheduler.StepLR(optimizer, step_size, gamma=0.1, last_epoch=-1)
step_size(int)- 学习率下降间隔数,若为 30,则会在 30、 60、 90…个 step 时,将学习率调整为lr*gamma。- gamma(float)- 学习率调整倍数,默认为 0.1 倍,即下降 10 倍。
- last_epoch(int)- 上一个 epoch 数,这个变量用来
指示学习率是否需要调整。当last_epoch 符合设定的间隔时,就会对学习率进行调整。当为-1 时,学习率设置为初始值。调整倍数为 gamma 倍,调整间隔为 step_size。间隔单位是step。需要注意的是, step 通常是指 epoch,不要弄成 iteration 了。
3. 按需调整学习率 MultiStepLR
torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones, gamma=0.1, last_epoch=-1)
- milestones(list)- 一个 list,
每一个元素代表何时调整学习率,list 元素必须是递增的。如 milestones=[30,80,120]- gamma(float)- 学习率调整倍数,默认为 0.1 倍,即下降 10 倍。
按设定的间隔调整学习率。这个方法适合后期调试使用,观察 loss 曲线,为每个实验定制学习率调整时机。
4. 指数衰减调整学习率 ExponentialLR
torch.optim.lr_scheduler.ExponentialLR(optimizer, gamma, last_epoch=-1)
gamma- 学习率调整倍数的底,指数为 epoch,即 gamma**epoch
5. 余弦退火调整学习率 CosineAnnealingLR
torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max, eta_min=0, last_epoch=-1)
- T_max(int)- 一次学习率周期的迭代次数,即
T_max 个 epoch 之后重新设置学习率。- eta_min(float)- 最小学习率,即在一个周期中,
学习率最小会下降到 eta_min,默认值为 0。以余弦函数为周期,并在每个周期最大值时重新设置学习率。以初始学习率为最大学习率,以 2 ∗ T m a x 2*Tmax2∗Tmax 为周期,在一个周期内先下降,后上升。
epochs = 60
optimizer = optim.SGD(model.parameters(),lr = config.lr,momentum=0.9,weight_decay=1e-4)
scheduler = lr_scheduler.CosineAnnealingLR(optimizer,T_max = (epochs // 9) + 1)
for epoch in range(epochs):
scheduler.step(epoch)
6. 自适应调整学习率 ReduceLROnPlateau
torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.1, patience=10, verbose=False, threshold=0.0001, threshold_mode='rel', cooldown=0, min_lr=0, eps=1e-08)
- mode(str)- 模式选择,有 min 和 max 两种模式,
min 表示当指标不再降低(如监测loss),max 表示当指标不再升高(如监测 accuracy)。- factor(float)- 学习率调整倍数(等同于其它方法的 gamma),即学习率更新为
lr = lr * factor- patience(int)-
忍受该指标多少个 step 不变化,当忍无可忍时,调整学习率。- verbose(bool)-
是否打印学习率信息, print(‘Epoch {:5d}: reducing learning rate of group {} to {:.4e}.’.format(epoch, i, new_lr))- threshold_mode(str)- 选择判断指标是否达最优的模式,有两种模式, rel 和 abs。
当 threshold_mode == rel,并且 mode == max 时, dynamic_threshold = best * ( 1 +threshold );
当 threshold_mode == rel,并且 mode == min 时, dynamic_threshold = best * ( 1 -threshold );
当 threshold_mode == abs,并且 mode== max 时, dynamic_threshold = best + threshold ;
当 threshold_mode == rel,并且 mode == max 时, dynamic_threshold = best - threshold;- threshold(float)- 配合 threshold_mode 使用。
cooldown(int)- “冷却时间“,当调整学习率之后,让学习率调整策略冷静一下,让模型再训练一段时间,再重启监测模式。- min_lr(float or list)-
学习率下限,可为 float,或者 list,当有多个参数组时,可用 list 进行设置。- eps(float)-
学习率衰减的最小值,当学习率变化小于 eps 时,则不调整学习率。
optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9)scheduler = ReduceLROnPlateau(optimizer, 'max',verbose=1,patience=3)for epoch in range(10): train(...) val_acc = validate(...) # 降低学习率需要在给出 val_acc 之后 scheduler.step(val_acc)
7. 自定义调整学习率 LambdaLR

torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda, last_epoch=-1)
- lr_lambda(function or list)- 一个
计算学习率调整倍数的函数,输入通常为 step,当有多个参数组时,设为 list。
8. 手动设置
def adjust_learning_rate(optimizer, lr): for param_group in optimizer.param_groups: param_group['lr'] = lrfor epoch in range(60): lr = 30e-5 if epoch > 25: lr = 15e-5 if epoch > 30: lr = 7.5e-5 if epoch > 35: lr = 3e-5 if epoch > 40: lr = 1e-5 adjust_learning_rate(optimizer, lr)
【AI】Pytorch_LearningRate的更多相关文章
- 【AI】Exponential Stochastic Cellular Automata for Massively Parallel Inference - 大规模并行推理的指数随机元胞自动机
[论文标题]Exponential Stochastic Cellular Automata for Massively Parallel Inference (19th-ICAIS,PMLR ...
- 【AI】【人工智能】【计算机】人工智能工程技术人员等职业信息公示
人社厅发[2019]48号 各省.自治区.直辖市及新疆生产建设兵团人力资源社会保障厅(局).市场监管局.统计局,国务院各部门.各直属机构.各中央企业.有关社会组织人事劳动保障工作机构,中央军委政治工作 ...
- 【AI】Android Pie中引入的AI功能
前言 “无AI,不未来”,绝对不是一句豪情壮语,AI早已进入到了我们生活当中.去年Google发布的Android Pie系统在AI功能方面就做了重大革新,本文就对Google在新系统中引入的AI功能 ...
- 【AI】Computing Machinery and Intelligence - 计算机器与智能
[论文标题] Computing Machinery and Intelligence (1950) [论文作者] A. M. Turing (Alan Mathison Turing) [论文链接] ...
- 【AI】【计算机】【中国人工智能学会通讯】【学会通讯2019年第01期】中国人工智能学会重磅发布 《2018 人工智能产业创新评估白皮书》
封面: 中国人工智能学会重磅发布 <2018 人工智能产业创新评估白皮书> < 2018 人工智能产业创新评估白皮书>由中国人工智能学会.国家工信安全中心.华夏幸福产业研究院. ...
- 【AI】蒙特卡洛搜索树
http://jeffbradberry.com/posts/2015/09/intro-to-monte-carlo-tree-search/ 蒙特卡洛方法与随机优化: http://iacs-co ...
- 【AI】PaddlePaddle-Docker运行
1.参考官方安装Docker环境,使用一键安装包安装 https://www.jianshu.com/p/b2766173d754 http://www.paddlepaddle.org/docume ...
- 【AI】神经网络基本词汇
neural networks 神经网络activation function 激活函数hyperbolic tangent 双曲正切函数bias units 偏置项activation 激活值for ...
- 【AI】基本概念-准确率、精准率、召回率的理解
样本全集:TP+FP+FN+TN TP:样本为正,预测结果为正 FP:样本为负,预测结果为正 TN:样本为负,预测结果为负 FN:样本为正,预测结果为负 准确率(accuracy):(TP+TN)/ ...
随机推荐
- python操作elasticsearch增、删、改、查
最近接触了个新东西--es数据库 这东西虽然被用的很多,但我是前些天刚刚接触的,发现其资料不多,学起来极其痛苦,写个文章记录下 导入库from elasticsearch import Elastic ...
- 题解 guP3956 棋盘
好吧本来这题可以用最短路跑完的,结果我硬是打了1.5小时的dfs... 其实这题并没有那么难,构造一个无向图再跑最短路即可. 我用的dj跑最短路 问题来了 如果(n,n)是无色的,那么图上就没有这个点 ...
- c语言:随机函数应用
#include <stdio.h> #include <time.h>//声明time 时间不可逆转一直在变 #include <math.h> #include ...
- C语言:指针
#include <stdio.h> #include <stdlib.h> int sum(int a,int b) { int c; c=a+b; printf(" ...
- CentOS7创建个人系统启动服务项的方法
CentOS7.6自定义系统启动项的方法(类似busybox里面的inittab)1.编写属于自己的unit服务文件,命令为my.service[Unit]Description=My-demo Se ...
- SpringBoot读取Resource下文件的几种方式(十五)
需求:提供接口下载resources目录下的模板文件,(或者读取resources下的文件)给后续批量导入数据提供模板文件. 方式一:ClassPathResource //获取模板文件:注意此处需要 ...
- win 10,Maven 配置
来源:https://www.cnblogs.com/lihan829/p/11503497.html 所需工具 : JDK 1.8 Maven 3.6.2 Windows 10 注Maven 3.2 ...
- 什么是jstl表达式,怎么应用
1.介绍 JSTL(JSP Standard Tag Library),JSP标准标签库,可以嵌入在jsp页面中使用标签的形式完成业务逻辑等功能.jstl出现的目的同el一样也是要代替jsp页面中的脚 ...
- ThinkPHP5 SQL注入漏洞 && 敏感信息泄露
访问看到用户名被显示了 http://192.168.49.2/index.php?ids[]=1&ids[]=2 访问http://your-ip/index.php?ids[0,updat ...
- HttpRunner3源码阅读:4. loader项目路径加载,用例文件转换、方法字典生成
loader.py 这个文件中主要是对yaml,json用例加载转换成用例处理, 预置函数加载成方法字典,路径加载等 可用资料 [importlib]. https://docs.python.org ...