pytorch-学习率调整-torch.optim.lr_scheduler

本文详细介绍了PyTorch中各种学习率调度器的使用方法,包括LambdaLR、StepLR、MultiStepLR等,解释了不同调度器的参数设置及如何在训练过程中调整学习率,帮助读者深入理解并灵活运用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

torch.optim.lr_scheduler

pytorch提供了以下学习率调整的方式,转自pytorch官网

Prior to PyTorch 1.1.0, the learning rate scheduler was expected to be called before the optimizer’s update; 1.1.0 changed this behavior in a BC-breaking way. If you use the learning rate scheduler (calling scheduler.step()) before the optimizer’s update (calling optimizer.step()), this will skip the first value of the learning rate schedule. If you are unable to reproduce results after upgrading to PyTorch 1.1.0, please check if you are calling scheduler.step() at the wrong time.

暗示pytorch1.1.0版本以后,schedule.step()要在optimizer.step()之后


  • torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda, last_epoch=-1)
Sets the learning rate of each parameter group to the initial lr times a given function. When last_epoch=-1, sets initial lr as lr.

Parameters
optimizer (Optimizer) – Wrapped optimizer.

lr_lambda (function or list) – A function which computes a multiplicative factor given an integer parameter epoch, or a list of such functions, one for each group in optimizer.param_groups.

last_epoch (int) – The index of last epoch. Default: -1.

Example

>>> # Assuming optimizer has two groups.
>>> lambda1 = lambda epoch: epoch // 30
>>> lambda2 = lambda epoch: 0.95 ** epoch
>>> scheduler = LambdaLR(optimizer, lr_lambda=[lambda1, lambda2])
>>> for epoch in range(100):
>>>     train(...)
>>>     validate(...)
>>>     scheduler.step()

上面代码是每30个epoch学习率*0.95?不是这样的,看这个
应该是只能传入一个参数,计算的是一个与epoch相关的学习率乘数因子
lr = scheduler.get_lr()这个函数get√
自己测试下

from torch.optim import Adam, lr_scheduler
from torchvision import models
import matplotlib.pyplot as plt
lambda1 = lambda epoch:epoch // 10
lambda2 = lambda epoch:0.5**epoch

alexnet = models.alexnet(pretrained=True)
optim = Adam(params=alexnet.parameters(), lr=0.1)
scheduler = lr_scheduler.LambdaLR(optim, lr_lambda=lambda2)


x = list(range(100))
y = []
for i in range(100):
    scheduler.step()
    lr = scheduler.get_lr()
    print(lr)
    y.append(lr[0])
    
plt.plot(x, y)

result


  • torch.optim.lr_scheduler.StepLR(optimizer, step_size, gamma=0.1, last_epoch=-1)
Sets the learning rate of each parameter group to the initial lr decayed by gamma every step_size epochs. When last_epoch=-1, sets initial lr as lr.

Parameters
optimizer (Optimizer) – Wrapped optimizer.

step_size (int) – Period of learning rate decay.

gamma (float) – Multiplicative factor of learning rate decay. Default: 0.1.

last_epoch (int) – The index of last epoch. Default: -1.

Example

>>> # Assuming optimizer uses lr = 0.05 for all groups
>>> # lr = 0.05     if epoch < 30
>>> # lr = 0.005    if 30 <= epoch < 60
>>> # lr = 0.0005   if 60 <= epoch < 90
>>> # ...
>>> scheduler = StepLR(optimizer, step_size=30, gamma=0.1)
>>> for epoch in range(100):
>>>     train(...)
>>>     validate(...)
>>>     scheduler.step()

这个比较好理解,每隔多少epoch学习率成比率下降,其实不是每个多少个epoch,你在每个batch后运行这个,他也会更新,所以是每运行多少次这个函数scheduler.step(),更新以下学习率


  • torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones, gamma=0.1, last_epoch=-1)
Set the learning rate of each parameter group to the initial lr decayed by gamma once the number of epoch reaches one of the milestones. When last_epoch=-1, sets initial lr as lr.

Parameters
optimizer (Optimizer) – Wrapped optimizer.

