Eight points are scattered around a straight line. A polynomial of degree 7 has eight weights, so it can pass through all eight points exactly, and its training error is . Its error against the true line is , far above the of a penalized fit later in this lesson, and one of its weights is . The weights are huge because the curve has to swing up and down to hit every noisy point.
What if large weights simply cost something? Then the fit would have to earn each big weight with a real improvement in the fit, and the noise could no longer buy a swing. That is regularization: add a price on the size of the weights to the loss. This lesson shows the two standard prices, L2 and L1, what each does, and why one of them switches weights off completely.
The penalized loss
You know how overfitting arises from P3.A3: a model with enough freedom fits the noise as well as the signal. P3.A2 gave the loss for a linear model, the squared error between the predictions and the targets . A penalized loss adds a second term:
The first term asks the model to fit the data. The second, , measures how large the weights are.
The number is the penalty strength, a hyperparameter. With you get plain least squares. As grows, the second term matters more and the weights shrink. The two standard choices of are norms from P1.B4:
- L2, ridge: , the squared length.
- L1, lasso: , the sum of absolute values.
(Ridge regression is also called Tikhonov regularization. “Lasso” stands for least absolute shrinkage and selection operator.)
One weight shows the whole idea. Take the loss , lowest at , and add the L2 penalty . The slope of the sum is , so
For this is , for it is and for it is . The penalty pulls the weight from the data’s favourite value toward , and a larger price pulls harder. (P1.F7 used this same example to show that a penalty and a constraint are two views of one problem, and we return to that below.)
L2 (ridge): shrink everything smoothly
For the squared error with an L2 penalty, , setting the gradient to zero (P1.C11) gives a linear system:
This is the normal equations of P3.A2 with added. In code you solve it with np.linalg.solve and do not form the inverse (P1.B9). The textbook form of the answer is .
Why it can always be solved. Without the penalty, has no inverse when columns of are copies of each other (P1.B7, P1.B11). Take the matrix of P1.B9, with column 2 equal to twice column 1:
Add : the matrix becomes , with determinant , so the system has exactly one solution. The reason is in the eigenvalues (P1.B12). The matrix has eigenvalues and . Adding adds to every eigenvalue, giving and , and a matrix whose eigenvalues are all non-zero is invertible. This holds in general: for any vector ,
so every eigenvalue of the new matrix is at least .
The answer for that example, with , is for . Plain least squares has infinitely many solutions here, and the smallest-length one is . The ridge solution is a slightly shrunk copy of it ( of its size), and it gives column 2 twice the weight of column 1, , as the smallest-length solution does.
The condition number falls too. The ratio of the largest to the smallest eigenvalue measures how wobbly a solve is (P1.B13). It was infinite here and is now. P1.F2 gave a gradient-descent version: for the P0.2 loss, with the penalty added, the Hessian eigenvalues and each rise by . With they are and , and with they are and . The ratio falls from to and then to , so gradient descent (P1.F3) has an easier valley. (That example penalized the bias to keep the numbers simple; see below for why real code does not. With this lesson’s penalty the Hessian would rise by ; P1.F2’s form is used so that the rise is exactly .)
What the shrinkage does. In the SVD of (P1.B13), ridge scales the contribution of each direction , compared with the pseudo-inverse solution, by , where is its singular value. Directions with are barely touched, and directions with , the ones where the data barely pin the weights down, are squashed. The above is . Ridge shrinks every weight smoothly, and generally no weight becomes exactly : with one weight, is only if .
The polynomial, regularized
Back to the eight points. The data below are made up (the noise values are typed in) around the true line , and the model has the features . Because we made the data up, we can measure the error against the true line.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
On the machine used for this lesson the table reads (the last column is the largest for , not counting the intercept):
lambda train test max|w_j|
0 0.000 0.897 93.45
0.0001 0.036 0.163 27.84
0.01 0.078 0.023 2.22
0.1 0.104 0.010 1.60
1 0.208 0.127 1.04
100 1.388 1.200 0.06
The training error only rises as grows, because the penalty stops the fit from chasing the points. The error against the true line falls first, to at , and then rises again once the weights are squeezed so hard that even the true trend is lost (: a nearly flat curve). The training error would have chosen , a poor fit to the truth. So cannot be chosen by training error; more on that below.
Weight decay, and where the Bayesian view fits
Gradient descent (P1.F3) on a loss plus (half of the ridge form above, so this is the same as P1.D11’s weight-decay ) has a penalty gradient , so one step is
The weights are first multiplied by , a little less than , and then take the usual step: they decay toward unless the data pull them back. This is weight decay. For plain gradient descent, weight decay and an L2 penalty are the same update. With adaptive optimizers such as Adam they are not the same, which is why “decoupled” weight decay (AdamW) exists; P4.13 and P4.17 explain this for neural networks.
P1.D11 showed where the penalty comes from. If the noise is Gaussian with standard deviation and each weight has a Gaussian prior with standard deviation , the most probable weights (the MAP estimate) minimize the ridge loss with . A narrow prior (small ) means a large , a strong belief that the weights are small.
L1 (lasso): switch weights off
Replace the squared length with the sum of absolute values. The L1 penalty has a corner at , and that corner changes everything.
One weight first. To keep the numbers simple, this section writes the lasso loss with a in front of the squared error:
This changes the meaning of by a factor of from P1.D11, whose lasso loss has no and writes the penalty strength ; here . For one weight, with data’s favourite value , minimize . If the slope is , which is zero at , valid when . If it is , valid when . In between, nothing moves the weight off : leaving to the right changes the cost at rate , and to the left at rate , and both are at least when . Together:
This is soft-thresholding. For and it gives : it subtracts a fixed amount . For and it gives exactly , because the data’s pull () is weaker than the price of a non-zero weight (). For it reaches once . Compare ridge on the same weight: takes a fixed fraction, so it is for and , and it is only when . The widget of P1.D11 draws this one-weight picture.
Several weights. If the columns of are orthonormal (), the weights separate and each one is soft-thresholded: , with the plain least-squares weight (for ridge in the same setting, ). In general there is no formula for the lasso solution, because which weights are exactly is not known in advance, but it is still a convex problem (P1.F2), so a solver finds the global minimum. A simple one is coordinate descent: update one weight at a time with a soft-threshold of the feature’s inner product with the current residual, divided by the feature’s squared length, and sweep over the weights. The code below runs a fixed number of sweeps (), enough to converge here.
A weight is exactly at the lasso solution when the data’s pull on it is no larger than : for a weight at , the slope of the data term, , must be at most . This also tells you when the whole solution is : when , where is column of .
A regularization path
The regularization path is the list of weights as grows. The data here are made up: examples, features standardized to mean and standard deviation , and (with the features numbered from ). Only features and matter, and feature is partly a copy of feature (correlation ).
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The output on the machine used for this lesson:
lambda_max = 133.0
ols 3.44 -0.33 -1.94 0.01 0.07
ridge 5 2.80 0.13 -1.68 -0.01 0.07
lasso 5 3.12 0.00 -1.77 0.00 0.00
ridge 20 1.93 0.53 -1.25 -0.05 0.07
lasso 20 2.76 0.00 -1.41 0.00 0.00
ridge 50 1.28 0.57 -0.84 -0.07 0.06
lasso 50 2.04 0.00 -0.69 0.00 0.00
ridge100 0.85 0.47 -0.55 -0.07 0.05
lasso100 0.82 0.00 0.00 0.00 0.00
ridge200 0.51 0.32 -0.33 -0.05 0.04
lasso200 0.00 0.00 0.00 0.00 0.00
Read it row by row. Ridge switches nothing off: all five weights are non-zero even at , and they all shrink together. Lasso is zero for features 2, 4 and 5 from on, keeps the two true features longest (feature 3 until is between and , feature 1 until reaches ), and is all zeros from , the lambda_max printed on the first line, . So lasso does feature selection: it picks a short list of features. It also shrinks the weights it keeps: at the weight is well below the plain value , which is the price of the penalty.
Correlated features. Feature 2 is partly a copy of feature 1. Lasso dropped it, but when features are strongly correlated, lasso can keep one of a group and drop the others, and which one it keeps can change with a small change in the data. Ridge instead spreads the credit across the group (feature 2 is not in the true model, so here the shared credit is wrong; ridge cannot tell the two apart). The elastic net mixes both penalties, , to get sparsity and group-sharing together. In the scikit-learn run below it keeps feature 2 with a small weight.
scikit-learn, and its penalty scaling
scikit-learn writes the same models, but it does not scale the penalty the same way for each. The objectives from the scikit-learn documentation (version 1.8) are:
Ridge(alpha): . This is this lesson’s ridge loss with .Lasso(alpha): . It divides the squared error by , so multiplying by gives this lesson’s lasso loss with .ElasticNet(alpha, l1_ratio): with =l1_ratio.
This is the same data as the cell above, with and , so the lasso uses alpha=20/40. The ridge and lasso rows match the rows of the cell (these blocks are a local run, not run in your browser, because scikit-learn is not available there).
from sklearn.linear_model import Ridge, Lasso, ElasticNet
ridge = Ridge(alpha=20, fit_intercept=False)
ridge.fit(X, y)
lasso = Lasso(alpha=20 / 40, fit_intercept=False) # alpha = lambda / N
lasso.fit(X, y)
enet = ElasticNet(alpha=0.5, l1_ratio=0.5, fit_intercept=False)
enet.fit(X, y)
ridge [ 1.93 0.53 -1.25 -0.05 0.07]
lasso [ 2.76 0. -1.41 0. 0. ]
enet [ 2.28 0.25 -1.31 0. 0. ]
Why corners give zeros: the geometry
Here is the picture that explains the lasso. Instead of adding a penalty, limit the size of the weights: minimize the loss subject to (L2) or (L1). With two weights the allowed set is a disc for L2, and a diamond with corners on the axes for L1 (P1.B4). The loss, for a linear model with squared error, has elliptical contours (P1.C5) around the unconstrained best weights . You are looking for the lowest contour that still touches the allowed set (P1.F7).
The two views are one problem. For a convex loss, each penalty strength gives the same answer as some size , and a larger matches a smaller . P1.F7’s example is the one-weight loss , whose answer for is . It is also the answer to “minimize with ”, and the constraint’s multiplier is . The widget shows this matching strength for each shape.
Things to try:
- The defaults (stretched ovals, , ). The L1 point is the corner : the weight is exactly and the ring appears. The L2 point is , with both weights non-zero. The losses are (L1) and (L2), and the matching penalties are (L1, in ) and (L2, in ), for the loss .
- Near the axis with the round contours (, ). L1 lands at and L2 at .
- On the diagonal with the round contours (, ). L1 lands at , on a side of the diamond and not at a corner. Both weights are non-zero. A corner is more likely to be touched, but nothing forces it.
- Slide up with the round contours at . The disc has radius and , and the diamond’s corners are at distance and . At the unconstrained best is inside both and the widget says the constraint does nothing. A weak penalty is a big .
- Slide down with the same settings. At L1 is and L2 is . A strong penalty is a small .
Why a corner wins. The loss contours are smooth. On a smooth boundary such as the circle, each point has exactly one direction of “straight out”, and a contour touches there only if its own tilt matches. At a corner of the diamond, a whole range of tilts fits, so many different ovals touch the diamond at the same corner. The loss centres that lead to a given corner fill a whole wedge-shaped region, so the corner is hit for a range of , while each smooth point of the circle is hit by a thin curve of them. The corners stick out the most, so an expanding oval tends to hit one first. A corner on an axis is a point where one weight is . This is the same fact as soft-thresholding: a weight at stays there while the data’s pull on it is at most .
In more dimensions the diamond becomes the cross-polytope (an octahedron in 3-D). With weights it has corners, all on the axes, where all but one weight is . Its edges lie in coordinate planes, where some weights are too. The sparse solutions sit on these corners and edges.
The bias term, feature scale and choosing λ
Leave the bias out. The bias (the intercept) only shifts the predictions up or down. It does not make the function wiggle, and shrinking it toward would make the model depend on where the origin of is. A tiny example: a model with no features but a bias, fitted to by minimizing , gives . With this is , half the mean , a loss with no benefit. So code usually does not penalize the bias (the polynomial cell above set the first entry of P to , and scikit-learn’s fit_intercept=True handles it the same way).
Put the features on a common scale. The penalty adds up the sizes of the weights (the same holds for lasso), but a weight’s size depends on the feature’s units: a feature measured in millimetres has a weight times smaller than the same feature in metres, so the penalty hardly touches it. For one centred feature, ridge keeps the fraction of the plain weight. With , a feature with standard deviation and keeps of its weight, and the same feature multiplied by keeps . So standardize first (P3.A11), and fit the scaler on the training data only.
Choose λ on held-out data. Training error is lowest at (the table above), so must be chosen on a validation set or by cross-validation (P3.A4): try values on a log scale, such as , because the useful range spans orders of magnitude, and keep the best. A test set is touched once, at the end. scikit-learn has RidgeCV and LassoCV for this.
Bias and variance. P3.A5 explains the trade-off: a flexible model has low bias and high variance. A larger moves a fit along that trade-off, toward more bias and less variance. The cell below refits the polynomial on fresh noisy copies of the same problem, with noise standard deviation that we chose.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
lambda bias^2 variance total
0 0.0001 0.2671 0.2672
0.001 0.0001 0.0905 0.0905
0.1 0.0040 0.0462 0.0502
1 0.0994 0.0290 0.1284
10 0.5660 0.0176 0.5836
From to the variance falls from to while the squared bias rises by only . Beyond that the bias grows faster than the variance falls, and the total error has its minimum near in this made-up setup.
Intuition
Picture a rubber band tying each weight to . The data pull each weight toward its favourite value, and the band pulls it back. A stiff band (large ) wins over weak evidence. L2 is a band that gets stiffer the further it stretches, so it always gives a little and no weight is pinned to . L1 is a band with a constant pull of strength however small the weight, so a weight whose evidence is weaker than cannot escape : that is the corner.
Math
Ridge: , solution , with for Gaussian noise and prior . In the SVD, each direction is scaled by .
Lasso: . One weight or orthonormal columns: . Coordinate descent: with the residual with feature left out. All weights are iff . Laplace prior with scale gives in this form.
Elastic net: ; for orthonormal columns .
Constraint form: minimize subject to ; for convex and , each has a matching . Weight decay: for the penalty .
Code
import numpy as np
def ridge(X, y, lam):
return np.linalg.solve(X.T @ X + lam * np.eye(X.shape[1]), X.T @ y) # solve, do not invert
def soft(z, lam):
return np.sign(z) * np.maximum(np.abs(z) - lam, 0.0)
print(soft(np.array([3.0, 0.8, -2.0]), 1.0)) # [ 2. 0. -1.]For real work use sklearn.linear_model.Ridge, Lasso, ElasticNet (and the CV versions) after a StandardScaler, remembering the alpha scalings above. Neural-network libraries have a weight_decay argument in their optimizers (P4.13, P4.17).
Go deeper Why ridge is a smooth shrink and a truncated SVD is a cliff
The pseudo-inverse (P1.B13) keeps a direction in full or drops it, depending on whether its singular value is above a cutoff. Ridge multiplies direction by , which falls smoothly from near to near as drops below . For the example above, and gives . It is a soft version of the same idea: trust the directions the data pin down and distrust the ones it does not.
Go deeper Other ways to regularize, and where they appear
A penalty is one form of regularization. Others limit what the model can fit without touching the loss: stopping training early, dropout, data augmentation and smaller models. P4.17 covers the neural-network versions and P4.18 augmentation. The penalties of this lesson also apply beyond linear regression: add to the loss of logistic regression (P3.A7) or of a neural network. There the problem has no closed form and is solved by gradient descent, where the penalty becomes the weight decay above.
Try it
The three cells above are the practical part. In the first, change lam and watch the test error against the true line fall, and rise again. In the path cell, add 130 and 133 to the list of lam values: lasso is all zeros at , but at the weight of feature 1 is still . In the third, compare the variance column with the bias column. In the widget, find a setting where L1 does not land on an axis, and one where L2 does.
Quiz
Check your understanding
Which penalty can make a fitted weight exactly , and why?
The L1 penalty has a constant slope on each side of , so a weight stays at while the data’s pull on it is no larger than . The L2 penalty is a smooth bowl, and its slope vanishes at , so any small pull moves the weight a little and the solution is , which is only when . A large L2 strength shrinks all weights toward without reaching it, and lasso does remove features without any hand deletion.
Why is invertible for every , even when two columns of are copies?
For the matrix of P1.B9 the eigenvalues go from and to and , and a matrix with no zero eigenvalue is invertible. Symmetry alone is not enough: is symmetric and has no inverse. A sum of an invertible matrix and a singular one can be singular (for example plus the singular matrix is , which has no inverse), so that rule is false, and the columns of are not changed at all.
The plain least-squares weights for an orthonormal design are . What does lasso with and give?
Soft-thresholding subtracts from the size: becomes , and is smaller than so it becomes exactly . The pair is what ridge gives, for each weight. The pair subtracts without stopping at , flipping the sign of the small weight. The unchanged pair would be the case .
A feature is converted from metres to millimetres (every value is times larger). With the same in ridge regression, what happens to its penalty?
The model needs a times smaller weight to make the same prediction, and the penalty on a tiny weight is tiny, so the fit is hardly shrunk (for and the kept fraction goes from to ). The result does depend on units, which is why features are standardized first (P3.A11). Larger feature values mean a smaller weight, not a larger one, and the fit does not fail.
You have examples and want the lasso loss with from scikit-learn’s
Lasso. Whichalphado you pass?scikit-learn minimizes . Multiplying by gives , so and . Passing would be a penalty times too strong. The values and come from multiplying where one should divide, or from dividing by the extra that is already cancelled by the .
Exercises
- Minimize for . What is , and what fraction of is it?
Show answer
, a quarter of the unpenalized weight . In general . - Soft-threshold with .
Show answer
: subtract from the size of and , and is below so it becomes . - Weight decay: with , and a loss gradient of , what is a weight of after one step and after ten steps?
Show answer
Each step multiplies by . After one step , after ten steps . - A lasso problem has . For which are all weights exactly ?
Show answer
For (in the form of this lesson). Below the solution is not all zeros. - Five targets are fitted by a constant with the penalty on the bias. Find for and say what is wrong with it.
Show answer
, half the mean , so every prediction is off by about with no benefit. The bias is left out of the penalty. - Show that the one-weight ridge problem with has the same answer as minimizing under , and find the constraint’s multiplier.
Show answer
The penalty answer is . The unconstrained best is outside , so the constraint is active at , with multiplier (the recipe of P1.F7).
Next: P3.A7 turns the same penalties to classification with logistic regression, P3.A11 covers feature scaling and data leakage, and P4.17 returns to weight decay inside neural networks.