Search

Search papers and lessons

L2 Regularization

Level 3 · 13 min read

L2 regularization adds a penalty on the squared size of the weights, so the fit trades a little accuracy on the training data for smaller, more stable weights that generalise better.

On this page

  • Colour = topic mix
  • Probability
  • Learning basics
  • Losses & regularization
  • Linear algebra
  • Discrete math
  • Sign in to see your progress

TL;DR

L2 regularization adds a price for large weights to the loss that a model minimises. The model still wants to fit the training data, but every unit of weight size costs it something, so it only keeps a large weight when the data really demands it. The result is smaller, steadier weights that usually predict new data better.

It is the simplest cure for Overfitting, and it is the same idea as weight decay in neural networks and ridge regression in statistics.

Where you'll see it: in the weight_decay setting of nearly every optimiser for neural networks, in ridge regression when features are strongly correlated, and in the Gaussian prior behind many Bayesian models.

Intuition

A leash on the weights

Picture a dog that wants to run to a bone (the lowest error on the training data) while its owner holds a leash tied to the origin. The dog can still reach the bone if the bone is close enough to the owner, but it will not drag the owner across the park to get there. The leash is the penalty. The longer the leash is pulled out, the more it costs.

Without a leash, a flexible model finds weights that fit every wiggle of the training set, including the noise. Those weights are often huge and cancel each other out: one large positive weight paired with a large negative weight on a nearly identical feature. Tiny changes in the input then produce large changes in the output. The leash stops that by making huge weights expensive.

−0.500.511.522.501234weight wloss
  • data loss only
  • data loss + penalty (strength 1)
The data alone is lowest at w = 1. Adding the penalty pulls the best weight to w = 0.5, a smaller value, at the cost of a worse fit to the data.

The plot is a one-weight toy. The data pulls the weight towards 1, the penalty pulls it towards 0, and the minimum sits between them. Making the penalty stronger moves the minimum closer to 0. This is the whole mechanism; the rest of the lesson is about making it precise and seeing what it costs.

Why the square

The penalty is the squared length of the weight vector, ∥w∥2\|\mathbf{w}\|^2. Squaring matters for two reasons. It is smooth everywhere, so it has a gradient at every point and gradient descent handles it without special cases. And it punishes big weights much more than small ones: a weight of 2 costs four times as much as a weight of 1, so the penalty pushes hardest on the largest weights. The cost is that it rarely sets a weight to exactly zero. That is what distinguishes it from L1 penalties, which can set weights to exactly zero.

flowchart LR
  A["Training data"] --> B["Data loss: how wrong the predictions are"]
  C["Weights w"] --> D["Penalty: lambda times squared length of w"]
  B --> E["Total loss = data loss + penalty"]
  D --> E
  E --> F["Minimise: smaller weights, slightly worse fit"]

The math

The penalised loss

Let L0(w)L_0(\mathbf{w}) be the ordinary loss, for example the sum of squared errors of a linear model. The regularised loss is

J(w)=L0(w)+λ∥w∥2.J(\mathbf{w}) = L_0(\mathbf{w}) + \lambda \|\mathbf{w}\|^2.

Here w\mathbf{w} is the weight vector, L0L_0 measures how well the model fits the data, and λ≥0\lambda \ge 0 (the Greek letter lambda) is the regularisation strength. It is a number you choose, usually by checking performance on a validation set. When λ=0\lambda = 0 you get back the original problem. As λ\lambda grows, the penalty dominates and the weights shrink towards zero.

For the linear model with the sum of squared errors, L0(w)=∥Xw−y∥2L_0(\mathbf{w}) = \|X\mathbf{w} - \mathbf{y}\|^2, where the rows of XX are the training inputs and y\mathbf{y} holds the targets. So

J(w)=∥Xw−y∥2+λ∥w∥2.J(\mathbf{w}) = \|X\mathbf{w} - \mathbf{y}\|^2 + \lambda \|\mathbf{w}\|^2.

The closed-form solution

Set the gradient of JJ to zero. Expanding as in linear regression, J(w)=w⊤X⊤Xw−2w⊤X⊤y+y⊤y+λw⊤wJ(\mathbf{w}) = \mathbf{w}^\top X^\top X \mathbf{w} - 2\mathbf{w}^\top X^\top \mathbf{y} + \mathbf{y}^\top \mathbf{y} + \lambda \mathbf{w}^\top \mathbf{w}. The gradient is

