Level 3 In-Depth AI · Classical Machine Learning
Regularization: L1 and L2
Fighting overfitting by charging the model for complexity. Add a penalty on large weights to the loss and the model must justify every weight it uses; ridge shrinks them all, lasso switches many off entirely, and stopping training early does something similar.
- Level
- ●●●●● Easy
- Reading
- 13 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 11 concepts →
- Quiz
- 5 questions ↓
This leads to
Dropout and Regularizing Neural NetworksThe full path from zero — 11 concepts before this one
- What Is AI?
- Derivatives and Slopes
- Vectors
- How Machines Learn
- Partial Derivatives and Gradients
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Training, Validation and Test Sets
- Linear Regression
- Overfitting and the Bias–Variance Tradeoff
- Regularization: L1 and L2
Read them roughly in this order. See it on the concept map →
Why it matters
The Overfitting and the Bias–Variance Tradeoff chapter showed a degree-11 polynomial threading every one of 12 noisy points and going wild in between. One fix is to use a simpler model. Regularization is another, usually better, fix: keep the flexible model, but add a cost for using its flexibility. The model may still bend, but only where the data clearly asks it to.
Regularization is everywhere. Scikit-learn's LogisticRegression applies it by default. Every large neural network, including the language models behind chatbots, is trained with weight decay, the deep-learning name for the L2 penalty in this chapter. Lasso, the L1 version, is a standard tool for picking out the few genes, words or sensors that matter among thousands. And early stopping, ending training before the model starts memorising, is used in almost every neural-network training run. Understanding regularization means you can use flexible models without being burned by them.
The intuition
Overfitted models have a tell-tale sign: huge weights. To pass exactly through every noisy point, the degree-11 polynomial needed coefficients in the hundreds of thousands, balanced against each other so that their enormous contributions cancel almost perfectly at the training points and explode everywhere else. Smooth, sensible functions usually have modest weights.
So add a second term to the loss that grows with the size of the weights:
Now the model faces a trade-off. Increasing a weight might fit the training data a little better, but it costs penalty. A weight survives only if it earns its keep. The number ("lambda") sets the exchange rate. With you are back to the unregularised model. With a huge all weights are crushed towards zero and the model predicts roughly the average for everything.
An analogy: you hire a contractor to fit a curve to your data and pay them by how close they get. Unregularised, they will happily build something absurdly elaborate. Regularised, you also charge them for every bit of material they use, so they build the simplest structure that does the job well.
Key idea Regularization adds a penalty on the size of the weights to the loss. L2 (ridge) penalises squared weights and shrinks all of them smoothly. L1 (lasso) penalises absolute weights and drives many of them to exactly zero. The strength is chosen on validation data.
How it works
L2 regularization: ridge regression
The L2 penalty is the sum of the squared weights. For linear regression the loss becomes:
This is ridge regression. The first term is the usual sum of squared errors from Linear Regression. The second is times the squared length of the weight vector. Note that the bias is not penalised: shifting all predictions up or down isn't "complexity".
Ridge keeps a closed-form solution. The normal equation gains one extra term:
is the identity matrix (1s on the diagonal, 0s elsewhere). Adding to the diagonal has a second benefit: it makes the matrix safely invertible even when features are duplicated or there are more features than examples. That is why ridge also cures the unstable weights caused by correlated features (multicollinearity).
In gradient descent, the penalty adds to each weight's gradient. Every step therefore shrinks each weight by a small fixed fraction before applying the data's push. That is why the deep-learning community calls it weight decay.
A worked example: ridge by hand
Return to the four students (hours 1, 2, 3, 4; scores 3, 5, 7, 8). With one feature and an unpenalised bias, the ridge slope has a simple formula. Using the sums of deviations from the Linear Regression chapter, and :
| Slope | Bias | |
|---|---|---|
| 0 | 8.5 / 5 = 1.70 | 1.50 |
| 1 | 8.5 / 6 = 1.42 | 2.21 |
| 5 | 8.5 / 10 = 0.85 | 3.63 |
| 100 | 8.5 / 105 = 0.08 | 5.55 |
The penalty simply adds to the denominator. As grows the slope shrinks towards 0, and the line flattens towards the average score, 5.75. It never reaches zero exactly.
L1 regularization: the lasso
The L1 penalty uses absolute values instead of squares:
This is the lasso ("least absolute shrinkage and selection operator"). (The in front is just scikit-learn's convention and changes only the scale of .) The difference from ridge looks small, and it has a dramatic effect: the lasso sets many weights to exactly zero. The resulting model uses only a subset of the features. This is called sparsity, and it makes lasso an automatic feature-selection method.
For one feature, the lasso has a neat solution called soft thresholding. For the students, with this scaling, and :
- : .
- : .
- : exactly. The feature is switched off.
Ridge divides the weight down; lasso subtracts a fixed amount and stops at zero. A feature whose evidence is weaker than gets no weight at all.
Why L1 gives zeros: the geometry
An equivalent way to write either penalty is as a budget: minimise the data loss, subject to the weights staying inside a region. For L2 the region is a circle (). For L1 it is a diamond ().
The diamond has sharp corners sitting on the axes, where some weights are zero. Expanding ellipses of the data loss are much more likely to hit a corner first than the middle of an edge. The circle has no corners, so it is almost always touched at a point where every weight is non-zero but smaller. In many dimensions the L1 "diamond" has a great many corners and edges on which many weights are zero, which is why the lasso produces such sparse models.
Watching the weights shrink
As rises, the two penalties trace different regularization paths: the value of each weight as a function of penalty strength.
Notice the correlated pair s1 and s2 (two cholesterol measures). Unregularised, they have large weights of opposite sign that mostly cancel. Both penalties tame them early. Under the lasso, s2 is dropped entirely at a small penalty.
Elastic net combines both penalties, . It keeps the lasso's sparsity while behaving better when features come in correlated groups: the lasso tends to pick one member of a group arbitrarily, while elastic net shares weight among them.
Early stopping
Gradient descent from small starting weights fits the broad, simple patterns first and the fine, noisy details later. So if you watch the validation loss during training, you typically see it fall, bottom out and then start to rise as the model begins to memorise, all while the training loss keeps falling. Early stopping means ending training at the bottom of the validation curve, or more practically, saving the model with the best validation score so far and stopping when it hasn't improved for a set number of epochs (the "patience").
Early stopping is a form of regularization: limiting the number of steps limits how far the weights can travel from their small starting values. For linear models trained with gradient descent it can be shown to behave much like an L2 penalty, with fewer steps corresponding to a larger . It is cheap, needs no change to the loss, and is standard in neural-network training and Gradient Boosting: XGBoost and LightGBM.
Neural networks use other regularisers too: Dropout and Regularizing Neural Networks, Data Augmentation, and to some extent Normalization Layers: BatchNorm and LayerNorm. They all aim at the same thing: stop the model from relying on accidents of the training set.
Choosing λ
The penalty strength is a hyperparameter: a setting you choose rather than one the training learns (Hyperparameter Tuning). Never choose it by training error, which is always lowest at . Choose it by validation error, ideally with Cross-Validation. Try values spread on a log scale (0.001, 0.01, 0.1, 1, 10, 100) because the useful range can span many orders of magnitude. Then narrow in.
One more rule: standardise the features first. The penalty treats every weight the same, but a weight's size depends on its feature's units. Measure a distance in millimetres instead of kilometres and its weight shrinks a millionfold, so it is barely penalised. After standardising, every feature competes on equal terms.
In code
Ridge from scratch, taming the wild degree-11 polynomial from the Overfitting and the Bias–Variance Tradeoff chapter (same 12 points, same seed):
import numpy as np
rng = np.random.default_rng(1)
def make_data(n):
x = rng.uniform(0, 1, n)
return x, np.sin(2 * np.pi * x) + rng.normal(0, 0.25, n)
x_tr, y_tr = make_data(12)
x_te, y_te = make_data(1000)
def features(x, degree=11): # columns x, x^2, ..., x^11
return np.column_stack([x ** k for k in range(1, degree + 1)])
F_tr, F_te = features(x_tr), features(x_te)
mu, sd = F_tr.mean(axis=0), F_tr.std(axis=0)
F_tr, F_te = (F_tr - mu) / sd, (F_te - mu) / sd # standardise
b = y_tr.mean() # bias: not penalised
for lam in [1e-6, 1e-4, 1e-2, 1, 100]:
# ridge closed form: w = (X^T X + lambda I)^-1 X^T (y - b)
w = np.linalg.solve(F_tr.T @ F_tr + lam * np.eye(11), F_tr.T @ (y_tr - b))
mse_tr = np.mean((F_tr @ w + b - y_tr) ** 2)
mse_te = np.mean((F_te @ w + b - y_te) ** 2)
print(f"lambda {lam:7g} train {mse_tr:.4f} test {mse_te:10.4f} |w| {np.linalg.norm(w):9.1f}")
# lambda 1e-06 train 0.0094 test 0.2611 |w| 70.8
# lambda 0.0001 train 0.0137 test 0.1294 |w| 16.5
# lambda 0.01 train 0.0282 test 0.0998 |w| 3.3
# lambda 1 train 0.0768 test 0.1878 |w| 0.6
# lambda 100 train 0.2277 test 0.4790 |w| 0.1
Read across: as grows the weight vector's length |w| falls from 70.8 to 0.1 and training error rises steadily. Test error falls, bottoms out at (0.0998, close to the best cubic's 0.075), then rises again as the model is squeezed too hard. That is the U-shaped curve from the overfitting chapter, with as the capacity dial turned the other way.
With scikit-learn, ridge and lasso on the diabetes data, and LassoCV choosing (called alpha there) by cross-validation:
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.linear_model import Ridge, Lasso, LassoCV
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
data = load_diabetes()
X_tr, X_te, y_tr, y_te = train_test_split(data.data, data.target, random_state=0)
for alpha in [0.1, 1, 10]:
ridge = make_pipeline(StandardScaler(), Ridge(alpha=alpha)).fit(X_tr, y_tr)
lasso = make_pipeline(StandardScaler(), Lasso(alpha=alpha)).fit(X_tr, y_tr)
zeros = np.sum(lasso[-1].coef_ == 0)
print(f"alpha {alpha:4}: ridge R^2 {ridge.score(X_te, y_te):.3f} | "
f"lasso R^2 {lasso.score(X_te, y_te):.3f}, {zeros} of 10 weights exactly 0")
# Let cross-validation choose alpha
cv = make_pipeline(StandardScaler(), LassoCV(cv=5)).fit(X_tr, y_tr)
kept = [n for n, w in zip(data.feature_names, cv[-1].coef_) if w != 0]
print(f"LassoCV alpha {cv[-1].alpha_:.3f}, test R^2 {cv.score(X_te, y_te):.3f}, kept {kept}")
# alpha 0.1: ridge R^2 0.359 | lasso R^2 0.356, 0 of 10 weights exactly 0
# alpha 1: ridge R^2 0.358 | lasso R^2 0.356, 2 of 10 weights exactly 0
# alpha 10: ridge R^2 0.358 | lasso R^2 0.332, 6 of 10 weights exactly 0
# LassoCV alpha 1.862, test R^2 0.356, kept ['sex', 'bmi', 'bp', 's1', 's2', 's3', 's5']
On this dataset, with only 10 features and 331 training patients, plain linear regression barely overfits, so regularization doesn't improve the test score much. Its value here is different: the lasso at alpha=10 uses just 4 features and loses little accuracy, giving a simpler model that is easier to explain. Regularization pays off most when features are many relative to examples. In Logistic Regression the same penalties appear through l1_ratio (0 for L2, 1 for L1; the older penalty="l1" / "l2" argument is deprecated since scikit-learn 1.8) and the parameter C, which is : smaller C means stronger regularization. In PyTorch, L2 is the weight_decay argument of the optimizer (Optimizers: SGD, Momentum and Adam).
Common pitfalls
- Forgetting to standardise. The penalty then hits features unevenly depending on their units. Put a
StandardScalerin the pipeline before the model. - Penalising the bias. The intercept should normally be free. Libraries handle this, but from-scratch code often penalises it by accident.
- Choosing λ on the test set, or by training error. Use validation data or cross-validation.
- Reading lasso's choices as the truth. When features are correlated, the lasso picks one more or less arbitrarily, and a slightly different sample may pick another. Zero weight means "not needed given the others", not "irrelevant".
- Mixing up conventions.
alphain scikit-learn'sRidgeandLassois , butCinLogisticRegressionand SVMs is . The loss scaling ( versus ) also changes what a given number means.
Watch out Regularization reduces variance but adds bias. If your model is underfitting (training error already high), more regularization makes it worse. Check the learning curve first (Overfitting and the Bias–Variance Tradeoff).
Where it leads
- Cross-Validation and Hyperparameter Tuning: how to choose properly.
- Logistic Regression and Support Vector Machines: classification models where L2 regularization is the default.
- Dropout and Regularizing Neural Networks, Data Augmentation and Normalization Layers: BatchNorm and LayerNorm: regularization for neural networks.
- Optimizers: SGD, Momentum and Adam: AdamW decouples weight decay from the adaptive step, a small change that matters in practice.
- Gradient Boosting: XGBoost and LightGBM: uses shrinkage (a small learning rate), tree-size limits and early stopping as regularisers.
- Bayes' Theorem: an L2 penalty is equivalent to a Gaussian prior belief that weights are small, and L1 to a Laplace prior.
A bit of history
The L2 idea was developed independently several times. Andrey Tikhonov introduced it in the 1940s–60s for solving unstable ("ill-posed") equations, so mathematicians call it Tikhonov regularization. Arthur Hoerl and Robert Kennard brought it into statistics as ridge regression in 1970, to deal with correlated predictors. Robert Tibshirani introduced the lasso in 1996, building on work on L1 penalties in signal processing, and the lasso launched a large field of sparse methods. Hui Zou and Trevor Hastie proposed the elastic net in 2005. Early stopping was used in neural-network training from the late 1980s, and weight decay has been standard there for as long. Today almost every large neural network is trained with AdamW, whose "W" stands for its separate handling of weight decay.
Try it
- Using the formula , find the that halves the students' slope. Check it with
Ridge(alpha=...)on the four points.- In the ridge-polynomial code, add
lam = 0.001andlam = 0.1. Where exactly is the best test error? Would you have found it with only the values given?- Replace
LassowithElasticNet(alpha=1, l1_ratio=0.5)in the scikit-learn code. How many weights are zero now?Hint for 1: you need .
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
An Introduction to Statistical Learning (with Python)
The friendliest rigorous introduction to classical ML, with Python labs. Free PDF.
StatQuest
Short, cheerful, very clear videos on statistics and nearly every ML algorithm.
scikit-learn: Linear Models
The user-guide chapter on ordinary least squares, ridge, lasso, elastic net and logistic regression, with the maths and runnable examples.
The Elements of Statistical Learning
The graduate-level reference for classical statistical learning. Free PDF.
Statistical Learning with Sparsity: The Lasso and Generalizations
The definitive book on the lasso and its relatives, written by its inventor and colleagues; the authors provide a free PDF.
Dive into Deep Learning
An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.
Machine Learning Crash Course
Short, practical lessons with interactive visualisations covering regression, classification, embeddings and neural nets.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/ml/regularization.md