Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 3: Classical Machine LearningCore Concepts

Regularization: L1 and L2

P3.A640 min●●○ IntermediateReviewed Dec 2, 2026

Why this matters for machine learning

A model with many features or a flexible curve can fit the noise in its training data. A penalty on the size of the weights makes big weights expensive, so the model keeps only the weights the data really supports.

Before this: Linear regression, Polynomial regression, underfitting and overfitting, Train, validation and test sets, The bias–variance trade-off, Norms and distances

After this lesson you can

  • Write a penalized loss, compute the ridge solution with a linear solve, and explain why X⊤X+λI\mathbf{X}^\top\mathbf{X}+\lambda\mathbf{I} is invertible for every λ>0\lambda>0
  • Explain, with the one-weight picture and the corners of the diamond, why L1 gives exact zeros and L2 does not
  • Read a regularization path, and say why the bias term is left out of the penalty and why features need a common scale
  • Match the penalty form to the constraint form, and convert the penalty strength between this lesson’s convention and scikit-learn’s

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 00. Its error against the true line is 0.8970.897, far above the 0.0100.010 of a penalized fit later in this lesson, and one of its weights is 93.4593.45. 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 Xw\mathbf{X}\mathbf{w} and the targets y\mathbf{y}. A penalized loss adds a second term:

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

The first term asks the model to fit the data. The second, R(w)R(\mathbf{w}), measures how large the weights are.

The number λ≥0\lambda\ge0 is the penalty strength, a hyperparameter. With λ=0\lambda=0 you get plain least squares. As λ\lambda grows, the second term matters more and the weights shrink. The two standard choices of R(w)R(\mathbf{w}) are norms from P1.B4:

  • L2, ridge: R=∥w∥22=∑jwj2R=\lVert\mathbf{w}\rVert_2^2=\sum_j w_j^2, the squared length.
  • L1, lasso: R=∥w∥1=∑j∣wj∣R=\lVert\mathbf{w}\rVert_1=\sum_j|w_j|, 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 (w−3)2(w-3)^2, lowest at w=3w=3, and add the L2 penalty αw2\alpha w^2. The slope of the sum is 2(w−3)+2αw=02(w-3)+2\alpha w=0, so

w=31+α.w=\frac{3}{1+\alpha}.

For α=0.5\alpha=0.5 this is 22, for α=1\alpha=1 it is 1.51.5 and for α=3\alpha=3 it is 0.750.75. The penalty pulls the weight from the data’s favourite value 33 toward 00, 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, J(w)=∥y−Xw∥2+λ∥w∥2J(\mathbf{w})=\lVert\mathbf{y}-\mathbf{X}\mathbf{w}\rVert^2+\lambda\lVert\mathbf{w}\rVert^2, setting the gradient to zero (P1.C11) gives a linear system:

(X⊤X+λI) w=X⊤y.(\mathbf{X}^\top\mathbf{X}+\lambda\mathbf{I})\,\mathbf{w}=\mathbf{X}^\top\mathbf{y}.

This is the normal equations of P3.A2 with λI\lambda\mathbf{I} 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 w^=(X⊤X+λI)−1X⊤y\hat{\mathbf{w}}=(\mathbf{X}^\top\mathbf{X}+\lambda\mathbf{I})^{-1}\mathbf{X}^\top\mathbf{y}.

Why it can always be solved. Without the penalty, X⊤X\mathbf{X}^\top\mathbf{X} has no inverse when columns of X\mathbf{X} are copies of each other (P1.B7, P1.B11). Take the matrix of P1.B9, with column 2 equal to twice column 1:

X=(122436),\mathbf{X}=\begin{pmatrix}1&2\\2&4\\3&6\end{pmatrix}, X⊤X=(14282856),det⁡=0.\mathbf{X}^\top\mathbf{X}=\begin{pmatrix}14&28\\28&56\end{pmatrix},\qquad\det=0 .

Add λ=1\lambda=1: the matrix becomes (15282857)\begin{pmatrix}15&28\\28&57\end{pmatrix}, with determinant 15⋅57−28⋅28=71≠015\cdot57-28\cdot28=71\ne0, so the system has exactly one solution. The reason is in the eigenvalues (P1.B12). The matrix X⊤X\mathbf{X}^\top\mathbf{X} has eigenvalues 00 and 7070. Adding λI\lambda\mathbf{I} adds λ\lambda to every eigenvalue, giving 11 and 7171, and a matrix whose eigenvalues are all non-zero is invertible. This holds in general: for any vector v≠0\mathbf{v}\ne\mathbf{0},

