Simple Algorithm
Machine Learning · Descent · 22 min

Regularization: Ridge & Lasso

Shrinking coefficients to trade a little bias for a lot less variance.

Give least squares a few hundred correlated features and it will fit the training set beautifully with coefficients that swing wildly from one sample to the next. Regularization puts a price on large coefficients. Ridge charges their squares and shrinks every one of them; the lasso charges their absolute values and sets some of them exactly to zero. One knob, λ\lambda, trades a little bias for a lot less variance.

What you’ll learn

  • Explain why least squares becomes unstable with many or strongly correlated features, using Cov⁡(w^)=σ2(X⊤X)−1\Cov(\hat{\mathbf w})=\sigma^2(X^\top X)^{-1} and the variance inflation factor.
  • Derive the ridge estimator (X⊤X+λI)−1X⊤y(X^\top X+\lambda I)^{-1}X^\top\mathbf y, show that it exists and is unique for every XX once λ>0\lambda>0, and read it as least squares on augmented data.
  • Derive soft thresholding, and explain from it and from the constraint picture why the lasso sets coefficients exactly to zero while ridge does not.
  • Fit penalized models correctly: standardize inside the cross-validation loop, leave the intercept unpenalized, choose λ\lambda by cross-validation, and use the elastic net for correlated groups of features.

When least squares overfits

Throughout this lesson and its deep dives, X∈Rn×pX\in\R^{n\times p} is the design matrix with nn examples and pp features (the regularization literature writes pp where other lessons write dd). The features are centered and the intercept is handled separately, a point we return to in step 4.

Least squares picks w^=(X⊤X)−1X⊤y\hat{\mathbf w}=(X^\top X)^{-1}X^\top\mathbf y (derived in Linear Regression & Least Squares). If the model y=Xw⋆+ε\mathbf y=X\mathbf w^\star+\boldsymbol\varepsilon is right, with noise of mean zero and covariance σ2I\sigma^2I, the estimate is unbiased and

Cov⁡(w^)=σ2 (X⊤X)−1.\Cov(\hat{\mathbf w})=\sigma^2\,(X^\top X)^{-1}.

Anything that makes X⊤XX^\top X nearly singular makes this covariance explode. Two situations do it all the time: many features relative to examples (when p>np>n, X⊤XX^\top X is singular, and if XX has rank nn, as it typically does, infinitely many weight vectors fit the training data exactly), and features that are strongly correlated with each other.

X⊤X=n(1ρρ1)⟹Var⁡(w^1)=Var⁡(w^2)=σ2n⋅11−ρ2,Corr⁡(w^1,w^2)=−ρX^\top X=n\begin{pmatrix}1&\rho\\ \rho&1\end{pmatrix}\quad\Longrightarrow\quad \Var(\hat w_1)=\Var(\hat w_2)=\frac{\sigma^2}{n}\cdot\frac{1}{1-\rho^2},\qquad \operatorname{Corr}(\hat w_1,\hat w_2)=-\rho
Two standardized features with correlation ρ\rho. The factor 1/(1−ρ2)1/(1-\rho^2) is the variance inflation factor: how much the correlation multiplies each coefficient's variance. The two estimates are negatively correlated, so when one comes out too large the other compensates. The data pin down w1+w2w_1+w_2 well and w1−w2w_1-w_2 badly.
Predict before you look

Two standardized features have correlation ρ=0.95\rho=0.95. By what factor is the variance of each least-squares coefficient larger than it would be with uncorrelated features?

Show the answer

10.3

1/(1−0.952)=1/0.0975≈10.31/(1-0.95^2)=1/0.0975\approx10.3. The standard errors grow by 10.3≈3.2\sqrt{10.3}\approx3.2. At ρ=0.99\rho=0.99 the factor is about 50: the model can still predict well, because w1+w2w_1+w_2 is stable, but the individual coefficients are close to meaningless.

Ridge regression

Ridge regression adds the squared length of the weight vector to the least-squares objective, with a strength λ≥0\lambda\ge0 that is a hyperparameter, not something fitted by minimizing training error. In this lesson λ\lambda multiplies the penalty against the sum of squared errors, as in Hastie, Tibshirani & Friedman. The widgets, glmnet and scikit-learn's Lasso average the error over the nn examples instead, so their λ\lambda is this lesson's divided by nn; The Lasso & Sparsity and Sparse Recovery Guarantees use that per-example scale too.

