在實驗過程中我們可能都對learning rate的選取而苦腦過
- learning rate過小:loss降低過慢
- learning rate過大:loss可能達不到最優,而可能在最優值範圍震動
其比較如下圖所示
解決辦法
1. 使用ReducLROnPlateau
1.1 介紹
該類是torch.optim.lr_scheduler.ReduceLROnPlateau()
使用方法如下:
class torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.1, patience=0,
verbose=False, threshold=0.0001, threshold_mode='rel', cooldown=0, min_lr=0, eps=1e-08)
參數說明:
- optimer指的是網絡的優化器
- mode (str) ,可選擇‘min’或者‘max’,min表示當監控量停止下降的時候,學習率將減小,max表示當監控量停止上升的時候,學習率將減小。默認值爲‘min’
- factor 學習率每次降低多少,new_lr = old_lr * factor
- patience=10,容忍網路的性能不提升的次數,高於這個次數就降低學習率
- verbose(bool) - 如果爲True,則爲每次更新向stdout輸出一條消息。 默認值:False
- threshold(float) - 測量新最佳值的閾值,僅關注重大變化。 默認值:1e-4
- cooldown: 減少lr後恢復正常操作之前要等待的時期數。 默認值:0。
- min_lr,學習率的下限
- eps ,適用於lr的最小衰減。 如果新舊lr之間的差異小於eps,則忽略更新。 默認值:1e-8。
1.2 使用注意事項
scheduler.step(train_loss) #這裏不再用optimizer.step()
import torch
..... # 此處省略部分代碼
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
scheduler = ReduceLROnPlateau(optimizer, 'min',factor=0.1, patience=10, verbose=True)
..... # 此處省略部分代碼
scheduler.step(train_loss) #這裏不再用optimizer.step()
# scheduler.step(val_loss)
2. 使用StepLR
2.1 介紹
該類是torch.optim.lr_scheduler.StepLR()
使用方法如下:
torch.optim.lr_scheduler.StepLR(optimizer,step_size=30,gamma=0.1)
參數說明:
- optimer指的是網絡的優化器
- step_size指的是step_size次更新一次learning rate,即new_lr = old_lr * gamma
- gamma指的是學習率每次降低多少,默認爲0.1
2.2 使用注意事項
scheduler.step(train_loss) #這裏不再用optimizer.step()
import torch
..... # 此處省略部分代碼
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer,step_size=30,gamma=0.1)
..... # 此處省略部分代碼
scheduler.step(train_loss) #這裏不再用optimizer.step()
# scheduler.step(val_loss)