L1 regularization: lasso, coordinate descent and elastic net
Explains why the L1 norm produces sparse solutions, from diamond-corner geometry to subgradient optimality conditions. Implements lasso with coordinate descent, soft-thresholding, regularization paths, and warm starts as in glmnet, then extends it to elastic net for correlated variables. Concludes with the Laplace-prior MAP interpretation and limits of lasso as a feature selector.
After this lesson you can
- Explain geometrically and using subgradients why lasso sets coefficients exactly to zero.
- Derive coordinate updates for lasso and elastic net as soft-thresholding of a partial correlation.
- Implement a warm-start regularization path from λ_max = max_j |x_jᵀy|/n.
- Compare lasso, ridge, and elastic net with correlated variables and justify the grouping effect.
- Identify when lasso selects poorly (strong correlation, irrepresentability condition) and know remedies such as relaxed lasso.
Before you start
Motivation: hundreds of candidates, few that matter
Ridge solves exploding coefficients, but not models nobody can read. With ridge all coefficients survive, shrunk but nonzero, which becomes a problem when is large:
- Quantitative finance signals. A team accumulates hundreds of candidate signals (momentum, reversals, accounting ratios, flows) to predict next month’s return. Most add nothing out of sample. A model with 300 small coefficients is impossible to audit, expensive to maintain, and fragile when the regime changes; one with 12 can be discussed signal by signal. You will see this in the factor zoo.
- Security detection. An executable or traffic classifier is built from thousands of features (system-call counts, byte n-grams, headers). For an analyst to trust an alert and for the detector to be cheap to evaluate, it helps to depend on few features and know which ones.
- Inference with many controls. In causality, choosing which of hundreds of potential confounders enter a regression is a selection problem; double selection with lasso addresses it using this lesson’s tool.
The classical answer is best subset selection: for each , regress on the variables that fit best. It is a combinatorial problem ( candidates) and generally NP-hard (Natarajan, 1995). Tibshirani (1996) proposed replacing with : the problem becomes convex and, surprisingly, still produces exactly zero coefficients. He called it lasso (least absolute shrinkage and selection operator).
This lesson explains why (geometry and optimality conditions), how to solve it at scale (coordinate descent with regularization paths, the algorithm in glmnet and scikit-learn), what fails with correlated variables and how elastic net fixes it, and how far to trust lasso as a feature selector. That final part matters most in practice.
Lasso
As in the ridge lesson, use standardized variables and centered response: with and for each column, , and an unpenalized intercept (equal to in these coordinates). Write for column of , so and is sample correlation between variables and .
Three comments on the definition:
- The scale is used by
glmnetand scikit-learn. With it does not depend on (the data term is an average) and optimality conditions are clean. Tibshirani used undivided sum of squares, multiplying by ; be careful comparing numbers across sources. - Equivalence of forms. For each with an active constraint there is a (the KKT multiplier) with the same solutions, and vice versa. The correspondence is monotone but data-dependent.
- Existence and uniqueness. is convex, continuous and coercive if , so it has a minimum. It need not be strictly convex (it certainly is not if ), but the fit is unique: if two solutions gave different fits, their midpoint would have a strictly lower objective because is strictly convex and convex. If columns of are in general position (for example, entries have a continuous distribution), the solution is unique with at most nonzero coefficients (Tibshirani, 2013); with centered data, at most , because centering removes a column degree of freedom.
Geometry: the diamond has corners
In two dimensions, , with the correlation matrix. Loss contours are ellipses centered on the ordinary least-squares (OLS) solution, and the constrained form seeks the first ellipse touching the ball . The L1 ball is a diamond with vertices on the axes. If the ellipse touches it at a vertex, one coefficient is exactly zero.
Initially, , and : the ellipse touches the diamond at vertex , so even though the least-squares estimate of is . This is not an accident of position: any inside the orange wedge leads to the same vertex. The wedge can be calculated exactly.
The vertex is a solution if and only if the ellipse cannot descend without leaving the ball. For a convex problem over convex , a point is optimal if and only if belongs to the normal cone of at , the set of directions with for all . Here . At a smooth boundary point the normal cone is a ray (the curve’s normal). At the diamond’s vertex it is an entire cone generated by normals of the two sides meeting there, and . Thus
This is a wedge with vertex and infinite area. The figure’s readouts give its angle and the fraction of the rectangle outside the ball covered by all four wedges: for L1, and . (In this symmetric example are eigenvectors of and the angle does not depend on ; generally it does.) With the L2 ball, the boundary is smooth at , the normal cone is the ray from and the region is the dashed ray : zero area. If has a continuous distribution, ridge gives zero with probability zero, while lasso does so with positive probability.
In dimensions the argument is the same and the effect stronger. The L1 ball is the cross-polytope: vertices (one nonzero coefficient), edges (two), faces of every dimension, and each face of dimension has a normal cone of dimension . The larger , the more low-dimensional “corners” can trap the solution.
Elastic net, studied below, mixes the two balls. Its boundary retains vertices on the axes (the L1 term has kinks), but its sides curve outward and each vertex’s normal cone narrows: with and wedges narrow to and cover of the rectangle; at they narrow to . With correlated variables elastic net sets zeros much less readily than lasso. That is exactly the property we seek.
Optimality conditions
Geometry convinces; optimality conditions also let us calculate. is not differentiable where any , so the tool is the subgradient. That of at is
Proof
is convex and finite throughout , so is a minimum if and only if . The quadratic part is differentiable with gradient , and by the sum rule (valid without additional assumptions when one term is differentiable) the subdifferential of is that gradient plus . Since is a sum of single-coordinate functions, its subdifferential is the Cartesian product . The condition reads coordinate by coordinate: , the statement.
∎These are the lasso optimality conditions, read as follows: is the correlation (with standardized variables) of variable with the residual. All active variables have the same absolute correlation with the residual, exactly , with the sign of their coefficient; inactive ones have at most . A variable enters when its correlation with what remains to explain reaches the common level. Since fit is unique, correlation vector is unique too, even if the solution is not.
The immediate consequence, proved in a guided exercise: the empty model is a solution if and only if
Above nothing is worth including; just below it, the variable most correlated with enters. Check this with diabetes data from the ridge lesson (442 patients and 10 clinical variables; response measures disease progression one year later).
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.linear_model import Lasso
datos = load_diabetes()
X0, y0, nombres = datos.data, datos.target, datos.feature_names
X = (X0 - X0.mean(0)) / X0.std(0) # media 0 y ||x_j||^2 = n
y = y0 - y0.mean()
n, p = X.shape
corr = X.T @ y / n
lam_max = np.abs(corr).max()
print(f"n = {n}, p = {p}; lambda_max = max_j |x_j^T y|/n = {lam_max:.3f} (variable '{nombres[np.argmax(np.abs(corr))]}')")
for f in (1.001, 0.999):
b = Lasso(alpha=f * lam_max, tol=1e-12, max_iter=100_000).fit(X, y).coef_
print(f"lambda = {f} lambda_max: coeficientes no nulos = {np.count_nonzero(b)}")
lam = 5.0
b = Lasso(alpha=lam, tol=1e-12, max_iter=100_000).fit(X, y).coef_
g = X.T @ (y - X @ b) / n # correlaciones con el residuo
act = b != 0
print(f"\nlambda = {lam}: activas {[nombres[j] for j in np.flatnonzero(act)]}")
print(" activas, x_j^T r / n:", np.round(g[act], 4), " signo(beta):", np.sign(b[act]).astype(int))
print(" inactivas, |x_j^T r| / n:", np.round(np.abs(g[~act]), 3), " (todas <= lambda)")scikit-learn’s Lasso minimizes exactly with alpha (and fits the intercept separately). Active-variable correlations with residual equal to the fourth decimal, with the sign of their coefficient; inactive correlations remain below. This verifies any lasso solution, whatever program produced it.
The orthonormal case: three ways to shrink
If columns are orthogonal, , the problem decouples. With ,
and each coefficient is chosen separately. Depending on the penalty:
| Method | Penalty | Estimate of | What it does |
|---|---|---|---|
| Best subset | hard thresholding: all or nothing | ||
| Lasso | soft thresholding: zeros and shifts | ||
| Ridge | proportional shrinkage |
The lasso row is soft thresholding, the proximal operator of ; you will prove it in an exercise. Best subset follows by comparing the only two candidates: costs and costs . Ridge is the previous lesson’s spectral view with all singular values equal.
The left figure shows bias in large coefficients. Hard thresholding leaves survivors intact. Soft subtracts from everything, even a coefficient of 10 nobody doubted was real. Ridge subtracts a fraction of the value, a bias growing without bound. The right translates this into error with unit noise. The cell calculates risks in closed form (the soft-threshold result is by Donoho and Johnstone, 1994) and checks them by Monte Carlo.
import numpy as np
from scipy.stats import norm
def riesgo_soft(th, lam):
a, b = lam - th, -lam - th
return (1 + lam**2 + (th**2 - lam**2 - 1) * (norm.cdf(a) - norm.cdf(b))
- (lam - th) * norm.pdf(lam + th) - (lam + th) * norm.pdf(lam - th))
def riesgo_hard(th, lam):
a, b = -lam - th, lam - th # W = Z - th ~ N(0, 1); Z < -lam <=> W < a; Z > lam <=> W > b
colas = norm.cdf(a) - a * norm.pdf(a) + norm.sf(b) + b * norm.pdf(b)
return colas + th**2 * (norm.cdf(b) - norm.cdf(a))
def riesgo_ridge(th, lam):
return (1 + lam**2 * th**2) / (1 + lam)**2
g = np.random.default_rng(1)
lam = 1.0
for th in (0.0, 1.0, 1.73, 3.0):
Z = th + g.normal(size=400_000) # Monte Carlo con 400 000 muestras de N(th, 1)
mc = [np.mean((Z * (np.abs(Z) > lam) - th) ** 2),
np.mean((np.sign(Z) * np.maximum(np.abs(Z) - lam, 0) - th) ** 2),
np.mean((Z / (1 + lam) - th) ** 2)]
ex = [riesgo_hard(th, lam), riesgo_soft(th, lam), riesgo_ridge(th, lam)]
print(f"theta = {th:4.2f} hard {ex[0]:.3f} (MC {mc[0]:.3f}) soft {ex[1]:.3f} (MC {mc[1]:.3f})"
f" ridge {ex[2]:.3f} (MC {mc[2]:.3f})")
th = np.linspace(0, 8, 8001)
rh = riesgo_hard(th, lam)
print(f"\nlam = 1: riesgo máximo de hard {rh.max():.3f} en theta = {th[rh.argmax()]:.2f};"
f" el de soft tiende a 1 + lam^2 = {1 + lam**2:.0f}")
print(f"ridge empeora a MCO (riesgo 1) desde theta = {np.sqrt(((1 + lam)**2 - 1) / lam**2):.3f}")With , if the true coefficient is zero, soft thresholding has risk versus for hard and for least squares. At the same both zero exactly the same , those with (68% of the time with and ); the difference lies in the rest: hard retains all of , with error , and soft subtracts , with error . When the coefficient is large, hard returns to risk , while soft stabilizes at and ridge exceeds least squares from and grows as . Hard thresholding pays in the intermediate region: its maximum risk, at , appears where the coefficient is small enough to be zeroed often and large enough that zeroing costs. No rule dominates the others: lasso buys stability (bounded, continuous risk) with constant bias in large coefficients. We return to that bias with relaxed lasso.
Coordinate descent
The one-variable function has explicit minimum . This suggests the algorithm: fix all but one coordinate, solve exactly in that one, and move to the next. This is coordinate descent from optimization, and for lasso the update is particularly clean.
This is coordinate descent for lasso: sweep cyclically, soft-thresholding the partial correlation until a pass changes nothing. Without standardized columns, curvature is instead of 1 and the update becomes ; this is the coordinate-methods version, with effective threshold depending on each variable’s units.
Initially (, , , starting at ), the first step sets , the second , and the third . On the fourth, partial correlation of has fallen to and thresholding sends it to exact zero: the profile minimum is at the kink of . The fifth step takes to optimum and no subsequent update moves anything. Remember two things. Zeros are reached in finitely many steps, not asymptotically, unlike subgradient methods except by chance. And at high the staircase becomes very fine: speed depends on column correlation.
Convergence. The objective is a differentiable convex function plus a coordinate-separable penalty, the structure for which Tseng (2001) proved cyclic coordinate descent converges to the minimum. You saw the need for separability in coordinate methods, along with the linear rate when the smooth part is strongly convex. A practical stopping rule uses maximum coefficient change in a pass and, for certification, the duality gap, which bounds and is calculated from the current residual (derived there; scikit-learn uses it as final criterion). The same problem can be solved with proximal methods updating all coordinates at once, ISTA and accelerated FISTA, whose step is exactly soft thresholding of a gradient step; with dense matrices and paths, coordinate descent often wins because each update is cheap and exploits zeros.
Regularization paths with warm starts
Usually the whole family matters, not one , so can be chosen by cross-validation. The regularization path is that family, calculated on a decreasing grid
with by default in glmnet and scikit-learn. The ratio is in scikit-learn and, in glmnet, if and if (then the problem becomes underdetermined near ). Three tricks used by glmnet (Friedman, Hastie and Tibshirani, 2010, plus later screening rules) make the entire path cost little more than one fit:
- Warm start. The solution at starts the fit at . Nearby values have nearby solutions, so each needs few passes. Start at , where the solution is known without computation.
- Active set. After a full pass, iterate only over nonzero variables to convergence, then make another full pass to check that none wants to enter.
- Screening rules. The sequential strong rule (Tibshirani and colleagues, 2012) discards variable in advance at if . It is not safe (it can discard a variable that should enter), so finally check optimality conditions for discarded variables and reinstate any violators.
Lab: lasso and elastic net from scratch
Implement coordinate descent with incremental residual for elastic net, containing lasso as (we derive the update in the elastic-net section; here it suffices that it is soft thresholding divided by ). The stopping criterion combines cheap maximum change with the duality gap, calculated only once the former is satisfied. The elastic-net gap comes from writing it as lasso on augmented data, justified later. On diabetes data, compare the warm-start path with scikit-learn’s lasso_path and enet_path.
import numpy as np, time
from sklearn.datasets import load_diabetes
from sklearn.linear_model import lasso_path, enet_path
datos = load_diabetes()
X0, y0, nombres = datos.data, datos.target, datos.feature_names
X = (X0 - X0.mean(0)) / X0.std(0)
y = y0 - y0.mean()
def soft(c, t):
return np.sign(c) * max(abs(c) - t, 0.0)
def brecha(X, y, b, r, lam, alpha):
"""Brecha de dualidad de la elastic net, vista como lasso sobre los datos aumentados
[X; sqrt(n lam (1 - alpha)) I], [y; 0]."""
n = len(y)
l1, l2 = lam * alpha, lam * (1 - alpha)
r_aum = np.concatenate([r, -np.sqrt(n * l2) * b]) # residuo de los datos aumentados
y_aum = np.concatenate([y, np.zeros(len(b))])
grad = X.T @ r - n * l2 * b # = X_aum^T r_aum
s = min(1.0, n * l1 / max(np.abs(grad).max(), 1e-300)) # escala que hace factible el punto dual
primal = r_aum @ r_aum / (2 * n) + l1 * np.abs(b).sum()
dual = (y @ y - (y_aum - s * r_aum) @ (y_aum - s * r_aum)) / (2 * n)
return primal - dual
def cd_enet(X, y, lam, alpha=1.0, b0=None, tol=1e-8, max_pasadas=10_000):
"""(1/2n)|y - Xb|^2 + lam (alpha |b|_1 + (1 - alpha)/2 |b|^2) por coordenadas cíclicas."""
n, p = X.shape
b = np.zeros(p) if b0 is None else b0.copy()
r = y - X @ b # residuo completo, actualizado en O(n)
sq = (X ** 2).sum(0) / n # = 1 con columnas estandarizadas
for k in range(1, max_pasadas + 1):
dmax = 0.0
for j in range(p):
c = X[:, j] @ r / n + sq[j] * b[j] # correlación parcial
nuevo = soft(c, lam * alpha) / (sq[j] + lam * (1 - alpha))
if nuevo != b[j]:
r -= (nuevo - b[j]) * X[:, j]
dmax = max(dmax, abs(nuevo - b[j]))
b[j] = nuevo
# parada barata por cambio máximo; certificado (brecha) solo cuando aquella se cumple
if dmax <= tol * max(np.abs(b).max(), 1.0) and brecha(X, y, b, r, lam, alpha) <= tol * (y @ y) / (2 * len(y)):
return b, k
return b, max_pasadas
def camino(X, y, alpha=1.0, K=60, eps=1e-2, tol=1e-8, caliente=True):
lam_max = np.abs(X.T @ y).max() / (len(y) * alpha)
lams = lam_max * np.logspace(0, np.log10(eps), K)
B, b, pasadas = np.zeros((K, X.shape[1])), None, 0
for i, lam in enumerate(lams):
b, k = cd_enet(X, y, lam, alpha, b if caliente else None, tol)
B[i], pasadas = b, pasadas + k
return lams, B, pasadas
for alpha in (1.0, 0.5):
t0 = time.perf_counter(); lams, B, pas = camino(X, y, alpha); t1 = time.perf_counter()
if alpha == 1.0:
_, Bsk, _ = lasso_path(X, y, alphas=lams, tol=1e-12, max_iter=100_000)
else:
_, Bsk, _ = enet_path(X, y, l1_ratio=alpha, alphas=lams, tol=1e-12, max_iter=100_000)
t2 = time.perf_counter()
entra = [np.argmax(B[:, j] != 0) if B[:, j].any() else len(lams) for j in range(B.shape[1])]
print(f"alpha = {alpha}: lambda_max = {lams[0]:.2f}, {pas} pasadas en {len(lams)} lambdas;"
f" max |propio - sklearn| = {np.abs(B - Bsk.T).max():.1e} (coeficientes de hasta {np.abs(B).max():.0f})")
print(f" tiempo propio / scikit-learn = {(t1 - t0) / (t2 - t1):.0f}")
print(" orden de entrada:", ", ".join(nombres[j] for j in np.argsort(entra, kind="stable")))
_, _, frio = camino(X, y, 1.0, caliente=False)
_, _, cal = camino(X, y, 1.0)
print(f"\nlasso, pasadas totales: arranque en frío {frio}, en caliente {cal}")
print(f"correlación entre s1 y s2: {X[:, 4] @ X[:, 5] / len(y):.3f}")The implementations agree to for coefficients up to 25 (lasso) and (elastic net): the fifteen-line algorithm is scikit-learn’s. Lasso brings variables in the order bmi, s5, bp, s3, sex, s6, s1, s4, age, s2: body mass index and s5 first (according to dataset documentation, possibly log serum triglycerides). Three more observations:
- Speed. The Python loop is five to fifteen times slower than scikit-learn’s Cython implementation (the cell prints the ratio, which varies by run). This is an implementation difference, not an algorithm difference: operation counts are the same.
- Elastic net converges in far fewer passes (561 versus 1790 for the same number of values). The L2 part adds to the quadratic matrix and improves conditioning, needed here:
s1ands2have correlation , so curvature along their difference is only (the pair’s eigenvalue), and coordinate descent moves slowly when both are active. - Warm starts save little at strict tolerance: 1790 passes versus 2299 from scratch, 22%. They save each ‘s initial transient; the linear convergence tail, dominant with and correlated columns, is the same. This is what you saw in coordinate methods, and why
glmnetcombines warm starts with an active set.
Elastic net
Lasso has three limitations Zou and Hastie (2005) noted when proposing elastic net:
- If , it selects at most variables (when the solution is unique), even if more are relevant.
- Among highly correlated variables it tends to keep one and zero the rest; which one depends on sample details.
- If and variables are highly correlated, ridge often predicts better, as Tibshirani (1996) observed in simulations.
The idea is to add a small L2 part to the L1 penalty.
Everything above extends naturally:
- Coordinate update. The L2 term adds to the profile for coordinate , becoming . Its minimum is
soft thresholding at level followed by ridge-like shrinkage.
- Optimality conditions and . if , and if . Since the L2 term has zero gradient at , the empty model is a solution if and only if .
- Augmented data. With and , : elastic net is lasso at level on rows (Zou and Hastie’s lemma 1 in their parameterization). has rank , so the objective is strictly convex, the solution unique, and it can have up to nonzero coefficients even if . This is the trick used for the lab’s duality gap.
The grouping effect
What matters is correlated variables. Start with the extreme case: identical columns . For lasso, any split with the same sign and sum gives the same fit and penalty : infinitely many solutions, and coordinate descent from zero keeps the first variable visited (the second’s partial correlation then no longer exceeds ). Elastic net with has a unique solution, and swapping and does not change the objective, so that solution satisfies : equal division. Nearly identical columns yield nearly equal division, which can be quantified.
Proof
Since and are nonzero and have the same sign , optimality gives and likewise for . Subtracting, , and Cauchy–Schwarz gives . With standardized columns, . Also , because the objective at is no greater than at , which is , and the penalty is nonnegative. Combining gives , as claimed.
∎As , the difference tends to zero: nearly identical variables receive nearly identical coefficients. Lasso () has no such bound. The figure shows a model where three highly correlated variables have exactly the same effect.
With lasso, one of the three group curves takes off first and takes almost everything; the others enter late or not at all. Changing seed changes the chosen variable even though the model is perfectly symmetric among them. With elastic net all three curves take off together and stay close. The cell repeats the experiment with another generator, at for lasso and the same L1 part (equal ) for elastic net with .
import numpy as np
from sklearn.linear_model import Lasso, ElasticNet
def grupo(rho, semilla, n=100):
"""Modelo de la figura: x1, x2, x3 con correlación rho; y = x1 + x2 + x3 + 1.5 x4 - x5 + 1.5 eps."""
g = np.random.default_rng(semilla)
z = g.normal(size=(n, 1))
X = g.normal(size=(n, 8))
X[:, :3] = np.sqrt(rho) * z + np.sqrt(1 - rho) * X[:, :3]
y = X @ np.array([1.0, 1.0, 1.0, 1.5, -1.0, 0, 0, 0]) + 1.5 * g.normal(size=n)
return (X - X.mean(0)) / X.std(0), y - y.mean()
alpha = 0.5
for rho in (0.5, 0.9, 0.99):
mayor, activas, disp, suma = np.zeros(3, int), [], [], []
for s in range(20):
X, y = grupo(rho, s)
lam = 0.25 * np.abs(X.T @ y).max() / len(y) # lambda_max / 4
bl = Lasso(alpha=lam).fit(X, y).coef_[:3]
be = ElasticNet(alpha=lam / alpha, l1_ratio=alpha).fit(X, y).coef_[:3] # misma parte L1
mayor[np.argmax(np.abs(bl))] += 1
activas.append([(bl != 0).sum(), (be != 0).sum()])
disp.append([bl.std(), be.std()])
suma.append([bl.sum(), be.sum()])
a, d, sm = np.mean(activas, 0), np.mean(disp, 0), np.mean(suma, 0)
print(f"rho = {rho}: activas del grupo: lasso {a[0]:.2f}, enet {a[1]:.2f}; desv. típica dentro del grupo:"
f" lasso {d[0]:.3f}, enet {d[1]:.3f}; suma del grupo: lasso {sm[0]:.2f}, enet {sm[1]:.2f}")
print(f" la mayor del lasso es x1, x2, x3 en {mayor[0]}, {mayor[1]}, {mayor[2]} de 20 muestras")
print("última muestra con rho = 0.99: lasso", np.round(bl, 3), " enet", np.round(be, 3))At both methods keep all three variables active and differ little (within-group standard deviation versus ). At , lasso keeps an average of three active with within-group standard deviation ; elastic net always keeps all three, with . The group variable with the largest lasso coefficient is , , or in 4, 8, and 8 of 20 samples: sampling chance selects it. In the last sample lasso gives and elastic net . The grouping theorem’s bound explains the difference: with , factor forces elastic net to give nearly equal coefficients. At the other extreme, ridge (the limit ) distributes equally well but does not zero any no-effect variables , , and : elastic net takes the best of both, and its is therefore selected by cross-validation with .
Double shrinkage
The sum of group coefficients shows elastic net’s price. Truth is 3; lasso gives on average at and elastic net . Both shrink, elastic net more. In the orthonormal case its solution is : first lasso soft thresholding, then extra ridge shrinkage. Zou and Hastie called this “naive” elastic net and proposed undoing the second shrinkage by multiplying the solution by (in their parameterization; in ours with standardized columns). glmnet and scikit-learn do not apply that correction: they return the naive version and let cross-validation choose and to compensate. Remember elastic-net coefficient magnitudes are doubly shrunk.
Bayesian interpretation: the Laplace prior
In the ridge lesson you saw regularization as MAP estimation: the L2 penalty is the logarithm of a Gaussian prior. Lasso corresponds to the Laplace distribution. With and independent with density ,
Multiplying by , which does not change the minimizer, the MAP estimator is lasso with : a more concentrated prior (smaller scale ) or more noise call for more regularization, and more data less. The Laplace density peaks at zero and has exponential tails heavier than Gaussian: it says “most coefficients are almost zero and some are large.” Elastic net corresponds to a prior proportional to , a compromise between the two.
Interpret this carefully:
- Sparsity belongs to the mode, not the posterior. MAP lands exactly at zero because the posterior maximum stays at the density peak. But under this prior, : posterior mean and median are not sparse, nor are posterior samples (the Bayesian lasso of Park and Casella, 2008).
- The Laplace prior is a poor sparsity model. Laplace samples are never zero and its peak is not strong enough to separate “zero” from “small.” Priors designed for this include spike-and-slab (mass at zero plus a broad component) and global-local shrinkage priors such as the horseshoe. What works well about lasso is the estimator, not its probabilistic interpretation.
The path is piecewise linear: LARS
Fix an interval of where active set and signs do not change, and suppose (active columns) has full rank. Active optimality conditions, , give
an affine function of . The lasso path is piecewise linear, with knots at values where an event occurs: an inactive variable reaches and enters, or an active coefficient reaches zero and leaves. Both times follow from linear equations in , so the exact path can be followed knot to knot. That is LARS (least angle regression, Efron, Hastie, Johnstone and Tibshirani, 2004): it advances in the direction keeping all active correlations with the residual equal (hence the name: that direction makes the same angle with all of them), and with a simple modification, removing a variable when its coefficient crosses zero, calculates the exact lasso path. The authors found the full path much cheaper than earlier methods. LARS was standard for lasso until coordinate descent displaced it: with many variables there are many knots (exponentially many in in the worst case, as Mairal and Yu proved in 2012), each requiring a factorization update, while each point on a warm-start grid costs a few cheap passes.
Lasso degrees of freedom
The degrees of freedom of a fit are . For ridge this was . Lasso is adaptive (it chooses variables by looking at ), so one might expect extra degrees of freedom, as with best subset, whose exceeds its number of chosen variables (Ye, 1998). The result is cleaner:
The proof idea uses Stein’s lemma: if is Lipschitz, . The lasso fit is continuous and piecewise linear in and, for almost every , and are locally constant. There, by the preceding formula, , with the projection onto . The second term does not depend on , so divergence is . The hard part is proving local constancy, not the calculation. The cell checks the calculation by finite differences.
import numpy as np
from sklearn.linear_model import Lasso
g = np.random.default_rng(0)
n, p = 50, 10
X = g.normal(size=(n, p)); X = (X - X.mean(0)) / X.std(0)
beta = np.zeros(p); beta[:3] = [2.0, -1.5, 1.0]
y = X @ beta + g.normal(size=n)
lam = 0.2
def ajuste(yy):
return X @ Lasso(alpha=lam, fit_intercept=False, tol=1e-13, max_iter=100_000).fit(X, yy).coef_
b = Lasso(alpha=lam, fit_intercept=False, tol=1e-13, max_iter=100_000).fit(X, y).coef_
A = np.flatnonzero(b)
h = 1e-6
J = np.column_stack([(ajuste(y + h * e) - ajuste(y - h * e)) / (2 * h) for e in np.eye(n)]) # d yhat / d y
XA = X[:, A]
H = XA @ np.linalg.solve(XA.T @ XA, XA.T) # proyector sobre col(X_A)
ev = np.linalg.eigvalsh((J + J.T) / 2)
print(f"|A| = {len(A)} variables activas")
print(f"traza de la jacobiana = {np.trace(J):.4f} max |J - H_A| = {np.abs(J - H).max():.1e}")
print(f"autovalores de J: {np.sum(np.abs(ev - 1) < 1e-4)} iguales a 1 y {np.sum(np.abs(ev) < 1e-4)} iguales a 0")With 3 active variables, the Jacobian trace is , the Jacobian agrees with projection to , and its eigenvalues are three ones and 47 zeros: locally lasso is least-squares regression on active variables shifted by a fixed amount.
Two effects exactly compensate. Choosing variables by looking at adds degrees of freedom; shrinking coefficients toward zero by the fixed amount removes them. Practically, the result gives a cheap information criterion for choosing : .
Limits of lasso as a feature selector
So far, lasso as an estimator. The most common practical question is different: are its selected variables the true ones? The honest answer is “sometimes,” and knowing when matters.
Instability with correlation
You saw this in the path figure: with highly correlated variables, lasso chooses one almost at random. Predictions from models choosing different group variables are nearly identical, so no prediction validation detects the problem. If interpretation is the goal (“variable 2 matters and 1 does not”), this is a serious error.
The irrepresentability condition
There is a subtler failure, occurring even without noise and with infinite data. Let be the true support of and the correlation matrix, partitioned into blocks , .
Proof
Suppose has support and signs . Since , active conditions give , namely . Inactive conditions give for , the stated condition. Conversely, if it holds, take small enough that has signs (such a value exists because no component of is zero). That vector, completed with zeros, satisfies all optimality conditions, sufficient by convexity.
∎The quantity contains coefficients from regressing each irrelevant variable on the relevant ones, weighted by signs. The condition requires no irrelevant variable be “represented” too well by relevant ones in the sign direction. Zhao and Yu (2006) called it the irrepresentability condition and proved that with noise it is nearly necessary and sufficient for lasso to select the correct model with probability tending to 1: the strong version (all components for some ) suffices with regularity conditions, and the weak version () is necessary. Meinshausen and Bühlmann (2006) reached the same condition, called neighborhood stability, when estimating graphs with lasso, and Wainwright (2009) gave exact sample-size thresholds.
The example can be solved by hand. With and , and : the condition fails if . It then fails in the worst way. Since and , the first variable to enter is , the one with no effect. While alone, . The other two enter together at (0.7 at ), and from then on, with by symmetry, active conditions for all three give
so never leaves: it tends to zero with but vanishes for no positive . With and the same , the quantity is and the path is perfect: the condition depends on signs of true coefficients, not only correlations.
Noise introduces a nuance visible in the lower readout: at , 46% of samples do have some with correct support. Repeat the proof’s reasoning with sample data. Let be sample irrepresentability and , with , be sample partial correlation of with response, which would be 0 without noise. The condition for the candidate with support is . If , it holds for some only if , then for : noise randomly pushes ‘s partial correlation against its bias and a on the noise scale exploits it. This is a coin toss that does not improve with more data. The cell checks it.
import numpy as np, warnings
from sklearn.linear_model import lasso_path
warnings.filterwarnings("ignore")
g = np.random.default_rng(0)
n, R = 100, 150
for rho in (0.2, 0.4, 0.6):
C = np.array([[1, 0, rho], [0, 1, rho], [rho, rho, 1]])
L = np.linalg.cholesky(C)
acierta, kappa, eta_neg = [], [], []
for _ in range(R):
X = g.normal(size=(n, 3)) @ L.T
y = X @ np.array([1.0, 1.0, 0.0]) + g.normal(size=n)
X = (X - X.mean(0)) / X.std(0); y = y - y.mean()
Cn, z = X.T @ X / n, X.T @ y / n
v = np.linalg.solve(Cn[:2, :2], Cn[:2, 2]) # C_SS^{-1} C_S3
kappa.append(v.sum()) # C_3S C_SS^{-1} s con s = (1, 1)
eta_neg.append(z[2] - v @ z[:2] < 0)
B = lasso_path(X, y, alphas=np.abs(z).max() * np.logspace(0, -3, 60))[1].T
acierta.append(np.any((B[:, 0] > 0) & (B[:, 1] > 0) & (B[:, 2] == 0)))
a, k, e = map(np.array, (acierta, kappa, eta_neg))
print(f"rho = {rho}: kappa muestral medio {k.mean():.2f}; soporte exacto en algún lambda: {a.mean():.0%}")
if (k > 1).any():
print(f" con kappa > 1: acierta el {a[k > 1].mean():.0%}; con kappa > 1 y eta < 0: {a[(k > 1) & e].mean():.0%};"
f" con kappa > 1 y eta > 0: {a[(k > 1) & ~e].mean():.0%}")At (population quantity 0.4), all samples have some with correct support, and at 91% do; failures are samples where noise raised sample above 1. At mean sample is and 49% succeed. The division is exact: among samples with , all with succeed and none with do. Since is zero-centered noise for any , that half does not disappear with more data, but cannot be exploited either: knowing which to choose would require knowing the support. Zhao and Yu study dominating noise ( in our scale), to which the proof’s argument applies directly.
Choosing λ by cross-validation selects too much
The minimizing prediction error is not the one recovering support. Good prediction favors small (soft-threshold bias costs error), and small admits spurious variables with tiny coefficients. Meinshausen and Bühlmann (2006) proved that prediction-optimal does not generally yield consistent selection. The next lab measures this.
Remedies
- Relaxed lasso (Meinshausen, 2007): use lasso with a to choose support , then refit on it with a smaller penalty with , choosing by cross-validation. This separates the two functions lasso performs with one parameter: selecting variables and shrinking. Hastie, Tibshirani and Tibshirani (2020) use a simplified version, the mixture , which performed best overall in their study: as good as lasso with weak signal and best subset with strong signal.
- Adaptive lasso (Zou, 2006): penalty with weights from an initial estimate , so large coefficients are penalized little. With fixed and a consistent initial estimator, it selects the correct support with probability tending to 1 without requiring irrepresentability (the oracle property).
- Stability selection (Meinshausen and Bühlmann, 2010): repeat lasso across many subsamples and retain variables chosen in a high fraction, controlling expected false positives. You will study it in feature selection.
- Honest inference after selection. p-values from regression fitted on lasso-selected variables are invalid because selection used the same data. Correct tools are selective inference or separate data for selection and inference.
Lab: support recovery with p = 500 and n = 100
A genuinely sparse problem: 500 variables, 100 observations, and 10 nonzero coefficients (, spaced 50 positions apart). Variables follow an AR(1) process, , so each relevant variable has correlated neighbors. For each , fit LassoCV and ElasticNetCV (with ) using 5-fold cross-validation on a grid of 20 values from to (so the cell fits Pyodide’s time limit), and count true positives (relevant variables selected, out of 10) and false positives (irrelevant selected, out of 490), averaging two samples.
import numpy as np, warnings
from sklearn.linear_model import LassoCV, ElasticNetCV
warnings.filterwarnings("ignore")
def soporte(rho, semilla, n=100, p=500, sigma=1.0):
g = np.random.default_rng(semilla)
X = np.empty((n, p)); X[:, 0] = g.normal(size=n)
E = g.normal(size=(n, p))
for j in range(1, p): # AR(1): corr(x_j, x_k) = rho^|j - k|
X[:, j] = rho * X[:, j - 1] + np.sqrt(1 - rho**2) * E[:, j]
beta = np.zeros(p)
beta[::50] = np.tile([1.0, -1.0], 5) # 10 variables con efecto, separadas 50 posiciones
return X, X @ beta + sigma * g.normal(size=n), beta != 0
print(" rho método VP (de 10) FP (de 490) tasa VP tasa FP")
for rho in (0.0, 0.5, 0.9):
for nombre, modelo in (("lasso", LassoCV(cv=5, alphas=20, eps=1e-2)),
("enet ", ElasticNetCV(l1_ratio=0.5, cv=5, alphas=20, eps=1e-2))):
vp, fp = [], []
for semilla in range(2):
X, y, S = soporte(rho, semilla)
sel = modelo.fit(X, y).coef_ != 0
vp.append((sel & S).sum()); fp.append((sel & ~S).sum())
print(f" {rho:.1f} {nombre} {np.mean(vp):5.1f} {np.mean(fp):6.1f} {np.mean(vp)/10:.2f} {np.mean(fp)/490:.3f}")Both methods find nearly all relevant variables (all 10 at , 9 at ), but at the cost of many false positives: lasso selects 50–70 irrelevant variables, 10–14% of 490, and elastic net even more (79–90.5). The final model has six to ten times as many variables as the true one. Two observations:
- Cross-validation optimizes prediction, not selection. Spurious variables enter with small coefficients barely changing validation error, and lowering to avoid biasing the 10 good ones more than compensates for their small added noise. This is Meinshausen and Bühlmann’s observation. If you want the variable list, you need another tool with explicit false-positive control: stability selection or rules such as
lambda.1se. - Here elastic net does not help selection. Its grouping effect pulls correlated neighbors of each relevant variable into the model; here those neighbors are irrelevant. The opposite happened in the path figure because the entire group had an effect. Grouping is a virtue when relevant variables come in groups and a cost when each has irrelevant neighbors. Your knowledge of the data, not the algorithm, tells you which case applies.
Lab: relaxed lasso
Soft-threshold bias has a practical consequence. If is chosen by cross-validation, lasso tends to select a small to avoid shrinking good coefficients too much, admitting spurious variables. Relaxed lasso separates the two functions. The cell implements the simplified version (the mixture) with lasso_path and least squares on each path support, chooses with 5-fold cross-validation, and compares it with pure lasso (, with chosen by the same validation) on 10 problems (, , 5 nonzero coefficients, noise ), measuring error on 2,000 test points.
import numpy as np, warnings
from sklearn.linear_model import lasso_path
warnings.filterwarnings("ignore")
def datos(semilla, n=100, p=50, n_test=2000, sigma=2.0):
g = np.random.default_rng(semilla)
X = g.normal(size=(n + n_test, p))
beta = np.zeros(p); beta[:5] = [3, -2, 2, -1.5, 1]
y = X @ beta + sigma * g.normal(size=n + n_test)
return X[:n], y[:n], X[n:], y[n:]
PHI = np.array([0.0, 0.25, 0.5, 0.75, 1.0]) # phi = 1 es el lasso; phi = 0, MCO sobre su soporte
def ajustes(X, y, lams):
"""Coeficientes relajados para cada (phi, lambda): array (len(PHI), len(lams), p) y sus interceptos."""
xm, ym = X.mean(0), y.mean()
Xc, yc = X - xm, y - ym
B = lasso_path(Xc, yc, alphas=lams)[1].T
M = np.zeros_like(B)
for k, b in enumerate(B):
S = b != 0
if S.any():
M[k, S] = np.linalg.lstsq(Xc[:, S], yc, rcond=None)[0]
C = PHI[:, None, None] * B[None] + (1 - PHI[:, None, None]) * M[None]
return C, ym - C @ xm
res = []
for semilla in range(10):
X, y, Xt, yt = datos(semilla)
n = len(y)
lams = np.abs((X - X.mean(0)).T @ (y - y.mean())).max() / n * np.logspace(0, -2.5, 40)
error = np.zeros((len(PHI), len(lams)))
pliegue = np.arange(n) % 5
for f in range(5):
tr = pliegue != f
C, c0 = ajustes(X[tr], y[tr], lams)
pred = np.einsum("klp,ip->kli", C, X[~tr]) + c0[:, :, None]
error += ((pred - y[~tr]) ** 2).mean(-1)
C, c0 = ajustes(X, y, lams)
i = np.argmin(error[-1]) # lasso: solo phi = 1
k, j = np.unravel_index(np.argmin(error), error.shape) # relajado: (phi, lambda) conjuntos
test = lambda c, b: np.mean((yt - Xt @ c - b) ** 2)
res.append([test(C[-1, i], c0[-1, i]), test(C[k, j], c0[k, j]), test(C[0, i], c0[0, i]),
np.count_nonzero(C[-1, i]), np.count_nonzero(C[k, j]), PHI[k], C[-1, i][0], C[k, j][0], lams[j] / lams[i]])
r = np.mean(res, 0)
print(f"error de test (varianza del ruido = 4): lasso {r[0]:.2f}, relajado {r[1]:.2f},"
f" MCO sobre el soporte del lasso {r[2]:.2f}")
print(f"variables elegidas (verdaderas: 5): lasso {r[3]:.1f}, relajado {r[4]:.1f}; phi medio elegido {r[5]:.2f}")
print(f"coeficiente de x1 (verdadero 3): lasso {r[6]:.2f}, relajado {r[7]:.2f}")
print("relajado mejor que el lasso en", sum(a[1] < a[0] for a in res), "de 10 problemas;",
f"lambda del relajado / lambda del lasso: entre {min(a[8] for a in res):.1f} y {max(a[8] for a in res):.1f}")Cross-validated lasso selects an average variables, over three times the 5 true ones, with test error at noise variance 4. Relaxed lasso keeps variables, reduces error to , and wins in 7 of 10 problems. All chose : pure least squares on support from a between and times larger than lasso’s, because a small is no longer needed to avoid shrinking good coefficients. The third error is the counterexample: refitting least squares on lasso’s chosen support without reselecting gives , worse than lasso itself, because it includes that support’s spurious variables without shrinkage (at least on average). Bias is also visible in coefficients: that of , truly 3, is with lasso and with relaxed lasso.
With scikit-learn and glmnet
In practice, fit lasso and elastic net with scikit-learn’s Lasso, ElasticNet, LassoCV, ElasticNetCV, and lasso_path / enet_path, or R’s glmnet. Standardization goes inside a pipeline so cross-validation refits it in each fold (otherwise it is data leakage).
import numpy as np, warnings
from sklearn.datasets import load_diabetes
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LassoCV, ElasticNetCV, Ridge, ElasticNet
from sklearn.model_selection import KFold
warnings.filterwarnings("ignore")
datos = load_diabetes()
X, y, nombres = datos.data, datos.target, np.array(datos.feature_names)
cv = KFold(5, shuffle=True, random_state=0)
lasso = make_pipeline(StandardScaler(), LassoCV(cv=cv)).fit(X, y)
m = lasso[-1]
print(f"LassoCV: alpha = {m.alpha_:.3f} (rejilla de {len(m.alphas_)} valores, de {m.alphas_.max():.2f} a {m.alphas_.min():.4f})")
print(" variables elegidas:", ", ".join(nombres[m.coef_ != 0]))
enet = make_pipeline(StandardScaler(), ElasticNetCV(l1_ratio=[0.1, 0.5, 0.9, 1.0], cv=cv)).fit(X, y)
e = enet[-1]
print(f"ElasticNetCV: l1_ratio = {e.l1_ratio_}, alpha = {e.alpha_:.3f}, {np.count_nonzero(e.coef_)} variables no nulas")
print(f" error de validación cruzada mínimo: lasso {m.mse_path_.mean(1).min():.0f}, elastic net {e.mse_path_.mean(2).min():.0f}")
# Correspondencia de escalas: Ridge usa la suma de cuadrados; ElasticNet, la media y el factor 1/2
Xs = StandardScaler().fit_transform(X)
n, a = len(y), 50.0
r = Ridge(alpha=a).fit(Xs, y).coef_
e0 = ElasticNet(alpha=a / n, l1_ratio=0.0, tol=1e-12, max_iter=100_000).fit(Xs, y).coef_
print(f"\nRidge(alpha={a:.0f}) frente a ElasticNet(alpha={a:.0f}/n, l1_ratio=0): max |dif| = {np.abs(r - e0).max():.1e}")LassoCV selects alpha and keeps 8 of 10 variables (excluding age and s2). ElasticNetCV, among four mixtures, selects l1_ratio , pure lasso, with the same validation error. This is unsurprising: with , , and one highly correlated pair there are no groups to distribute. Elastic net pays off when is large or variables come in groups. The final two lines confirm conversion between Ridge and ElasticNet to rounding.
The correspondence between libraries, the most common source of errors when comparing results:
| scikit-learn | glmnet (R) | |
|---|---|---|
| Objective | ||
| Our | alpha | lambda |
| Our | l1_ratio | alpha |
| Standardization of | none: do it in the pipeline | standardize=TRUE by default; returns coefficients on original scale |
| Response | unchanged | with family="gaussian", internally standardized (variance using ) to compute its grid |
| Grid | 100 values, | nlambda = 100, lambda.min.ratio if , otherwise |
| Cross-validation | LassoCV, ElasticNetCV (5 folds by default) | cv.glmnet (10 folds), with lambda.min and lambda.1se |
Ridge(alpha=a) minimizes without averaging: it equals ElasticNet(alpha=a/n, l1_ratio=0), as the cell checks. Because it internally standardizes response, glmnet documentation recommends passing already standardized if reproducing results in another program. lambda.1se is the ridge lesson’s one-standard-error rule: the largest with validation error within one standard error of the minimum, giving sparser models with little predictive loss.
Common mistakes
Exercises
Lasso(alpha=0.1) with . A paper writes lasso as . What in the paper gives exactly the same solution?LassoCV on all the data, then estimate the error of least-squares regression on those 15 using 10-fold cross-validation. You obtain a validation of 0.6. What do you conclude?More than one answer may be correct.
Step 1 of 4. What form does take with ?
Step 1 of 4. What condition characterizes a minimum of ?
lasso_cd(X, y, lam, tol=1e-10, max_pasadas=20000), minimizing without an intercept and with columns not necessarily standardized, using cyclic coordinate descent. Maintain the residual and update it in after each coordinate change. Stop when the largest coefficient change in a pass is less than tol. The tests compare with sklearn.linear_model.Lasso(fit_intercept=False) for several , including .import numpy as np
def lasso_cd(X, y, lam, tol=1e-10, max_pasadas=20000):
"""Lasso (1/2n)|y - X b|^2 + lam |b|_1 sin término independiente, por coordenadas cíclicas."""
X = np.asarray(X, dtype=float)
y = np.asarray(y, dtype=float)
n, p = X.shape
b = np.zeros(p)
r = y.copy() # residuo y - X b
curv = (X ** 2).sum(axis=0) / n # curvatura de cada coordenada, |x_j|^2 / n
# tu código: para cada pasada, recorre j, calcula la correlación parcial,
# aplica el umbral suave con el nivel adecuado y actualiza r
return bSummary
- Geometry: the constrained solution lands on a diamond corner for a positive-area set of positions of (a wedge), whereas the L2 ball touches the axes only on a zero-area set.
- Optimality conditions: for active variables and in absolute value for inactive ones; the empty model is optimal if and only if .
- With orthonormal design: hard thresholding (best subset), soft thresholding (lasso) and proportional shrinkage (ridge). Soft thresholding has bounded risk but subtracts from large coefficients.
- Coordinate descent: with partial correlation and the residual updated in ; the path is traversed from using warm starts, an active set and screening rules.
- Elastic net adds an L2 part: a unique solution, up to variables with , and similar coefficients for correlated variables (the grouping effect), at the cost of double shrinkage.
- Lasso is the MAP estimator with a Laplace prior, its path is piecewise linear (LARS), and its degrees of freedom are the expected number of active variables.
- As a selector it is unstable under correlation, inconsistent when irrepresentability fails, and prone to false positives with chosen by cross-validation. Remedies include relaxed lasso, adaptive lasso, stability selection and selective inference.