.. _sec_rmsprop:
RMSProp
=======
:numref:`sec_adagrad` における重要な問題の1つは、学習率が事実上
:math:`\mathcal{O}(t^{-\frac{1}{2}})`
のあらかじめ定められたスケジュールで減少していくことである。これは一般に凸問題には適しているが、深層学習で遭遇するような非凸問題には必ずしも理想的ではない。それでも、Adagrad
の座標ごとの適応性は、前処理器として非常に望ましいものである。
:cite:t:`Tieleman.Hinton.2012`
は、スケジュールによる学習率の調整と座標適応的な学習率を切り離すための簡単な修正として、RMSProp
アルゴリズムを提案した。問題は、Adagrad が勾配 :math:`\mathbf{g}_t`
の二乗を状態ベクトル
:math:`\mathbf{s}_t = \mathbf{s}_{t-1} + \mathbf{g}_t^2`
に蓄積していくことである。その結果、正規化がないため
:math:`\mathbf{s}_t`
は際限なく増大し続け、アルゴリズムが収束するにつれて本質的には線形に増えていく。
この問題を修正する1つの方法は、\ :math:`\mathbf{s}_t / t`
を使うことである。\ :math:`\mathbf{g}_t`
の分布が適切であれば、これは収束する。残念ながら、この手続きは値の完全な軌跡を記憶するため、極限的な挙動が重要になるまでに非常に長い時間がかかるかもしれない。別の方法として、モメンタム法で用いたのと同じようにリーキー平均を使うことができる。すなわち、あるパラメータ
:math:`\gamma > 0` に対して
:math:`\mathbf{s}_t \leftarrow \gamma \mathbf{s}_{t-1} + (1-\gamma) \mathbf{g}_t^2`
とする。他の部分をすべて変えずに残すと RMSProp になる。
アルゴリズム
------------
式を詳しく書き下してみよう。
.. math::
\begin{aligned}
\mathbf{s}_t & \leftarrow \gamma \mathbf{s}_{t-1} + (1 - \gamma) \mathbf{g}_t^2, \\
\mathbf{x}_t & \leftarrow \mathbf{x}_{t-1} - \frac{\eta}{\sqrt{\mathbf{s}_t + \epsilon}} \odot \mathbf{g}_t.
\end{aligned}
定数 :math:`\epsilon > 0` は通常 :math:`10^{-6}`
に設定され、ゼロ除算や過度に大きなステップサイズを避けるために用いられる。この展開により、学習率
:math:`\eta`
を、各座標ごとに適用されるスケーリングとは独立に制御できるようになる。リーキー平均の観点では、これまでモメンタム法で行ったのと同じ推論を適用できる。\ :math:`\mathbf{s}_t`
の定義を展開すると
.. math::
\begin{aligned}
\mathbf{s}_t & = (1 - \gamma) \mathbf{g}_t^2 + \gamma \mathbf{s}_{t-1} \\
& = (1 - \gamma) \left(\mathbf{g}_t^2 + \gamma \mathbf{g}_{t-1}^2 + \gamma^2 \mathbf{g}_{t-2} + \ldots, \right).
\end{aligned}
:numref:`sec_momentum`
と同様に、\ :math:`1 + \gamma + \gamma^2 + \ldots, = \frac{1}{1-\gamma}`
を用いる。したがって、重みの総和は :math:`1`
に正規化され、観測の半減期は :math:`\gamma^{-1}` になる。さまざまな
:math:`\gamma` の選択について、過去40ステップの重みを可視化してみよう。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
from d2l import torch as d2l
import torch
import math
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
%matplotlib inline
from d2l import mxnet as d2l
import math
from mxnet import np, npx
npx.set_np()
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
d2l.set_figsize()
gammas = [0.95, 0.9, 0.8, 0.7]
for gamma in gammas:
x = d2l.numpy(d2l.arange(40))
d2l.plt.plot(x, (1-gamma) * gamma ** x, label=f'gamma = {gamma:.2f}')
d2l.plt.xlabel('time');
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
from d2l import tensorflow as d2l
import tensorflow as tf
import math
.. raw:: html
.. raw:: html
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
d2l.set_figsize()
gammas = [0.95, 0.9, 0.8, 0.7]
for gamma in gammas:
x = d2l.numpy(d2l.arange(40))
d2l.plt.plot(x, (1-gamma) * gamma ** x, label=f'gamma = {gamma:.2f}')
d2l.plt.xlabel('time');
.. figure:: output_rmsprop_88e24e_17_0.svg
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
d2l.set_figsize()
gammas = [0.95, 0.9, 0.8, 0.7]
for gamma in gammas:
x = d2l.numpy(d2l.arange(40))
d2l.plt.plot(x, (1-gamma) * gamma ** x, label=f'gamma = {gamma:.2f}')
d2l.plt.xlabel('time');
.. raw:: latex
\diilbookstyleoutputcell
.. parsed-literal::
:class: output
[06:58:30] ../src/storage/storage.cc:196: Using Pooled (Naive) StorageManager for CPU
.. figure:: output_rmsprop_88e24e_20_1.svg
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
def rmsprop_2d(x1, x2, s1, s2):
g1, g2, eps = 0.2 * x1, 4 * x2, 1e-6
s1 = gamma * s1 + (1 - gamma) * g1 ** 2
s2 = gamma * s2 + (1 - gamma) * g2 ** 2
x1 -= eta / math.sqrt(s1 + eps) * g1
x2 -= eta / math.sqrt(s2 + eps) * g2
return x1, x2, s1, s2
def f_2d(x1, x2):
return 0.1 * x1 ** 2 + 2 * x2 ** 2
eta, gamma = 0.4, 0.9
d2l.show_trace_2d(f_2d, d2l.train_2d(rmsprop_2d))
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
d2l.set_figsize()
gammas = [0.95, 0.9, 0.8, 0.7]
for gamma in gammas:
x = d2l.numpy(d2l.arange(40))
d2l.plt.plot(x, (1-gamma) * gamma ** x, label=f'gamma = {gamma:.2f}')
d2l.plt.xlabel('time');
.. figure:: output_rmsprop_88e24e_26_0.svg
.. raw:: html
.. raw:: html
ゼロからの実装
--------------
これまでと同様に、二次関数 :math:`f(\mathbf{x})=0.1x_1^2+2x_2^2`
を用いて RMSProp の軌跡を観察する。 :numref:`sec_adagrad`
では、学習率を 0.4 にして Adagrad
を使ったとき、学習率が急速に下がりすぎるため、アルゴリズムの後半で変数の移動が非常に遅くなったことを思い出してほしい。\ :math:`\eta`
は別々に制御されるので、RMSProp ではこのようなことは起こらない。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
def rmsprop_2d(x1, x2, s1, s2):
g1, g2, eps = 0.2 * x1, 4 * x2, 1e-6
s1 = gamma * s1 + (1 - gamma) * g1 ** 2
s2 = gamma * s2 + (1 - gamma) * g2 ** 2
x1 -= eta / math.sqrt(s1 + eps) * g1
x2 -= eta / math.sqrt(s2 + eps) * g2
return x1, x2, s1, s2
def f_2d(x1, x2):
return 0.1 * x1 ** 2 + 2 * x2 ** 2
eta, gamma = 0.4, 0.9
d2l.show_trace_2d(f_2d, d2l.train_2d(rmsprop_2d))
.. raw:: latex
\diilbookstyleoutputcell
.. parsed-literal::
:class: output
epoch 20, x1: -0.010599, x2: 0.000000
.. figure:: output_rmsprop_88e24e_32_1.svg
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
def rmsprop_2d(x1, x2, s1, s2):
g1, g2, eps = 0.2 * x1, 4 * x2, 1e-6
s1 = gamma * s1 + (1 - gamma) * g1 ** 2
s2 = gamma * s2 + (1 - gamma) * g2 ** 2
x1 -= eta / math.sqrt(s1 + eps) * g1
x2 -= eta / math.sqrt(s2 + eps) * g2
return x1, x2, s1, s2
def f_2d(x1, x2):
return 0.1 * x1 ** 2 + 2 * x2 ** 2
eta, gamma = 0.4, 0.9
d2l.show_trace_2d(f_2d, d2l.train_2d(rmsprop_2d))
.. raw:: latex
\diilbookstyleoutputcell
.. parsed-literal::
:class: output
epoch 20, x1: -0.010599, x2: 0.000000
.. figure:: output_rmsprop_88e24e_35_1.svg
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
data_iter, feature_dim = d2l.get_data_ch11(batch_size=10)
d2l.train_ch11(rmsprop, init_rmsprop_states(feature_dim),
{'lr': 0.01, 'gamma': 0.9}, data_iter, feature_dim);
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
def rmsprop_2d(x1, x2, s1, s2):
g1, g2, eps = 0.2 * x1, 4 * x2, 1e-6
s1 = gamma * s1 + (1 - gamma) * g1 ** 2
s2 = gamma * s2 + (1 - gamma) * g2 ** 2
x1 -= eta / math.sqrt(s1 + eps) * g1
x2 -= eta / math.sqrt(s2 + eps) * g2
return x1, x2, s1, s2
def f_2d(x1, x2):
return 0.1 * x1 ** 2 + 2 * x2 ** 2
eta, gamma = 0.4, 0.9
d2l.show_trace_2d(f_2d, d2l.train_2d(rmsprop_2d))
.. raw:: latex
\diilbookstyleoutputcell
.. parsed-literal::
:class: output
epoch 20, x1: -0.010599, x2: 0.000000
.. figure:: output_rmsprop_88e24e_41_1.svg
.. raw:: html
.. raw:: html
次に、深層ネットワークで使うための RMSProp
を実装する。こちらも同様に簡単である。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
def init_rmsprop_states(feature_dim):
s_w = d2l.zeros((feature_dim, 1))
s_b = d2l.zeros(1)
return (s_w, s_b)
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
def init_rmsprop_states(feature_dim):
s_w = d2l.zeros((feature_dim, 1))
s_b = d2l.zeros(1)
return (s_w, s_b)
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
def init_rmsprop_states(feature_dim):
s_w = tf.Variable(d2l.zeros((feature_dim, 1)))
s_b = tf.Variable(d2l.zeros(1))
return (s_w, s_b)
.. raw:: html
.. raw:: html
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
def rmsprop(params, states, hyperparams):
gamma, eps = hyperparams['gamma'], 1e-6
for p, s in zip(params, states):
with torch.no_grad():
s[:] = gamma * s + (1 - gamma) * torch.square(p.grad)
p[:] -= hyperparams['lr'] * p.grad / torch.sqrt(s + eps)
p.grad.data.zero_()
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
def rmsprop(params, states, hyperparams):
gamma, eps = hyperparams['gamma'], 1e-6
for p, s in zip(params, states):
s[:] = gamma * s + (1 - gamma) * np.square(p.grad)
p[:] -= hyperparams['lr'] * p.grad / np.sqrt(s + eps)
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
def rmsprop(params, grads, states, hyperparams):
gamma, eps = hyperparams['gamma'], 1e-6
for p, s, g in zip(params, states, grads):
s[:].assign(gamma * s + (1 - gamma) * tf.math.square(g))
p[:].assign(p - hyperparams['lr'] * g / tf.math.sqrt(s + eps))
.. raw:: html
.. raw:: html
初期学習率を 0.01、重み付け項 :math:`\gamma` を 0.9
に設定する。つまり、\ :math:`\mathbf{s}` は平均して過去
:math:`1/(1-\gamma) = 10` 個の二乗勾配を集約する。
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
data_iter, feature_dim = d2l.get_data_ch11(batch_size=10)
d2l.train_ch11(rmsprop, init_rmsprop_states(feature_dim),
{'lr': 0.01, 'gamma': 0.9}, data_iter, feature_dim);
.. raw:: latex
\diilbookstyleoutputcell
.. parsed-literal::
:class: output
loss: 0.244, 0.246 sec/epoch
.. figure:: output_rmsprop_88e24e_68_1.svg
簡潔な実装
----------
RMSProp はかなり人気のあるアルゴリズムなので、\ ``Trainer``
インスタンスでも利用できる。必要なのは、\ ``rmsprop``
という名前のアルゴリズムを使ってインスタンス化し、\ :math:`\gamma`
をパラメータ ``gamma1`` に割り当てることだけである。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
trainer = torch.optim.RMSprop
d2l.train_concise_ch11(trainer, {'lr': 0.01, 'alpha': 0.9},
data_iter)
.. raw:: latex
\diilbookstyleoutputcell
.. parsed-literal::
:class: output
loss: 0.243, 0.133 sec/epoch
.. figure:: output_rmsprop_88e24e_72_1.svg
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
d2l.train_concise_ch11('rmsprop', {'learning_rate': 0.01, 'gamma1': 0.9},
data_iter)
.. raw:: latex
\diilbookstyleoutputcell
.. parsed-literal::
:class: output
loss: 0.246, 0.355 sec/epoch
.. figure:: output_rmsprop_88e24e_75_1.svg
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
trainer = tf.keras.optimizers.RMSprop
d2l.train_concise_ch11(trainer, {'learning_rate': 0.01, 'rho': 0.9},
data_iter)
.. raw:: latex
\diilbookstyleoutputcell
.. parsed-literal::
:class: output
loss: 0.249, 1.316 sec/epoch
.. figure:: output_rmsprop_88e24e_78_1.svg
.. raw:: html
.. raw:: html
まとめ
------
- RMSProp は Adagrad
と非常によく似ており、どちらも勾配の二乗を用いて係数をスケーリングする。
- RMSProp はモメンタムとリーキー平均を共有している。ただし、RMSProp
ではこの手法を係数ごとの前処理器の調整に用いる。
- 実際には、学習率は実験者がスケジュール調整する必要がある。
- 係数 :math:`\gamma`
は、各座標のスケールを調整するときにどれだけ長い履歴を考慮するかを決定する。
演習
----
1. :math:`\gamma = 1` とすると、実験的に何が起こるか。なぜか。
2. 最適化問題を回転させて、\ :math:`f(\mathbf{x}) = 0.1 (x_1 + x_2)^2 + 2 (x_1 - x_2)^2`
を最小化してみよ。収束はどうなるか。
3. Fashion-MNIST での学習など、実際の機械学習問題で RMSProp
を試してみよ。学習率の調整方法を変えて実験せよ。
4. 最適化が進むにつれて :math:`\gamma` を調整したいか。RMSProp
はこれにどれくらい敏感か。