Sign in

L2 penalty

L2 norm weight penalty (ridge)

A regulariser added to the loss that charges for the squared size of every weight, which shrinks all weights toward zero.

Overview

Large weights let a model react sharply to small changes in its input, which is often a sign of fitting noise. The L2 penalty adds a cost equal to half the sum of squared weights, times a strength λ\lambda. The cost of a weight grows with its square, so big weights are discouraged far more than small ones. The resulting pull toward zero is proportional to the weight itself, so weights shrink but rarely reach zero. The penalty's gradient is added to the data gradient before the optimiser sees it, which is not the same as decoupled weight decay.

A short history

Andrey Tikhonov developed this form of regularisation for unstable inverse problems, and Arthur Hoerl and Robert Kennard introduced it to statistics as ridge regression in 1970. In neural networks it became known as weight decay, since with plain gradient descent the penalty shrinks each weight by a constant factor per step. Ilya Loshchilov and Frank Hutter showed in 2017 that this equivalence fails for Adam, which led to the decoupled form used in AdamW.

How it works

  1. Take the weights, one array or a list of arrays.
  2. In forward, sum the squares of all weights and multiply by 12λ\tfrac{1}{2}\lambda. Add this to the data loss.
  3. In backward, return λw\lambda w for each weight array.
  4. Add that to the gradient of the data loss. The helper add_to does both additions in one call.
  5. Give the combined gradient to the optimiser.

Watch out for

  • With Adam and other adaptive optimisers this is not weight decay. The penalty gradient is rescaled per weight along with the data gradient, so weights with large gradients are barely regularised. AdamW exists to fix that.
  • Conventions differ on the factor of one half. A value of λ\lambda quoted for λ∥w∥2\lambda\lVert w\rVert^{2} is twice as strong as the same value here.
  • Penalising biases and normalisation scales usually hurts. Pass only the weight matrices.
  • It does not produce sparse models. Weights become small, not zero, so it does not select features.

Use cases

When to use it

A default guard against overfitting for linear models and networks trained with plain SGD or momentum. It also keeps ill-conditioned problems, such as regression with correlated features, well behaved.

In industry

Economics and social science
Ridge regression is used when predictors are strongly correlated, where ordinary least squares gives unstable coefficients.
Computer vision
Convolutional networks trained with SGD and momentum, such as ResNet, use an L2 penalty on the weights as their main regulariser.
Genomics and breeding
Ridge style models predict traits from many thousands of genetic markers, each given a small shrunken effect.

Choosing it: what must hold

  • A model that overfits or has unstable weights, and a validation set to choose the penalty strength.
  • An optimiser such as SGD, for which adding the penalty to the loss behaves as true weight decay.
  • Features or layers on comparable scales, with biases and normalisation parameters usually left out of the penalty.

When to choose something else

IfUse instead
You train with Adam or another adaptive optimiserDecoupled weight decay as in AdamW
You want many weights to be exactly zeroL1 penalty
The network overfits despite weight shrinkageDropout or early stopping in addition

Math foundations

  1. The penalty

    Ω(w)=λ2 ∥w∥22=λ2∑iwi2\Omega(w) = \frac{\lambda}{2}\,\lVert w \rVert_2^{2} = \frac{\lambda}{2}\sum_{i} w_i^{2}

    Half the sum of squared weights, scaled by the strength λ\lambda. The half is there so the gradient has no factor of 2.

  2. The objective being minimised

    J(w)=Ldata(w)+λ2 ∥w∥22J(w) = \mathcal{L}_{\text{data}}(w) + \frac{\lambda}{2}\,\lVert w \rVert_2^{2}

    The data loss plus the penalty. The optimiser sees one combined loss and does not know the two parts apart.

  3. The gradient

    ∇Ω(w)=λ w\nabla \Omega(w) = \lambda\,w

    A pull toward zero in proportion to each weight. This is what backward returns, to be added to the data gradient.

  4. What it does under plain SGD

    w←w−η (∇Ldata(w)+λw)=(1−ηλ) w−η ∇Ldata(w)w \leftarrow w - \eta\,\big(\nabla \mathcal{L}_{\text{data}}(w) + \lambda w\big) = (1 - \eta\lambda)\,w - \eta\,\nabla \mathcal{L}_{\text{data}}(w)

    Each step first multiplies the weights by a factor just under 1, then applies the data gradient. This is the origin of the name weight decay, and for plain SGD the two are the same thing.

  5. Why it differs under adaptive optimisers

    w←w−η ∇Ldata(w)+λwv^+ϵw \leftarrow w - \eta\,\frac{\nabla \mathcal{L}_{\text{data}}(w) + \lambda w}{\sqrt{\hat{v}} + \epsilon}

    A simplified adaptive step, without momentum. The penalty term is divided by the same per-weight scale as the data gradient, so the shrink factor is no longer 1−ηλ1 - \eta\lambda. Decoupled weight decay applies the shrink outside this division.

Symbols

w,wiw, w_i
the weights and one of them
λ\lambda
penalty strength, lam in the config, default 0.0001
Ω(w)\Omega(w)
the penalty
Ldata\mathcal{L}_{\text{data}}
the loss on the data, without the penalty
J(w)J(w)
the full objective
η\eta
the learning rate
v^\hat{v}
an adaptive optimiser's running estimate of the squared gradient, per weight
ϵ\epsilon
a small constant that prevents division by zero

