python
import math
import torch
import torch.nn as nn
# 1 次元(学習率の対数)のベイズ最適化を、ガウス過程と期待改善量(EI)で書いた例
torch.manual_seed(0)
X_train, y_train = torch.randn(512, 20), torch.randint(0, 2, (512,))
X_val, y_val = torch.randn(256, 20), torch.randint(0, 2, (256,))
def objective(u: float) -> float:
"""u は 0〜1。学習率 10^(−4 + 3u)(0.0001〜0.1)で小さなモデルを学習し、検証の損失を返す"""
lr = 10 ** (-4 + 3 * u)
model = nn.Sequential(nn.Linear(20, 64), nn.ReLU(), nn.Linear(64, 2))
opt = torch.optim.SGD(model.parameters(), lr=lr)
loss_fn = nn.CrossEntropyLoss()
for _ in range(200):
opt.zero_grad()
loss_fn(model(X_train), y_train).backward()
opt.step()
with torch.no_grad():
return loss_fn(model(X_val), y_val).item()
def matern52(a, b, length=0.2, amp=1.0):
r = (a[:, None] - b[None, :]).abs() / length
return amp * (1 + math.sqrt(5) * r + 5.0 / 3.0 * r ** 2) * torch.exp(-math.sqrt(5) * r)
def gp_posterior(x_obs, y_obs, x, noise=1e-4):
mean = y_obs.mean()
K = matern52(x_obs, x_obs) + noise * torch.eye(len(x_obs))
L = torch.linalg.cholesky(K)
k_s = matern52(x_obs, x)
alpha = torch.cholesky_solve((y_obs - mean)[:, None], L)
mu = mean + (k_s.T @ alpha).squeeze(1)
v = torch.linalg.solve_triangular(L, k_s, upper=False)
var = (matern52(x, x).diagonal() - (v ** 2).sum(0)).clamp_min(1e-12)
return mu, var.sqrt()
def expected_improvement(mu, sigma, best):
normal = torch.distributions.Normal(torch.zeros((), dtype=mu.dtype), torch.ones((), dtype=mu.dtype))
gamma = (best - mu) / sigma
return sigma * (gamma * normal.cdf(gamma) + normal.log_prob(gamma).exp())
grid = torch.linspace(0, 1, 501, dtype=torch.float64)
x_obs = torch.rand(3, dtype=torch.float64) # 1. 初めの 3 点をランダムに試す
y_obs = torch.tensor([objective(u.item()) for u in x_obs], dtype=torch.float64)
for step in range(10): # 2〜5 を 10 回繰り返す
y_std = (y_obs - y_obs.mean()) / (y_obs.std() + 1e-9) # 損失の尺度をそろえてから当てはめる
mu, sigma = gp_posterior(x_obs, y_std, grid)
ei = expected_improvement(mu, sigma, y_std.min())
u_next = grid[ei.argmax()]
y_next = objective(u_next.item())
x_obs = torch.cat([x_obs, u_next[None]])
y_obs = torch.cat([y_obs, torch.tensor([y_next], dtype=torch.float64)])
print(f"{step + 1:2d} 回目: 学習率 {10 ** (-4 + 3 * u_next.item()):.5f}, 検証の損失 {y_next:.4f}")
best = y_obs.argmin()
print("最も良かった学習率:", 10 ** (-4 + 3 * x_obs[best].item()))