Sub topic 12
L2 regularisation (ridge and weight decay)
This chapter assumes you know linear regression, mean squared error, and scikit-learn's fit and predict. It also assumes you have seen why a high-degree polynomial overfits.
The idea
A flexible model overfits partly because it uses very large coefficients to chase noise. L2 regularisation discourages this by adding a penalty on the squared size of the weights to the loss:
loss = sum((y - prediction)^2) + alpha * sum(w_j^2)The hyperparameter alpha (called lambda in many texts) sets the strength. With alpha = 0 you get ordinary least squares. As alpha grows, the weights shrink toward zero. They get small but rarely reach exactly zero. Linear regression with this penalty is called ridge regression.
The intercept is normally not penalised. Shifting every prediction by a constant should not count as complexity.
Choosing alpha by cross-validation
The code below reuses the degree-15 polynomial on noisy sine data. Scaling sits inside the pipeline, so each fold is scaled using only its own training data.
import numpy as np
from sklearn.model_selection import cross_val_score
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))
scores = cross_val_score(model, X, y, cv=5, scoring="neg_mean_squared_error")
print(alpha, round(-scores.mean(), 3))Expect a U-shaped pattern. Tiny values of alpha leave the model overfitting, and the very large value pushes it toward a flat line that underfits. The best value usually sits in between. Your exact numbers depend on the data and the library version.
Weight decay in neural networks
Gradient descent on an L2-penalised loss changes each weight update to:
w = (1 - lr * lambda) * w - lr * gradientEach step first shrinks the weight by a small factor, then applies the usual gradient step. This is why the same idea is called weight decay. In Keras, kernel_regularizer=keras.regularizers.l2(1e-3) adds the penalty to the loss for one layer.
For plain SGD, the penalty and weight decay are equivalent. For adaptive optimisers such as Adam they differ, because the penalty's gradient gets rescaled along with the rest. Decoupled versions such as AdamW apply the decay directly to the weights. They are usually preferred when you want weight decay with Adam.
Common errors
- Fitting the scaler on all the data before cross-validation, which leaks information from the validation folds.
- Comparing
alphavalues with the test set instead of cross-validation. - Searching
alphaon a linear grid. Use a logarithmic grid, such as1e-4to1e2. - Penalising the intercept in hand-written code.
Exercise
A ridge model has a training error of 0.02 and a cross-validated error of 0.35. Should you raise or lower alpha, and why?
Show answer
Raise it. The large gap between training and validation error indicates overfitting (high variance). A larger alpha shrinks the weights and reduces model flexibility. Check the result with cross-validation, and stop raising alpha once the validation error starts rising again.