v⊤(X⊤X+λI)v=∥Xv∥2+λ∥v∥2≥λ∥v∥2>0,\begin{aligned} \mathbf{v}^\top(\mathbf{X}^\top\mathbf{X}+\lambda\mathbf{I})\mathbf{v}&=\lVert\mathbf{X}\mathbf{v}\rVert^2+\lambda\lVert\mathbf{v}\rVert^2\\ &\ge\lambda\lVert\mathbf{v}\rVert^2>0, \end{aligned}

so every eigenvalue of the new matrix is at least λ>0\lambda>0.

The answer for that example, with y=(1,2,3)\mathbf{y}=(1,2,3), is w=(0.1972,0.3944)\mathbf{w}=(0.1972,0.3944) for λ=1\lambda=1. Plain least squares has infinitely many solutions here, and the smallest-length one is (0.2,0.4)(0.2,0.4). The ridge solution is a slightly shrunk copy of it (70/71=0.98670/71=0.986 of its size), and it gives column 2 twice the weight of column 1, w2=2w1w_2=2w_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 71/1=7171/1=71 now. P1.F2 gave a gradient-descent version: for the P0.2 loss, with the penalty λ2(w2+b2)\tfrac{\lambda}{2}(w^2+b^2) added, the Hessian eigenvalues 11.0911.09 and 0.240.24 each rise by λ\lambda. With λ=1\lambda=1 they are 12.0912.09 and 1.241.24, and with λ=2\lambda=2 they are 13.0913.09 and 2.242.24. The ratio falls from 4646 to 9.89.8 and then to 5.85.8, so gradient descent (P1.F3) has an easier valley. (That example penalized the bias bb to keep the numbers simple; see below for why real code does not. With this lesson’s penalty λ∥w∥2\lambda\lVert\mathbf{w}\rVert^2 the Hessian would rise by 2λ2\lambda; P1.F2’s λ2\tfrac\lambda2 form is used so that the rise is exactly λ\lambda.)

What the shrinkage does. In the SVD of X\mathbf{X} (P1.B13), ridge scales the contribution of each direction ii, compared with the pseudo-inverse solution, by σi2/(σi2+λ)\sigma_i^2/(\sigma_i^2+\lambda), where σi\sigma_i is its singular value. Directions with σi2≫λ\sigma_i^2\gg\lambda are barely touched, and directions with σi2≪λ\sigma_i^2\ll\lambda, the ones where the data barely pin the weights down, are squashed. The 0.9860.986 above is 70/(70+1)70/(70+1). Ridge shrinks every weight smoothly, and generally no weight becomes exactly 00: with one weight, w=z/(1+λ)w=z/(1+\lambda) is 00 only if z=0z=0.

The polynomial, regularized

Back to the eight points. The data below are made up (the noise values are typed in) around the true line y=1+2xy=1+2x, and the model has the features 1,x,x2,…,x71,x,x^2,\dots,x^7. Because we made the data up, we can measure the error against the true line.

Try it: ridge on the degree-7 polynomial

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 ∣wj∣|w_j| for j≥1j\ge1, 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 λ\lambda grows, because the penalty stops the fit from chasing the points. The error against the true line falls first, to 0.0100.010 at λ=0.1\lambda=0.1, and then rises again once the weights are squeezed so hard that even the true trend is lost (λ=100\lambda=100: a nearly flat curve). The training error would have chosen λ=0\lambda=0, a poor fit to the truth. So λ\lambda 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 LL plus λ2∥w∥2\tfrac{\lambda}{2}\lVert\mathbf{w}\rVert^2 (half of the ridge form above, so this λ\lambda is the same as P1.D11’s weight-decay λ\lambda) has a penalty gradient λw\lambda\mathbf{w}, so one step is

w←w−η(∇L+λw)=(1−ηλ) w−η∇L.\begin{aligned} \mathbf{w}&\leftarrow\mathbf{w}-\eta(\nabla L+\lambda\mathbf{w})\\ &=(1-\eta\lambda)\,\mathbf{w}-\eta\nabla L . \end{aligned}

