プリンキピア

第3章回帰のための線形ニューラルネットワーク

3.7.3. Implementation from Scratch3.7.3 ゼロからの実装

Now, let’s try implementing weight decay from scratch. Since minibatch stochastic gradient descent is our optimizer, we just need to add the squared ℓ2 penalty to the original loss function.
英語のヒント
では、重み減衰をゼロから実装してみよう。最適化手法はミニバッチ確率的勾配降下法なので、元の損失関数に二乗ℓ2罰則を加えるだけでよい。

3.7.3.1. Defining ℓ2 Norm Penalty3.7.3.1 ℓ2ノルムの罰則の定義

Perhaps the most convenient way of implementing this penalty is to square all terms in place and sum them.
英語のヒント
この罰則を実装する最も便利な方法は、おそらく、すべての項をその場で二乗して足し合わせることである。
def l2_penalty(w):
    return (w ** 2).sum() / 2

3.7.3.2. Defining the Model3.7.3.2 モデルの定義

In the final model, the linear regression and the squared loss have not changed since Section 3.4, so we will just define a subclass of d2l.LinearRegressionScratch. The only change here is that our loss now includes the penalty term.
英語のヒント
最終的なモデルでは、線形回帰と二乗損失は3.4節から変わっていないので、d2l.LinearRegressionScratchのサブクラスを定義するだけにする。ここでの唯一の変更は、損失に罰則項が含まれるようになったことである。
class WeightDecayScratch(d2l.LinearRegressionScratch):
    def __init__(self, num_inputs, lambd, lr, sigma=0.01):
        super().__init__(num_inputs, lr, sigma)
        self.save_hyperparameters()

    def loss(self, y_hat, y):
        return (super().loss(y_hat, y) +
                self.lambd * l2_penalty(self.w))
The following code fits our model on the training set with 20 examples and evaluates it on the validation set with 100 examples.
英語のヒント
次のコードは、20個の事例からなる訓練集合でモデルを当てはめ、100個の事例からなる検証集合で評価する。
data = Data(num_train=20, num_val=100, num_inputs=200, batch_size=5)
trainer = d2l.Trainer(max_epochs=10)

def train_scratch(lambd):
    model = WeightDecayScratch(num_inputs=200, lambd=lambd, lr=0.01)
    model.board.yscale='log'
    trainer.fit(model, data)
    print('L2 norm of w:', float(l2_penalty(model.w)))

3.7.3.3. Training without Regularization3.7.3.3 正則化なしの訓練

We now run this code with lambd = 0, disabling weight decay. Note that we overfit badly, decreasing the training error but not the validation error—a textbook case of overfitting.
英語のヒント
では、このコードをlambd = 0で実行し、重み減衰を無効にする。ひどく過学習し、訓練誤差は下がるが検証誤差は下がらないことに注意してほしい。過学習の教科書どおりの例である。
train_scratch(0)
L2 norm of w: 0.009948714636266232

3.7.3.4. Using Weight Decay3.7.3.4 重み減衰を使う

Below, we run with substantial weight decay. Note that the training error increases but the validation error decreases. This is precisely the effect we expect from regularization.
英語のヒント
下では、かなりの重み減衰をかけて実行する。訓練誤差は増えるが、検証誤差は減ることに注意してほしい。これはまさに、正則化に期待する効果である。
train_scratch(3)
L2 norm of w: 0.0017270983662456274