Sub topic 12
L2 regularisation (ridge and weight decay)
This chapter assumes you know ordinary least squares, the idea of a loss function, the train/validation split, and scikit-learn's fit/predict workflow. It also assumes you have seen a high-degree polynomial overfit noisy data. Here you will learn what the L2 penalty does to a model, why it needs scaled features, and how the same idea appears in neural networks as weight decay.
The penalised loss
Regularisation adds a cost for complexity to the training loss. L2 regularisation charges for the squared size of the weights:
loss = data_loss + alpha * (w1² + w2² + ... + wp²)
For linear regression with squared error, this model is called ridge regression. The hyperparameter alpha sets the strength of the penalty. Some libraries call it lambda, and others use its inverse, such as C in scikit-learn's LogisticRegression.
- With
alpha = 0you get ordinary least squares. - As
alphagrows, the weights are pulled toward zero, and the model becomes smoother and less flexible. - As
alphagoes to infinity, all weights approach zero and the model predicts a constant.
The intercept is not penalised. Shifting the whole prediction up or down says nothing about complexity, so scikit-learn leaves the intercept out of the penalty.
What the penalty does
Large weights let a model change its output sharply for a small change in the input. A degree-15 polynomial fitted to 28 noisy points does exactly that, using huge coefficients with opposite signs to chase individual points. The L2 penalty makes those coefficients expensive, so the optimiser prefers a smoother curve that fits slightly worse on the training set.
Ridge has a closed-form solution, with centred data:
w = (XᵀX + alpha·I)⁻¹ Xᵀy
Adding alpha to the diagonal has two effects:
- It makes the matrix invertible even when features are perfectly correlated, so ridge is a standard fix for multicollinearity.
- It shrinks the solution along directions where the data carries little information, which are the directions that mostly fit noise.
The next snippet checks the formula against scikit-learn. Centring the data handles the unpenalised intercept.
import numpy as np
from sklearn.linear_model import Ridge
rng = np.random.default_rng(1)
X = rng.normal(size=(50, 3))
y = X @ np.array([2.0, -1.0, 0.5]) + rng.normal(0, 0.3, size=50)
alpha = 5.0
Xc = X - X.mean(axis=0)
yc = y - y.mean()
w = np.linalg.solve(Xc.T @ Xc + alpha * np.eye(3), Xc.T @ yc)
sk = Ridge(alpha=alpha).fit(X, y)
print(np.allclose(w, sk.coef_))This prints True.
Shrinkage, not selection
L2 shrinks every weight smoothly. It rarely sets a weight exactly to zero, so a ridge model keeps all of its features. If you want a model that drops features, see the next chapter on L1. Among correlated features, ridge tends to spread the weight across them. Ordinary least squares may assign large positive and negative weights to the same pair.
Scale features first
The penalty adds up squared weights, so it treats all weights as comparable. That is only true if the features are on comparable scales. A feature measured in millimetres needs a small weight to have the same effect as one measured in kilometres. The penalty would then punish the millimetre feature far less than it should, and the result would depend on your choice of units.
Put a StandardScaler before the ridge model. Keep it inside a Pipeline, so that cross-validation fits the scaler on each training fold only. The next example fits the degree-15 polynomial from earlier chapters and prints the size of the coefficient vector for several values of alpha.
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import Ridge
rng = np.random.default_rng(0)
X = rng.uniform(-3, 3, size=(40, 1))
y = np.sin(X).ravel() + rng.normal(0, 0.2, size=40)
for alpha in (1e-4, 1e-2, 1, 100):
model = make_pipeline(PolynomialFeatures(15), StandardScaler(), Ridge(alpha=alpha))
model.fit(X, y)
coef = model[-1].coef_
print(alpha, round(float(np.linalg.norm(coef)), 2))The norm of the coefficients falls as alpha rises. Run it and check that this holds. To pick the best alpha, compare cross-validated error, as in the chapter on choosing the regularisation strength. Search over a logarithmic grid such as 1e-4 to 1e2. RidgeCV does this search efficiently for you.
Weight decay in neural networks
In a neural network, L2 regularisation is usually called weight decay. Take the loss L + (lambda/2) * ||w||². Its gradient adds lambda * w, so a plain gradient step becomes:
w ← w − lr · (∇L + lambda · w) = (1 − lr · lambda) · w − lr · ∇L
Each step first multiplies the weights by a number slightly below 1, then applies the usual gradient update. That multiplication is the "decay".
Two details cause confusion in practice:
- The constant differs between libraries. Keras
regularizers.l2(1e-3)adds1e-3 * sum(w²)to the loss, with no factor of one half. So it equals a weight decay of2e-3in the formula above. - With adaptive optimisers such as Adam, an L2 term in the loss is not the same as decay applied directly to the weights. The gradient term gets rescaled by the optimiser, so weights with large gradients are decayed less. AdamW applies the decay separately from the gradient, which is usually what you want.
import torch
model = torch.nn.Linear(20, 1)
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=1e-2)Biases and normalisation parameters are often excluded from weight decay, for the same reason the intercept is excluded in ridge.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Not scaling features | Penalty depends on units, so some features are over- or under-shrunk | Add `StandardScaler` inside the pipeline |
| Scaling on all data before cross-validation | Validation folds leak into the scaler | Scale inside a `Pipeline` |
| Choosing `alpha` on the test set | Optimistic test estimate | Tune with cross-validation, then test once |
| Searching `alpha` on a linear grid | Misses the useful range | Use a log grid |
| Expecting zero coefficients | Ridge shrinks but keeps all features | Use L1 or elastic net |
| Mixing up `alpha` and `C` | Strength moves in the wrong direction | Remember `C` is the inverse of the strength |
| Treating Keras `l2` as the same as `weight_decay` elsewhere | Strength differs by a constant factor | Check each library's definition |
Exercise
A ridge model gets training MSE 0.04 and validation MSE 0.30 at alpha = 0.001. You raise alpha to 10 and get training MSE 0.09 and validation MSE 0.12. Then you raise it to 10000 and get training MSE 0.55 and validation MSE 0.58. Explain each step in terms of bias and variance, and say which alpha you would keep.
Show answer
At alpha = 0.001 the large gap between training and validation error shows high variance (overfitting). At alpha = 10 the penalty shrinks the weights. Training error rises a little (more bias) but validation error drops a lot (less variance), so the model generalises better. At alpha = 10000 both errors are high and close together, which is high bias (underfitting), because the weights are shrunk almost to zero. Keep alpha = 10, which has the lowest validation error. Ideally, confirm this with cross-validation over a log grid, then evaluate once on the test set.
Exercise
Why does the fitted pipeline in this chapter place StandardScaler before Ridge, and why is the scaler inside the pipeline rather than applied to the whole dataset first?
Show answer
Ridge penalises the sum of squared weights, so features on larger or smaller scales would be shrunk unevenly and results would depend on units. Standardising puts the weights on a comparable footing. Inside the pipeline, cross-validation refits the scaler on each training fold only, so no information from the validation fold leaks into the scaling.