The weights are first multiplied by 1−ηλ1-\eta\lambda, a little less than 11, and then take the usual step: they decay toward 00 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 σ\sigma and each weight has a Gaussian prior with standard deviation τ\tau, the most probable weights (the MAP estimate) minimize the ridge loss with λ=σ2/τ2\lambda=\sigma^2/\tau^2. A narrow prior (small τ\tau) means a large λ\lambda, 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 00, and that corner changes everything.

One weight first. To keep the numbers simple, this section writes the lasso loss with a 12\tfrac12 in front of the squared error:

J(w)=12∥y−Xw∥2+λ∥w∥1.J(\mathbf{w})=\tfrac12\lVert\mathbf{y}-\mathbf{X}\mathbf{w}\rVert^2+\lambda\lVert\mathbf{w}\rVert_1 .

This changes the meaning of λ\lambda by a factor of 22 from P1.D11, whose lasso loss has no 12\tfrac12 and writes the penalty strength λ1\lambda_1; here λ=λ1/2\lambda=\lambda_1/2. For one weight, with data’s favourite value zz, minimize 12(w−z)2+λ∣w∣\tfrac12(w-z)^2+\lambda|w|. If w>0w>0 the slope is w−z+λw-z+\lambda, which is zero at w=z−λw=z-\lambda, valid when z>λz>\lambda. If w<0w<0 it is w=z+λw=z+\lambda, valid when z<−λz<-\lambda. In between, nothing moves the weight off 00: leaving 00 to the right changes the cost at rate λ−z\lambda-z, and to the left at rate λ+z\lambda+z, and both are at least 00 when ∣z∣≤λ|z|\le\lambda. Together:

w∗=sign(z) max⁡(∣z∣−λ,  0).w^*=\mathrm{sign}(z)\,\max\bigl(|z|-\lambda,\;0\bigr).

This is soft-thresholding. For z=3z=3 and λ=1\lambda=1 it gives 22: it subtracts a fixed amount λ\lambda. For z=0.8z=0.8 and λ=1\lambda=1 it gives exactly 00, because the data’s pull (0.80.8) is weaker than the price of a non-zero weight (11). For z=3z=3 it reaches 00 once λ≥3\lambda\ge3. Compare ridge on the same weight: z/(1+λ)z/(1+\lambda) takes a fixed fraction, so it is 1.51.5 for z=3z=3 and λ=1\lambda=1, and it is 00 only when z=0z=0. The widget of P1.D11 draws this one-weight picture.

Several weights. If the columns of X\mathbf{X} are orthonormal (X⊤X=I\mathbf{X}^\top\mathbf{X}=\mathbf{I}), the weights separate and each one is soft-thresholded: wj=sign(zj)max⁡(∣zj∣−λ,0)w_j=\mathrm{sign}(z_j)\max(|z_j|-\lambda,0), with zjz_j the plain least-squares weight (for ridge in the same setting, zj/(1+λ)z_j/(1+\lambda)). In general there is no formula for the lasso solution, because which weights are exactly 00 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 (500500), enough to converge here.

A weight is exactly 00 at the lasso solution when the data’s pull on it is no larger than λ\lambda: for a weight at 00, the slope of the data term, ∣∂L/∂wj∣|\partial L/\partial w_j|, must be at most λ\lambda. This also tells you when the whole solution is 0\mathbf{0}: when λ≥max⁡j∣xj⊤y∣\lambda\ge\max_j|\mathbf{x}_j^\top\mathbf{y}|, where xj\mathbf{x}_j is column jj of X\mathbf{X}.

A regularization path

The regularization path is the list of weights as λ\lambda grows. The data here are made up: N=40N=40 examples, 55 features standardized to mean 00 and standard deviation 11, and y=3x1−2x3+noisey=3x_1-2x_3+\text{noise} (with the features numbered from 11). Only features 11 and 33 matter, and feature 22 is partly a copy of feature 11 (correlation 0.660.66).