Worked by hand

Weights w=(3,−4)w = (3, -4) with λ=0.1\lambda = 0.1. Compute the penalty and its gradient, then one SGD step with η=0.5\eta = 0.5 and a data gradient of zero.

Ω=12×0.1×(9+16)=1.25\Omega = \tfrac{1}{2} \times 0.1 \times (9 + 16) = 1.25
∇Ω=0.1×(3,−4)=(0.3,  −0.4)\nabla \Omega = 0.1 \times (3, -4) = (0.3,\; -0.4)
w←(1−0.5×0.1) (3,−4)=0.95×(3,−4)=(2.85,  −3.8)w \leftarrow (1 - 0.5 \times 0.1)\,(3, -4) = 0.95 \times (3, -4) = (2.85,\; -3.8)

The penalty is 1.25. With no data gradient, both weights shrink by the same 5 percent, so the larger one moves more in absolute terms.

Visual example

Loading the example.

Try this

  • Move across the curve: the height is what the model is charged.
  • Move each control and watch which part of the curve it changes.

Code sample

import numpy as np
from impl import L2Penalty
from config import L2PenaltyConfig

pen = L2Penalty(L2PenaltyConfig(lam=0.01))
w = np.array([0.5, -1.0, 2.0])
data_loss, data_grad = 1.0, np.zeros(3)                  # stand-ins for your model's loss and gradient
loss, grad = pen.add_to(data_loss, data_grad, w)         # 1.0 + 0.005 * 5.25, and data_grad + 0.01 * w
w = w - 0.1 * grad                                       # the optimiser sees the combined gradient
Read the implementation (55 lines)
"""L2 weight penalty added to the loss: 0.5 * lam * sum(w^2). This is not decoupled weight decay.

NumPy only. `forward` returns the penalty to add to the loss, `backward` its gradient with respect to the weights
(lam * w), which must be added to the loss gradient before the optimiser step.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import L2PenaltyConfig
except ImportError:  # run from the template's own folder
    from config import L2PenaltyConfig

def _as_list(weights) -> tuple[list, bool]:
    """Weights as a list of float arrays, plus whether a list (or tuple) was given rather than one array."""
    if isinstance(weights, (list, tuple)):
        return [np.asarray(w, dtype=float) for w in weights], True
    return [np.asarray(weights, dtype=float)], False


class L2Penalty:
    """0.5 * lam * sum(w^2) over one weight array or a list of them."""

    def __init__(self, config: L2PenaltyConfig | None = None) -> None:
        self.config = config or L2PenaltyConfig()

    def forward(self, weights) -> float:
        """weights: one array of any shape, or a list of arrays. Returns the penalty as a float."""
        arrays, _ = _as_list(weights)
        return float(0.5 * self.config.lam * sum((w**2).sum() for w in arrays))

    def backward(self, weights):
        """Gradient of the penalty with respect to the weights: lam * w.

        Returns one array, or a list of arrays, matching what was given. Add it to the gradient of the data
        loss; the sum is what the optimiser sees.
        """
        arrays, was_list = _as_list(weights)
        grads = [self.config.lam * w for w in arrays]
        return grads if was_list else grads[0]

    def add_to(self, loss: float, grads, weights) -> tuple:
        """Convenience: returns (loss + penalty, grads + penalty gradient).

        loss: the data loss. grads: its gradient, one array or a list matching `weights`.
        """
        grad_arrays, was_list = _as_list(grads)
        pen_grads, _ = _as_list(self.backward(weights))
        if len(grad_arrays) != len(pen_grads):
            raise ValueError("grads and weights must hold the same number of arrays")
        total = [g + p for g, p in zip(grad_arrays, pen_grads)]
        return loss + self.forward(weights), (total if was_list else total[0])

    __call__ = forward
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
7, run with python3 -m unittest -v

Practice

Build L2Penalty(L2PenaltyConfig(lam=0.1)) and reproduce the worked example with forward and backward. Then call add_to with a data loss of 2.0 and a data gradient of (1, 1) and check both returned values by hand. Repeat with a list of two weight arrays.

Check on learning

  1. For plain SGD, an L2 penalty and multiplying the weights by 1−ηλ1 - \eta\lambda each step are identical. Why does that equivalence break for Adam?
    A way to think about it

    Adam divides each weight's gradient by a running scale. Follow the λw\lambda w term through that division for a weight with large gradients and one with small gradients.

  2. L2 shrinks weights but almost never makes them exactly zero, while L1 does. What in the two gradients explains this?
    A way to think about it

    The L2 pull is λw\lambda w, which fades as ww approaches zero. Compare with a pull whose size does not depend on ww.

  3. Why does a penalty on weight size reduce overfitting at all?
    A way to think about it

    Small weights mean the output changes slowly with the input. Ask what kind of function is needed to pass exactly through noisy training points.

  4. A layer is followed by batch normalisation, which rescales its output. What does shrinking that layer's weights do to the function the network computes?
    A way to think about it

    Normalisation undoes any uniform rescaling of the weights, so the output is unchanged. Consider what the penalty then actually alters: the effective step size.