torch.optim.lr_scheduler.OneCycleLR 学习与理解

一、功能和参数

1.1、通过图像直观地理解 OneCycleLR 的过程:

补充:

生成该图像的代码:

来自:torch.optim.lr_scheduler.OneCycleLR用法_dxz_tust的博客-CSDN博客

import cv2
import torch.nn as nn
import torch
from torchvision.models import AlexNet
import matplotlib.pyplot as plt
#定义2分类网络
steps = []
lrs = []
# ## !!!!下面这一行如果感觉太慢,可以使用:model = torch.nn.Linear(2, 1) !!!!
model = AlexNet(num_classes=2)
# ------------------------------------------
lr = 0.1
optimizer = torch.optim.SGD(model.parameters(), lr=lr, momentum=0.9)

#total_steps:总的batch数,这个参数设置后就不用设置epochs和steps_per_epoch,anneal_strategy 默认是"cos"方式,当然也可以选择"linear"
#注意,这里的max_lr和你优化器中的lr并不是同一个
#注意,无论你optim中的lr设置是啥,最后起作用的还是max_lr
scheduler =torch.optim.lr_scheduler.OneCycleLR(optimizer,max_lr=0.9,total_steps=100, verbose=True)
# ------------------------------------------
for epoch in range(10):
    for batch in range(10):
        scheduler.step()
        lrs.append(scheduler.get_lr()[0])
        steps.append(epoch*10+batch)
 
 
plt.figure()
plt.legend()
plt.plot(steps, lrs, label='OneCycle')
plt.savefig("dd.png")

1.2、参数介绍

上图中的值,就是参数的默认值。

详细介绍:(英文挺容易理解,就不再翻译了。)

optimizer (Optimizer): Wrapped optimizer.
max_lr (float or list): Upper learning rate boundaries in the cycle
    for each parameter group.
total_steps (int): The total number of steps in the cycle. Note that
    if a value is not provided here, then it must be inferred by providing
    a value for epochs and steps_per_epoch.
    Default: None
epochs (int): The number of epochs to train for. This is used along
    with steps_per_epoch in order to infer the total number of steps in the cycle
    if a value for total_steps is not provided.
    Default: None
steps_per_epoch (int): The number of steps per epoch to train for. This is
    used along with epochs in order to infer the total number of steps in the
    cycle if a value for total_steps is not provided.
    Default: None
pct_start (float): The percentage of the cycle (in number of steps) spent
    increasing the learning rate.
    Default: 0.3
anneal_strategy (str): {'cos', 'linear'}
    Specifies the annealing strategy: "cos" for cosine annealing(退火), "linear" for
    linear annealing(退火).
    Default: 'cos'
cycle_momentum (bool): If ``True``, momentum is cycled inversely(相反地)
    to learning rate between 'base_momentum' and 'max_momentum'.
    Default: True
base_momentum (float or list): Lower momentum boundaries in the cycle
    for each parameter group. Note that momentum is cycled inversely
    to learning rate; at the peak of a cycle, momentum is
    'base_momentum' and learning rate is 'max_lr'.
    Default: 0.85
max_momentum (float or list): Upper momentum boundaries in the cycle
    for each parameter group. Functionally,
    it defines the cycle amplitude(振幅) (max_momentum - base_momentum).
    Note that momentum is cycled inversely
    to learning rate; at the start of a cycle, momentum is 'max_momentum'
    and learning rate is 'base_lr'

    Default: 0.95
div_factor (float): Determines the initial learning rate via
    initial_lr = max_lr/div_factor
    Default: 25
final_div_factor (float): Determines the minimum learning rate via
    min_lr = initial_lr/final_div_factor (可以看出,最终的lr是非常非常小的
    Default: 1e4
three_phase (bool): If ``True``, use a third phase of the schedule to annihilate(消灭) the
    learning rate according to 'final_div_factor' instead of modifying the second
    phase (the first two phases will be symmetrical about the step indicated by
    'pct_start').

    Default: False
last_epoch (int): The index of the last batch. This parameter is used when
    resuming a training job. Since `step()` should be invoked after each
    batch instead of after each epoch, this number represents the total
    number of *batches* computed, not the total number of epochs computed.(这句话的意思是:last_epoch表示已经训练了多少个batches,而不是训练了多少个epochs)
    When last_epoch=-1, the schedule is started from the beginning.
    Default: -1
verbose (bool): If ``True``, prints a message to stdout for
    each update. Default: ``False``.

关于参数我的一些理解:

  1. optimizer 学习率是要在优化器中使用的。这个参数就是用于指定这个学习率用于哪个优化器。根据我的观察,其实就是给optimizer加了一个调整学习率的HOOK
  2. max_lr 就是【1.1、】图的上界;
  3. total_steps 或者 (epochs + steps_per_epoch)二者必须设置其中一个(官方文档:You must either provide a value for total_steps or provide a value for both epochs and steps_per_epoch.)原因是计算每一步的学习率需要用到 total_steps 。通过(epochs + steps_per_epoch)可以计算出total_steps(total_steps = epochs * steps_per_epoch)
  4. pct_start 表示【1.1、】图的上升阶段占 total_steps 的比例;
  5. anneal_strategy 表示【1.1、】途中下降阶段的策略:cos、linear;
  6. cycle_momentum 这个不怎么理解,直接使用默认值就可以了
  7. max_momentum 这个也不怎么理解,使用默认值就可以了;关于单词“inversely”的含义可以参考其中标红的部分
  8. div_factor 确定初始学习率,即【1.1、】图最左侧的起点,使用默认值就可以
  9. final_div_factor 确定最终的学习率,即【1.1、】图最右侧的终点,使用默认值就可以
  10. three_phase 这个后面单独细讲
  11. last_epoch 看英语解释就可以,比较容易理解
  12. verbose 看英语解释就可以,比较容易理解

1.2.1、关于参数 three_phase 的介绍

【1.1、】中图只有上升和下降两个阶段。将【1.1、】图的代码增加 three_phase=True 参数后,

scheduler =torch.optim.lr_scheduler.OneCycleLR(optimizer,total_steps=100,max_lr=0.9,three_phase=True)

其图像会变成下面这样:

 整个图将分为3个部分:①上升阶段,②第一个下降阶段,③第二个下降阶段

并且:① 和 ② 是对称的

①和②在total_steps中的占比都是pct_start。所以pct_start如果大于等于0.5,那么即使设置了tree_phase参数,也不会出现③这个阶段。

补充:如果上升和下降都采用线性(linear)的方法,图像会类似于下图:

(来自:侵权立删)

1.2.2、three_phase 对训练效果影响的注意点

官方有这么一句话:The default behaviour of this scheduler follows the fastai implementation of 1cycle, which claims that "unpublished work has shown even better results by using only two phases". To mimic the behaviour of the original paper instead, set ``three_phase=True``.

即,论文中的 OneCycleLR() 是三阶段的,但是有人验证过了,三阶段的训练效果没有二阶段的训练效果好。所以直接使用默认值 False 更好一些。

1.3、官方的使用例子

data_loader = torch.utils.data.DataLoader(...)
optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9)
scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=0.01, steps_per_epoch=len(data_loader), epochs=10)
for epoch in range(10):
    for batch in data_loader:
        train_batch(...)
        scheduler.step()

