The Lasso & Sparsity
L1 geometry, soft thresholding, coordinate descent and paths.
The lasso is a convex problem whose solutions are exactly sparse, and a few lines of subgradient calculus explain nearly everything about it: when the answer is zero, which features enter first, why the fitted values are unique even when the coefficients are not, and why the whole solution path is piecewise linear. This lesson derives those facts, builds the algorithms that exploit them, proves that the lasso's degrees of freedom are simply its number of nonzeros, and shows where correlated features trip it up.
What you’ll learn
- Derive the lasso's subgradient optimality conditions and their consequences: , the equicorrelation set, uniqueness of the fit, and at most nonzeros.
- Derive and implement coordinate descent with soft thresholding, warm starts and a decreasing grid of , and explain why it converges.
- Prove that the lasso path is piecewise linear in and describe how LARS and homotopy methods trace it, including their worst case.
- Show that the lasso fit is the residual of a projection onto a convex polyhedron, and deduce that its degrees of freedom equal the expected number of nonzero coefficients.
- Prove the elastic net's grouping bound for correlated features, and place the lasso among its nonconvex, structured and combinatorial alternatives.
Optimality conditions
This lesson uses the scaling of glmnet and scikit-learn,
with centered and standardized columns, , so that is on the scale of a correlation. This is exactly the regpath widget's and scikit-learn's alpha; the sum-of-squares of Regularization: Ridge & Lasso is times larger. The objective is convex but not differentiable where a coordinate is zero, so optimality is stated with the subdifferential of the absolute value: for and . A point minimizes a convex function exactly when is among its subgradients.
Three consequences follow directly.
- When the answer is zero. At the residual is , so is optimal exactly when . Just below the single feature with the largest enters.
- The fit is unique. Even when the coefficients are not (see below), all solutions share the same fitted values , the same residual, and therefore the same set of features whose residual correlation reaches .
- Sparsity has a ceiling. If the columns of are in general position, which holds with probability one when the features have a continuous distribution, the solution is unique and has at most nonzero coefficients (R. J. Tibshirani, 2013). So with and continuous features, the lasso never selects more than of them.
Suppose and both attain the minimum value but . Take their midpoint . The loss is strictly convex as a function of the fitted vector :
The penalty is convex, so it is at most the average at the midpoint. Adding the two inequalities, the midpoint beats the minimum, a contradiction:
With standardized features, you lower slightly below . Which feature gets the first nonzero coefficient?
- The one with the largest least-squares coefficient
- The one with the largest absolute correlation with
- The one with the largest variance
- All features enter together, with tiny coefficients
Show the answer
B. The one with the largest absolute correlation with
At the KKT conditions read for all . The first to be violated as falls is the feature with the largest , which for standardized features is the largest absolute correlation with .
Coordinate descent
Freeze every coordinate but . With the partial residual and , the objective in is plus a constant, where . That one-dimensional problem is solved by soft thresholding:
written with the full residual , since . Keeping up to date, each update costs and a sweep over all features .
During coordinate descent a coefficient has current value , its correlation with the full residual is , and . What value does the update give ?
Show the answer
0.6
The partial-residual correlation is , and . Forgetting to add back the coefficient's own contribution, , would wrongly delete a strong feature. At the fixed point , which is the KKT condition .
import numpy as np
def soft(z, t):
return np.sign(z) * np.maximum(np.abs(z) - t, 0.0)
def lasso_cd(X, y, lam, w, tol=1e-8):
"""min (1/2n)||y - Xw||^2 + lam*||w||_1; columns scaled so (1/n)||x_j||^2 = 1."""
n = len(y)
w, r = w.copy(), y - X @ w # keep the residual up to date
while True:
biggest = 0.0
for j in range(X.shape[1]):
new = soft(X[:, j] @ r / n + w[j], lam) # partial-residual correlation
r -= X[:, j] * (new - w[j])
biggest, w[j] = max(biggest, abs(new - w[j])), new
if biggest < tol:
return w
lam_max = np.max(np.abs(X.T @ y)) / len(y) # every coefficient is 0 for lam >= lam_max
w, path = np.zeros(X.shape[1]), []
for lam in lam_max * np.logspace(0, -3, 100): # decreasing grid with warm starts
w = lasso_cd(X, y, lam, w)
path.append(w)Pathwise coordinate descent, the approach of glmnet (Friedman, Hastie & Tibshirani, 2010). Each fit starts from the previous solution, which is already close, so a few sweeps suffice. Production code adds two tricks: sweep only the current nonzeros until they converge and then check the KKT conditions for the rest, and use screening rules to skip features that are predicted to stay at zero, again verified by a KKT check.
Why does cycling through one-dimensional updates find the global minimum of a non-differentiable function? The objective is a smooth convex part plus a penalty that is a sum of functions of single coordinates. For that structure, a point where no single coordinate can improve is a global minimum, and cyclic coordinate descent converges (Tseng, 2001). The separability matters: for the fused lasso penalty , coordinate descent can stall at a non-optimal point. Proximal gradient methods (ISTA and its accelerated version FISTA) are the main alternative, treated in Proximal & Projected Methods.
The path is piecewise linear
Fix an interval of on which the active set and the signs do not change. The KKT conditions on form a linear system (assume has full column rank):
Solve it. The solution is affine in :
The residual correlations of the active features all equal and shrink at the same rate as falls: the path moves in the equiangular direction. It bends only when an inactive feature's correlation catches up with (it joins ) or an active coefficient reaches zero (it leaves ):
Least angle regression, LARS (Efron, Hastie, Johnstone & Tibshirani, 2004), walks along these equiangular directions; with one modification, dropping a variable whose coefficient hits zero instead of letting it change sign, it computes the entire lasso regularization path, one kink at a time, each with a rank-one update of a factorization of . Homotopy methods (Osborne, Presnell & Turlach, 2000) trace the same path. On typical data the number of kinks is modest, comparable to , but in the worst case it is exponential in , although an approximate path with segments, every point optimal to within a relative duality gap , always exists (Mairal & Yu, 2012). For large problems, coordinate descent on a grid of values is usually faster; exact paths remain valuable for theory and for small or moderate problems.
Think first As decreases, can a feature that has entered the lasso model later leave it again?
Yes. Between kinks every active coefficient moves linearly, and one of them can reach zero, typically when a correlated feature that entered later takes over its role. The lasso drops it at that point (it may re-enter later). Plain LARS would let it cross zero and change sign, which violates the KKT sign condition; that difference is exactly the lasso modification. Forward stepwise selection, by contrast, never removes anything. (In the widget's eight-feature problem it does not happen: once a path reaches zero it stays there.)
Degrees of freedom from a projection
Multiply the objective by and write . Introduce with a multiplier :
Minimizing over gives and the value . Minimizing over gives if and otherwise. The dual problem:
Strong duality holds ( is strictly feasible), and links the optima. The dual solution is the Euclidean projection of onto the convex polyhedron (bounded, a polytope, when has rank ), and it is the lasso residual:
This explains the uniqueness of the fit (projections are unique) and gives its degrees of freedom. For , Stein's lemma says that for any fitting rule that is Lipschitz,
Projections onto convex sets are 1-Lipschitz, and so is . Near almost every the active set and signs are locally constant, and then the KKT solution above gives , with the projection onto the span of the active columns: the divergence is . Hence , which is the expected number of nonzero coefficients when the columns are in general position (Zou, Hastie & Tibshirani, 2007; Tibshirani & Taylor, 2012, for general ).
So is an unbiased estimate of the lasso's degrees of freedom, and is an unbiased estimate of , its error in estimating the mean at the observed inputs (Mallows' , or Stein's unbiased risk estimate). The lasso searches over features, which costs degrees of freedom, and shrinks the survivors, which saves some; remarkably, the two effects cancel exactly. Effective Complexity & Degrees of Freedom develops this covariance view for any fitting procedure.
Think first Best-subset selection with features, chosen by searching all subsets, also produces nonzero coefficients. Are its degrees of freedom also about ?
No: typically more, sometimes far more. The search picks the subset that fits this noise best, so the fitted values react strongly to the noise, and exceeds . The fitted values are also discontinuous in (the chosen subset jumps), so Stein's lemma does not even apply. The lasso escapes both problems because its fit is a continuous, Lipschitz function of , and its shrinkage pays back exactly what its search costs.
Correlated features and beyond
If two columns are identical, the lasso's penalty depends only on for same-signed splits, so a whole segment of solutions is optimal; with near-duplicates the solution is unique but unstable, flipping between the two as the data change. The elastic net (Zou & Hastie, 2005) adds a ridge term. In their original "naive" form, with unit-norm columns, it provably holds correlated features together:
Suppose and are nonzero with the same sign . Both KKT conditions hold, with residual :
Subtract them: the terms cancel, leaving
Bound the right side by Cauchy–Schwarz. With unit-norm columns, where ; and , because the objective at is no larger than at :
As the two coefficients are forced together; Zou and Hastie state this bound (their Theorem 1) with the larger in place of . They also show that the naive elastic net is a lasso on augmented data with extra rows, so it can select all features even when , and they rescale the naive estimate by to undo the double shrinkage of the two penalties.
Key takeaways
- KKT: active features have residual correlation exactly , inactive ones at most . Hence iff , the fitted values are always unique, and in general position at most coefficients are nonzero.
- Coordinate descent updates for each; separability of the penalty guarantees convergence, and warm starts along a decreasing grid make whole paths cheap.
- The path is piecewise linear: between kinks ; LARS with the lasso modification and homotopy methods trace it, with exponentially many kinks in the worst case.
- The lasso fit is for a convex polyhedron ; by Stein's lemma its degrees of freedom equal , the expected number of nonzeros in general position.
- Correlated features make the lasso pick one arbitrarily; the elastic net's ridge term bounds by , holding groups together.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
At a lasso solution, feature has . Which condition must hold?
- Feature is uncorrelated with all the other features
- Feature 's least-squares coefficient is zero
Show the answer
C.
Zero is optimal for coordinate when the data's pull on it, its correlation with the current residual, is no larger than the penalty's slope . Nothing more is required: the feature can be correlated with and with other features.
A lasso fit with columns in general position has 12 nonzero coefficients. What is an unbiased estimate of its degrees of freedom?
- More than 12, because the lasso searched over features
- 12
- Fewer than 12, because the coefficients are shrunk
- , the total number of features
Show the answer
B. 12
The divergence of the lasso fit is almost everywhere, so by Stein's lemma is an unbiased estimate of . The search inflates the degrees of freedom and the shrinkage deflates them, and for the lasso the two effects cancel exactly.
Two columns of are identical, and at the chosen the lasso gives the pair a nonzero total weight. Which statement is true?
- The lasso has no solution
- The coefficient vector is unique and splits the weight evenly
- The fitted values change depending on which solution the algorithm returns
- The fitted values are unique, but infinitely many coefficient vectors attain them
Show the answer
D. The fitted values are unique, but infinitely many coefficient vectors attain them
Any same-signed split of the total weight between the copies gives the same fit and the same penalty, so a whole segment of coefficient vectors is optimal. The fitted values are unique for every lasso problem, by strict convexity of the loss in .
Between two consecutive kinks of the lasso path, how do the active coefficients depend on ?
- Linearly
- Like , as in ridge
- Exponentially
- They stay constant
Show the answer
A. Linearly
With the active set and signs fixed, the KKT conditions are a linear system whose right side is affine in : .
Further reading
- R. Tibshirani, "Regression shrinkage and selection via the lasso," Journal of the Royal Statistical Society B 58(1), 267–288 (1996).
- B. Efron, T. Hastie, I. Johnstone & R. Tibshirani, "Least angle regression," Annals of Statistics 32(2), 407–499 (2004).
- J. Friedman, T. Hastie & R. Tibshirani, "Regularization paths for generalized linear models via coordinate descent," Journal of Statistical Software 33(1), 1–22 (2010).
- H. Zou, T. Hastie & R. Tibshirani, "On the 'degrees of freedom' of the lasso," Annals of Statistics 35(5), 2173–2192 (2007).
- T. Hastie, R. Tibshirani & M. Wainwright, Statistical Learning with Sparsity: The Lasso and Generalizations (CRC Press, 2015).