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")
相关推荐
Predestination王瀞潞10 分钟前
Python oct() 函数
开发语言·python
B站_计算机毕业设计之家30 分钟前
python汽车数据分析可视化系统 爬虫 懂车帝 毕业设计 Django框架 vue框架 大数据✅
爬虫·python·数据分析·django·汽车·推荐算法·懂车帝
fl17683131 分钟前
基于python+tkinter实现的自动组卷评卷考试系统python源码+课程设计+项目说明
开发语言·python·课程设计
王琦031835 分钟前
Python 综合大作业
python
Dxy12393102161 小时前
Python自动连接已保存WiFi
开发语言·python
依旧很淡定2 小时前
Selenium(Python)创建Chrome浏览器实例
chrome·python·selenium
中文Python2 小时前
小白中文Python-db_桌面小黄鸭宠物
数据库·python·pygame·宠物·中文python·小白学python
it技术2 小时前
Pytorch项目实战 :基于RNN的实现情感分析
pytorch·后端
MoRanzhi12033 小时前
12. Pandas 数据合并与拼接(concat 与 merge)
数据库·人工智能·python·数学建模·矩阵·数据分析·pandas
qianmo20213 小时前
基于gitpage实现网页托管的方式方法
python