milestones (list) – List of epoch indices. Must be increasing.

gamma (float) – Multiplicative factor of learning rate decay. Default: 0.1.

last_epoch (int) – The index of last epoch. Default: -1.

Example

>>> # Assuming optimizer uses lr = 0.05 for all groups
>>> # lr = 0.05     if epoch < 30
>>> # lr = 0.005    if 30 <= epoch < 80
>>> # lr = 0.0005   if epoch >= 80
>>> scheduler = MultiStepLR(optimizer, milestones=[30,80], gamma=0.1)
>>> for epoch in range(100):
>>>     train(...)
>>>     validate(...)
>>>     scheduler.step()

和上面的差不多,这里是传入一个列表


  • torch.optim.lr_scheduler.ExponentialLR(optimizer, gamma, last_epoch=-1)
Set the learning rate of each parameter group to the initial lr decayed by gamma every epoch. When last_epoch=-1, sets initial lr as lr.

Parameters
optimizer (Optimizer) – Wrapped optimizer.

gamma (float) – Multiplicative factor of learning rate decay.

last_epoch (int) – The index of last epoch. Default: -1.

单纯的指数降低,是不是太快了0.0


  • torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max, eta_min=0, last_epoch=-1)
    torchguanwang
Parameters
optimizer (Optimizer) – Wrapped optimizer.

T_max (int) – Maximum number of iterations.

eta_min (float) – Minimum learning rate. Default: 0.

last_epoch (int) – The index of last epoch. Default: -1.

还有好多没看了,用到再看吧2333

  • 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)

  • torch.optim.lr_scheduler.CyclicLR(optimizer, base_lr, max_lr, step_size_up=2000, step_size_down=None, mode='triangular', gamma=1.0, scale_fn=None, scale_mode='cycle', cycle_momentum=True, base_momentum=0.8, max_momentum=0.9, last_epoch=-1)

  • torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr, total_steps=None, epochs=None, steps_per_epoch=None, pct_start=0.3, anneal_strategy='cos', cycle_momentum=True, base_momentum=0.85, max_momentum=0.95, div_factor=25.0, final_div_factor=10000.0, last_epoch=-1)

  • torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizer, T_0, T_mult=1, eta_min=0, last_epoch=-1)

