python
import math
import torch
import torch.nn as nn
# 論文の式 (5)。本文の表の値を計算する
def cosine_lr(t_cur, t_i, eta_max=0.05, eta_min=0.0):
return eta_min + 0.5 * (eta_max - eta_min) * (1 + math.cos(math.pi * t_cur / t_i))
print([round(cosine_lr(t, 10), 3) for t in [0, 2.5, 5, 7.5, 10]])
# [0.05, 0.043, 0.025, 0.007, 0.0]
# SGDR(ウォームリスタートあり)を PyTorch で使う例
model = nn.Sequential(nn.Flatten(), nn.Linear(28 * 28, 256), nn.ReLU(), nn.Linear(256, 10))
optimizer = torch.optim.SGD(model.parameters(), lr=0.05, momentum=0.9)
# T_0 = 10 エポック、周期を 2 倍ずつ伸ばす(10, 20, 40, 80 エポック)
scheduler = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizer, T_0=10, T_mult=2, eta_min=0.0)
criterion = nn.CrossEntropyLoss()
epochs = 150 # 10 + 20 + 40 + 80 = 150 で、4 周期目の終わり(学習率が最小)に止まる
iters = 100 # 1 エポックあたりのミニバッチ数(ダミー)
for epoch in range(epochs):
for i in range(iters):
images = torch.randn(64, 1, 28, 28)
labels = torch.randint(0, 10, (64,))
optimizer.zero_grad()
loss = criterion(model(images), labels)
loss.backward()
optimizer.step()
# ミニバッチごとに、小数のエポックを渡して学習率を更新する
scheduler.step(epoch + i / iters)
# リスタートなしのコサインアニーリング:T_max は step() を呼ぶ回数
# (エポックごとに step() を呼ぶならエポック数、ミニバッチごとなら総ステップ数)
optimizer2 = torch.optim.SGD(model.parameters(), lr=0.05)
scheduler2 = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer2, T_max=150, eta_min=0.0)