∇J(w)=2(X⊤Xw−X⊤y)+2λw.\nabla J(\mathbf{w}) = 2\left(X^\top X \mathbf{w} - X^\top \mathbf{y}\right) + 2\lambda \mathbf{w}.

Setting it to zero and collecting the terms in w\mathbf{w}:

(X⊤X+λI)w=X⊤y⟹w^ridge=(X⊤X+λI)−1X⊤y.\left(X^\top X + \lambda I\right)\mathbf{w} = X^\top \mathbf{y} \quad\Longrightarrow\quad \hat{\mathbf{w}}_{\text{ridge}} = \left(X^\top X + \lambda I\right)^{-1} X^\top \mathbf{y}.

Here II is the identity matrix, and the hat marks an estimate from data. This is the same formula as ordinary least squares with λI\lambda I added. That addition is the whole trick. Even when X⊤XX^\top X is singular (it has no inverse, which happens when some feature is an exact combination of others), adding λI\lambda I with λ>0\lambda \gt 0 makes the matrix invertible. A matrix is invertible exactly when none of its eigenvalues (the stretch factors of the matrix along its special directions) is zero. Every eigenvalue of X⊤XX^\top X is non-negative, and adding λI\lambda I shifts each one up by λ\lambda to a value that is strictly positive.

The gradient-descent view

Most models are trained by Gradient Descent, not by a closed form. The penalty fits in cleanly. With learning rate η\eta,

w←w−η(∇L0(w)+2λw)=(1−2ηλ) w−η∇L0(w).\mathbf{w} \leftarrow \mathbf{w} - \eta\left(\nabla L_0(\mathbf{w}) + 2\lambda \mathbf{w}\right) = (1 - 2\eta\lambda)\,\mathbf{w} - \eta \nabla L_0(\mathbf{w}).

The first term multiplies the current weights by a factor a little below 1 on every step, before the data gradient is applied. That shrinking is why the method is called weight decay. Each step decays the weights a little, and the data gradient pushes back where the data needs it.

Example
One gradient step with decay

Take w=2\mathbf{w} = 2 (a single weight), η=0.1\eta = 0.1, λ=0.5\lambda = 0.5, and a data gradient ∇L0=1.0\nabla L_0 = 1.0.

  1. Penalty gradient: 2λw=2×0.5×2=2.02\lambda w = 2 \times 0.5 \times 2 = 2.0.
  2. Total gradient: 1.0+2.0=3.01.0 + 2.0 = 3.0.
  3. Update: w←2−0.1×3.0=1.7w \leftarrow 2 - 0.1 \times 3.0 = 1.7.
  4. Check with the decay form: (1−2×0.1×0.5)×2−0.1×1.0=0.9×2−0.1=1.7(1 - 2 \times 0.1 \times 0.5) \times 2 - 0.1 \times 1.0 = 0.9 \times 2 - 0.1 = 1.7. The two forms agree.

The weight moved from 2 to 1.7. Part of that move came from the data and part from the decay.

The Bayesian reading

The penalty has a probabilistic meaning that explains where it comes from. Suppose the targets are yi=w⊤xi+εiy_i = \mathbf{w}^\top \mathbf{x}_i + \varepsilon_i with Gaussian noise εi∼N(0,σ2)\varepsilon_i \sim \mathcal{N}(0, \sigma^2) (see Gaussian (Normal) Distribution), and put a Gaussian prior on the weights, w∼N(0,τ2I)\mathbf{w} \sim \mathcal{N}(\mathbf{0}, \tau^2 I). Maximising the posterior probability of w\mathbf{w} (the maximum a posteriori estimate) means minimising the negative log of likelihood times prior. Multiply that by 2σ22\sigma^2 and the constants drop out, leaving

∥Xw−y∥2+σ2τ2∥w∥2.\|X\mathbf{w} - \mathbf{y}\|^2 + \frac{\sigma^2}{\tau^2} \|\mathbf{w}\|^2.

This is exactly JJ with λ=σ2/τ2\lambda = \sigma^2 / \tau^2. A strong belief that the weights are small (small τ\tau) means a large λ\lambda. A noisy measurement (large σ\sigma) also means a large λ\lambda, because the data deserves less trust.

