torch 实现inverse-square-root scheduler

python 复制代码
import cv2
import torch.nn as nn
import torch
from torchvision.models import AlexNet
import matplotlib.pyplot as plt

from torch.optim.lr_scheduler import LambdaLR
def get_inverse_sqrt_scheduler(optimizer, num_warmup_steps, num_cooldown_steps, num_training_steps):
    # linearly warmup for the first args.warmup_updates
    lr_step = 1 / num_warmup_steps
    # then, decay prop. to the inverse square root of the update number
    decay_factor = num_warmup_steps**0.5
    decayed_lr = decay_factor * (num_training_steps - num_cooldown_steps) ** -0.5
    def lr_lambda(current_step: int):
        if current_step < num_warmup_steps:
            return float(current_step * lr_step)
        elif current_step > (num_training_steps - num_cooldown_steps):
            return max(0.0, float(decayed_lr * (num_training_steps - current_step) / num_cooldown_steps))
        else:
            return float(decay_factor * current_step**-0.5)

    return LambdaLR(optimizer, lr_lambda, last_epoch=-1)

#定义2分类网络
steps = []
lrs = []
model = AlexNet(num_classes=2)
lr = 0.1
optimizer = torch.optim.SGD(model.parameters(), lr=lr, momentum=0.9)
#前10steps warmup ,中间70steps正常衰减,最后20个steps期间衰减到0
scheduler = get_inverse_sqrt_scheduler(optimizer,num_warmup_steps=10, num_cooldown_steps=20, num_training_steps=100)
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='inverse_sqrt')
plt.savefig("dd.png")
相关推荐
算法熔炉13 分钟前
深度学习面试八股文(1)——训练
人工智能·深度学习·面试
算法熔炉13 分钟前
深度学习面试八股文(2)——训练
人工智能·深度学习·算法
Dxy123931021614 分钟前
Python类入门:用“汽车工厂”理解面向对象编程
python
拉普拉斯妖10818 分钟前
DAY35 模型可视化与推理
python
无垠的广袤20 分钟前
【启明云端 WT9932S3-Nano 开发板】介绍、环境搭建、工程测试
python·单片机·嵌入式硬件
2301_7644413329 分钟前
PMC政策文本量化评估
python·算法·信息可视化
木土雨成小小测试员31 分钟前
Python测试开发之跨域请求
开发语言·python
闲人编程32 分钟前
静态文件处理与模板渲染深度指南
python·渲染·毕设·模板引擎·静态文件·codecapsule
deephub41 分钟前
PyCausalSim:基于模拟的因果发现的Python框架
开发语言·python·机器学习·因果发现
南_山无梅落1 小时前
8.Python3字典(dict):键值的增删改查_入门到进阶
python·算法