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.
- data loss only
- data loss + penalty (strength 1)
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, . 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 be the ordinary loss, for example the sum of squared errors of a linear model. The regularised loss is
Here is the weight vector, measures how well the model fits the data, and (the Greek letter lambda) is the regularisation strength. It is a number you choose, usually by checking performance on a validation set. When you get back the original problem. As grows, the penalty dominates and the weights shrink towards zero.
For the linear model with the sum of squared errors, , where the rows of are the training inputs and holds the targets. So
The closed-form solution
Set the gradient of to zero. Expanding as in linear regression, . The gradient is
Setting it to zero and collecting the terms in :
Here is the identity matrix, and the hat marks an estimate from data. This is the same formula as ordinary least squares with added. That addition is the whole trick. Even when is singular (it has no inverse, which happens when some feature is an exact combination of others), adding with 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 is non-negative, and adding shifts each one up by 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 ,
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.
Take (a single weight), , , and a data gradient .
- Penalty gradient: .
- Total gradient: .
- Update: .
- Check with the decay form: . 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 with Gaussian noise (see Gaussian (Normal) Distribution), and put a Gaussian prior on the weights, . Maximising the posterior probability of (the maximum a posteriori estimate) means minimising the negative log of likelihood times prior. Multiply that by and the constants drop out, leaving
This is exactly with . A strong belief that the weights are small (small ) means a large . A noisy measurement (large ) also means a large , because the data deserves less trust.
The effect on the weights
For a single feature with no intercept, the features reduce to one number and the ordinary solution is . The ridge solution is . The factor is always between 0 and 1, so the weight is shrunk by a fixed proportion. The larger is compared to , the stronger the shrinkage.
Worked examples
Data: and . Single weight, no intercept, so .
- .
- .
- Ordinary least squares: .
- Ridge with : .
- The shrinkage factor is , so the ridge weight is , 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.
Two features that are almost copies of each other. Data rows: with target 2, and with target 2.2. The model is .
- , with determinant . Almost singular.
- .
- Ordinary least squares: the inverse is , which gives . The fit is exact, but it puts all the weight on and none on , which is arbitrary, since and carry almost the same information.
- Ridge with : with determinant . The numerator is , so .
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 a lot, but they move much less.
Use the one-feature setting from the tiny example, where and . The shrinkage factor is .
| Shrinkage factor | Ridge weight | |
|---|---|---|
| 0 | 1.00 | 1.40 |
| 1 | 0.83 | 1.17 |
| 5 | 0.50 | 0.70 |
| 20 | 0.20 | 0.28 |
Interpretation: as grows, the weight glides towards 0 but never reaches it for any finite . Choosing 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.
- shrinkage factor 5/(5 + lambda)
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.
| Situation | Problem | Better choice |
|---|---|---|
| Lots of data, simple model | The penalty only adds bias and slightly hurts fit | Small , or none |
| Correlated features | Ordinary least squares is unstable | Ridge regression (this lesson) |
| Want to zero out irrelevant features | L2 shrinks every weight but rarely makes one exactly zero | An L1 penalty, or feature selection |
| Scale of inputs differs wildly | A feature measured in millimetres gets a tiny weight and is penalised less per unit | Standardise the inputs before penalising |
| Penalising the intercept | The intercept is pulled towards zero, which biases the fit towards the origin | Leave the intercept out of the penalty |
Some practical warnings:
- Not all "weight decay" is the same. In plain gradient descent, adding 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.
- depends on the scale of the loss. If you average the loss over a batch instead of summing, the same means a much stronger penalty. Always check which convention a library uses.
- Do not tune 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 and ordinary solution , what is the ridge weight with ?Show answer
The ridge weight is . The penalty shrank the weight by a quarter, from 2 to 1.5.
QuestionWhy does adding 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, is nearly singular, so its inverse is huge and the ordinary weights swing wildly with tiny changes in the data. Adding with moves every eigenvalue up by , 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.