<think>好的,我现在需要向用户介绍PyTorch中的torch.optim.lr_scheduler.CosineAnnealingWarmRestarts。首先,我应该回忆一下这个学习率调度器的基本概念和用途。 用户可能已经知道学习率调度器的作用,但需要具体了解余弦退火热重启的特点。我记得这个调度器是基于论文《SGDR: Stochastic Gradient Descent with Warm Restarts》提出的,所以可能需要提到这一点。 接下来,我需要解释它的工作原理。根据CosineAnnealingWarmRestarts,学习率会按余弦函数周期性地调整,并且在每个周期结束时重启,同时保持一定的动量,以帮助跳出局部最优。这里的关键参数应该是T_0(初始周期长度)和T_mult(周期长度的乘数),可能还有eta_min(最低学习率)。 然后,我应该考虑用户可能的应用场景,比如当模型训练陷入平稳时,使用这个调度器可以重启学习率,帮助跳出局部最优。或者,在需要动态调整学习率的情况下,它比固定学习率或阶梯式下降更有效。 还需要注意如何在实际代码中使用这个调度器。比如,用户需要先定义一个优化器,然后创建这个调度器,并确保在训练循环中调用scheduler.step()。例如: optimizer = torch.optim.SGD(model.parameters(), lr=0.1) scheduler = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizer, T_0=50, T_mult=2, eta_min=0.001) 在每个epoch后执行scheduler.step()。同时,T_0是第一个周期的epoch数,T_mult是每次重启后周期长度乘以的系数,比如T_mult=2表示周期长度变为原来的两倍。 可能需要解释参数eta_min,默认是0,但有时候设置为非零值可以防止学习率过小。此外,每个周期结束后,学习率会从eta_min回到初始值,然后开始新的余弦下降。 用户可能会问这个调度器与其他调度器(如StepLR、ReduceLROnPlateau)的区别,所以需要准备比较。比如,StepLR是固定步长调整,而CosineAnnealingWarmRestarts是平滑周期调整,有助于跳出局部最优。 还要注意常见问题,比如什么时候使用这个调度器,比如当训练损失停滞时,或者希望模型探索更多参数空间时。此外,参数设置的建议,比如初始T_0可能需要根据数据集大小和模型复杂度调整,T_mult通常设置为1或2。 最后,总结这个调度器的优点,比如自动调整、避免手动调整学习率的麻烦,以及通过重启机制提升模型性能的可能性。可能还需要提醒用户在实际使用中结合验证集效果进行调整。</think>以下是对`torch.optim.lr_scheduler.CosineAnnealingWarmRestarts` 的详细介绍: --- ### 1. **基本概念** 这是 PyTorch 中一种**周期性调整学习率**的调度器,基于论文《SGDR: Stochastic Gradient Descent with Warm Restarts》提出。它通过**余弦函数**动态调整学习率,并在每个周期结束时执行“热重启”(Warm Restart),帮助模型跳出局部最优解。 --- ### 2. **核心公式** 学习率按以下公式变化: $$ \eta_t = \eta_{\text{min}} + \frac{1}{2}(\eta_{\text{max}} - \eta_{\text{min}})\left(1 + \cos\left(\frac{T_{\text{cur}}}{T_i} \pi\right)\right) $$ - $\eta_{\text{max}}$: 初始学习率 - $\eta_{\text{min}}$: 最低学习率(默认 0) - $T_i$: 第 $i$ 个周期的长度 - $T_{\text{cur}}$: 当前周期内的 epoch 计数 --- ### 3. **关键参数** | 参数 | 说明 | |-------|-------| | `T_0` | 第一个周期的长度(epoch 数) | | `T_mult` | 周期长度增长因子(默认 1,表示固定周期) | | `eta_min` | 最低学习率(默认 0) | | `last_epoch` | 恢复训练时的起始 epoch(通常无需手动设置) | --- ### 4. **工作流程** 1. **余弦下降**:学习率从初始值 $\eta_{\text{max}}$ 平滑降至 $\eta_{\text{min}}$。 2. **热重启**:周期结束时,学习率重置为 $\eta_{\text{max}}$,开始新周期。 3. **周期扩展**:若 `T_mult > 1`,后续周期长度按 $T_i = T_0 \times T_{\text{mult}}^i$ 增长。 --- ### 5. **代码示例** ```python import torch from torch.optim import SGD from torch.optim.lr_scheduler import CosineAnnealingWarmRestarts # 定义优化器 optimizer = SGD(model.parameters(), lr=0.1) # 创建调度器 scheduler = CosineAnnealingWarmRestarts( optimizer, T_0=50, # 初始周期长度=50 epochs T_mult=2, # 每次重启后周期长度翻倍 eta_min=1e-5 # 最低学习率 ) # 训练循环 for epoch in range(100): train(...) scheduler.step() # 更新学习率 ``` --- ### 6. **典型应用场景** - 模型训练陷入**损失平台期**时,通过重启跳出局部最优 - 替代固定学习率或阶梯式下降策略 - 需要平衡**探索**(高学习率)与**收敛**(低学习率)的场景 --- ### 7. **对比其他调度器** | 调度器 | 特点 | |--------|------| | `StepLR` | 固定步长降低学习率,突变式调整 | | `ReduceLROnPlateau` | 基于验证指标动态调整 | | `CosineAnnealingWarmRestarts` | 周期性平滑调整 + 重启机制 | --- ### 8. **注意事项** - **初始周期长度 `T_0`**:通常设为总训练 epoch 数的 1/5 到 1/10 - **`T_mult` 选择**:设为 1 表示固定周期长度,设为 2 逐步延长周期 - **与早停法结合**:重启机制可能干扰早停判断,需谨慎配合 --- 通过这种动态调整策略,模型可以更充分地探索参数空间,同时避免手动调整学习率的繁琐。实际效果需结合具体任务验证。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值