第12章最適化アルゴリズム
12.10.2. Implementation12.10.2 実装
Implementing Adam from scratch is not very daunting. For convenience we store the time step counter in the
hyperparams dictionary. Beyond that all is straightforward.英語のヒント
Adamをゼロから実装するのは、それほど手ごわくない。便宜上、時間ステップのカウンターを辞書
hyperparamsに格納する。それ以外はすべて素直である。%matplotlib inline
import torch
from d2l import torch as d2l
def init_adam_states(feature_dim):
v_w, v_b = torch.zeros((feature_dim, 1)), torch.zeros(1)
s_w, s_b = torch.zeros((feature_dim, 1)), torch.zeros(1)
return ((v_w, s_w), (v_b, s_b))
def adam(params, states, hyperparams):
beta1, beta2, eps = 0.9, 0.999, 1e-6
for p, (v, s) in zip(params, states):
with torch.no_grad():
v[:] = beta1 * v + (1 - beta1) * p.grad
s[:] = beta2 * s + (1 - beta2) * torch.square(p.grad)
v_bias_corr = v / (1 - beta1 ** hyperparams['t'])
s_bias_corr = s / (1 - beta2 ** hyperparams['t'])
p[:] -= hyperparams['lr'] * v_bias_corr / (torch.sqrt(s_bias_corr)
+ eps)
p.grad.data.zero_()
hyperparams['t'] += 1We are ready to use Adam to train the model. We use a learning rate of .
英語のヒント
Adamを使ってモデルを訓練する準備ができた。学習率はを使う。
data_iter, feature_dim = d2l.get_data_ch11(batch_size=10)
d2l.train_ch11(adam, init_adam_states(feature_dim),
{'lr': 0.01, 't': 1}, data_iter, feature_dim);loss: 0.243, 0.193 sec/epochA more concise implementation is straightforward since
adam is one of the algorithms provided as part of the Gluon trainer optimization library. Hence we only need to pass configuration parameters for an implementation in Gluon.英語のヒント
adamはGluonのtrainerの最適化ライブラリの一部として提供されているアルゴリズムの一つなので、もっと簡潔な実装は素直である。したがって、Gluonでの実装には、設定のパラメータを渡すだけでよい。trainer = torch.optim.Adam
d2l.train_concise_ch11(trainer, {'lr': 0.01}, data_iter)loss: 0.243, 0.152 sec/epoch