PyTorch框架学习十四——学习率调整策略
PyTorch框架學(xué)習(xí)十四——學(xué)習(xí)率調(diào)整策略
- 一、_LRScheduler類
- 二、六種常見的學(xué)習(xí)率調(diào)整策略
- 1.StepLR
- 2.MultiStepLR
- 3.ExponentialLR
- 4.CosineAnnealingLR
- 5.ReduceLRonPlateau
- 6.LambdaLR
在上次筆記優(yōu)化器的內(nèi)容中介紹了學(xué)習(xí)率的概念,但是在整個訓(xùn)練過程中學(xué)習(xí)率并不是一直不變的,一般學(xué)習(xí)率是要先設(shè)置的大一些,然后在訓(xùn)練過程中慢慢減小。這次筆記就簡單介紹一下PyTorch中學(xué)習(xí)率調(diào)整策略。
一、_LRScheduler類
是各種具體學(xué)習(xí)率調(diào)整策略方法函數(shù)所要繼承的基類。
主要屬性:
- optimizer:關(guān)聯(lián)的優(yōu)化器
- last_epoch:記錄epoch數(shù)
- base_lrs:記錄初始學(xué)習(xí)率
主要方法:
- step():更新下一個epoch的學(xué)習(xí)率。
- get_lr():虛函數(shù),計算下一個epoch的學(xué)習(xí)率。
二、六種常見的學(xué)習(xí)率調(diào)整策略
1.StepLR
功能:等間隔調(diào)整學(xué)習(xí)率。
torch.optim.lr_scheduler.StepLR(optimizer, step_size, gamma=0.1, last_epoch=-1)參數(shù)如下:
調(diào)整方式:lr = lr * gamma
舉個栗子:
# 導(dǎo)入模塊、設(shè)定超參數(shù)、給定權(quán)重數(shù)據(jù) import torch import torch.optim as optim import numpy as np import matplotlib.pyplot as plt torch.manual_seed(1)LR = 0.1 iteration = 10 max_epoch = 200weights = torch.randn((1), requires_grad=True) target = torch.zeros((1))optimizer = optim.SGD([weights], lr=LR, momentum=0.9)# StepLR,每隔50輪下降一次學(xué)習(xí)率 scheduler_lr = optim.lr_scheduler.StepLR(optimizer, step_size=50, gamma=0.1) # 設(shè)置學(xué)習(xí)率下降策略lr_list, epoch_list = list(), list() for epoch in range(max_epoch):# 獲取當(dāng)前l(fā)r,新版本用 get_last_lr()函數(shù),舊版本用get_lr()函數(shù),具體看UserWarninglr_list.append(scheduler_lr.get_last_lr())epoch_list.append(epoch)for i in range(iteration):loss = torch.pow((weights - target), 2)loss.backward()optimizer.step()optimizer.zero_grad()scheduler_lr.step()plt.plot(epoch_list, lr_list, label="Step LR Scheduler") plt.xlabel("Epoch") plt.ylabel("Learning rate") plt.legend() plt.show()繪制出的結(jié)果如圖所示:
從圖中可見每隔50輪學(xué)習(xí)率下降為原來的0.1倍。
2.MultiStepLR
功能:按照給定間隔調(diào)整學(xué)習(xí)率。
torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones, gamma=0.1, last_epoch=-1)參數(shù)如下:
調(diào)整方式:lr = lr * gamma
舉個栗子:
milestones = [50, 125, 160] scheduler_lr = optim.lr_scheduler.MultiStepLR(optimizer, milestones=milestones, gamma=0.1)lr_list, epoch_list = list(), list() for epoch in range(max_epoch):lr_list.append(scheduler_lr.get_last_lr())epoch_list.append(epoch)for i in range(iteration):loss = torch.pow((weights - target), 2)loss.backward()optimizer.step()optimizer.zero_grad()scheduler_lr.step()plt.plot(epoch_list, lr_list, label="Multi Step LR Scheduler\nmilestones:{}".format(milestones)) plt.xlabel("Epoch") plt.ylabel("Learning rate") plt.legend() plt.show()結(jié)果如下圖所示:
從圖中可見,在我們設(shè)定的位置:50/125/160輪時學(xué)習(xí)率下降為原來的0.1倍。
3.ExponentialLR
功能:按指數(shù)衰減調(diào)整lr。
torch.optim.lr_scheduler.ExponentialLR(optimizer, gamma, last_epoch=-1)參數(shù)需要關(guān)注的只有一個:
- gamma:指數(shù)的底。
調(diào)整策略:lr = lr * gamma ^ epoch
舉個栗子:
gamma = 0.95 scheduler_lr = optim.lr_scheduler.ExponentialLR(optimizer, gamma=gamma)lr_list, epoch_list = list(), list() for epoch in range(max_epoch):lr_list.append(scheduler_lr.get_last_lr())epoch_list.append(epoch)for i in range(iteration):loss = torch.pow((weights - target), 2)loss.backward()optimizer.step()optimizer.zero_grad()scheduler_lr.step()plt.plot(epoch_list, lr_list, label="Exponential LR Scheduler\ngamma:{}".format(gamma)) plt.xlabel("Epoch") plt.ylabel("Learning rate") plt.legend() plt.show()學(xué)習(xí)率變化結(jié)果如下圖所示:
4.CosineAnnealingLR
功能:余弦周期調(diào)整lr。
torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max, eta_min=0, last_epoch=-1)參數(shù)如下所示:
調(diào)整方式:
學(xué)習(xí)率變化曲線如下圖所示:
T_max設(shè)置為50,所以0-50下降,50-100上升,以此類推。
5.ReduceLRonPlateau
功能:監(jiān)控指標(biāo),當(dāng)指標(biāo)不再變化則調(diào)整。
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)參數(shù)如下所示:
舉個栗子:
loss_value = 0.5 accuray = 0.9factor = 0.1 mode = "min" patience = 10 cooldown = 10 min_lr = 1e-4 verbose = Truescheduler_lr = optim.lr_scheduler.ReduceLROnPlateau(optimizer, factor=factor, mode=mode, patience=patience,cooldown=cooldown, min_lr=min_lr, verbose=verbose)for epoch in range(max_epoch):for i in range(iteration):# train(...)optimizer.step()optimizer.zero_grad()# if epoch == 5:# loss_value = 0.4scheduler_lr.step(loss_value)結(jié)果如下所示:
Epoch 12: reducing learning rate of group 0 to 1.0000e-02. Epoch 33: reducing learning rate of group 0 to 1.0000e-03. Epoch 54: reducing learning rate of group 0 to 1.0000e-04.6.LambdaLR
功能:自定義調(diào)整策略。
torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda, last_epoch=-1)參數(shù)主要就一個:
lr_lambda:函數(shù)或list。
舉個例子:
lr_init = 0.1weights_1 = torch.randn((6, 3, 5, 5)) weights_2 = torch.ones((5, 5))optimizer = optim.SGD([{'params': [weights_1]},{'params': [weights_2]}], lr=lr_init)lambda1 = lambda epoch: 0.1 ** (epoch // 20) lambda2 = lambda epoch: 0.95 ** epochscheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=[lambda1, lambda2])lr_list, epoch_list = list(), list() for epoch in range(max_epoch):for i in range(iteration):# train(...)optimizer.step()optimizer.zero_grad()scheduler.step()lr_list.append(scheduler.get_lr())epoch_list.append(epoch)print('epoch:{:5d}, lr:{}'.format(epoch, scheduler.get_lr()))plt.plot(epoch_list, [i[0] for i in lr_list], label="lambda 1") plt.plot(epoch_list, [i[1] for i in lr_list], label="lambda 2") plt.xlabel("Epoch") plt.ylabel("Learning Rate") plt.title("LambdaLR") plt.legend() plt.show()結(jié)果如下圖所示,一個是每隔20輪學(xué)習(xí)率下降為0.1倍,一個是指數(shù)衰減,底為0.95:
總結(jié)
以上是生活随笔為你收集整理的PyTorch框架学习十四——学习率调整策略的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python学习笔记(运算符)
- 下一篇: openMP的简单使用