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

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

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)

您可能感兴趣的与本文相关的镜像

PyTorch 2.5

PyTorch 2.5

PyTorch
Cuda

PyTorch 是一个开源的 Python 机器学习库,基于 Torch 库,底层由 C++ 实现,应用于人工智能领域,如计算机视觉和自然语言处理

PyTorch 中,`torch.optim.lr_scheduler.ReduceLROnPlateau` 是一种动态调整学习率的调度器,适用于训练过程中验证损失趋于稳定的情况。它通过监测指定的指标(如验证损失),当指标在一定次数的 epoch 中不再显著改善时,自动降低学习率。这种策略可以提高模型的收敛性并防止陷入局部最优解。 ### 使用方式 `ReduceLROnPlateau` 的基本使用方式如下: ```python from torch.optim.lr_scheduler import ReduceLROnPlateau # 定义优化器 optimizer = torch.optim.Adam(model.parameters(), lr=0.001) # 定义调度器 scheduler = ReduceLROnPlateau(optimizer, mode='min', factor=0.1, patience=5, verbose=True) # 在训练循环中使用 for epoch in range(num_epochs): model.train() for inputs, targets in train_loader: optimizer.zero_grad() outputs = model(inputs) loss = loss_function(outputs, targets) loss.backward() optimizer.step() # 验证阶段 model.eval() with torch.no_grad(): val_loss = 0 for inputs, targets in val_loader: outputs = model(inputs) val_loss += loss_function(outputs, targets).item() # 根据验证损失调整学习率 scheduler.step(val_loss) ``` ### 参数说明 1. **mode**:监测指标的变化方向,可以是 `'min'`(指标越小越好)或 `'max'`(指标越大越好)。 2. **factor**:学习率衰减的乘数因子。例如,如果当前学习率为 `0.001`,且触发调整,则新的学习率为 `0.001 * factor`。 3. **patience**:在指标没有改善的情况下等待的 epoch 数量。只有当连续 `patience` 个 epoch 没有改善时才会触发学习率调整。 4. **verbose**:是否在调整学习率时打印信息。如果设置为 `True`,会在每次调整时输出日志信息。 5. **threshold**:衡量指标是否改善的阈值。默认情况下,如果指标的变化小于 `threshold`,则认为没有改善。 6. **cooldown**:每次调整学习率后重新开始监测的冷却期,防止过早调整。 7. **min_lr**:学习率的下限,避免学习率过小导致模型无法更新。 8. **eps**:学习率的最小变化量,用于防止学习率更新过小。 ### 示例场景 假设模型在训练过程中验证损失在 5 个 epoch 内没有显著降低,`ReduceLROnPlateau` 会将学习率乘以 `factor`(例如从 `0.001` 降低到 `0.0001`),以尝试进一步优化模型性能。 ### 注意事项 - **验证损失监测**:确保在每个 epoch 结束后计算验证损失,并将其传递给 `scheduler.step()` 方法。 - **避免过早调整**:通过设置 `patience` 和 `cooldown` 参数,防止学习率调整过于频繁。 - **学习率下限**:设置 `min_lr` 可以避免学习率过低,导致模型参数无法有效更新。 ### 与其他调度器对比 `StepLR` 是一种固定步长调整学习率的调度器,而 `ReduceLROnPlateau` 则根据验证损失动态调整学习率。例如,`StepLR` 的使用方式如下: ```python from torch.optim.lr_scheduler import StepLR scheduler = StepLR(optimizer, step_size=10, gamma=0.1) ``` 在每训练 10 个 epoch 后,学习率会乘以 `gamma`。相比之下,`ReduceLROnPlateau` 更适合于验证损失变化不确定的场景,能够根据实际情况灵活调整学习率。 ### 代码示例 以下是一个完整的训练循环示例,包含 `ReduceLROnPlateau` 的使用: ```python import torch import torch.nn as nn from torch.utils.data import DataLoader from torch.optim.lr_scheduler import ReduceLROnPlateau # 定义模型 class SimpleModel(nn.Module): def __init__(self): super(SimpleModel, self).__init__() self.linear = nn.Linear(10, 1) def forward(self, x): return self.linear(x) # 初始化模型、优化器和调度器 model = SimpleModel() optimizer = torch.optim.Adam(model.parameters(), lr=0.01) scheduler = ReduceLROnPlateau(optimizer, mode='min', factor=0.1, patience=5, verbose=True) # 假设的数据加载器 train_loader = DataLoader(torch.randn(100, 10), batch_size=10) val_loader = DataLoader(torch.randn(20, 10), batch_size=10) # 训练循环 num_epochs = 20 for epoch in range(num_epochs): model.train() for inputs in train_loader: optimizer.zero_grad() outputs = model(inputs) loss = nn.MSELoss()(outputs, torch.randn(outputs.shape)) loss.backward() optimizer.step() # 验证阶段 model.eval() val_loss = 0 with torch.no_grad(): for inputs in val_loader: outputs = model(inputs) val_loss += nn.MSELoss()(outputs, torch.randn(outputs.shape)).item() # 根据验证损失调整学习率 scheduler.step(val_loss) ``` ###
评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值