knn pytorch_PyTorch--lr_scheduler.step()和optimizer.step()的先后顺序

实验基于PyTorch==1.2.0

resume模型的时候想恢复optimizer的学习率

optimizer不会保存last_step等状态,而scheduler是根据last_step来恢复学习率的,而scheduler的last_step默认是-1,所以不能正常恢复学习率。
有两个办法可以解决,一个是同时加载scheduler的状态,另一个是调用scheduler.step(),我建议是加载scheduler的状态,因为scheduler还保存了其他的状态

  • 不正确的做法
import 
0 optim: 0.005000000000000001
0 scheduler: 0.5
1 optim: 0.5
1 scheduler: 0.5
2 optim: 0.05
2 scheduler: 0.05
3 optim: 0.05
3 scheduler: 0.05
4 optim: 0.005000000000000001
4 scheduler: 0.005000000000000001

结果并不像我们预期的那样

  • 正确的做法
import 
0 optim: 0.005000000000000001
0 scheduler: 0.005000000000000001
1 optim: 0.0005000000000000001
1 scheduler: 0.0005000000000000001
2 optim: 0.0005000000000000001
2 scheduler: 0.0005000000000000001
3 optim: 5.000000000000001e-05
3 scheduler: 5.000000000000001e-05
4 optim: 5.000000000000001e-05
4 scheduler: 5.000000000000001e-05

结果如我们预期的那样

为什么scheduler.step()需要在optimizer.step()的后面调用

scheduler.step()的其中一个作用是调整学习率,如果调用scheduler.step(),则会改变optimizer中的学习率

  • 不正确的用法
import 
0 scheduler: 0.5
0 optim: 0.5
1 scheduler: 0.5
1 optim: 0.05
2 scheduler: 0.05
2 optim: 0.05
3 scheduler: 0.05
3 optim: 0.005000000000000001
4 scheduler: 0.005000000000000001
4 optim: 0.005000000000000001
/home/zhouzaida/.local/lib/python3.6/site-packages/torch/optim/lr_scheduler.py:82: UserWarning: Detected call of `lr_scheduler.step()` before `optimizer.step()`. In PyTorch 1.1.0 and later, you should call them in the opposite order: `optimizer.step()` before `lr_scheduler.step()`. Failure to do this will result in PyTorch skipping the first value of the learning rate schedule.See more details at https:// pytorch.org/docs/stable /optim.html#how-to-adjust-learning-rate
" https:// pytorch.org/docs/stable /optim.html#how-to-adjust-learning-rate ", UserWarning)

可以发现,optimizer学习率并不像我们预期的那样,在0、1的时候为0.5,结果确是1的时候就为0.05,这是不正确的,当然,PyTorch也给出了提示

  • 正确的用法
import 
0 optim: 0.5
0 scheduler: 0.5
1 optim: 0.5
1 scheduler: 0.5
2 optim: 0.05
2 scheduler: 0.05
3 optim: 0.05
3 scheduler: 0.05
4 optim: 0.005000000000000001
4 scheduler: 0.005000000000000001

optimizer学习率如我们预期的那样

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值