DerivationThe ridge estimator
  1. J(w)=∥y−Xw∥2+λ∥w∥2J(\mathbf w)=\norm{\mathbf y-X\mathbf w}^2+\lambda\norm{\mathbf w}^2

    The objective is a sum of two convex quadratics:

  2. ∇J(w)=−2X⊤(y−Xw)+2λw=0⟺(X⊤X+λI) w=X⊤y\nabla J(\mathbf w)=-2X^\top(\mathbf y-X\mathbf w)+2\lambda\mathbf w=\mathbf 0\quad\Longleftrightarrow\quad(X^\top X+\lambda I)\,\mathbf w=X^\top\mathbf y

    Its gradient vanishes at the minimizer:

  3. v⊤(X⊤X+λI)v=∥Xv∥2+λ∥v∥2>0\mathbf v^\top(X^\top X+\lambda I)\mathbf v=\norm{X\mathbf v}^2+\lambda\norm{\mathbf v}^2>0

    For λ>0\lambda>0 the matrix is positive definite whatever XX is, even with p>np>n or duplicated columns, because for every v≠0\mathbf v\ne\mathbf 0:

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

    So it is invertible, JJ is strictly convex, and the minimizer is unique:

Two special cases show what the penalty does. With orthonormal features (X⊤X=IX^\top X=I) the least-squares coefficients are zj=xj⊤yz_j=\mathbf x_j^\top\mathbf y, and ridge divides every one of them by the same factor: w^j=zj/(1+λ)\hat w_j=z_j/(1+\lambda). With correlated features the shrinkage is uneven. Ridge shrinks hardest along the directions in which the features barely vary, exactly where least squares was least reliable. For the two correlated features above, that is the poorly determined difference w1−w2w_1-w_2, so ridge first pulls the two weights toward each other, then shrinks their sum. The Convergence lesson Ridge Regression in Depth makes this precise with the singular value decomposition.

Check your understanding

You fit ridge regression with λ=0.1\lambda=0.1 to 50 examples with 200 features. Which statement is true?

  1. There is no unique solution, because X⊤XX^\top X is singular when p>np>n
  2. A unique solution exists only if the features are uncorrelated
  3. A unique solution exists, because X⊤X+λIX^\top X+\lambda I is positive definite for every λ>0\lambda>0
  4. A unique solution exists only if λ\lambda exceeds the largest eigenvalue of X⊤XX^\top X
Show the answer

C. A unique solution exists, because X⊤X+λIX^\top X+\lambda I is positive definite for every λ>0\lambda>0

X⊤XX^\top X has rank at most 50, so it is singular, but adding λI\lambda I lifts every eigenvalue by λ\lambda: the smallest becomes λ>0\lambda>0. Least squares alone would have infinitely many exact fits; ridge picks one.

The lasso: shrinkage that selects

The lasso (Tibshirani, 1996) charges the absolute values of the weights instead:

w^=arg min⁡w 12∥y−Xw∥2+λ∥w∥1,∥w∥1=∑j=1p∣wj∣.\hat{\mathbf w}=\argmin_{\mathbf w}\ \tfrac12\norm{\mathbf y-X\mathbf w}^2+\lambda\norm{\mathbf w}_1,\qquad\norm{\mathbf w}_1=\sum_{j=1}^p\abs{w_j}.

(The factor 12\tfrac12 just makes the thresholds below come out as exactly λ\lambda.) The objective is convex but has a kink wherever a weight is zero, so there is no closed form in general. With orthonormal features it splits into pp separate one-dimensional problems, min⁡w12(w−zj)2+λ∣w∣\min_w\tfrac12(w-z_j)^2+\lambda\abs w, which we can solve by hand.

