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, , 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 and the variance inflation factor.
- Derive the ridge estimator , show that it exists and is unique for every once , 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 by cross-validation, and use the elastic net for correlated groups of features.
When least squares overfits
Throughout this lesson and its deep dives, is the design matrix with examples and features (the regularization literature writes where other lessons write ). The features are centered and the intercept is handled separately, a point we return to in step 4.
Least squares picks (derived in Linear Regression & Least Squares). If the model is right, with noise of mean zero and covariance , the estimate is unbiased and
Anything that makes nearly singular makes this covariance explode. Two situations do it all the time: many features relative to examples (when , is singular, and if has rank , as it typically does, infinitely many weight vectors fit the training data exactly), and features that are strongly correlated with each other.
Two standardized features have correlation . By what factor is the variance of each least-squares coefficient larger than it would be with uncorrelated features?
Show the answer
10.3
. The standard errors grow by . At the factor is about 50: the model can still predict well, because 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 that is a hyperparameter, not something fitted by minimizing training error. In this lesson 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 examples instead, so their is this lesson's divided by ; The Lasso & Sparsity and Sparse Recovery Guarantees use that per-example scale too.
The objective is a sum of two convex quadratics:
Its gradient vanishes at the minimizer:
For the matrix is positive definite whatever is, even with or duplicated columns, because for every :
So it is invertible, is strictly convex, and the minimizer is unique:
Two special cases show what the penalty does. With orthonormal features () the least-squares coefficients are , and ridge divides every one of them by the same factor: . 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 , 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.
You fit ridge regression with to 50 examples with 200 features. Which statement is true?
- There is no unique solution, because is singular when
- A unique solution exists only if the features are uncorrelated
- A unique solution exists, because is positive definite for every
- A unique solution exists only if exceeds the largest eigenvalue of
Show the answer
C. A unique solution exists, because is positive definite for every
has rank at most 50, so it is singular, but adding lifts every eigenvalue by : the smallest becomes . 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:
(The factor just makes the thresholds below come out as exactly .) 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 separate one-dimensional problems, , which we can solve by hand.
If the solution is positive, the objective is differentiable there and its derivative must vanish. That is consistent only when :
Symmetrically for a negative solution:
Otherwise , and is optimal: the penalty's slope at zero can be anything in , enough to cancel the data's pull . Together these define the soft-thresholding operator:
The same story has a picture. Minimizing the error subject to a budget, , is equivalent to the penalized form (each corresponds to some ). The 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 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.
Features are orthonormal and the least-squares coefficients are . What does the lasso with return?
Show the answer
A.
Soft thresholding moves each coefficient toward zero and stops at zero: , (since ), . 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 and the features and leave the intercept out of the penalty. Penalizing it would make the fit depend on where the origin of happens to be: adding 100 to every target would no longer simply add 100 to every prediction.
Choosing . Use K-fold cross-validation over a log-spaced grid. For the lasso the grid can start at , 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 ), and run down to a small fraction of it. Take the with the lowest cross-validation error, or the one-standard-error rule: the largest whose error is within one standard error of that minimum, a simpler model that is statistically as good.
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 , so its is this lesson's divided by ; Ridge minimizes , so there . Both fit an unpenalized intercept by default.
The elastic net (Zou & Hastie, 2005) mixes the two penalties, with (scikit-learn calls l1_ratio). It fixes two weaknesses of the lasso. With the lasso can select at most 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, . What do ridge and the lasso do with their two weights?
Only the sum affects the fit. Ridge's penalty 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 equals 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 both penalties give least squares (when it is unique). As every coefficient goes to zero and the model predicts the mean of everywhere. In between, raising 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, with , and its effective degrees of freedom slide continuously from at down to . For the lasso the number of nonzero coefficients plays the same role, a fact proved in The Lasso & Sparsity.
| Method | Penalty | Closed form | Exact zeros | Unique solution | Correlated features |
|---|---|---|---|---|---|
| Least squares | none | yes, if invertible | no | only if | high variance |
| Ridge | yes | no | always () | shares weight among them | |
| Lasso | only for orthonormal | yes | usually (always for the fitted values) | tends to keep one | |
| Elastic net | mix of both | no | yes | always () | keeps the group together |
| Best subset | number of nonzeros | no (combinatorial search) | yes | not in general | unstable choice |
Key takeaways
- Least squares has covariance , which explodes when features are many or correlated; with correlation each coefficient's variance is inflated by .
- Ridge, , exists and is unique for every once ; it is least squares on data augmented with , and it shrinks most where the data say least.
- The lasso's penalty has a kink at zero, so it soft-thresholds, , 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 by cross-validation (or the one-standard-error rule), and use the elastic net for correlated groups or .
- is a continuous bias–variance dial: effective degrees of freedom fall from to as it grows.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Why should features be standardized before fitting the lasso?
- Because standardizing makes invertible
- Because the penalty charges all coefficients on one scale, while a coefficient's size depends on its feature's units
- Because the lasso has a unique solution only for standardized features
- 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.
In ridge regression with an unpenalized intercept, what does the model predict as ?
- Zero for every input
- The least-squares predictions
- Predictions that grow without bound
- 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 . The model has been shrunk to the simplest possible predictor: all bias, no variance.
Cross-validation error is nearly flat over a range of around its minimum. Which does the one-standard-error rule choose?
- The largest whose CV error is within one standard error of the minimum
- The with the smallest CV error
- The smallest whose CV error is within one standard error of the minimum
- The at which the CV error's standard error is smallest
Show the answer
A. The largest 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 , which for the lasso also means the fewest features.
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?
- The lasso cannot be fitted when
- The elastic net is unbiased, so its coefficients can be read as true effects
- 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
- 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 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.
As increases from 0 in ridge regression, what happens to the training error and the variance of the coefficients?
- Training error falls and variance rises
- Training error rises and variance falls
- Both fall
- Neither changes until 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
- Ridge Regression in Depth · SVD shrinkage, effective degrees of freedom and the Bayesian view.
- The Lasso & Sparsity · L1 geometry, soft thresholding, coordinate descent and paths.
- Sparse Recovery Guarantees · When the lasso finds the truth: restricted eigenvalues and compressed sensing.
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).