python
import torch
import torch.nn as nn
# AdaDelta の1ステップを、論文の Algorithm 1 どおりに書いたもの
def adadelta_step(x, grad, eg2, edx2, rho=0.95, eps=1e-6):
eg2 = rho * eg2 + (1 - rho) * grad ** 2 # 勾配の2乗の移動平均 E[g^2]_t
dx = -torch.sqrt(edx2 + eps) / torch.sqrt(eg2 + eps) * grad # RMS[Δx]_{t-1} / RMS[g]_t を掛ける
edx2 = rho * edx2 + (1 - rho) * dx ** 2 # 更新量の2乗の移動平均 E[Δx^2]_t
return x + dx, eg2, edx2
# PyTorch の Adadelta と同じ結果になるかを確かめる(lr=1.0 で論文と同じ計算)
torch.manual_seed(0)
w = torch.randn(5, requires_grad=True)
w_manual = w.detach().clone()
eg2 = torch.zeros_like(w_manual) # E[g^2]_0 = 0
edx2 = torch.zeros_like(w_manual) # E[Δx^2]_0 = 0
optimizer = torch.optim.Adadelta([w], lr=1.0, rho=0.95, eps=1e-6) # 論文の設定(PyTorch の既定は rho=0.9)
for t in range(10):
loss = ((w - 3.0) ** 2).sum()
optimizer.zero_grad()
loss.backward()
grad = w.grad.detach().clone()
optimizer.step()
w_manual, eg2, edx2 = adadelta_step(w_manual, grad, eg2, edx2)
print(torch.allclose(w.detach(), w_manual, atol=1e-6)) # True になるはず
# 実際の学習での使い方(MNIST の 2 層ネットワーク。学習率は探さない)
model = nn.Sequential(nn.Flatten(), nn.Linear(784, 500), nn.ReLU(),
nn.Linear(500, 300), nn.ReLU(), nn.Linear(300, 10))
optimizer = torch.optim.Adadelta(model.parameters(), lr=1.0, rho=0.95, eps=1e-6)
x = torch.randn(100, 1, 28, 28) # ダミーのミニバッチ(論文と同じ 100 枚)
y = torch.randint(0, 10, (100,))
loss = nn.functional.cross_entropy(model(x), y)
optimizer.zero_grad()
loss.backward()
optimizer.step()