Try it: ridge and lasso paths

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 λ=200\lambda=200, and they all shrink together. Lasso is zero for features 2, 4 and 5 from λ=5\lambda=5 on, keeps the two true features longest (feature 3 until λ\lambda is between 5050 and 100100, feature 1 until λ\lambda reaches 133133), and is all zeros from λ=133\lambda=133, the lambda_max printed on the first line, max⁡j∣xj⊤y∣\max_j|\mathbf{x}_j^\top\mathbf{y}|. So lasso does feature selection: it picks a short list of features. It also shrinks the weights it keeps: at λ=50\lambda=50 the weight 2.042.04 is well below the plain value 3.443.44, 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, 12∥y−Xw∥2+λ1∥w∥1+λ22∥w∥2\tfrac12\lVert\mathbf{y}-\mathbf{X}\mathbf{w}\rVert^2+\lambda_1\lVert\mathbf{w}\rVert_1+\tfrac{\lambda_2}{2}\lVert\mathbf{w}\rVert^2, 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): ∥y−Xw∥2+α∥w∥2\lVert\mathbf{y}-\mathbf{X}\mathbf{w}\rVert^2+\alpha\lVert\mathbf{w}\rVert^2. This is this lesson’s ridge loss with α=λ\alpha=\lambda.
  • Lasso(alpha): 12N∥y−Xw∥2+α∥w∥1\tfrac{1}{2N}\lVert\mathbf{y}-\mathbf{X}\mathbf{w}\rVert^2+\alpha\lVert\mathbf{w}\rVert_1. It divides the squared error by 2N2N, so multiplying by NN gives this lesson’s lasso loss with λ=Nα\lambda=N\alpha.
  • ElasticNet(alpha, l1_ratio): 12N∥y−Xw∥2+αρ∥w∥1+α(1−ρ)2∥w∥2\tfrac{1}{2N}\lVert\mathbf{y}-\mathbf{X}\mathbf{w}\rVert^2+\alpha\rho\lVert\mathbf{w}\rVert_1+\tfrac{\alpha(1-\rho)}{2}\lVert\mathbf{w}\rVert^2 with ρ\rho = l1_ratio.

