python
import math
import random
import torch
import torch.nn as nn
torch.manual_seed(0)
X_train, y_train = torch.randn(1024, 20), torch.randint(0, 2, (1024,))
X_val, y_val = torch.randn(512, 20), torch.randint(0, 2, (512,))
# 探す空間:学習率(対数)と隠れ層の幅。KDE を当てはめやすいよう、どちらも [0, 1] に直して持つ
def decode(u):
return {"lr": 10 ** (-4 + 3 * u[0]), "hidden": int(16 + u[1] * 240)}
def train_and_eval(state, epochs):
"""候補を epochs エポック目まで学習し(前の段の続きから再開)、検証の損失を返す"""
if "model" not in state:
cfg = decode(state["u"])
state["model"] = nn.Sequential(nn.Linear(20, cfg["hidden"]), nn.ReLU(), nn.Linear(cfg["hidden"], 2))
state["opt"] = torch.optim.SGD(state["model"].parameters(), lr=cfg["lr"], momentum=0.9)
state["done"] = 0
model, opt, loss_fn = state["model"], state["opt"], nn.CrossEntropyLoss()
model.train()
for _ in range(int(epochs) - state["done"]):
for xb, yb in zip(X_train.split(64), y_train.split(64)):
opt.zero_grad()
loss_fn(model(xb), yb).backward()
opt.step()
state["done"] = int(epochs)
model.eval()
with torch.no_grad():
return loss_fn(model(X_val), y_val).item()
def kde(points):
"""多次元のガウスカーネルの KDE(幅はスコットの目安)。密度の関数と幅を返す"""
pts = torch.tensor(points)
n, d = pts.shape
bw = (pts.std(0, unbiased=True).clamp_min(1e-3)) * n ** (-1.0 / (d + 4))
def pdf(x):
z = (x[None, :] - pts) / bw
return torch.exp(-0.5 * (z ** 2).sum(1)).mean() / bw.prod()
return pdf, pts, bw
def sample_config(D, d, rng, rho=1/3, q=0.15, n_samples=64, bw_factor=3.0):
"""論文のアルゴリズム 2(ρ・q・N_s・b_w の値はこの例で決めたもの)"""
n_min = d + 1
if rng.random() < rho: # 1 行目:確率 ρ で乱数
return [rng.random() for _ in range(d)]
budgets = [b for b, obs in D.items() if len(obs) >= n_min + 2]
if not budgets: # 3 行目:観測が足りなければ乱数
return [rng.random() for _ in range(d)]
obs = sorted(D[max(budgets)], key=lambda t: t[1]) # 2 行目:観測が十分ある最大の予算
n_l = max(n_min, int(q * len(obs))) # 式 (3)
n_g = max(n_min, len(obs) - n_l)
l, l_pts, l_bw = kde([u for u, _ in obs[:n_l]]) # 4 行目:良い組の密度 l(x)
g, _, _ = kde([u for u, _ in obs[-n_g:]]) # 悪い組の密度 g(x)
best, best_ratio = None, -1.0
for _ in range(n_samples): # 5 行目:l'(x)(幅を b_w 倍)から引く
center = l_pts[rng.randrange(len(l_pts))]
x = (center + torch.randn(len(center)) * l_bw * bw_factor).clamp(0, 1)
ratio = (l(x) / g(x).clamp_min(1e-32)).item()
if ratio > best_ratio: # 6 行目:l(x)/g(x) が最大のもの
best, best_ratio = x.tolist(), ratio
return best
def bohb(b_max=27, eta=3, d=2, n_iter=2, seed=0):
rng = random.Random(seed)
D = {} # 予算ごとの観測 [(u, 損失), ...]
s_max = int(math.log(b_max) / math.log(eta) + 1e-9)
best = (float("inf"), None)
for _ in range(n_iter):
for s in range(s_max, -1, -1): # Hyperband と同じ bracket の回し方
n = math.ceil((s_max + 1) / (s + 1) * eta ** s)
T = [{"u": sample_config(D, d, rng)} for _ in range(n)] # ここだけが Hyperband と違う
for i in range(s + 1): # Successive Halving
b = b_max * eta ** (i - s)
losses = [train_and_eval(t, b) for t in T]
for t, loss in zip(T, losses):
D.setdefault(b, []).append((t["u"], loss))
if loss < best[0]:
best = (loss, decode(t["u"]))
T = [t for _, t in sorted(zip(losses, T), key=lambda p: p[0])[:max(1, len(T) // eta)]]
return best
print(bohb())