The effect on the weights

For a single feature with no intercept, the features reduce to one number s=∑ixi2s = \sum_i x_i^2 and the ordinary solution is w^0=(∑ixiyi)/s\hat{w}_0 = (\sum_i x_i y_i)/s. The ridge solution is w^λ=w^0⋅ss+λ\hat{w}_\lambda = \hat{w}_0 \cdot \frac{s}{s + \lambda}. The factor ss+λ\frac{s}{s+\lambda} is always between 0 and 1, so the weight is shrunk by a fixed proportion. The larger λ\lambda is compared to ss, the stronger the shrinkage.

Worked examples

Example
A tiny one-feature fit

Data: x=(1,2)x = (1, 2) and y=(1,3)y = (1, 3). Single weight, no intercept, so X=(12)X = \begin{pmatrix} 1 \\ 2 \end{pmatrix}.

  1. X⊤X=12+22=5X^\top X = 1^2 + 2^2 = 5.
  2. X⊤y=1×1+2×3=7X^\top \mathbf{y} = 1 \times 1 + 2 \times 3 = 7.
  3. Ordinary least squares: w^0=7/5=1.4\hat{w}_0 = 7 / 5 = 1.4.
  4. Ridge with λ=1\lambda = 1: w^1=7/(5+1)=7/6≈1.167\hat{w}_1 = 7 / (5 + 1) = 7/6 \approx 1.167.
  5. The shrinkage factor is 5/6≈0.8335/6 \approx 0.833, so the ridge weight is 0.833×1.4=1.1670.833 \times 1.4 = 1.167, matching step 4.

Interpretation: the penalty pulled the weight from 1.40 to 1.17. The fit to the data is a little worse, and the weight is a little less extreme.

Example
Correlated features

Two features that are almost copies of each other. Data rows: (1,1)(1, 1) with target 2, and (1,1.1)(1, 1.1) with target 2.2. The model is y^=w1x1+w2x2\hat{y} = w_1 x_1 + w_2 x_2.

  1. X⊤X=(22.12.12.21)X^\top X = \begin{pmatrix} 2 & 2.1 \\ 2.1 & 2.21 \end{pmatrix}, with determinant 2×2.21−2.12=0.012 \times 2.21 - 2.1^2 = 0.01. Almost singular.
  2. X⊤y=(4.2, 4.42)X^\top \mathbf{y} = (4.2, \ 4.42).
  3. Ordinary least squares: the inverse is 10.01(2.21−2.1−2.12)\frac{1}{0.01}\begin{pmatrix} 2.21 & -2.1 \\ -2.1 & 2 \end{pmatrix}, which gives w^0=(0,2)\hat{\mathbf{w}}_0 = (0, 2). The fit is exact, but it puts all the weight on x2x_2 and none on x1x_1, which is arbitrary, since x1x_1 and x2x_2 carry almost the same information.
  4. Ridge with λ=0.01\lambda = 0.01: X⊤X+λI=(2.012.12.12.22)X^\top X + \lambda I = \begin{pmatrix} 2.01 & 2.1 \\ 2.1 & 2.22 \end{pmatrix} with determinant 0.05220.0522. The numerator is (0.042, 0.0642)(0.042, \ 0.0642), so w^λ≈(0.80, 1.23)\hat{\mathbf{w}}_\lambda \approx (0.80, \ 1.23).

Interpretation: the ridge weights are shared between the two correlated features and stay moderate, while the unpenalised solution is fragile. Small changes in the data would move (0,2)(0, 2) a lot, but they move (0.80,1.23)(0.80, 1.23) much less.

Example
Shrinkage as the penalty grows

Use the one-feature setting from the tiny example, where s=5s = 5 and w^0=1.4\hat{w}_0 = 1.4. The shrinkage factor is 55+λ\frac{5}{5 + \lambda}.

λ\lambdaShrinkage factorRidge weight
01.001.40
10.831.17
50.500.70
200.200.28

Interpretation: as λ\lambda grows, the weight glides towards 0 but never reaches it for any finite λ\lambda. Choosing λ\lambda is a trade between fitting the training data and keeping the weight small, and the right trade is the one that does best on held-out data.

0510152000.20.40.60.81lambda (penalty strength)weight / ordinary weight
  • shrinkage factor 5/(5 + lambda)
