python コピー
import math
import torch
import torch.nn as nn
"""
N-BEATS の小さな実装(論文 arXiv:1905.10437 の 3章・式1〜3 に沿う)
入力 x: [バッチ, 過去の窓の長さ t] → 出力: [バッチ, 未来の窓の長さ H]
"""
class Block(nn.Module):
def __init__(self, backcast_len, horizon, width, theta_b_dim, theta_f_dim, basis="generic"):
super().__init__()
# 全結合層 + ReLU を 4 つ(式 1)
self.fc = nn.Sequential(
nn.Linear(backcast_len, width), nn.ReLU(),
nn.Linear(width, width), nn.ReLU(),
nn.Linear(width, width), nn.ReLU(),
nn.Linear(width, width), nn.ReLU(),
)
# 2 つに分かれて係数 θ^b・θ^f を出す線形層
self.theta_b = nn.Linear(width, theta_b_dim, bias=False)
self.theta_f = nn.Linear(width, theta_f_dim, bias=False)
self.basis = basis
if basis == "generic":
# 汎用:基底も学習する線形層(V θ + b)
self.g_b = nn.Linear(theta_b_dim, backcast_len)
self.g_f = nn.Linear(theta_f_dim, horizon)
else:
# 傾向・季節:基底の行列を固定(学習しない)
self.register_buffer("V_b", self.make_basis(basis, backcast_len, theta_b_dim))
self.register_buffer("V_f", self.make_basis(basis, horizon, theta_f_dim))
@staticmethod
def make_basis(kind, length, dim):
t = torch.arange(length, dtype=torch.float32) / length # t = [0, 1, ..., length-1] / length
if kind == "trend": # 式 2:t^0, t^1, ..., t^p(dim = p + 1)
return torch.stack([t ** i for i in range(dim)])
half = dim // 2 # 式 3:cos(2π i t) と sin(2π i t)
cos = [torch.cos(2 * math.pi * i * t) for i in range(half)]
sin = [torch.sin(2 * math.pi * i * t) for i in range(half)]
return torch.stack(cos + sin)
def forward(self, x):
h = self.fc(x)
tb, tf = self.theta_b(h), self.theta_f(h)
if self.basis == "generic":
return self.g_b(tb), self.g_f(tf)
return tb @ self.V_b, tf @ self.V_f # 係数で基底を重み付けして足す
class NBeats(nn.Module):
def __init__(self, blocks):
super().__init__()
self.blocks = nn.ModuleList(blocks)
def forward(self, x):
residual, forecast = x, 0
for block in self.blocks:
backcast, partial = block(residual)
residual = residual - backcast # 過去の窓の側は引き算
forecast = forecast + partial # 未来の窓の側は足し算
return forecast
H, L = 18, 6 * 18 # 未来の窓 18(M4 の月ごと)、過去の窓 6H
# 汎用の構成(N-BEATS-G):30 スタック × 1 ブロック、幅 512
generic = NBeats([Block(L, H, 512, 32, 32, "generic") for _ in range(30)])
# 解釈できる構成(N-BEATS-I):傾向(3 ブロック、重みを共有)→ 季節(3 ブロック、重みを共有)
trend = Block(L, H, 256, 3, 3, "trend") # 多項式の次数 p = 2 → 係数 3 個
season = Block(L, H, 2048, 2 * (H // 2), 2 * (H // 2), "seasonality")
interpretable = NBeats([trend] * 3 + [season] * 3) # 同じブロックを 3 回使う=重みの共有
model = interpretable
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
def smape(y_hat, y):
# 論文は sMAPE で学習するとき、分母の勾配を止めて安定させる
denom = (y.abs() + y_hat.abs()).detach().clamp_min(1e-8)
return (200 * (y - y_hat).abs() / denom).mean()
x = torch.rand(1024, L) + 1.0 # 過去の窓(1,024 本の系列から切り出す)
y = torch.rand(1024, H) + 1.0 # 未来の窓の正解
model.train()
optimizer.zero_grad()
loss = smape(model(x), y)
loss.backward()
optimizer.step()
model.eval()
with torch.no_grad():
pred = model(x) # [1024, 18]