二、一个可以直接使用的OneCycleLR配置

scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=0.01, total_steps=100)

three_phase 使用默认值(False)效果更好。

  • 8
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 你可以通过 pip 命令来安装 OneCycleLR 库,具体命令如下: ``` pip install torch-lr-finder ``` 安装完成后,你就可以在 Python 中使用 OneCycleLR 库了。如果你使用的是 Jupyter Notebook,可以在 Notebook 中执行以下命令来检查 OneCycleLR 是否安装成功: ``` import torch_lr_finder ``` 如果没有报错,说明 OneCycleLR 安装成功了。 ### 回答2: 要安装OneCycleLR,需要按照以下步骤进行操作。 首先,确保你已经安装了Python环境和PyTorch库。PyTorch是一个用于深度学习的开源框架,可以通过pip命令安装。 接下来,使用pip命令安装torchvision库。该库提供了图像数据处理和模型预训练等功能,是PyTorch的一部分。 在安装了必要的库之后,你可以开始编写代码。打开一个文本编辑器,并创建一个新的Python脚本。导入必要的库,包括torchtorchvision。 接着,你需要使用torchvision.datasets模块加载训练数据集。例如,你可以使用CIFAR-10数据集进行演示。从torchvision.datasets导入CIFAR10,并使用该类的构造函数创建一个实例。 然后,利用torch.utils.data.DataLoader对数据进行预处理,包括标准化和数据增强。这个类可以帮助你有效地加载和处理数据。 接下来,导入torch.optim模块,使用该模块的函数创建一个优化器对象。例如,你可以使用SGD(随机梯度下降)优化器。 然后,使用torch.optim.lr_scheduler模块导入OneCycleLR类。创建一个OneCycleLR对象,并将其传递给优化器的学习率参数。 接着,使用torch.nn模块导入神经网络模型(例如,ResNet)。 在训练循环中,首先将模型设为训练模式,并将优化器的梯度清零。然后根据数据集的大小,迭代训练数据并计算损失。 最后,根据优化器的梯度更新模型参数,并更新学习率。使用torchvision.transforms模块对测试数据进行变换。然后,使用测试数据对模型进行评估。 以上是安装OneCycleLR的基本步骤。根据你的实际需求,你可能需要进行一些额外的配置和调整。如果需要更详细的操作指南,可以参考PyTorch官方文档和相关教程。 ### 回答3: 要安装OneCycleLR,首先确保已经安装了PyTorch库。OneCycleLR是PyTorch中的一个学习率调度器,可以在训练过程中自动调整学习率。以下是安装步骤: 1. 打开你的Python环境(如Anaconda Prompt或Jupyter Notebook)。 2. 确认你已经安装了PyTorch库。可以通过在命令行中运行以下命令来检查: `conda list` 或 `pip list`。如果已安装PyTorch,则会列出版本号。 3. 在Python环境中,可以通过运行以下命令来安装torchvision: `pip install torchvision`。 4. 一旦安装了torchvision,你就可以使用以下命令安装OneCycleLR: `pip install torch-lr-finder`。这是一个包含了OneCycleLR的PyTorch插件。 5. 安装完成后,你就可以在代码中导入OneCycleLR: `from torch_lr_finder import LRFinder`。 6. 现在你可以在训练代码中使用OneCycleLR。例如,你可以使用以下代码块来设置学习率调度器: ```python import torch.optim as optim from torch.optim.lr_scheduler import OneCycleLR # 创建你的模型和优化器 model = ... optimizer = optim.SGD(model.parameters(), lr=0.1) # 创建一个学习率调度器 scheduler = OneCycleLR(optimizer, max_lr=0.1, epochs=10, steps_per_epoch=len(train_loader)) # 在训练循环中使用学习率调度器 for epoch in range(epochs): for batch_idx, (inputs, targets) in enumerate(train_loader): # 训练模型 ... optimizer.step() # 更新模型参数 scheduler.step() # 调整学习率 ``` 以上就是在PyTorch中安装和使用OneCycleLR的步骤,通过OneCycleLR可以有效地调整学习率并提高模型的训练效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值