第12章最適化アルゴリズム
12.5.4. Implementation from Scratch12.5.4 ゼロからの実装
Recall the minibatch stochastic gradient descent implementation from Section 3.4. In the following we provide a slightly more general implementation. For convenience it has the same call signature as the other optimization algorithms introduced later in this chapter. Specifically, we add the status input
states and place the hyperparameter in dictionary hyperparams. In addition, we will average the loss of each minibatch example in the training function, so the gradient in the optimization algorithm does not need to be divided by the batch size.英語のヒント
3.4節のミニバッチ確率的勾配降下法の実装を思い出そう。以下では、もう少し一般的な実装を与える。便宜上、この章で後に紹介するほかの最適化アルゴリズムと同じ呼び出しの形をもたせる。具体的には、状態の入力
statesを加え、ハイパーパラメータを辞書hyperparamsに入れる。さらに、訓練関数で各ミニバッチの事例の損失を平均するので、最適化アルゴリズムでの勾配をバッチの大きさで割る必要はない。def sgd(params, states, hyperparams):
for p in params:
p.data.sub_(hyperparams['lr'] * p.grad)
p.grad.data.zero_()Next, we implement a generic training function to facilitate the use of the other optimization algorithms introduced later in this chapter. It initializes a linear regression model and can be used to train the model with minibatch stochastic gradient descent and other algorithms introduced subsequently.
英語のヒント
次に、この章で後に紹介するほかの最適化アルゴリズムを使いやすくするため、汎用の訓練関数を実装する。これは線形回帰のモデルを初期化し、ミニバッチ確率的勾配降下法や、その後に紹介するほかのアルゴリズムでモデルを訓練するのに使える。
#@save
def train_ch11(trainer_fn, states, hyperparams, data_iter,
feature_dim, num_epochs=2):
# Initialization
w = torch.normal(mean=0.0, std=0.01, size=(feature_dim, 1),
requires_grad=True)
b = torch.zeros((1), requires_grad=True)
net, loss = lambda X: d2l.linreg(X, w, b), d2l.squared_loss
# Train
animator = d2l.Animator(xlabel='epoch', ylabel='loss',
xlim=[0, num_epochs], ylim=[0.22, 0.35])
n, timer = 0, d2l.Timer()
for _ in range(num_epochs):
for X, y in data_iter:
l = loss(net(X), y).mean()
l.backward()
trainer_fn([w, b], states, hyperparams)
n += X.shape[0]
if n % 200 == 0:
timer.stop()
animator.add(n/X.shape[0]/len(data_iter),
(d2l.evaluate_loss(net, data_iter, loss),))
timer.start()
print(f'loss: {animator.Y[0][-1]:.3f}, {timer.sum()/num_epochs:.3f} sec/epoch')
return timer.cumsum(), animator.Y[0]Let’s see how optimization proceeds for batch gradient descent. This can be achieved by setting the minibatch size to 1500 (i.e., to the total number of examples). As a result the model parameters are updated only once per epoch. There is little progress. In fact, after 6 steps progress stalls.
英語のヒント
バッチ勾配降下法で最適化がどう進むかを見よう。これは、ミニバッチの大きさを1500(つまり事例の総数)に設定すれば実現できる。その結果、モデルのパラメータはエポックごとに1回しか更新されない。ほとんど前進しない。実際、6ステップの後に進み具合が止まる。
def train_sgd(lr, batch_size, num_epochs=2):
data_iter, feature_dim = get_data_ch11(batch_size)
return train_ch11(
sgd, None, {'lr': lr}, data_iter, feature_dim, num_epochs)
gd_res = train_sgd(1, 1500, 10)loss: 0.247, 0.020 sec/epochWhen the batch size equals 1, we use stochastic gradient descent for optimization. For simplicity of implementation we picked a constant (albeit small) learning rate. In stochastic gradient descent, the model parameters are updated whenever an example is processed. In our case this amounts to 1500 updates per epoch. As we can see, the decline in the value of the objective function slows down after one epoch. Although both the procedures processed 1500 examples within one epoch, stochastic gradient descent consumes more time than gradient descent in our experiment. This is because stochastic gradient descent updated the parameters more frequently and since it is less efficient to process single observations one at a time.
英語のヒント
バッチの大きさが1のとき、最適化に確率的勾配降下法を使う。実装を簡単にするため、一定の(小さいとはいえ)学習率を選んだ。確率的勾配降下法では、事例が一つ処理されるたびにモデルのパラメータが更新される。この場合、エポックあたり1500回の更新になる。見てのとおり、目的関数の値の下がり方は1エポックの後に鈍くなる。どちらの手続きも1エポックで1500個の事例を処理したが、この実験では確率的勾配降下法の方が勾配降下法より時間を食う。これは、確率的勾配降下法がパラメータをもっと頻繁に更新したからであり、また単一の観測を一つずつ処理するのは効率が悪いからである。
sgd_res = train_sgd(0.005, 1)loss: 0.245, 0.685 sec/epochFinally, when the batch size equals 100, we use minibatch stochastic gradient descent for optimization. The time required per epoch is shorter than the time needed for stochastic gradient descent and the time for batch gradient descent.
英語のヒント
最後に、バッチの大きさが100のとき、最適化にミニバッチ確率的勾配降下法を使う。エポックあたりに必要な時間は、確率的勾配降下法に必要な時間よりも、バッチ勾配降下法の時間よりも短い。
mini1_res = train_sgd(.4, 100)loss: 0.246, 0.025 sec/epochReducing the batch size to 10, the time for each epoch increases because the workload for each batch is less efficient to execute.
英語のヒント
バッチの大きさを10に減らすと、各バッチの作業量を実行する効率が下がるので、各エポックの時間が増える。
mini2_res = train_sgd(.05, 10)loss: 0.246, 0.090 sec/epochNow we can compare the time vs. loss for the previous four experiments. As can be seen, although stochastic gradient descent converges faster than GD in terms of number of examples processed, it uses more time to reach the same loss than GD because computing the gradient example by example is not as efficient. Minibatch stochastic gradient descent is able to trade-off convergence speed and computation efficiency. A minibatch size of 10 is more efficient than stochastic gradient descent; a minibatch size of 100 even outperforms GD in terms of runtime.
英語のヒント
では、前の四つの実験について、時間と損失を比べよう。見てのとおり、処理した事例の数で見れば確率的勾配降下法はGDより速く収束するが、事例ごとに勾配を計算するのは効率が劣るので、同じ損失に達するのにGDより多くの時間を使う。ミニバッチ確率的勾配降下法は、収束の速さと計算の効率をうまく折り合わせられる。ミニバッチの大きさが10なら確率的勾配降下法より効率がよく、ミニバッチの大きさが100なら実行時間でGDを上回りさえする。
d2l.set_figsize([6, 3])
d2l.plot(*list(map(list, zip(gd_res, sgd_res, mini1_res, mini2_res))),
'time (sec)', 'loss', xlim=[1e-2, 10],
legend=['gd', 'sgd', 'batch size=100', 'batch size=10'])
d2l.plt.gca().set_xscale('log')