第3章回帰のための線形ニューラルネットワーク
3.4.4. Training3.4.4 訓練
Now that we have all of the parts in place (parameters, loss function, model, and optimizer), we are ready to implement the main training loop. It is crucial that you understand this code fully since you will employ similar training loops for every other deep learning model covered in this book. In each epoch, we iterate through the entire training dataset, passing once through every example (assuming that the number of examples is divisible by the batch size). In each iteration, we grab a minibatch of training examples, and compute its loss through the model’s
training_step method. Then we compute the gradients with respect to each parameter. Finally, we will call the optimization algorithm to update the model parameters. In summary, we will execute the following loop:英語のヒント
これで部品(パラメータ、損失関数、モデル、最適化手法)がすべてそろったので、主な訓練ループを実装する準備ができた。この本で扱うほかのすべての深層学習モデルでも同様の訓練ループを使うので、このコードを完全に理解することが決定的に重要である。各エポックで、訓練データセット全体をたどり、すべての事例を一度ずつ通る(事例の数がバッチの大きさで割り切れると仮定する)。各反復で、訓練事例のミニバッチをつかみ、モデルの
training_stepメソッドでその損失を計算する。次に、各パラメータについての勾配を計算する。最後に、最適化アルゴリズムを呼び出してモデルのパラメータを更新する。まとめると、次のループを実行する。- Initialize parameters
英語のヒント
パラメータを初期化する - Repeat until done
英語のヒント
終わるまで繰り返す- Compute gradient
英語のヒント
勾配を計算する - Update parameters
英語のヒント
パラメータを更新する
Recall that the synthetic regression dataset that we generated in Section 3.3 does not provide a validation dataset. In most cases, however, we will want a validation dataset to measure our model quality. Here we pass the validation dataloader once in each epoch to measure the model performance. Following our object-oriented design, the
prepare_batch and fit_epoch methods are registered in the d2l.Trainer class (introduced in Section 3.2.4).英語のヒント
@d2l.add_to_class(d2l.Trainer) #@save
def prepare_batch(self, batch):
return batch
@d2l.add_to_class(d2l.Trainer) #@save
def fit_epoch(self):
self.model.train()
for batch in self.train_dataloader:
loss = self.model.training_step(self.prepare_batch(batch))
self.optim.zero_grad()
with torch.no_grad():
loss.backward()
if self.gradient_clip_val > 0: # To be discussed later
self.clip_gradients(self.gradient_clip_val, self.model)
self.optim.step()
self.train_batch_idx += 1
if self.val_dataloader is None:
return
self.model.eval()
for batch in self.val_dataloader:
with torch.no_grad():
self.model.validation_step(self.prepare_batch(batch))
self.val_batch_idx += 1We are almost ready to train the model, but first we need some training data. Here we use the
SyntheticRegressionData class and pass in some ground truth parameters. Then we train our model with the learning rate lr=0.03 and set max_epochs=3. Note that in general, both the number of epochs and the learning rate are hyperparameters. In general, setting hyperparameters is tricky and we will usually want to use a three-way split, one set for training, a second for hyperparameter selection, and the third reserved for the final evaluation. We elide these details for now but will revise them later.英語のヒント
モデルを訓練する準備はほぼできたが、まず訓練データが必要である。ここでは
SyntheticRegressionDataクラスを使い、正解のパラメータを渡す。それから、学習率lr=0.03でモデルを訓練し、max_epochs=3とする。一般に、エポックの数も学習率もハイパーパラメータであることに注意してほしい。一般に、ハイパーパラメータの設定は扱いが難しく、普通は3分割を使いたい。一つは訓練用、二つ目はハイパーパラメータの選択用、三つ目は最終評価のためにとっておく。今はこうした細部は省くが、後で見直す。model = LinearRegressionScratch(2, lr=0.03)
data = d2l.SyntheticRegressionData(w=torch.tensor([2, -3.4]), b=4.2)
trainer = d2l.Trainer(max_epochs=3)
trainer.fit(model, data)Because we synthesized the dataset ourselves, we know precisely what the true parameters are. Thus, we can evaluate our success in training by comparing the true parameters with those that we learned through our training loop. Indeed they turn out to be very close to each other.
英語のヒント
データセットは自分で合成したので、本当のパラメータが何かを正確に知っている。したがって、本当のパラメータと、訓練ループで学習したパラメータを比べることで、訓練の成功を評価できる。実際、両者はとても近いことがわかる。
with torch.no_grad():
print(f'error in estimating w: {data.w - model.w.reshape(data.w.shape)}')
print(f'error in estimating b: {data.b - model.b}')error in estimating w: tensor([ 0.1408, -0.1493])
error in estimating b: tensor([0.2130])We should not take the ability to exactly recover the ground truth parameters for granted. In general, for deep models unique solutions for the parameters do not exist, and even for linear models, exactly recovering the parameters is only possible when no feature is linearly dependent on the others. However, in machine learning, we are often less concerned with recovering true underlying parameters, but rather with parameters that lead to highly accurate prediction (Vapnik, 1992). Fortunately, even on difficult optimization problems, stochastic gradient descent can often find remarkably good solutions, owing partly to the fact that, for deep networks, there exist many configurations of the parameters that lead to highly accurate prediction.
英語のヒント
正解のパラメータを厳密に取り戻せる能力を当然のことと思ってはいけない。一般に、深いモデルではパラメータの一意な解は存在せず、線形モデルでさえ、パラメータを厳密に取り戻せるのは、どの特徴量もほかの特徴量に線形従属しないときだけである。しかし機械学習では、根底にある本当のパラメータを取り戻すことよりも、非常に正確な予測につながるパラメータのほうに関心があることが多い(Vapnik, 1992)。幸い、難しい最適化問題でも、確率的勾配降下法はしばしば驚くほどよい解を見つけられる。その理由の一つは、深いネットワークでは、非常に正確な予測につながるパラメータの配置がたくさん存在することにある。