DerivationSoft thresholding
  1. w>0:w=z−λ(needs z>λ)w>0:\quad w=z-\lambda\qquad(\text{needs }z>\lambda)

    If the solution is positive, the objective is differentiable there and its derivative w−z+λw-z+\lambda must vanish. That is consistent only when z>λz>\lambda:

  2. w<0:w=z+λ(needs z<−λ)w<0:\quad w=z+\lambda\qquad(\text{needs }z<-\lambda)

    Symmetrically for a negative solution:

  3. w^=Sλ(z)=sign⁡(z) (∣z∣−λ)+\hat w=S_\lambda(z)=\sign(z)\,\big(\abs z-\lambda\big)_+

    Otherwise ∣z∣≤λ\abs z\le\lambda, and w=0w=0 is optimal: the penalty's slope at zero can be anything in [−λ,λ][-\lambda,\lambda], enough to cancel the data's pull −z-z. Together these define the soft-thresholding operator:

The same story has a picture. Minimizing the error subject to a budget, ∥w∥1≤t\norm{\mathbf w}_1\le t, is equivalent to the penalized form (each λ\lambda corresponds to some tt). The ℓ1\ell_1 ball is a diamond whose corners lie on the axes. The error's elliptical contours grow from the least-squares solution until they first touch the diamond, and a corner sticks out, so the first contact is often there: a solution with zeros. The ℓ2\ell_2 ball is round, and the touching point almost never lies on an axis. This is sparsity: the lasso does feature selection and estimation in one convex problem.

Check your understanding

Features are orthonormal and the least-squares coefficients are z=(3, −0.5, 1.2)\mathbf z=(3,\,-0.5,\,1.2). What does the lasso with λ=1\lambda=1 return?

  1. (2, 0, 0.2)(2,\ 0,\ 0.2)
  2. (1.5, −0.25, 0.6)(1.5,\ -0.25,\ 0.6)
  3. (3, 0, 1.2)(3,\ 0,\ 1.2)
  4. (2, −1.5, 0.2)(2,\ -1.5,\ 0.2)
Show the answer

A. (2, 0, 0.2)(2,\ 0,\ 0.2)

Soft thresholding moves each coefficient λ=1\lambda=1 toward zero and stops at zero: 3→23\to2, −0.5→0-0.5\to0 (since 0.5≤10.5\le1), 1.2→0.21.2\to0.2. The large coefficient is shrunk too, which is the lasso's bias.

Penalized regression in practice

