python
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import NegativeBinomial, Normal
"""
DeepAR の小さな実装(論文 arXiv:1704.04110 の 3章に沿う)
z: [バッチ, 長さ] の値、x: [バッチ, 長さ, 共変量の数] の共変量(未来の窓の時刻も分かっているもの)
"""
class DeepAR(nn.Module):
def __init__(self, n_cov, n_items, emb_dim=20, hidden=40, layers=3, likelihood="negbin"):
super().__init__()
self.likelihood = likelihood
self.item_emb = nn.Embedding(n_items, emb_dim) # 商品(系列)の分類の埋め込み
self.lstm = nn.LSTM(1 + n_cov + emb_dim, hidden, num_layers=layers, batch_first=True)
self.out_mu = nn.Linear(hidden, 1) # μ(ガウス分布の平均・負の二項分布の平均)
self.out_shape = nn.Linear(hidden, 1) # σ(ガウス分布)または α(負の二項分布)
def _inputs(self, z_prev, x, item):
# 1 つ前の値(スケールで割ったもの)・共変量・商品の埋め込みを並べる
e = self.item_emb(item).unsqueeze(1).expand(-1, x.size(1), -1)
return torch.cat([z_prev.unsqueeze(-1), x, e], dim=-1)
def _dist(self, h, nu):
o_mu, o_s = self.out_mu(h).squeeze(-1), self.out_shape(h).squeeze(-1)
if self.likelihood == "gaussian":
# μ は線形、σ は Softplus。大きさに関わる両方に ν を掛けて戻す
return Normal(o_mu * nu, F.softplus(o_s) * nu + 1e-6)
# 負の二項分布:μ = ν·softplus(o_μ)、α = softplus(o_α)/√ν(3.3 節)
mu = nu * F.softplus(o_mu) + 1e-6
alpha = F.softplus(o_s) / nu.sqrt() + 1e-6
# torch の NegativeBinomial(total_count=r, probs=p) の平均は r·p/(1−p)。r = 1/α、p = αμ/(1+αμ) で平均 μ・分散 μ+μ²α になる
return NegativeBinomial(total_count=1.0 / alpha, probs=alpha * mu / (1.0 + alpha * mu))
@staticmethod
def scale(z_cond):
return 1.0 + z_cond.mean(dim=1, keepdim=True) # ν = 1 + 過去の窓の平均
def loss(self, z, x, item, t0):
"""学習:入力は正解の 1 つ前の値。全時刻の負の対数尤度の平均を返す(論文は t0 = 0 として過去の窓も含める)"""
nu = self.scale(z[:, :t0])
z_prev = F.pad(z[:, :-1], (1, 0)) / nu # z_{t-1}。z_0 = 0
h, _ = self.lstm(self._inputs(z_prev, x, item))
return -self._dist(h, nu).log_prob(z).mean()
@torch.no_grad()
def sample(self, z_cond, x, item, n_samples=200):
"""予測:過去の窓を読み、未来の窓を 1 ステップずつサンプリングする。戻り値 [n_samples, バッチ, 未来の窓の長さ]"""
t0, horizon = z_cond.size(1), x.size(1) - z_cond.size(1)
nu = self.scale(z_cond)
z_prev = F.pad(z_cond[:, :-1], (1, 0)) / nu
_, state = self.lstm(self._inputs(z_prev, x[:, :t0], item)) # 過去の窓を読む
rep = lambda t: t.repeat_interleave(n_samples, dim=0)
state = tuple(s.repeat_interleave(n_samples, dim=1) for s in state)
last, nu_r, item_r = rep(z_cond[:, -1:]), rep(nu), rep(item)
out = []
for k in range(horizon):
xk = rep(x[:, t0 + k:t0 + k + 1])
h, state = self.lstm(self._inputs(last / nu_r, xk, item_r), state)
last = self._dist(h, nu_r).sample() # 引いた値を次の入力に戻す
out.append(last)
return torch.cat(out, dim=1).view(-1, n_samples, horizon).transpose(0, 1)
# 使い方(週ごとの売上:過去の窓 52 週、未来の窓 52 週、共変量 3 個)
model = DeepAR(n_cov=3, n_items=1000)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
z = torch.poisson(torch.rand(64, 104) * 5) # 両方の窓に正解がある学習用の窓
x = torch.randn(64, 104, 3) # 年齢・週などの共変量(標準化済み)
item = torch.randint(0, 1000, (64,))
model.train()
optimizer.zero_grad()
loss = model.loss(z, x, item, t0=52)
loss.backward()
optimizer.step()
model.eval()
samples = model.sample(z[:, :52], x, item) # [200, 64, 52]
p50 = samples.quantile(0.5, dim=0) # 中央値の予測
p90 = samples.quantile(0.9, dim=0) # 90% 点(在庫の判断などに使う)