第3章回帰のための線形ニューラルネットワーク
3.4.3. Defining the Optimization Algorithm3.4.3 最適化アルゴリズムの定義
As discussed in Section 3.1, linear regression has a closed-form solution. However, our goal here is to illustrate how to train more general neural networks, and that requires that we teach you how to use minibatch SGD. Hence we will take this opportunity to introduce your first working example of SGD. At each step, using a minibatch randomly drawn from our dataset, we estimate the gradient of the loss with respect to the parameters. Next, we update the parameters in the direction that may reduce the loss.
英語のヒント
3.1節で論じたように、線形回帰には閉じた形の解がある。しかし、ここでの目標は、もっと一般的なニューラルネットワークをどう訓練するかを示すことであり、そのためにはミニバッチSGDの使い方を教える必要がある。そこで、この機会に、初めての動くSGDの例を紹介する。各ステップで、データセットから無作為に取り出したミニバッチを使って、パラメータについての損失の勾配を推定する。次に、損失を減らしうる方向にパラメータを更新する。
The following code applies the update, given a set of parameters, a learning rate
lr. Since our loss is computed as an average over the minibatch, we do not need to adjust the learning rate against the batch size. In later chapters we will investigate how learning rates should be adjusted for very large minibatches as they arise in distributed large-scale learning. For now, we can ignore this dependency.英語のヒント
次のコードは、パラメータの集合と学習率
lrが与えられたときに更新を適用する。損失はミニバッチにわたる平均として計算されるので、学習率をバッチの大きさに合わせて調整する必要はない。後の章では、分散型の大規模学習で生じるような非常に大きなミニバッチのとき、学習率をどう調整すべきかを調べる。今はこの依存関係を無視してよい。We define our
SGD class, a subclass of d2l.HyperParameters (introduced in Section 3.2.1), to have a similar API as the built-in SGD optimizer. We update the parameters in the step method. The zero_grad method sets all gradients to 0, which must be run before a backpropagation step.英語のヒント
d2l.HyperParameters(3.2.1節で紹介した)のサブクラスとしてSGDクラスを定義し、組み込みのSGD最適化手法と似たAPIをもたせる。パラメータはstepメソッドで更新する。zero_gradメソッドはすべての勾配を0にし、誤差逆伝播のステップの前に実行しなければならない。class SGD(d2l.HyperParameters): #@save
"""Minibatch stochastic gradient descent."""
def __init__(self, params, lr):
self.save_hyperparameters()
def step(self):
for param in self.params:
param -= self.lr * param.grad
def zero_grad(self):
for param in self.params:
if param.grad is not None:
param.grad.zero_()We next define the
configure_optimizers method, which returns an instance of the SGD class.英語のヒント
次に、
SGDクラスのインスタンスを返すconfigure_optimizersメソッドを定義する。@d2l.add_to_class(LinearRegressionScratch) #@save
def configure_optimizers(self):
return SGD([self.w, self.b], self.lr)