Lasso Regression and L1 Sparsity
A geneticist has measured 20,000 gene expression levels for 200 patients. They want to predict disease risk. Ordinary least squares cannot even be computed — there are far more features than samples. Even if it could be computed, the resulting model would assign nonzero weight to nearly every gene. This would hide the few genes that actually matter. The scientist does not just want accurate predictions. They want a short, interpretable list of culprit genes. This is precisely the problem that Lasso regression was built to solve. Lasso — Least Absolute Shrinkage and Selection Operator — modifies ordinary linear regression. It penalizes the sum of absolute values of the coefficients rather than their squared magnitudes. This single change, from an L2 penalty to an L1 penalty, has a dramatic geometric consequence. Instead of shrinking every coefficient a little (as Ridge Regression and L2 Regularization does), Lasso pushes many coefficients to exactly zero. The model performs automatic variable selection as a byproduct of fitting. No separate feature-selection step is required. This matters enormously in real systems. In genomics, finance, and text classification, feature counts routinely dwarf sample counts. Sparse, interpretable models are often more trustworthy and more actionable than dense black-box predictors. Lasso is also the entry point into a much larger family of sparsity-inducing methods. These include elastic net, group lasso, and compressed sensing. All of them exploit the same geometric idea in different settings. This article builds the L1 penalty from first principles. It explains precisely why it induces sparsity, both geometrically and via subgradient conditions. It works through the coordinate descent algorithm used to fit it in practice. Finally, it contrasts Lasso directly with ridge regression, so the tradeoffs are concrete rather than folklore.
- Lasso adds an L1 penalty, , to the least-squares loss, unlike ridge's L2 penalty .
- The L1 penalty's non-smooth corners at zero cause many coefficients to be set exactly to zero — automatic feature selection.
- Geometrically, the diamond-shaped L1 constraint region has vertices on the axes; contours of the loss typically first touch a vertex, giving sparse solutions.
- There is no closed-form solution in general; coordinate descent with soft-thresholding is the standard, provably convergent fitting algorithm.
- Lasso struggles with groups of correlated features (picks one arbitrarily) — elastic net mixes L1 and L2 to fix this.
- The regularization strength controls the sparsity/bias tradeoff and is chosen by cross-validation.
The L1 penalty's sharp corners at zero make coefficient shrinkage collapse all the way to zero, turning regularization into automatic feature selection.
The idea
Ordinary least squares fits , minimizing the residual sum of squares over observations and features. When is large relative to , or when features are correlated, OLS estimates have high variance and are hard to interpret — nearly every coefficient is nonzero and none can be trusted individually. Regularization addresses this by adding a penalty on the size of to the objective, trading a bit of bias for a large reduction in variance.
Lasso regression solves
where is a tuning parameter controlling regularization strength. This is the L1-penalized analogue of ridge regression, which instead penalizes . The equivalent constrained form makes the geometry explicit:
for some budget that is a decreasing function of . The feasible region is a cross-polytope (a diamond in 2D, an octahedron in 3D) with sharp vertices lying exactly on the coordinate axes. Ridge's equivalent feasible region, , is a smooth ball with no corners at all. This single geometric difference — corners versus smoothness — is the entire reason Lasso produces sparse solutions and ridge does not. The intercept is typically left unpenalized (center and standardize before fitting), and features are standardized to unit variance so that the penalty treats all coefficients on a comparable scale — otherwise a feature measured in millimeters versus kilometers would be penalized asymmetrically for no principled reason.
How it works
Why sparsity emerges: the geometric argument
Consider two predictors, so . The least-squares loss has elliptical contours centered at the OLS solution . The regularized solution is the point where the smallest such ellipse touches the constraint region. For ridge (a disk), the boundary is smooth everywhere, so the touching point can land anywhere on the circle — generically at a point with both coordinates nonzero. For Lasso (a diamond), the boundary has flat edges meeting at sharp corners on the axes ( and ). Because the corners stick out and the ellipse's tangent direction rotates continuously as it grows, a substantial fraction of ellipse orientations first touch the diamond exactly at a corner, where one coordinate is zero. This is not a special coincidence — it happens for a positive-measure range of data configurations, which is why sparsity is the rule rather than the exception when is large enough.
Why sparsity emerges: the subgradient argument
The rigorous version of this argument uses subgradients, since is not differentiable at zero. Writing the objective as , the optimality condition (Karush–Kuhn–Tucker for convex, non-smooth objectives) at coordinate is:
where if , and (any value in that interval) if . Define the partial correlation . The condition says:
- If : , so exactly.
- If : for some , which is satisfiable whenever .
So any feature whose correlation with the current residual is weaker than in absolute value gets set to exactly zero, because zero is a valid subgradient solution there — no infinitesimal push in either direction can decrease the objective, since the L1 penalty's slope at zero is , steeper than the pull of a weak feature. Ridge's penalty derivative as , so it exerts no resistance right at zero — any nonzero correlation, however small, pulls the coefficient away from zero. That is the algebraic root of the geometric picture above.
Coordinate descent with soft-thresholding
Because the objective is convex but non-smooth, no closed-form solution exists in general (unlike ridge, which has ). The standard, highly efficient algorithm is coordinate descent: fix all coefficients but one, solve that one-dimensional subproblem in closed form, and cycle. For a single coordinate , holding all other () fixed, the subproblem reduces (after standardizing columns of to unit norm) to a univariate lasso problem whose exact minimizer is the soft-thresholding operator:
where is the correlation of feature with the partial residual (the residual after removing the effect of every other feature). This single formula is the entire computational engine of Lasso. ``` ALGORITHM: Coordinate Descent for Lasso INPUT: standardized X (n x p, unit-norm columns), centered y (length n), lambda >= 0, tolerance eps, max_iter OUTPUT: coefficient vector beta (length p) beta <- zeros(p) r <- y # r = current residual, y - X*beta, beta=0 initially repeat until max coefficient change < eps or iter == max_iter: for j = 1 .. p:
# remove feature j's current contribution from the residual r <- r + x_j * beta[j]
# compute correlation of residual with feature j c_j <- (1/n) * dot(x_j, r)
# soft-threshold update (closed-form 1-D minimizer) beta_old <- beta[j] beta[j] <- sign(c_j) * max(|c_j| - lambda, 0)
# re-insert feature j's (new) contribution r <- r - x_j beta[j] iter <- iter + 1 return beta ``` Each pass over all coordinates is one "epoch." In practice the algorithm is run over a path* of decreasing values (warm-starting each fit from the solution at the previous, larger ), which both accelerates convergence and produces the full regularization path used for model selection via cross-validation.
Complexity & correctness
Time complexity. Each coordinate update in the algorithm above costs (a dot product of length- vectors for , plus residual bookkeeping). One full epoch over all coordinates costs . If the algorithm runs for epochs to converge, total cost is . In practice is small (tens to low hundreds) because coordinate descent on this objective enjoys fast, often linear, empirical convergence, and warm-starting along a -path reduces further at each step. This is the same order of complexity as a single ridge solve via naive matrix inversion, , but coordinate descent is typically far cheaper when is large and sparsity is present, since coordinates that are zero can be skipped cheaply (active-set / working-set strategies restrict updates to a shrinking candidate set).
Space complexity. to store , plus for the residual and coefficient vectors — no matrix needs to be formed or inverted, which is a major practical advantage over the ridge closed-form solution when is large.
Correctness argument. The Lasso objective
is convex (a sum of a convex quadratic and a convex norm), though not differentiable. Coordinate descent is guaranteed to converge to the global minimum for this specific objective because: 1. Each coordinate subproblem is solved exactly. Fixing , the restriction of to is a strictly convex function of one variable (quadratic plus term), whose unique minimizer is exactly the soft-threshold formula derived from setting the subgradient to zero. There is no approximation error at each step — every coordinate update strictly decreases (or leaves it unchanged if already optimal). 2. The non-differentiable part is separable across coordinates (), which is precisely the condition (Tseng's theorem for block coordinate descent on non-smooth convex functions) under which cyclic coordinate descent is guaranteed to converge to a global minimum, not merely a stationary point or local optimum. This separability is essential — coordinate descent is not generally guaranteed to work on non-smooth objectives whose non-smooth part couples coordinates together. 3. Since is convex and the sequence of iterates has monotonically non-increasing objective values bounded below (by zero), and each coordinate is optimized exactly, the iterates converge to a point satisfying the global KKT/subgradient stationarity condition for every coordinate simultaneously — which for a convex function is sufficient for global optimality.
Uniqueness caveat. The optimal fitted values are always unique (strict convexity of the squared-error term in ensures this), but the coefficient vector itself need not be unique when columns of are exactly collinear — multiple sparse solutions can achieve the same loss. This is a real and important caveat, discussed further below.
Honest tradeoffs. Lasso trades a small increase in bias (shrinking true nonzero coefficients toward zero, sometimes past their true magnitude) for a large reduction in variance and, uniquely among common penalties, for interpretability via sparsity. It is not universally better than ridge: when all features genuinely contribute a little (a "dense" true signal), ridge's smooth shrinkage often achieves lower prediction error, because Lasso's hard zeroing throws away weak-but-real signal. Lasso also cannot select more than features when (a known limitation), and it handles groups of correlated features poorly, arbitrarily picking one and zeroing the rest even when they are equally informative.
Worked example
Consider observations and standardized features (mean zero, unit variance columns), predicting a centered target .
| obs | ||||
|---|---|---|---|---|
| 1 | 1.2 | 1.1 | -0.3 | 2.0 |
| 2 | -0.8 | -0.9 | 0.4 | -1.6 |
| 3 | 0.5 | 0.4 | 1.5 | 0.9 |
| 4 | -0.9 | -0.6 | -1.6 | -1.3 |
Note and are highly correlated (both track the same up/down pattern), while is comparatively weakly related to . We trace one coordinate descent epoch starting from , using .
Update . With , the partial residual is just . Compute :
Soft-threshold: . Residual is updated by subtracting from .
Update . Recompute the partial residual and its correlation with ; because and are nearly collinear, has already absorbed most of the signal that would otherwise explain. The resulting works out to a small value — call it — smaller in magnitude than . Soft-threshold: . is set exactly to zero — not because is uninformative about on its own (it is almost as predictive as ), but because once 's effect is already accounted for, the remaining signal for is too weak to overcome the threshold. This is the "pick one out of a correlated group" behavior mentioned above, made concrete.
Update . Suppose the resulting correlation , above threshold. Then .
End of epoch 1: — already sparse after a single pass, with eliminated despite being marginally almost as useful as . Subsequent epochs refine these values slightly as the residual keeps being redistributed, but the support (which coefficients are nonzero) typically stabilizes quickly. Contrast with ridge on the same data: ridge would assign both and moderate, similarly-sized nonzero weights, splitting credit between the two correlated features rather than eliminating one.
Common pitfalls & traps
| Pitfall | Why it happens | Fix |
|---|---|---|
| Forgetting to standardize features | The L1 penalty treats raw coefficient magnitude the same regardless of feature scale, so unscaled features are penalized unfairly | Standardize (zero mean, unit variance) every predictor column before fitting |
| Penalizing the intercept | Shrinking the intercept biases predictions toward zero for no statistical reason | Center and , or explicitly exclude from the penalty term |
| Choosing by training error alone | Training loss is minimized at (equivalent to OLS), which overfits and is never sparse | Use k-fold cross-validation on held-out prediction error to select |
| Assuming is unique | With collinear features, several sparse coefficient vectors can achieve identical loss and identical fitted values | Report fitted values / prediction as the reliable quantity; treat individual coefficient identities with caution under collinearity |
| Trusting a selected variable as "causal" | Lasso selects one variable from a correlated group somewhat arbitrarily, driven by noise in the sample | Use stability selection or bootstrap resampling to check how consistently a feature is selected |
| Applying vanilla gradient descent naively at | has no derivative at zero; naive gradient descent oscillates or fails to actually zero out coefficients | Use coordinate descent with soft-thresholding, or a proximal gradient method (ISTA/FISTA) designed for non-smooth penalties |
Pioneers & history
Origins · 1 minRobert Tibshirani and how this was discovered
Robert Tibshirani introduced the Lasso in a 1996 paper published in the Journal of the Royal Statistical Society, Series B, framing it explicitly as a method that combines the shrinkage benefits of ridge regression with automatic variable selection. He built on the constrained-optimization view of penalized regression and connected it to earlier work on non-negative garrote estimators. Tibshirani, together with Trevor Hastie and Jerome Friedman, subsequently developed much of the modern computational and theoretical machinery around sparse regression, including the LARS algorithm and coordinate descent solvers that made Lasso practical at scale.
Where this matters
Lasso and its L1-penalty machinery are load-bearing components of modern statistical practice wherever feature counts are large or interpretability is required. In genomics and bioinformatics, Lasso-based methods identify small panels of genetic markers associated with disease from datasets where the number of genes vastly exceeds the number of patients. In finance, sparse regression selects a manageable set of economic indicators from thousands of correlated candidates for risk models, where regulators demand explainable, auditable coefficients rather than opaque dense models. In natural language processing and text classification, L1-regularized linear models (and L1-regularized logistic regression, its classification analogue) produce compact, interpretable models over enormous bag-of-words or n-gram feature spaces. The same soft-thresholding mechanism underlies compressed sensing, a signal-processing technique for reconstructing sparse signals from far fewer measurements than the signal's dimension, which relies on exactly the same L1-minimization principle to recover sparse solutions from underdetermined linear systems. Modern deep learning also borrows the idea: L1 regularization is applied to neural network weights to induce sparse, prunable architectures, and the proximal gradient methods used to fit Lasso (ISTA and its accelerated variant FISTA) are foundational building blocks in the broader toolkit of Gradient Descent for Parameter Estimation-based optimization for non-smooth objectives across machine learning.
Ask the tutor: How does the LARS algorithm compute the entire Lasso regularization path in one efficient pass, and why is the path piecewise linear in λ?
Why is there no closed-form solution for Lasso the way there is for ridge?
Ridge's penalty, , is smooth (differentiable everywhere), so setting the gradient of the full objective to zero yields a linear system, , solvable directly by matrix inversion. Lasso's penalty, , is not differentiable at zero, so the objective's minimizer must be characterized using subgradients rather than gradients. The resulting optimality conditions are piecewise rather than linear — different equations apply depending on which coefficients are zero versus nonzero — and which coefficients fall into each category is exactly what makes the problem hard to solve in one algebraic step. Coordinate descent sidesteps this by solving each one-dimensional piece exactly and cheaply, cycling until the joint solution stabilizes.
How should I choose the regularization parameter lambda in practice?
The standard approach is k-fold cross-validation: fit Lasso across a decreasing grid of values (using warm starts for efficiency), and for each measure prediction error on held-out folds. Two common choices from the resulting cross-validation curve are `lambda.min`, the value achieving the lowest average validation error, and the "one-standard-error rule" `lambda.1se`, the largest whose validation error is within one standard error of the minimum. The one-standard-error rule is often preferred in practice because it yields a sparser, more parsimonious model with essentially indistinguishable predictive performance, guarding against overfitting to noise in the cross-validation estimate itself.
Does Lasso work when there are more features than observations (p > n)?
Yes, and this is one of its primary use cases — ordinary least squares is not even well-defined when , since is singular, but Lasso remains well-posed because the penalty term regularizes the otherwise underdetermined problem. However, a known limitation is that Lasso can select at most nonzero coefficients when , regardless of how large the true number of relevant features might be, since the active set is constrained by the rank of . This is one motivation for elastic net, which relaxes this cap by combining the L1 penalty with an L2 term.
What is the relationship between Lasso and Bayesian statistics?
Lasso has an elegant Bayesian interpretation: the L1-penalized estimate is exactly the maximum a posteriori (MAP) estimate under a Laplace (double-exponential) prior placed on each coefficient, . The Laplace distribution has a sharp peak at zero, concentrating prior probability mass there, which is the Bayesian analogue of the sparsity-inducing corner in the L1 constraint geometry. Ridge, correspondingly, is the MAP estimate under a Gaussian prior, whose smooth bell shape does not concentrate mass at exactly zero and hence never produces exact sparsity. This connection is part of a broader dictionary between penalized frequentist estimators and Bayesian priors.
How does elastic net improve on plain Lasso?
Elastic net combines the L1 and L2 penalties, minimizing . The L1 term still induces sparsity, while the added L2 term smooths the selection behavior among correlated features: instead of picking one feature from a correlated group and zeroing the rest, elastic net tends to select or shrink correlated groups together, distributing coefficient mass among them. It also removes the cap on the number of selected features that plain Lasso has, since the L2 component keeps the combined penalty strictly convex. The tradeoff is an additional hyperparameter, the mixing weight between the two penalties, that must also be tuned by cross-validation.
Can Lasso be used for classification, not just regression?
Yes — the same L1 penalty is added to the negative log-likelihood of a classification model, most commonly logistic regression, giving L1-regularized (or "sparse") logistic regression. The optimization changes from a quadratic loss to a logistic loss, so the coordinate updates no longer have the exact soft-thresholding closed form, but a local quadratic approximation at each step (iteratively reweighted least squares combined with coordinate descent) recovers a nearly identical algorithm in practice. The sparsity benefits carry over directly: L1-regularized logistic regression is widely used for text classification and other high-dimensional discrete prediction tasks where interpretable, sparse decision boundaries are valuable.
Why does the coefficient path matter, and what does it look like?
As decreases from a very large value (where all coefficients are zero) toward zero (recovering the OLS solution), each coefficient traces a path, entering the model (becoming nonzero) at some threshold and generally growing in magnitude as shrinks further. Plotting all coefficient paths against reveals the order in which features enter the model — a ranked measure of relative importance — and is a standard diagnostic plot produced automatically by software like glmnet. The Least Angle Regression (LARS) algorithm computes this entire path efficiently in one pass, exploiting the fact that the path is piecewise linear in .