Regularization
Penalise complexity with L1, L2 and elastic net to trade a little bias for less variance.
Lesson 24 of 6614 minIntermediate
You will learn to
- Explain L1 and L2 penalties
- Predict the effect of the penalty strength
- Use L1 for sparse feature selection
Before this lesson
Intuition
A model that fits its training data perfectly is often a model with wild coefficients. To pass through every point it swings its weights to large positive and negative values that cancel each other out, and a small change in the data changes them a lot. This is the high-variance behaviour described in overfitting and bias-variance.
Regularization adds a price tag to large weights. The model must now balance two aims: fit the data and keep the weights small. It will accept a slightly worse fit if it saves a lot of weight. The result is a simpler, steadier model.
Think of a household budget. Without a limit you could spend on anything. With a spending limit you must choose, and you give up the least useful purchases first. The penalty strength is how tight the limit is.
There are two classic penalties:
- L2 (ridge) penalises the sum of squared weights. It shrinks all the weights smoothly, in proportion to their size. Correlated features share the weight.
- L1 (lasso) penalises the sum of absolute weights. It can push weak weights all the way to zero, so the model uses only some of the features.
Elastic net mixes the two.
Picture it
The dashed circles are lines of equal loss, growing outwards from the unpenalised best fit. The penalty makes the model stay inside the shaded area. For the circle, the closest point is a smooth spot where both weights are non-zero but smaller. For the diamond, the closest point is the corner on the horizontal axis, so the second weight is exactly zero. The picture is for illustration.
The math
For a linear model with weights and a training loss (for example squared error), the regularized objective is
The strength (called alpha in many libraries) is a hyperparameter you choose. With there is no penalty. As grows, the weights shrink towards zero and the model moves from low bias and high variance towards high bias and low variance. The best value lies in between and is found with cross-validation.
The penalty depends on the size of the weights, which depends on the scale of the features. A feature measured in small units needs a big weight and is penalised more. So standardise the features before a penalised model.
In logistic regression, libraries often use the inverse scale: the parameter multiplies the loss instead, so a small means strong regularization, roughly .
Elastic net uses (up to constants), where is called l1_ratio: 1 is pure L1 and 0 is pure L2.
Worked example
Take the simplest case, where the features are standardised and independent of each other. Without a penalty, the best weights are 2.0 and 0.3: the first feature matters, the second is weak. In this special case the penalised solutions have a closed form (using the objective: half the mean squared error, plus alpha times the sum of absolute weights for lasso, or alpha over two times the sum of squared weights for ridge):
- Ridge divides each weight by .
- Lasso subtracts from the absolute value of each weight, and stops at zero.
| alpha | Ridge: w1, w2 | Lasso: w1, w2 |
|---|---|---|
| 0 | 2.00, 0.30 | 2.00, 0.30 |
| 0.2 | 1.67, 0.25 | 1.80, 0.10 |
| 0.5 | 1.33, 0.20 | 1.50, 0.00 |
| 2 | 0.67, 0.10 | 0.00, 0.00 |
Read it row by row:
- Ridge never reaches zero. It shrinks both weights by the same factor, so their ratio stays the same (6.7 to 1).
- Lasso removes the weak weight first. At alpha 0.5 the second feature is gone, and the model keeps only the first with weight 1.5.
- At alpha 2 even the strong feature is switched off. Too strong a penalty underfits.
Real data has correlated features, so the results are less tidy. If two features carry the same signal, lasso tends to keep one and drop the other, and which one it keeps can change with small changes in the data. Ridge splits the weight between them.
The conventions for alpha differ between algorithms (the lasso and ridge loss may be scaled differently), so the same alpha does not give the same strength in the two. Compare models by their validation scores, not by their alphas.
How mlflow does it
The model catalog includes the penalised linear models directly:
- Ridge Regression (regression) and Ridge Classifier (classification), with the hyperparameter alpha.
- Lasso Regression (regression), with alpha.
- Elastic Net (regression), with alpha and l1_ratio.
- Logistic Regression (classification), with C, plus penalty and l1_ratio for the type of penalty.
Add several of them in the Models part and let the leaderboard show which strength of penalty works for your data. In Manual mode you can set the values yourself. Other algorithms are regularized in their own ways, with depth limits, minimum leaf sizes or learning rates, as covered in the algorithms and hyperparameters references.
Common mistakes
- Forgetting to scale the features. The penalty falls unevenly on the features, and the result depends on units. Add a scaler before a penalised model.
- Using regularization to fix underfitting. A penalty adds bias. If the model already underfits, make it more flexible or improve the features.
- Choosing alpha on the training score. The training score always prefers alpha near 0. Choose it with cross-validation.
- Reading lasso's zeros as proof that a feature is useless. With correlated features lasso keeps one of them, and the choice can seem arbitrary. A feature set to zero may carry the same signal as one that was kept.
- Mixing up alpha and C. In ridge and lasso a bigger alpha means stronger regularization. In logistic regression a bigger C means weaker regularization.
Try it in mlflow
Compare ridge and lasso
- Open Pipelines and pick a regression pipeline with Standardise chosen for its numeric columns.
- In the Models part add Ridge Regression and Lasso Regression.
- Train, then open the run and compare the two candidates on the leaderboard.
- Open each model card and compare the Estimator hyperparameters (alpha). Train again with a larger alpha in Manual mode and watch the score.