◆ AI All-in-One

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
↗ Plan a path here

Read first

Overfitting and the Bias–Variance TradeoffLinear Regression

This leads to

Dropout and Regularizing Neural Networks
The full path from zero — 11 concepts before this one
  1. What Is AI?
  2. Derivatives and Slopes
  3. Vectors
  4. How Machines Learn
  5. Partial Derivatives and Gradients
  6. Supervised, Unsupervised and Reinforcement Learning
  7. Gradient Descent
  8. Supervised Learning
  9. Training, Validation and Test Sets
  10. Linear Regression
  11. Overfitting and the Bias–Variance Tradeoff
  12. 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:

total loss=how badly you fit the data+λ×how big your weights are\text{total loss} = \text{how badly you fit the data} + \lambda \times \text{how big your weights are}

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 ("lambda") sets the exchange rate. With λ=0\lambda = 0 you are back to the unregularised model. With a huge λ\lambda 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 λ\lambda 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:

L(w,b)=∑i=1N(w⋅xi+b−yi)2+λ∑j=1dwj2L(\mathbf{w}, b) = \sum_{i=1}^{N} (\mathbf{w} \cdot \mathbf{x}_i + b - y_i)^2 + \lambda \sum_{j=1}^{d} w_j^2

This is ridge regression. The first term is the usual sum of squared errors from Linear Regression. The second is λ\lambda times the squared length of the weight vector. Note that the bias bb 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:

w=(X⊤X+λI)−1X⊤y\mathbf{w} = (\mathbf{X}^\top \mathbf{X} + \lambda \mathbf{I})^{-1} \mathbf{X}^\top \mathbf{y}

I\mathbf{I} is the identity matrix (1s on the diagonal, 0s elsewhere). Adding λ\lambda 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 2λwj2\lambda w_j 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, ∑(xi−xˉ)(yi−yˉ)=8.5\sum (x_i - \bar{x})(y_i - \bar{y}) = 8.5 and ∑(xi−xˉ)2=5\sum (x_i - \bar{x})^2 = 5:

w=8.55+λw = \frac{8.5}{5 + \lambda}
λ\lambda Slope ww Bias b=yˉ−wxˉb = \bar{y} - w\bar{x}
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 λ\lambda to the denominator. As λ\lambda 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:

L(w,b)=12N∑i=1N(w⋅xi+b−yi)2+λ∑j=1d∣wj∣L(\mathbf{w}, b) = \frac{1}{2N}\sum_{i=1}^{N} (\mathbf{w} \cdot \mathbf{x}_i + b - y_i)^2 + \lambda \sum_{j=1}^{d} \lvert w_j \rvert

This is the lasso ("least absolute shrinkage and selection operator"). (The 12N\frac{1}{2N} in front is just scikit-learn's convention and changes only the scale of λ\lambda.) 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, 1N∑(xi−xˉ)(yi−yˉ)=8.5/4=2.125\frac{1}{N}\sum (x_i - \bar{x})(y_i - \bar{y}) = 8.5/4 = 2.125 and 1N∑(xi−xˉ)2=5/4=1.25\frac{1}{N}\sum (x_i - \bar{x})^2 = 5/4 = 1.25:

w=max⁡(2.125−λ, 0)1.25w = \frac{\max(2.125 - \lambda,\ 0)}{1.25}
  • λ=0.5\lambda = 0.5: w=1.625/1.25=1.3w = 1.625 / 1.25 = 1.3.
  • λ=1\lambda = 1: w=1.125/1.25=0.9w = 1.125 / 1.25 = 0.9.
  • λ≥2.125\lambda \ge 2.125: w=0w = 0 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 λ\lambda 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 (w12+w22≤t2w_1^2 + w_2^2 \le t^2). For L1 it is a diamond (∣w1∣+∣w2∣≤t\lvert w_1 \rvert + \lvert w_2 \rvert \le t).

w₁ w₂ ŵ (no penalty) L2 penalty (ridge) budget: w₁² + w₂² ≤ t² (0.67, 1.12) touches the circle at a point with both weights non-zero w₁ w₂ ŵ (no penalty) L1 penalty (lasso) budget: |w₁| + |w₂| ≤ t (0.00, 1.30) touches the diamond at a corner: w₁ is exactly 0
Fig. 1 The data loss has elliptical contours centred on the unpenalised solution ŵ. The regularised solution is where the smallest ellipse first touches the budget region. A circle (L2, left) is usually touched at a point where both weights are non-zero. A diamond (L1, right) is usually touched at a corner, where one weight is exactly zero.

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 λ\lambda rises, the two penalties trace different regularization paths: the value of each weight as a function of penalty strength.

-40 -20 0 20 40 0.01 1 100 10000 Ridge (L2) penalty strength α (log scale) → weight 0.01 0.1 1 10 100 Lasso (L1) penalty strength α (log scale) → s5 bmi s2 bp sex s1 Standardised diabetes data. Ridge shrinks every weight smoothly towards 0; lasso sets them to exactly 0, one by one.
Fig. 2 Coefficient paths on the standardised diabetes data. Left, ridge: every weight glides smoothly towards zero as the penalty grows. Right, lasso: weights hit zero one at a time and stay there; at α = 10, six of the ten are already exactly zero.

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, λ1∑∣wj∣+λ2∑wj2\lambda_1 \sum \lvert w_j \rvert + \lambda_2 \sum w_j^2. 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 λ\lambda. 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 λ=0\lambda = 0. 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 λ\lambda 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.01\lambda = 0.01 (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 λ\lambda as the capacity dial turned the other way.

With scikit-learn, ridge and lasso on the diabetes data, and LassoCV choosing λ\lambda (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 1/λ1/\lambda: 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 StandardScaler in 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. alpha in scikit-learn's Ridge and Lasso is λ\lambda, but C in LogisticRegression and SVMs is 1/λ1/\lambda. The loss scaling (∑\sum versus 12N∑\frac{1}{2N}\sum) 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

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

  1. Using the formula w=8.5/(5+λ)w = 8.5/(5 + \lambda), find the λ\lambda that halves the students' slope. Check it with Ridge(alpha=...) on the four points.
  2. In the ridge-polynomial code, add lam = 0.001 and lam = 0.1. Where exactly is the best test error? Would you have found it with only the values given?
  3. Replace Lasso with ElasticNet(alpha=1, l1_ratio=0.5) in the scikit-learn code. How many weights are zero now?

Hint for 1: you need 5+λ=105 + \lambda = 10.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. You raise the ridge penalty λ from 0 to a very large value. What happens to the model?

  2. You have 2,000 candidate genes and want a model that uses only a handful of them. Which penalty fits best?

  3. How should you choose the regularization strength λ?

  4. One feature is measured in millimetres and another in kilometres, and neither is standardised before adding an L2 penalty. What goes wrong?

  5. Your model's training error is already high. A colleague suggests more regularization. Good idea?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Video

StatQuest

Josh Starmer · Beginner · Free

Short, cheerful, very clear videos on statistics and nearly every ML algorithm.

Docs

scikit-learn: Linear Models

scikit-learn · Intermediate · Free

The user-guide chapter on ordinary least squares, ridge, lasso, elastic net and logistic regression, with the maths and runnable examples.

Book

Dive into Deep Learning

Zhang, Lipton, Li & Smola · Intermediate · Free

An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.

Course

Machine Learning Crash Course

Google · Beginner · Free

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