Sub topic 10
Regularisation: penalising complexity
This chapter assumes you know what a loss function is, how linear regression fits parameters by minimising a loss, and how to use scikit-learn's fit and predict. It also assumes you have seen overfitting: a model with low training error and much higher validation error. This chapter explains the general idea behind the fixes. Later chapters cover each specific method in detail.
The core idea
Overfitting happens when a model has enough freedom to fit noise in the training set. You can reduce that freedom in two ways:
- Choose a less flexible model, for example a lower polynomial degree.
- Keep the flexible model, but make extreme solutions costly.
Regularisation is the second option. It changes what the optimiser is minimising. Instead of only the data loss, it minimises the data loss plus a penalty on model complexity:
total_loss(w) = data_loss(w) + lambda * penalty(w)Here w is the vector of model parameters. data_loss is the usual loss, such as mean squared error. penalty(w) is a number that grows as the parameters become more extreme. lambda is the regularisation strength. Scikit-learn calls it alpha in Ridge and Lasso. Keras and some other libraries use other names, and some put the strength on the data loss instead (scikit-learn's C is an inverse strength).
The optimiser now has two competing goals. The data loss pulls the parameters toward values that fit the training set. The penalty pulls them toward values that are small or simple. The result is a compromise.
Why a penalty reduces overfitting
A flexible model that overfits usually needs large, finely balanced parameters. A degree-15 polynomial can swing sharply between training points, and that takes large coefficients that cancel each other out. A smooth curve needs only modest coefficients.
If the penalty grows with the size of the parameters, the optimiser accepts a slightly worse training fit in return for much smaller parameters. The model gives up some training accuracy and gets a smoother function. That usually lowers variance, the sensitivity of the fitted model to the particular training sample, at the cost of some extra bias.
This means regularisation moves a model along the bias-variance trade-off without changing its architecture. A strongly penalised degree-15 model behaves like a much simpler model. The number of parameters is the same, but the effective capacity is lower.
Seeing the effect in code
The following script fits the same degree-15 polynomial with four penalty strengths. It prints the training error and the sum of squared coefficients, which is a simple measure of how large the parameters are.
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_squared_error
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)
coefs = model[-1].coef_
train_mse = mean_squared_error(y, model.predict(X))
print(alpha, round(train_mse, 3), round(float(np.sum(coefs ** 2)), 2))As alpha increases, expect two trends. The sum of squared coefficients falls, because the penalty is shrinking the parameters. The training error rises, because the model is no longer free to chase every point. The training error alone does not tell you which alpha is best. You need validation data or cross-validation for that, which is the subject of the strength-tuning chapter.
What the penalty usually applies to
Some details are common to most penalised models:
- The intercept (bias term) is normally not penalised. Shifting every prediction by a constant is not a form of complexity. Scikit-learn leaves the intercept out of the penalty by default.
- The penalty acts on the size of the parameters, so it depends on the units of the features. Features on very different scales get unequal treatment. The next chapter covers why you should scale features first.
- Only the training objective includes the penalty. When you report validation or test error, use the plain data loss, such as MSE, so that results with different
lambdavalues are comparable. lambdais a hyperparameter. The optimiser does not learn it from the training data. If it did, it would setlambdato zero, because that always gives the lowest training loss.
Two limiting cases
The strength lambda controls where you land on the underfitting-overfitting scale.
| Setting of lambda | Behaviour | Typical symptom |
|---|---|---|
| Zero or tiny | Same as the unregularised model | Low training error, high validation error |
| Moderate | Parameters shrunk, smoother fit | Validation error near its minimum |
| Very large | Parameters pushed close to zero | Both errors high (underfitting) |
At the large extreme, a linear model predicts roughly a constant (the mean of the targets), since all slope parameters are near zero. Too much regularisation produces underfitting, so more is not always better.
Different penalties, different behaviours
The choice of penalty(w) determines the behaviour of the fitted model:
- The sum of squared parameters (L2) shrinks all parameters smoothly and rarely makes any of them exactly zero. This is ridge regression, called weight decay in neural networks.
- The sum of absolute values (L1) can set some parameters exactly to zero, which removes features. This is lasso.
- A weighted mix of the two is elastic net.
The following chapters cover each in detail.
Regularisation beyond explicit penalties
In a broader sense, regularisation is any technique that reduces overfitting, whether or not you can write it as a term added to the loss. Several methods in this tutorial fit that description:
- Early stopping halts training when validation loss stops improving. This limits how far the parameters travel from their small initial values, which has an effect similar to a penalty.
- Dropout randomly disables units during training, so the network cannot rely on any single unit.
- Data augmentation adds transformed copies of training examples, so the model sees more variety.
All of these act on the same problem: reducing a model's ability to fit noise that does not generalise.
A probabilistic view
There is a useful interpretation, which you can skip on a first read. Minimising squared error alone corresponds to maximum likelihood estimation with Gaussian noise. Adding an L2 penalty corresponds to maximum a posteriori estimation with a Gaussian prior on the parameters, centred at zero. An L1 penalty corresponds to a Laplace prior. The penalty therefore encodes a prior belief that parameters should be small, and lambda sets how strongly you hold that belief relative to the evidence in the data.
Exercise
A ridge model with alpha=0.001 has training MSE 0.04 and validation MSE 0.45. After raising alpha to 10, training MSE is 0.09 and validation MSE is 0.12. Explain what happened, and say what you would expect if alpha were raised to 100000.
Show answer
With a tiny alpha the model is almost unregularised and overfits: it fits the training set very well but generalises poorly. Raising alpha to 10 shrinks the parameters and smooths the fit. Training error rises because the model has less freedom, but validation error falls sharply, so generalisation improved. At alpha=100000 the penalty dominates, so the parameters are pushed close to zero and the model predicts roughly the mean of the targets. Both training and validation MSE would be high, which is underfitting.
Exercise
Why can't the optimiser learn lambda by minimising the regularised training loss together with the parameters?
Show answer
The penalty term is never negative, so the total training loss is lowest when lambda is zero. The optimiser would remove the penalty and the model would overfit. Lambda has to be chosen by evaluating the plain data loss on held-out data, for example with cross-validation.