gpt4 book ai didi

python - 关于pytorch学习率调度器

转载 作者:行者123 更新时间:2023-12-01 19:29:13 25 4
gpt4 key购买 nike

这是我的代码

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时,我找不到这个问题。

最佳答案

是的,“问题”在于 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( ) 函数(参见 here ):

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

关于python - 关于pytorch学习率调度器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59599603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com