Scale. Least squares does not care about units: measure a feature in millimeters instead of meters and its coefficient shrinks a thousandfold while the predictions stay the same. A penalty does care, because it charges every coefficient on the same scale. So put features on a common scale first (standardization: subtract each feature's mean and divide by its standard deviation), with statistics computed on the training data only.

Intercept. Center y\mathbf y and the features and leave the intercept out of the penalty. Penalizing it would make the fit depend on where the origin of yy happens to be: adding 100 to every target would no longer simply add 100 to every prediction.

Choosing λ\lambda. Use K-fold cross-validation over a log-spaced grid. For the lasso the grid can start at λmax⁡=∥X⊤y∥∞\lambda_{\max}=\norm{X^\top\mathbf y}_\infty, the smallest value at which every coefficient is zero (step 3's thresholds show why: a coefficient leaves zero only when its correlation with the residual exceeds λ\lambda), and run down to a small fraction of it. Take the λ\lambda with the lowest cross-validation error, or the one-standard-error rule: the largest λ\lambda whose error is within one standard error of that minimum, a simpler model that is statistically as good.

python
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Lasso
from sklearn.model_selection import GridSearchCV

# The scaler lives inside the pipeline, so every CV fold refits it on that
# fold's training part: no statistics leak in from the held-out part.
pipe = make_pipeline(StandardScaler(), Lasso(max_iter=10_000))
grid = {"lasso__alpha": np.logspace(-3, 1, 30)}
search = GridSearchCV(pipe, grid, cv=5, scoring="neg_mean_squared_error")
search.fit(X_train, y_train)

model = search.best_estimator_
print(search.best_params_, model.score(X_test, y_test))
print("features kept:", np.flatnonzero(model[-1].coef_))

scikit-learn's Lasso minimizes 12n∥y−Xw∥2+α∥w∥1\frac1{2n}\norm{\mathbf y-X\mathbf w}^2+\alpha\norm{\mathbf w}_1, so its α\alpha is this lesson's λ\lambda divided by nn; Ridge minimizes ∥y−Xw∥2+α∥w∥2\norm{\mathbf y-X\mathbf w}^2+\alpha\norm{\mathbf w}^2, so there α=λ\alpha=\lambda. Both fit an unpenalized intercept by default.

The elastic net (Zou & Hastie, 2005) mixes the two penalties, λ(α∥w∥1+1−α2∥w∥2)\lambda\big(\alpha\norm{\mathbf w}_1+\tfrac{1-\alpha}2\norm{\mathbf w}^2\big) with 0≤α≤10\le\alpha\le1 (scikit-learn calls α\alpha l1_ratio). It fixes two weaknesses of the lasso. With p>np>n the lasso can select at most nn features before it saturates. And from a group of highly correlated features it tends to keep one, more or less arbitrarily, and drop the rest, so the selected set changes from sample to sample. The ridge part makes the objective strictly convex and pulls correlated features in together, with similar weights.

Think first Two features are exact copies, x1=x2\mathbf x_1=\mathbf x_2. What do ridge and the lasso do with their two weights?

Only the sum w1+w2w_1+w_2 affects the fit. Ridge's penalty w12+w22w_1^2+w_2^2 is smallest, for a given sum, when the weights are equal, and ridge's solution is unique, so it splits the weight evenly. The lasso's penalty ∣w1∣+∣w2∣\abs{w_1}+\abs{w_2} equals ∣w1+w2∣\abs{w_1+w_2} for every split with matching signs, so every such split is optimal: the lasso has infinitely many solutions, all with the same predictions, and an algorithm returns whichever it happens to reach (coordinate descent usually puts everything on one copy). The elastic net, like ridge, splits evenly.

λ as a bias–variance knob

At λ=0\lambda=0 both penalties give least squares (when it is unique). As λ→∞\lambda\to\infty every coefficient goes to zero and the model predicts the mean of y\mathbf y everywhere. In between, raising λ\lambda adds bias and removes variance, the bias–variance trade-off with a continuous dial: training error rises steadily, and test error typically falls, bottoms out, then rises.

A fitted ridge model is a linear smoother, y^=Hλy\hat{\mathbf y}=H_\lambda\mathbf y with Hλ=X(X⊤X+λI)−1X⊤H_\lambda=X(X^\top X+\lambda I)^{-1}X^\top, and its effective degrees of freedom tr⁡Hλ\operatorname{tr}H_\lambda slide continuously from rank⁡X\rank X at λ=0\lambda=0 down to 00. For the lasso the number of nonzero coefficients plays the same role, a fact proved in The Lasso & Sparsity.

MethodPenaltyClosed formExact zerosUnique solutionCorrelated features
Least squaresnoneyes, if X⊤XX^\top X invertiblenoonly if rank⁡X=p\rank X=phigh variance
Ridgeλ∥w∥22\lambda\norm{\mathbf w}_2^2yesnoalways (λ>0\lambda>0)shares weight among them
Lassoλ∥w∥1\lambda\norm{\mathbf w}_1only for orthonormal XXyesusually (always for the fitted values)tends to keep one
Elastic netmix of bothnoyesalways (α<1\alpha<1)keeps the group together
Best subsetnumber of nonzeros ≤k\le kno (combinatorial search)yesnot in generalunstable choice
Best subset is the most direct way to get sparsity, but searching all subsets is NP-hard in general. The lasso is its convex relaxation: on the cube ∥w∥∞≤1\norm{\mathbf w}_\infty\le1, the ℓ1\ell_1 norm is the largest convex function that never exceeds the count of nonzeros (its convex envelope).

Key takeaways

  • Least squares has covariance σ2(X⊤X)−1\sigma^2(X^\top X)^{-1}, which explodes when features are many or correlated; with correlation ρ\rho each coefficient's variance is inflated by 1/(1−ρ2)1/(1-\rho^2).
  • Ridge, (X⊤X+λI)−1X⊤y(X^\top X+\lambda I)^{-1}X^\top\mathbf y, exists and is unique for every XX once λ>0\lambda>0; it is least squares on data augmented with λI\sqrt\lambda I, and it shrinks most where the data say least.
  • The lasso's ℓ1\ell_1 penalty has a kink at zero, so it soft-thresholds, Sλ(z)=sign⁡(z)(∣z∣−λ)+S_\lambda(z)=\sign(z)(\abs z-\lambda)_+, and sets weak coefficients exactly to zero: estimation and feature selection in one convex problem.
  • Standardize features inside each cross-validation fold, leave the intercept unpenalized, choose λ\lambda by cross-validation (or the one-standard-error rule), and use the elastic net for correlated groups or p>np>n.
  • λ\lambda is a continuous bias–variance dial: effective degrees of freedom fall from rank⁡X\rank X to 00 as it grows.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Why should features be standardized before fitting the lasso?

  1. Because standardizing makes X⊤XX^\top X invertible
  2. Because the penalty charges all coefficients on one scale, while a coefficient's size depends on its feature's units
  3. Because the lasso has a unique solution only for standardized features
  4. Because standardized features make the lasso unbiased
Show the answer

B. Because the penalty charges all coefficients on one scale, while a coefficient's size depends on its feature's units

Measuring a feature in smaller units makes its coefficient larger and therefore more heavily penalized, so the selected set would depend on arbitrary unit choices. Standardizing puts every feature on the same footing. Least squares alone is unaffected by units.

Question 2

In ridge regression with an unpenalized intercept, what does the model predict as λ→∞\lambda\to\infty?

  1. Zero for every input
  2. The least-squares predictions
  3. Predictions that grow without bound
  4. The mean of the training targets, for every input
Show the answer

D. The mean of the training targets, for every input

The penalty drives every slope to zero, but the intercept is free, and the best constant under squared error is the mean yˉ\bar y. The model has been shrunk to the simplest possible predictor: all bias, no variance.

Question 3

Cross-validation error is nearly flat over a range of λ\lambda around its minimum. Which λ\lambda does the one-standard-error rule choose?

  1. The largest λ\lambda whose CV error is within one standard error of the minimum
  2. The λ\lambda with the smallest CV error
  3. The smallest λ\lambda whose CV error is within one standard error of the minimum
  4. The λ\lambda at which the CV error's standard error is smallest
Show the answer

A. The largest λ\lambda whose CV error is within one standard error of the minimum

Within one standard error the differences are noise, so the rule takes the most regularized, simplest model among the statistically tied ones: the largest λ\lambda, which for the lasso also means the fewest features.

Question 4

A gene-expression study has 80 samples and 5,000 genes, and genes in the same pathway are strongly correlated. Why is the elastic net often preferred to the lasso here?

  1. The lasso cannot be fitted when p>np>n
  2. The elastic net is unbiased, so its coefficients can be read as true effects
  3. The lasso can keep at most 80 genes and tends to pick one gene per correlated group; the ridge part lets correlated genes enter together and makes the solution unique
  4. The elastic net has no tuning parameters
Show the answer

C. The lasso can keep at most 80 genes and tends to pick one gene per correlated group; the ridge part lets correlated genes enter together and makes the solution unique

Both weaknesses come from the lasso's geometry: a solution with more than nn nonzeros is never needed, and among near-duplicates any one will do. Adding a squared penalty makes the objective strictly convex, which forces near-duplicates to receive similar weights.

Question 5

As λ\lambda increases from 0 in ridge regression, what happens to the training error and the variance of the coefficients?

  1. Training error falls and variance rises
  2. Training error rises and variance falls
  3. Both fall
  4. Neither changes until λ\lambda exceeds the noise variance
Show the answer

B. Training error rises and variance falls

Least squares already minimizes training error, so any penalty can only raise it. The penalty pulls the coefficients toward zero, which makes them less sensitive to the noise in a particular sample: lower variance, higher bias. Test error, the sum of both effects, usually falls first and then rises.

Go deeper

Further reading

  • T. Hastie, R. Tibshirani & J. Friedman, The Elements of Statistical Learning, 2nd ed. (Springer, 2009), chapter 3.
  • A. E. Hoerl & R. W. Kennard, "Ridge regression: biased estimation for nonorthogonal problems," Technometrics 12(1), 55–67 (1970).
  • R. Tibshirani, "Regression shrinkage and selection via the lasso," Journal of the Royal Statistical Society B 58(1), 267–288 (1996).
  • H. Zou & T. Hastie, "Regularization and variable selection via the elastic net," Journal of the Royal Statistical Society B 67(2), 301–320 (2005).