pytorch-scheduler(调度器)

scheduler简介


scheduler(调度器)是一种用于调整优化算法中学习率的机制。学习率是控制模型参数更新幅度的关键超参数,而调度器根据预定的策略在训练过程中动态地调整学习率。
优化器负责根据损失函数的梯度更新模型的参数,而调度器则负责调整优化过程中使用的特定参数,通常是学习率。调度器通过调整学习率帮助优化器更有效地搜索参数空间,避免陷入局部最小值,并加快收敛速度。
调度器允许实现复杂的训练策略,学习率预热、周期性调整或突然降低学习率,这些策略对于优化器的性能至关重要。

学习率绘图函数
我们设定一简单的模型,得带100 epoch,绘制迭代过程中loss的变化

import os
import torch
from torch.optim import lr_scheduler
import matplotlib.pyplot as plt

# 模拟训练过程,每循环一次更新一次学习率
def get_lr_scheduler(optim, scheduler, total_step):
    '''
    get lr values
    '''
    lrs = []
    for step in range(total_step):
        lr_current = optim.param_groups[0]['lr']
        lrs.append(lr_current)
        if scheduler is not None:
            scheduler.step()
    return lrs
# 将损失函数替换为学习率,模拟根据损失函数进行自适调整的学习率变化 
def get_lr_scheduler1(optim, scheduler, total_step):
    '''
    get lr values
    '''
    lrs = []
    for step in range(total_step):
        lr_current = optim.param_groups[0]['lr']
        lrs.append(lr_current)
        if scheduler is not None:
            scheduler.step(lr_current)
    return lrs

余弦拟退火(CosineAnnealingLR)

torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max, eta_min=0, last_epoch=-1, verbose=‘deprecated’)
cosine形式的退火学习率变化机制,顾名思义,学习率变化曲线是cos形式的,定义一个正弦曲线需要四个参数,周期、最大最小值、相位。其中周期=2T_max,eta_min周期函数的峰值,last_epoch表示加载模型的迭代步数,定义cos曲线的初始位置,当它为-1时,参数不生效,初始相位就是0,否则就是last_epochT_max/pi。
在这里插入图片描述当 last_epoch=-1 时,将初始学习率设置为学习率。请注意,由于计划是递归定义的,学习率可以同时被此调度程序之外的其他操作者修改。如果学习率仅由这个调度程序设置,那么每个步骤的学习率变为:
\begin{aligned}
\eta_t = \eta_{min} + \frac{1}{2}(\eta_{max} - \eta_{min})\left(1 +
\cos\left(\frac{T_{cur}}{T_{max}}\pi\right)\right)
\end{aligned}

def plot_cosine_aneal():
    plt.clf()
    optim = torch.optim.Adam([{
   'params': model.parameters(),
                            'initial_lr': initial_lr}], lr=initial_lr)

    scheduler = lr_scheduler.CosineAnnealingLR(
        optim, T_max=40, eta_min=0.2)
    lrs = get_lr_scheduler(optim, scheduler, total_step)
    plt.plot(lrs, label='eta_min=0.2,,last epoch=-1')
    
    # if not re defined, the init lr will be lrs[-1]
    optim = torch.optim.Adam([{
   'params': model.parameters(),
                            'initial_lr': initial_lr}], lr=initial_lr)
    scheduler = lr_scheduler.CosineAnnealingLR(
        optim, T_max=40, eta_min=0.2, last_epoch=10)
    lrs = get_lr_scheduler(optim, scheduler, total_step)
    plt.plot(lrs, label='eta_min=0.2,,last epoch=10')

    # eta_min
    scheduler = lr_scheduler.CosineAnnealingLR(
        optim, T_max=40, eta_min=0.5, last_epoch=10)
    lrs = get_lr_scheduler(optim, scheduler, total_step)
    plt.plot(lrs, label='eta_min=0.5,,last epoch=10')

    plt.title('CosineAnnealingLR')
    plt.legend()
    plt.show()
plot_cosine_aneal()

在这里插入图片描述

LambdaLR

torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda = function, last_epoch=- 1, verbose=False)
LambdaLR 可以根据用户定义的 lambda 函数或 lambda 函数列表来调整学习率。当您想要实现标准调度器未提供的自定义学习率计划时,这种调度器特别有用。
Lambda 函数是使用 Python 中的 lambda 关键字定义的小型匿名函数。
Lambda 函数应该接受一个参数(周期索引)并返回一个乘数,学习率将乘以这个乘数。

def plot_lambdalr():
    plt.clf()
    # Lambda1
    optim = torch.optim.Adam(model.parameters(), lr=initial_lr)
    scheduler = lr_scheduler.LambdaLR(
        optim, lr_lambda=lambda step: step%40/100.)
    lrs = get_lr_scheduler(optim, scheduler, total_step)
    plt.plot(lrs,label='lambda step: step%40/100.')

    #Lambda2
    optim = torch.optim.Adam(model.parameters(), lr=initial_lr)
    scheduler = lr_scheduler.LambdaLR(
        optim, lr_lambda=lambda step: max(0, 1 - step / 100))
    lrs = get_lr_scheduler(optim, scheduler, total_step)
    plt.plot(lrs,label='lambda step: max(0, 1 - step / 100)')

    plt.title('LambdaLR')
    plt.legend()
    plt.show()
    
plot_lambdalr()

在这里插入图片描述

MultiplicativeLR

torch.optim.lr_scheduler.MultiplicativeLR(optimizer, lr_lambda, last_epoch=-1, verbose=‘deprecated’)
学习率在达到特定的epoch时降低,将每个参数组的学习率乘以指定函数给出的因子,通常用于在训练的不同阶段使用不同的学习率。当 last_epoch=-1 时,将初始学习率设置为学习率。

def plot_multiplicativelr():
    plt.clf()
    optim = torch.optim.Adam
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

云朵不吃雨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值