python コピー
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
Bayes by Backprop(Blundell et al., 2015)の小さな実装
重み 1 本ごとに平均 μ と ρ を持ち、σ = log(1 + exp(ρ)) とする(3.2節)
事前分布は 2 つの正規分布のスケール混合(式 (7))、損失は式 (2) のモンテカルロ近似
"""
PI, SIGMA1, SIGMA2 = 0.5, math.exp(-0), math.exp(-6) # 論文の候補 π∈{1/4,1/2,3/4}, −log σ1∈{0,1,2}, −log σ2∈{6,7,8}
def log_gaussian(x, mu, sigma):
return -0.5 * math.log(2 * math.pi) - torch.log(sigma) - (x - mu) ** 2 / (2 * sigma ** 2)
def log_scale_mixture_prior(w):
p1 = torch.exp(log_gaussian(w, 0.0, torch.tensor(SIGMA1)))
p2 = torch.exp(log_gaussian(w, 0.0, torch.tensor(SIGMA2)))
return torch.log(PI * p1 + (1 - PI) * p2 + 1e-30).sum()
class BayesLinear(nn.Module):
def __init__(self, in_features, out_features):
super().__init__()
self.w_mu = nn.Parameter(torch.empty(out_features, in_features).uniform_(-0.1, 0.1))
self.w_rho = nn.Parameter(torch.full((out_features, in_features), -5.0))
self.b_mu = nn.Parameter(torch.zeros(out_features))
self.b_rho = nn.Parameter(torch.full((out_features,), -5.0))
self.log_q = 0.0 # log q(w|θ)(直近に取り出した重みでの値)
self.log_prior = 0.0 # log P(w)
def forward(self, x):
w_sigma = F.softplus(self.w_rho) # σ = log(1 + exp(ρ))
b_sigma = F.softplus(self.b_rho)
w = self.w_mu + w_sigma * torch.randn_like(w_sigma) # w = μ + σ ∘ ε(推論のときも毎回取り出す)
b = self.b_mu + b_sigma * torch.randn_like(b_sigma)
self.log_q = log_gaussian(w, self.w_mu, w_sigma).sum() + log_gaussian(b, self.b_mu, b_sigma).sum()
self.log_prior = log_scale_mixture_prior(w) + log_scale_mixture_prior(b)
return F.linear(x, w, b)
class BayesMLP(nn.Module):
def __init__(self, in_dim=784, hidden=400, out_dim=10):
super().__init__()
self.layers = nn.ModuleList([BayesLinear(in_dim, hidden), BayesLinear(hidden, hidden), BayesLinear(hidden, out_dim)])
def forward(self, x):
x = x.flatten(1)
for i, layer in enumerate(self.layers):
x = layer(x)
if i < len(self.layers) - 1:
x = F.relu(x)
return x
def complexity_cost(self):
# log q(w|θ) − log P(w):KL[q || P] の 1 サンプルの推定
return sum(l.log_q - l.log_prior for l in self.layers)
def elbo_loss(model, x, y, num_batches, n_samples=1):
"""式 (8):複雑さのコストを 1/M(M はミニバッチの数)に分け、尤度のコストを足す"""
loss = 0.0
for _ in range(n_samples):
logits = model(x)
nll = F.cross_entropy(logits, y, reduction="sum") # −log P(D_i | w)
loss = loss + model.complexity_cost() / num_batches + nll
return loss / n_samples
@torch.no_grad()
def predict(model, x, n_samples=10):
"""重みを n_samples 組取り出して、ソフトマックスの確率を平均する"""
probs = torch.stack([F.softmax(model(x), dim=1) for _ in range(n_samples)]) # [S, B, K]
mean = probs.mean(dim=0)
entropy = -(mean * torch.log(mean + 1e-12)).sum(dim=1) # 予測のエントロピー(不確かさ)
return mean, entropy
# 使い方
# model = BayesMLP()
# optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
# for x, y in train_loader:
# loss = elbo_loss(model, x, y, num_batches=len(train_loader))
# optimizer.zero_grad(); loss.backward(); optimizer.step()
# mean, entropy = predict(model, x_test)