第12章最適化アルゴリズム
12.9.2. Implementation12.9.2 実装
Adadelta needs to maintain two state variables for each variable, and . This yields the following implementation.
英語のヒント
Adadeltaは、変数ごとに二つの状態変数とを保持する必要がある。これにより、次の実装になる。
%matplotlib inline
import torch
from d2l import torch as d2l
def init_adadelta_states(feature_dim):
s_w, s_b = torch.zeros((feature_dim, 1)), torch.zeros(1)
delta_w, delta_b = torch.zeros((feature_dim, 1)), torch.zeros(1)
return ((s_w, delta_w), (s_b, delta_b))
def adadelta(params, states, hyperparams):
rho, eps = hyperparams['rho'], 1e-5
for p, (s, delta) in zip(params, states):
with torch.no_grad():
# In-place updates via [:]
s[:] = rho * s + (1 - rho) * torch.square(p.grad)
g = (torch.sqrt(delta + eps) / torch.sqrt(s + eps)) * p.grad
p[:] -= g
delta[:] = rho * delta + (1 - rho) * g * g
p.grad.data.zero_()Choosing amounts to a half-life time of 10 for each parameter update. This tends to work quite well. We get the following behavior.
英語のヒント
を選ぶことは、パラメータの更新ごとに半減期が10であることにあたる。これはかなりうまくいく傾向がある。次のようなふるまいが得られる。
data_iter, feature_dim = d2l.get_data_ch11(batch_size=10)
d2l.train_ch11(adadelta, init_adadelta_states(feature_dim),
{'rho': 0.9}, data_iter, feature_dim);loss: 0.245, 0.160 sec/epochFor a concise implementation we simply use the Adadelta algorithm from high-level APIs. This yields the following one-liner for a much more compact invocation.
英語のヒント
簡潔な実装のためには、単に高水準のAPIのAdadeltaのアルゴリズムを使う。これにより、ずっとコンパクトな呼び出しのための、次の1行のコードになる。
trainer = torch.optim.Adadelta
d2l.train_concise_ch11(trainer, {'rho': 0.9}, data_iter)loss: 0.243, 0.119 sec/epoch