This is the same data as the cell above, with λ=20\lambda=20 and N=40N=40, so the lasso uses alpha=20/40. The ridge and lasso rows match the λ=20\lambda=20 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 ∥w∥2≤t\lVert\mathbf{w}\rVert_2\le t (L2) or ∥w∥1≤t\lVert\mathbf{w}\rVert_1\le t (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 w∗\mathbf{w}^*. 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 λ>0\lambda>0 gives the same answer as some size tt, and a larger λ\lambda matches a smaller tt. P1.F7’s example is the one-weight loss (w−3)2+αw2(w-3)^2+\alpha w^2, whose answer for α=1\alpha=1 is w=1.5w=1.5. It is also the answer to “minimize (w−3)2(w-3)^2 with w2≤1.52w^2\le1.5^2”, and the constraint’s multiplier is μ=1=α\mu=1=\alpha. The widget shows this matching strength for each shape.

Loss contours against the L2 disc and the L1 diamond

Loss L(w) = ½ (w − w*)ᵀ A (w − w*): curvatures 4 and 0.6, turned by 20°.

-3-3-2-2-1-10112233w₁w₂
  • unconstrained minimum w* (drag me)
  • L2 disc and its best point
  • L1 diamond and its best point
unconstrained best w* = (2, 1.5)
L2 disc: w = (1.354, 0.647), loss 1.719, matching penalty μ = 2.41
L1 diamond: w = (1.5, 0), loss 2.392, matching penalty λ = 3.44

The L1 solution is on the w₁ axis: w₂ is exactly 0. The loss contour touches the diamond at a corner.

The L2 solution is a smooth touching point: both weights are non-zero.

Grey ovals are contours of the loss (lower toward the centre dot w*). The dashed ovals pass through each best point: they touch the shape there. The disc has radius t and the diamond has corners at distance t on the axes. The matching penalty is the strength μ (for L2, in L + μ/2·‖w‖²) or λ (for L1, in L + λ‖w‖₁) that gives the same point as the constraint, with L(w) = ½(w − w*)ᵀA(w − w*).

The weight plane of a model with two weights. Grey ovals are contours of the loss, lowest at the circled dot w* (drag it, or use its sliders or arrow keys). The blue disc is the L2 constraint and the pink diamond the L1 constraint, both of size t. The blue dot is the best point inside the disc and the pink diamond marker the best point inside the diamond, each computed exactly; dashed ovals through them show the contour touching the shape. A green ring marks an L1 solution that sits on an axis, where one weight is exactly 0. Choose the contour shape, move w* and change t.

Things to try:

  • The defaults (stretched ovals, w∗=(2,1.5)\mathbf{w}^*=(2,1.5), t=1.5t=1.5). The L1 point is the corner (1.5,0)(1.5,0): the weight w2w_2 is exactly 00 and the ring appears. The L2 point is (1.354,0.647)(1.354,0.647), with both weights non-zero. The losses are 2.3922.392 (L1) and 1.7191.719 (L2), and the matching penalties are λ=3.44\lambda=3.44 (L1, in L+λ∥w∥1L+\lambda\lVert\mathbf{w}\rVert_1) and μ=2.41\mu=2.41 (L2, in L+μ2∥w∥2L+\tfrac\mu2\lVert\mathbf{w}\rVert^2), for the loss L=12(w−w∗)⊤A(w−w∗)L=\tfrac12(\mathbf{w}-\mathbf{w}^*)^\top A(\mathbf{w}-\mathbf{w}^*).
  • Near the w1w_1 axis with the round contours (w∗=(2.2,0.5)\mathbf{w}^*=(2.2,0.5), t=1.5t=1.5). L1 lands at (1.5,0)(1.5,0) and L2 at (1.463,0.332)(1.463,0.332).
  • On the diagonal with the round contours (w∗=(1.8,1.8)\mathbf{w}^*=(1.8,1.8), t=1.5t=1.5). L1 lands at (0.75,0.75)(0.75,0.75), 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 tt up with the round contours at w∗=(2.2,0.5)\mathbf{w}^*=(2.2,0.5). The disc has radius tt and ∥w∗∥2=2.26\lVert\mathbf{w}^*\rVert_2=2.26, and the diamond’s corners are at distance tt and ∥w∗∥1=2.7\lVert\mathbf{w}^*\rVert_1=2.7. At t=3t=3 the unconstrained best is inside both and the widget says the constraint does nothing. A weak penalty is a big tt.
  • Slide tt down with the same settings. At t=0.5t=0.5 L1 is (0.5,0)(0.5,0) and L2 is (0.488,0.111)(0.488,0.111). A strong penalty is a small tt.

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 w∗\mathbf{w}^* that lead to a given corner fill a whole wedge-shaped region, so the corner is hit for a range of w∗\mathbf{w}^*, 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 00. This is the same fact as soft-thresholding: a weight at 00 stays there while the data’s pull on it is at most λ\lambda.

In more dimensions the diamond becomes the cross-polytope (an octahedron in 3-D). With dd weights it has 2d2d corners, all on the axes, where all but one weight is 00. Its edges lie in coordinate planes, where some weights are 00 too. The sparse solutions sit on these corners and edges.

The bias term, feature scale and choosing λ

Leave the bias out. The bias bb (the intercept) only shifts the predictions up or down. It does not make the function wiggle, and shrinking it toward 00 would make the model depend on where the origin of yy is. A tiny example: a model with no features but a bias, fitted to y=(9,10,11,10,10)y=(9,10,11,10,10) by minimizing ∑(yi−b)2+λb2\sum(y_i-b)^2+\lambda b^2, gives b=∑yi/(N+λ)b=\sum y_i/(N+\lambda). With λ=5\lambda=5 this is 50/10=550/10=5, half the mean 1010, a loss with no benefit. So code usually does not penalize the bias (the polynomial cell above set the first entry of P to 00, 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 10001000 times smaller than the same feature in metres, so the penalty hardly touches it. For one centred feature, ridge keeps the fraction ∑x2/(∑x2+λ)\sum x^2/(\sum x^2+\lambda) of the plain weight. With λ=100\lambda=100, a feature with standard deviation 11 and ∑x2=100\sum x^2=100 keeps 100/(100+100)=0.5100/(100+100)=0.5 of its weight, and the same feature multiplied by 10001000 keeps 0.9999990.999999. So standardize first (P3.A11), and fit the scaler on the training data only.

Choose λ on held-out data. Training error is lowest at λ=0\lambda=0 (the table above), so λ\lambda must be chosen on a validation set or by cross-validation (P3.A4): try values on a log scale, such as 10−4,10−3,…,10210^{-4},10^{-3},\dots,10^{2}, 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 λ\lambda moves a fit along that trade-off, toward more bias and less variance. The cell below refits the polynomial on 20002000 fresh noisy copies of the same problem, with noise standard deviation 0.350.35 that we chose.

Try it: bias and variance of ridge

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 λ=0\lambda=0 to λ=0.1\lambda=0.1 the variance falls from 0.2670.267 to 0.0460.046 while the squared bias rises by only 0.0040.004. Beyond that the bias grows faster than the variance falls, and the total error has its minimum near λ=0.1\lambda=0.1 in this made-up setup.

Intuition

Picture a rubber band tying each weight to 00. The data pull each weight toward its favourite value, and the band pulls it back. A stiff band (large λ\lambda) 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 00. L1 is a band with a constant pull of strength λ\lambda however small the weight, so a weight whose evidence is weaker than λ\lambda cannot escape 00: that is the corner.

Math

Ridge: J=∥y−Xw∥2+λ∥w∥2J=\lVert\mathbf{y}-\mathbf{X}\mathbf{w}\rVert^2+\lambda\lVert\mathbf{w}\rVert^2, solution (X⊤X+λI)w=X⊤y(\mathbf{X}^\top\mathbf{X}+\lambda\mathbf{I})\mathbf{w}=\mathbf{X}^\top\mathbf{y}, with λ=σ2/τ2\lambda=\sigma^2/\tau^2 for Gaussian noise σ\sigma and prior τ\tau. In the SVD, each direction is scaled by σi2/(σi2+λ)\sigma_i^2/(\sigma_i^2+\lambda).

Lasso: J=12∥y−Xw∥2+λ∥w∥1J=\tfrac12\lVert\mathbf{y}-\mathbf{X}\mathbf{w}\rVert^2+\lambda\lVert\mathbf{w}\rVert_1. One weight or orthonormal columns: w=sign(z)max⁡(∣z∣−λ,0)w=\mathrm{sign}(z)\max(|z|-\lambda,0). Coordinate descent: wj←soft(xj⊤r,λ)/∥xj∥2w_j\leftarrow\mathrm{soft}(\mathbf{x}_j^\top\mathbf{r},\lambda)/\lVert\mathbf{x}_j\rVert^2 with r\mathbf{r} the residual with feature jj left out. All weights are 00 iff λ≥max⁡j∣xj⊤y∣\lambda\ge\max_j|\mathbf{x}_j^\top\mathbf{y}|. Laplace prior with scale β\beta gives λ=σ2/β\lambda=\sigma^2/\beta in this form.

Elastic net: 12∥y−Xw∥2+λ1∥w∥1+λ22∥w∥2\tfrac12\lVert\mathbf{y}-\mathbf{X}\mathbf{w}\rVert^2+\lambda_1\lVert\mathbf{w}\rVert_1+\tfrac{\lambda_2}{2}\lVert\mathbf{w}\rVert^2; for orthonormal columns wj=soft(zj,λ1)/(1+λ2)w_j=\mathrm{soft}(z_j,\lambda_1)/(1+\lambda_2).

Constraint form: minimize L(w)L(\mathbf{w}) subject to R(w)≤tR(\mathbf{w})\le t; for convex LL and RR, each λ>0\lambda>0 has a matching tt. Weight decay: w←(1−ηλ)w−η∇L\mathbf{w}\leftarrow(1-\eta\lambda)\mathbf{w}-\eta\nabla L for the penalty λ2∥w∥2\tfrac\lambda2\lVert\mathbf{w}\rVert^2.

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 ii by σi2/(σi2+λ)\sigma_i^2/(\sigma_i^2+\lambda), which falls smoothly from near 11 to near 00 as σi2\sigma_i^2 drops below λ\lambda. For the example above, σ2=70\sigma^2=70 and λ=1\lambda=1 gives 70/71=0.98670/71=0.986. 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 λ∥w∥2\lambda\lVert\mathbf{w}\rVert^2 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 133133, but at 130130 the weight of feature 1 is still 0.0750.075. 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

  1. Which penalty can make a fitted weight exactly 00, and why?

  2. Why is X⊤X+λI\mathbf{X}^\top\mathbf{X}+\lambda\mathbf{I} invertible for every λ>0\lambda>0, even when two columns of X\mathbf{X} are copies?

  3. The plain least-squares weights for an orthonormal design are z=(2.5,0.4)z=(2.5,0.4). What does lasso with 12∥y−Xw∥2+λ∥w∥1\tfrac12\lVert\mathbf{y}-\mathbf{X}\mathbf{w}\rVert^2+\lambda\lVert\mathbf{w}\rVert_1 and λ=1\lambda=1 give?

  4. A feature is converted from metres to millimetres (every value is 10001000 times larger). With the same λ\lambda in ridge regression, what happens to its penalty?

  5. You have N=50N=50 examples and want the lasso loss 12∥y−Xw∥2+λ∥w∥1\tfrac12\lVert\mathbf{y}-\mathbf{X}\mathbf{w}\rVert^2+\lambda\lVert\mathbf{w}\rVert_1 with λ=10\lambda=10 from scikit-learn’s Lasso. Which alpha do you pass?

Exercises

  1. Minimize (w−4)2+λw2(w-4)^2+\lambda w^2 for λ=3\lambda=3. What is ww, and what fraction of 44 is it?
    Show answerw=4/(1+3)=1w=4/(1+3)=1, a quarter of the unpenalized weight 44. In general w=z/(1+λ)w=z/(1+\lambda).
  2. Soft-threshold z=(3,−0.5,1.2)z=(3,-0.5,1.2) with λ=1\lambda=1.
    Show answer(2,0,0.2)(2,0,0.2): subtract 11 from the size of 33 and 1.21.2, and 0.50.5 is below 11 so it becomes 00.
  3. Weight decay: with η=0.1\eta=0.1, λ=0.5\lambda=0.5 and a loss gradient of 00, what is a weight of 22 after one step and after ten steps?
    Show answerEach step multiplies by 1−ηλ=0.951-\eta\lambda=0.95. After one step 1.91.9, after ten steps 2⋅0.9510=1.1972\cdot0.95^{10}=1.197.
  4. A lasso problem has X⊤y=(40,−15,5)\mathbf{X}^\top\mathbf{y}=(40,-15,5). For which λ\lambda are all weights exactly 00?
    Show answerFor λ≥max⁡j∣xj⊤y∣=40\lambda\ge\max_j|\mathbf{x}_j^\top\mathbf{y}|=40 (in the 12\tfrac12 form of this lesson). Below 4040 the solution is not all zeros.
  5. Five targets y=(9,10,11,10,10)y=(9,10,11,10,10) are fitted by a constant bb with the penalty λb2\lambda b^2 on the bias. Find bb for λ=5\lambda=5 and say what is wrong with it.
    Show answerb=∑y/(N+λ)=50/10=5b=\sum y/(N+\lambda)=50/10=5, half the mean 1010, so every prediction is off by about 55 with no benefit. The bias is left out of the penalty.
  6. Show that the one-weight ridge problem (w−3)2+αw2(w-3)^2+\alpha w^2 with α=0.5\alpha=0.5 has the same answer as minimizing (w−3)2(w-3)^2 under ∣w∣≤2|w|\le2, and find the constraint’s multiplier.
    Show answerThe penalty answer is 3/1.5=23/1.5=2. The unconstrained best 33 is outside ∣w∣≤2|w|\le2, so the constraint is active at w=2w=2, with multiplier μ=(3−2)/2=0.5=α\mu=(3-2)/2=0.5=\alpha (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.

Key takeaways

  • A penalized loss is loss plus λ\lambda times a measure of the weights’ size. λ=0\lambda=0 is plain fitting; a larger λ\lambda pushes the weights toward 00 and gives a simpler model with higher bias and lower variance.
  • L2 (ridge) penalizes ∥w∥2\lVert\mathbf{w}\rVert^2. The solution (X⊤X+λI)−1X⊤y(\mathbf{X}^\top\mathbf{X}+\lambda\mathbf{I})^{-1}\mathbf{X}^\top\mathbf{y} exists for every λ>0\lambda>0 (each eigenvalue rises by λ\lambda), is computed with a solve, and shrinks all weights smoothly without making them exactly 00.
  • L1 (lasso) penalizes ∥w∥1\lVert\mathbf{w}\rVert_1. It has no general closed form, but for one weight the answer is soft-thresholding, sign(z)max⁡(∣z∣−λ,0)\mathrm{sign}(z)\max(|z|-\lambda,0): weights whose pull is weaker than λ\lambda become exactly 00.
  • Geometrically the penalty is a constraint: minimize the loss inside a disc (L2) or a diamond (L1). The loss contour touches the diamond at a corner on an axis, which means a zero weight, and touches the disc at a smooth point.
  • Weight decay equals an L2 penalty for plain gradient descent but not for adaptive optimizers such as Adam (hence AdamW). The L2 penalty is a Gaussian prior and the L1 penalty a Laplace prior.
  • Practical rules: leave the bias unpenalized, put the features on a common scale first, choose λ\lambda on validation data from a log-spaced grid, and check how a library scales its penalty (scikit-learn’s Lasso divides the squared error by 2N2N).
Found a mistake? Tell us