【问题标题】:About pytorch learning rate scheduler关于pytorch学习率调度器
【发布时间】:2020-01-06 04:28:37
【问题描述】:

这是我的代码

optimizer = optim.SGD(net.parameters(), lr=0.1)
scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=5, gamma=0.5)

for i in range(15):
    lr = scheduler.get_lr()[0]
    lr1 = optimizer.param_groups[0]["lr"]
    print(i, lr, lr1)
    scheduler.step()

这是结果

0 0.1 0.1
1 0.1 0.1
2 0.1 0.1
3 0.1 0.1
4 0.1 0.1
5 0.025 0.05
6 0.05 0.05
7 0.05 0.05
8 0.05 0.05
9 0.05 0.05
10 0.0125 0.025
11 0.025 0.025
12 0.025 0.025
13 0.025 0.025
14 0.025 0.025

我们可以看到,当scheduler.step()被应用时,学习率先下降了0.25倍,然后又反弹回了0.5倍。是scheduler.get_lr()lr的问题还是scheduler.step()的问题

关于环境

  • python=3.6.9
  • pytorch=1.1.0

另外,使用pytorch=0.4.1的时候找不到这个问题。

【问题讨论】:

    标签: python pytorch


    【解决方案1】:

    是的,“问题”在于get_lr()的使用。要获取当前的LR,你需要的其实是get_last_lr()


    如果你看看implementation

    def get_lr(self):
        if not self._get_lr_called_within_step:
            warnings.warn("To get the last learning rate computed by the scheduler, "
                          "please use `get_last_lr()`.", UserWarning)
    
        if (self.last_epoch == 0) or (self.last_epoch % self.step_size != 0):
            return [group['lr'] for group in self.optimizer.param_groups]
        return [group['lr'] * self.gamma
                for group in self.optimizer.param_groups]
    

    在step=5时,不满足条件(因为step_size=5),会返回lr * gamma尴尬的是,当您从 step() 函数中调用 get_lr() 时应该会收到警告(正如您在上面的实现中看到的那样),但显然您没有。警告仅在 3 个月前添加,因此您不会在 v1.1.0 上拥有它。

    为了完整起见,step() 方法所做的是将last_epoch 加1,并通过调用get_lr() 函数更新LR(参见here):

    self.last_epoch += 1
    values = self.get_lr()
    

    【讨论】:

    • 您引用的实现是针对最新的 pytorch 版本 1.3.1,而不是 1.1.0。所以这可能就是 Vincent_Ho 没有收到警告信息的原因。在他的版本中也没有 get_last_lr() 方法。
    • @AndreasK。哦耶;还有:)我相应地更新了答案。谢谢!
    猜你喜欢
    • 2020-03-19
    • 2020-11-16
    • 2021-03-13
    • 1970-01-01
    • 2022-12-23
    • 2021-12-03
    • 2017-11-26
    • 2021-09-27
    • 2019-09-03
    相关资源
    最近更新 更多