プリンキピア

第12章最適化アルゴリズム

12.6.2. Practical Experiments12.6.2 実際の実験

Let’s see how momentum works in practice, i.e., when used within the context of a proper optimizer. For this we need a somewhat more scalable implementation.
英語のヒント
モメンタムが実際に、つまり適切なオプティマイザの文脈で使われたときに、どう働くかを見よう。そのためには、もう少し規模を広げられる実装が要る。

12.6.2.1. Implementation from Scratch12.6.2.1 ゼロからの実装

Compared with (minibatch) stochastic gradient descent the momentum method needs to maintain a set of auxiliary variables, i.e., velocity. It has the same shape as the gradients (and variables of the optimization problem). In the implementation below we call these variables states.
英語のヒント
(ミニバッチ)確率的勾配降下法と比べて、モメンタム法は補助変数、つまり速度の組を保持する必要がある。それは勾配(と最適化問題の変数)と同じ形状をもつ。以下の実装では、これらの変数をstatesと呼ぶ。
def init_momentum_states(feature_dim):
    v_w = torch.zeros((feature_dim, 1))
    v_b = torch.zeros(1)
    return (v_w, v_b)

def sgd_momentum(params, states, hyperparams):
    for p, v in zip(params, states):
        with torch.no_grad():
            v[:] = hyperparams['momentum'] * v + p.grad
            p[:] -= hyperparams['lr'] * v
        p.grad.data.zero_()
Let’s see how this works in practice.
英語のヒント
これが実際にどう働くかを見よう。
def train_momentum(lr, momentum, num_epochs=2):
    d2l.train_ch11(sgd_momentum, init_momentum_states(feature_dim),
                   {'lr': lr, 'momentum': momentum}, data_iter,
                   feature_dim, num_epochs)

data_iter, feature_dim = d2l.get_data_ch11(batch_size=10)
train_momentum(0.02, 0.5)
loss: 0.245, 0.153 sec/epoch
When we increase the momentum hyperparameter momentum to 0.9, it amounts to a significantly larger effective sample size of 11−0.9=10. We reduce the learning rate slightly to 0.01 to keep matters under control.
英語のヒント
モメンタムのハイパーパラメータmomentumを0.9に上げると、実質的な標本の大きさがずっと大きな11−0.9=10になる。事態を制御下に置くため、学習率を少し下げて0.01にする。
train_momentum(0.01, 0.9)
loss: 0.248, 0.109 sec/epoch
Reducing the learning rate further addresses any issue of non-smooth optimization problems. Setting it to 0.005 yields good convergence properties.
英語のヒント
学習率をさらに下げると、なめらかでない最適化問題の問題点はどれも解消される。それを0.005に設定すると、よい収束の性質が得られる。
train_momentum(0.005, 0.9)
loss: 0.243, 0.107 sec/epoch

12.6.2.2. Concise Implementation12.6.2.2 簡潔な実装

There is very little to do in Gluon since the standard sgd solver already had momentum built in. Setting matching parameters yields a very similar trajectory.
英語のヒント
標準のsgdソルバーにはすでにモメンタムが組み込まれていたので、Gluonでやることはほとんどない。対応するパラメータを設定すると、とてもよく似た軌跡が得られる。
trainer = torch.optim.SGD
d2l.train_concise_ch11(trainer, {'lr': 0.005, 'momentum': 0.9}, data_iter)
loss: 0.250, 0.108 sec/epoch