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 . 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
- Take the weights, one array or a list of arrays.
- In
forward, sum the squares of all weights and multiply by . Add this to the data loss. - In
backward, return for each weight array. - Add that to the gradient of the data loss. The helper
add_todoes both additions in one call. - 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 quoted for 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
| If | Use instead |
|---|---|
| You train with Adam or another adaptive optimiser | Decoupled weight decay as in AdamW |
| You want many weights to be exactly zero | L1 penalty |
| The network overfits despite weight shrinkage | Dropout or early stopping in addition |
Math foundations
The penalty
Half the sum of squared weights, scaled by the strength . The half is there so the gradient has no factor of 2.
The objective being minimised
The data loss plus the penalty. The optimiser sees one combined loss and does not know the two parts apart.
The gradient
A pull toward zero in proportion to each weight. This is what
backwardreturns, to be added to the data gradient.What it does under plain SGD
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.
Why it differs under adaptive optimisers
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 . Decoupled weight decay applies the shrink outside this division.
Symbols
- the weights and one of them
- penalty strength,
lamin the config, default 0.0001 - the penalty
- the loss on the data, without the penalty
- the full objective
- the learning rate
- an adaptive optimiser's running estimate of the squared gradient, per weight
- a small constant that prevents division by zero
Worked by hand
Weights with . Compute the penalty and its gradient, then one SGD step with and a data gradient of zero.
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 gradientRead 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
- For plain SGD, an L2 penalty and multiplying the weights by 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 term through that division for a weight with large gradients and one with small gradients.
- 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 , which fades as approaches zero. Compare with a pull whose size does not depend on .
- 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.
- 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.