For the tiny example, the weight shrinks smoothly as lambda grows. The markers are the values in the table above.

Tradeoffs and failure modes

Regularization is not free. It adds bias to the estimate in exchange for less variance, and the right amount depends on how much data you have and how noisy it is.

SituationProblemBetter choice
Lots of data, simple modelThe penalty only adds bias and slightly hurts fitSmall λ\lambda, or none
Correlated featuresOrdinary least squares is unstableRidge regression (this lesson)
Want to zero out irrelevant featuresL2 shrinks every weight but rarely makes one exactly zeroAn L1 penalty, or feature selection
Scale of inputs differs wildlyA feature measured in millimetres gets a tiny weight and is penalised less per unitStandardise the inputs before penalising
Penalising the interceptThe intercept is pulled towards zero, which biases the fit towards the originLeave the intercept out of the penalty

Some practical warnings:

  • Not all "weight decay" is the same. In plain gradient descent, adding 2λw2\lambda\mathbf{w} to the gradient is equivalent to L2 regularization. With adaptive optimisers such as Adam, the decay is often applied differently, and the two diverge. Loshchilov and Hutter (2017) showed that decoupling the decay from the adaptive step gives better results, which is why AdamW exists.
  • λ\lambda depends on the scale of the loss. If you average the loss over a batch instead of summing, the same λ\lambda means a much stronger penalty. Always check which convention a library uses.
  • Do not tune λ\lambda on the test set. Pick it on a validation set, then report the test error once.

History

The idea goes back to the Soviet mathematician Andrey Tikhonov, who in the mid-twentieth century used a penalty on the size of a solution to make ill-posed inverse problems stable. The general version is often called Tikhonov regularization. In statistics, Arthur Hoerl and Robert Kennard named and popularised ridge regression in 1970, to deal with the unstable coefficients that appear when predictors are strongly correlated. Their paper is the origin of the name "ridge".

The Bayesian reading, that the penalty is a Gaussian prior, was made explicit as statistics and machine learning converged in the 1990s and 2000s. Books such as Bishop's Pattern Recognition and Machine Learning present it as the standard view.

In neural networks, weight decay was used for years as a simple penalty added to the loss. Its role was clarified when adaptive optimisers became standard: Loshchilov and Hutter's 2017 paper separated the decay from the adaptive gradient step, and that decoupled form is now common in large-model training. It caught on because it is cheap, adds almost no code, and works across model families.

Check yourself

QuestionIn one sentence, what does the L2 penalty do to the weights, and what does it cost the model on the training data?Show answer

It pushes every weight towards zero by charging for the squared size of the weight vector, so large weights need strong evidence from the data to survive. The cost is a slightly worse fit to the training data, traded for better generalisation to new data.

QuestionFor one feature with s=∑ixi2=3s = \sum_i x_i^2 = 3 and ordinary solution w^0=2\hat{w}_0 = 2, what is the ridge weight with λ=1\lambda = 1?Show answer

The ridge weight is w^0⋅ss+λ=2×34=1.5\hat{w}_0 \cdot \frac{s}{s + \lambda} = 2 \times \frac{3}{4} = 1.5. The penalty shrank the weight by a quarter, from 2 to 1.5.

QuestionWhy does adding λI\lambda I fix the problem when two features are almost identical, and why does the fix matter in practice?Show answer

When two features are nearly identical, X⊤XX^\top X is nearly singular, so its inverse is huge and the ordinary weights swing wildly with tiny changes in the data. Adding λI\lambda I with λ>0\lambda \gt 0 moves every eigenvalue up by λ\lambda, so the matrix is safely invertible and the solution is stable. In practice this means the model splits the weight across the correlated features instead of assigning it arbitrarily.

QuestionYou train a network with a weight decay setting, validation loss is high, and training loss is very low. You double the decay. What do you expect, and what would you check next?Show answer

Doubling the decay should strengthen the penalty and shrink the weights further, which often narrows the gap between training and validation loss if the model was overfitting. If validation loss does not improve, or training loss rises too much, the decay was too strong. Next you would check the learning rate, whether the decay is applied in the same way as the optimiser expects (for example decoupled in AdamW), and whether the inputs are standardised so the penalty treats features fairly.

Sources