Module contents
Lesson 5 of 24Core 95 min

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 pp 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 kk, regress on the kk variables that fit best. It is a combinatorial problem ((pk)\binom{p}{k} candidates) and generally NP-hard (Natarajan, 1995). Tibshirani (1996) proposed replacing ∥β∥0≤k\norm{\vb{\beta}}_0 \le k with ∥β∥1≤t\norm{\vb{\beta}}_1 \le t: 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: X∈Rn×p\mat{X} \in \R^{n\times p} with ∑ixij=0\sum_i x_{ij} = 0 and 1n∑ixij2=1\frac1n\sum_i x_{ij}^2 = 1 for each column, ∑iyi=0\sum_i y_i = 0, and an unpenalized intercept (equal to yˉ\bar y in these coordinates). Write xj\vb{x}_j for column jj of X\mat{X}, so ∥xj∥2=n\norm{\vb{x}_j}^2 = n and ρjk=xj⊤xk/n\rho_{jk} = \vb{x}_j\T\vb{x}_k/n is sample correlation between variables jj and kk.

Three comments on the definition:

  • The scale 12n\frac{1}{2n} is used by glmnet and scikit-learn. With it λ\lambda does not depend on nn (the data term is an average) and optimality conditions are clean. Tibshirani used undivided sum of squares, multiplying λ\lambda by 2n2n; be careful comparing numbers across sources.
  • Equivalence of forms. For each tt with an active constraint there is a λ≥0\lambda \ge 0 (the KKT multiplier) with the same solutions, and vice versa. The correspondence is monotone but data-dependent.
  • Existence and uniqueness. FλF_\lambda is convex, continuous and coercive if λ>0\lambda > 0, so it has a minimum. It need not be strictly convex (it certainly is not if p>np > n), but the fit Xβ^\mat{X}\hat{\vb{\beta}} is unique: if two solutions gave different fits, their midpoint would have a strictly lower objective because ∥⋅∥2\norm{\cdot}^2 is strictly convex and ∥⋅∥1\norm{\cdot}_1 convex. If columns of X\mat{X} are in general position (for example, entries have a continuous distribution), the solution is unique with at most min⁡(n,p)\min(n, p) nonzero coefficients (Tibshirani, 2013); with centered data, at most min⁡(n−1,p)\min(n - 1, p), because centering removes a column degree of freedom.

Geometry: the diamond has corners

In two dimensions, 12n∥y−Xβ∥2=cte+12(β−β^MCO)⊤R(β−β^MCO)\frac{1}{2n}\norm{\vb{y} - \mat{X}\vb{\beta}}^2 = \text{cte} + \frac12(\vb{\beta} - \hat{\vb{\beta}}_{\text{MCO}})\T\mat{R}(\vb{\beta} - \hat{\vb{\beta}}_{\text{MCO}}), with R=X⊤X/n\mat{R} = \mat{X}\T\mat{X}/n 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 ∥β∥1≤t\norm{\vb{\beta}}_1 \le t. The L1 ball is a diamond with vertices on the axes. If the ellipse touches it at a vertex, one coefficient is exactly zero.

InteractiveWhy L1 produces zeros
β̂
  • penalty ball
  • loss ellipse touching the ball
  • region with β^2=0\hat\beta_2 = 0
  • region with β^1=0\hat\beta_1 = 0
Penalty
1.00
0.50
Constrained β^\hat{\vb{\beta}}(1.000, 0.000)
β^MCO\hat{\vb{\beta}}_{\text{MCO}}(2.20, 0.80)
Equivalent λ\lambda (penalized form)1.600
Angle of each wedge90.0°
Fraction of the box (outside the ball) with a zero46.2 %
The ellipse touches the ball at a corner: β^2=0\hat\beta_2 = 0 exactly, even though β^MCO,2=0.80\hat\beta_{\text{MCO},2} = 0.80. Any β^MCO\hat{\vb{\beta}}_{\text{MCO}} inside the shaded wedge yields the same corner.
Explicit model: two standardized variables with correlation ρ\rho, so loss is 12(β−β^MCO)⊤R(β−β^MCO)\frac12(\vb{\beta} - \hat{\vb{\beta}}_{\text{MCO}})\T\mat{R}(\vb{\beta} - \hat{\vb{\beta}}_{\text{MCO}}). The violet ball is α∥β∥1+1−α2∥β∥22≤\alpha\norm{\vb{\beta}}_1 + \frac{1-\alpha}{2}\norm{\vb{\beta}}_2^2 \le (its value at (t,0)(t, 0)): L1 if α=1\alpha = 1, L2 if α=0\alpha = 0. Shaded wedges are the exact set of β^MCO\hat{\vb{\beta}}_{\text{MCO}} positions whose constrained solution has a zero coefficient (orange: β^2=0\hat\beta_2 = 0; aqua: β^1=0\hat\beta_1 = 0). Drag β^MCO\hat{\vb{\beta}}_{\text{MCO}} into and out of a wedge, switch to L2 and elastic net, and raise ρ\rho with elastic net.

Initially, β^MCO=(2.2,0.8)\hat{\vb{\beta}}_{\text{MCO}} = (2.2, 0.8), ρ=0.5\rho = 0.5 and t=1t = 1: the ellipse touches the diamond at vertex (1,0)(1, 0), so β^2=0\hat\beta_2 = 0 even though the least-squares estimate of β2\beta_2 is 0.80.8. This is not an accident of position: any β^MCO\hat{\vb{\beta}}_{\text{MCO}} 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 min⁡f\min f over convex KK, a point v∈K\vb{v} \in K is optimal if and only if −∇f(v)-\grad f(\vb{v}) belongs to the normal cone of KK at v\vb{v}, the set of directions u\vb{u} with u⊤(w−v)≤0\vb{u}\T(\vb{w} - \vb{v}) \le 0 for all w∈K\vb{w} \in K. Here −∇f(v)=R(β^MCO−v)-\grad f(\vb{v}) = \mat{R}(\hat{\vb{\beta}}_{\text{MCO}} - \vb{v}). At a smooth boundary point the normal cone is a ray (the curve’s normal). At the diamond’s vertex (t,0)(t, 0) it is an entire cone generated by normals of the two sides meeting there, (1,1)(1, 1) and (1,−1)(1, -1). Thus

β^=(t,0)  ⟺  β^MCO∈(t,0)+R−1{μ(1,s):μ≥0, ∣s∣≤1}.\hat{\vb{\beta}} = (t, 0) \iff \hat{\vb{\beta}}_{\text{MCO}} \in (t, 0) + \mat{R}^{-1}\{\mu(1, s) : \mu \ge 0,\ \abs{s} \le 1\}.

This is a wedge with vertex (t,0)(t, 0) 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, 90°90° and 46.2 %46.2\,\%. (In this symmetric example (1,±1)(1, \pm 1) are eigenvectors of R\mat{R} and the angle does not depend on ρ\rho; generally it does.) With the L2 ball, the boundary is smooth at (t,0)(t, 0), the normal cone is the ray from (1,0)(1, 0) and the region is the dashed ray (t,0)+μR−1(1,0)(t, 0) + \mu\mat{R}^{-1}(1, 0): zero area. If β^MCO\hat{\vb{\beta}}_{\text{MCO}} has a continuous distribution, ridge gives zero with probability zero, while lasso does so with positive probability.

In pp dimensions the argument is the same and the effect stronger. The L1 ball is the cross-polytope: 2p2p vertices (one nonzero coefficient), edges (two), faces of every dimension, and each face of dimension k−1k - 1 has a normal cone of dimension p−k+1p - k + 1. The larger pp, 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 α=0.5\alpha = 0.5 and ρ=0.5\rho = 0.5 wedges narrow to 38.7°38.7° and cover 18.7 %18.7\,\% of the rectangle; at ρ=0.9\rho = 0.9 they narrow to 8°8°. 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. FλF_\lambda is not differentiable where any βj=0\beta_j = 0, so the tool is the subgradient. That of ∣⋅∣\abs{\cdot} at t∈Rt \in \R is

∂∣t∣={{sign⁡(t)}t≠0,[−1,1]t=0.\partial\abs{t} = \begin{cases} \{\operatorname{sign}(t)\} & t \neq 0, \\ [-1, 1] & t = 0. \end{cases}
Proof

FλF_\lambda is convex and finite throughout Rp\R^p, so β^\hat{\vb{\beta}} is a minimum if and only if 0∈∂Fλ(β^)\vb{0} \in \partial F_\lambda(\hat{\vb{\beta}}). The quadratic part is differentiable with gradient −1nX⊤(y−Xβ)-\frac1n\mat{X}\T(\vb{y} - \mat{X}\vb{\beta}), and by the sum rule (valid without additional assumptions when one term is differentiable) the subdifferential of FλF_\lambda is that gradient plus λ ∂∥β∥1\lambda\,\partial\norm{\vb{\beta}}_1. Since ∥⋅∥1\norm{\cdot}_1 is a sum of single-coordinate functions, its subdifferential is the Cartesian product ∂∣β1∣×⋯×∂∣βp∣\partial\abs{\beta_1} \times \cdots \times \partial\abs{\beta_p}. The condition 0∈∂Fλ(β^)\vb{0} \in \partial F_\lambda(\hat{\vb{\beta}}) reads coordinate by coordinate: 1nxj⊤r^∈λ ∂∣β^j∣\frac1n\vb{x}_j\T\hat{\vb{r}} \in \lambda\,\partial\abs{\hat\beta_j}, the statement.

∎

These are the lasso optimality conditions, read as follows: 1nxj⊤r^\frac1n\vb{x}_j\T\hat{\vb{r}} is the correlation (with standardized variables) of variable jj with the residual. All active variables have the same absolute correlation with the residual, exactly λ\lambda, with the sign of their coefficient; inactive ones have at most λ\lambda. A variable enters when its correlation with what remains to explain reaches the common level. Since fit Xβ^\mat{X}\hat{\vb{\beta}} is unique, correlation vector X⊤r^/n\mat{X}\T\hat{\vb{r}}/n is unique too, even if the solution is not.

The immediate consequence, proved in a guided exercise: the empty model β^=0\hat{\vb{\beta}} = \vb{0} is a solution if and only if

λ≥λmax⁡=1nmax⁡j∣xj⊤y∣=1n∥X⊤y∥∞.\lambda \ge \lambda_{\max} = \frac1n\max_j \abs{\vb{x}_j\T\vb{y}} = \frac1n\norm{\mat{X}\T\vb{y}}_\infty.

Above λmax⁡\lambda_{\max} nothing is worth including; just below it, the variable most correlated with y\vb{y} enters. Check this with diabetes data from the ridge lesson (442 patients and 10 clinical variables; response measures disease progression one year later).

[ ]Optimality conditions and λ_max on the diabetes dataBrowser
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 FλF_\lambda with alpha =λ= \lambda (and fits the intercept separately). Active-variable correlations with residual equal ±5\pm 5 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, X⊤X/n=I\mat{X}\T\mat{X}/n = \mat{I}, the problem decouples. With z=X⊤y/n=β^MCO\vb{z} = \mat{X}\T\vb{y}/n = \hat{\vb{\beta}}_{\text{MCO}},

12n∥y−Xβ∥2=12n∥y∥2−z⊤β+12∥β∥2=12∥β−z∥2+cte,\frac{1}{2n}\norm{\vb{y} - \mat{X}\vb{\beta}}^2 = \frac{1}{2n}\norm{\vb{y}}^2 - \vb{z}\T\vb{\beta} + \frac12\norm{\vb{\beta}}^2 = \frac12\norm{\vb{\beta} - \vb{z}}^2 + \text{cte},

and each coefficient is chosen separately. Depending on the penalty:

MethodPenaltyEstimate of βj\beta_jWhat it does
Best subsetλ22∥β∥0\frac{\lambda^2}{2}\norm{\vb{\beta}}_0zj 1[∣zj∣>λ]z_j\,\ind[\abs{z_j} > \lambda]hard thresholding: all or nothing
Lassoλ∥β∥1\lambda\norm{\vb{\beta}}_1S(zj,λ)=sign⁡(zj)(∣zj∣−λ)+S(z_j, \lambda) = \operatorname{sign}(z_j)(\abs{z_j} - \lambda)_+soft thresholding: zeros and shifts
Ridgeλ2∥β∥22\frac{\lambda}{2}\norm{\vb{\beta}}_2^2zj/(1+λ)z_j/(1 + \lambda)proportional shrinkage

The lasso row is soft thresholding, the proximal operator of λ∣⋅∣\lambda\abs{\cdot}; you will prove it in an exercise. Best subset follows by comparing the only two candidates: βj=zj\beta_j = z_j costs λ2/2\lambda^2/2 and βj=0\beta_j = 0 costs zj2/2z_j^2/2. Ridge is the previous lesson’s spectral view with all singular values equal.

InteractiveHard, soft, and ridge
Estimate versus z=β^MCOz = \hat\beta_{\text{MCO}} (orthonormal design)
identity (OLS)
Risk E[(β^−θ)2]\E[(\hat\beta - \theta)^2] with β^MCO∼N(θ,1)\hat\beta_{\text{MCO}} \sim \Normal(\theta, 1)
OLSθ
  • best subset (hard threshold)
  • lasso (soft threshold)
  • ridge (proportional shrinkage)
  • least squares
1.00
z=β^MCOz = \hat\beta_{\text{MCO}}2.50
Best subset (hard)2.500
Lasso (soft)1.500
Ridge1.250
Hard risk at θ=0\theta = 00.801
Soft risk at θ=0\theta = 00.151
Ridge risk at θ=0\theta = 00.250
Maximum hard risk (at θ\theta)1.261 (1.73)
Soft risk as θ→∞\theta \to \infty2.000
For large coefficients, hard has no bias, soft always subtracts λ=1.00\lambda = 1.00 and ridge subtracts a fraction λ/(1+λ)=0.50\lambda/(1+\lambda) = 0.50 of the value: its error grows without bound with θ\theta.
Explicit model: orthonormal design, z=β^MCOz = \hat\beta_{\text{MCO}}, and the table's three rules with the same λ\lambda. Left, estimate against zz; right, closed-form mean squared error E[(β^−θ)2]\E[(\hat\beta - \theta)^2] when z∼N(θ,1)z \sim \Normal(\theta, 1). Move λ\lambda and compare: which wins when the true coefficient is zero, moderate, and large?

The left figure shows bias in large coefficients. Hard thresholding leaves survivors intact. Soft subtracts λ\lambda from everything, even a coefficient of 10 nobody doubted was real. Ridge subtracts a fraction λ/(1+λ)\lambda/(1 + \lambda) 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.

[ ]Risk of the three rules with unit noiseBrowser
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 λ=1\lambda = 1, if the true coefficient is zero, soft thresholding has risk 0.1510.151 versus 0.8010.801 for hard and 11 for least squares. At the same λ\lambda both zero exactly the same zz, those with ∣z∣≤λ\abs{z} \le \lambda (68% of the time with θ=0\theta = 0 and λ=1\lambda = 1); the difference lies in the rest: hard retains all of zz, with error z2>λ2z^2 > \lambda^2, and soft subtracts λ\lambda, with error (∣z∣−λ)2(\abs{z} - \lambda)^2. When the coefficient is large, hard returns to risk 11, while soft stabilizes at 1+λ2=21 + \lambda^2 = 2 and ridge exceeds least squares from θ=1.732\theta = 1.732 and grows as θ2/4\theta^2/4. Hard thresholding pays in the intermediate region: its maximum risk, 1.2611.261 at θ≈1.73\theta \approx 1.73, 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 12(u−c)2+λ∣u∣\frac12(u - c)^2 + \lambda\abs{u} has explicit minimum S(c,λ)S(c, \lambda). 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.

12n∥r(j)−βjxj∥2+λ∣βj∣\frac{1}{2n}\norm{\vb{r}^{(j)} - \beta_j\vb{x}_j}^2 + \lambda\abs{\beta_j}
With other coordinates fixed, FλF_\lambda is this function of βj\beta_j plus a constant. Partial residual r(j)=y−∑k≠jβkxk\vb{r}^{(j)} = \vb{y} - \sum_{k\neq j}\beta_k\vb{x}_k is what remains to explain without variable jj.
1/4

This is coordinate descent for lasso: sweep j=1,…,pj = 1, \dots, p cyclically, soft-thresholding the partial correlation until a pass changes nothing. Without standardized columns, curvature is ∥xj∥2/n\norm{\vb{x}_j}^2/n instead of 1 and the update becomes S(xj⊤r(j)/n,λ)/(∥xj∥2/n)S(\vb{x}_j\T\vb{r}^{(j)}/n, \lambda)/(\norm{\vb{x}_j}^2/n); this is the coordinate-methods version, with effective threshold λn/∥xj∥2\lambda n/\norm{\vb{x}_j}^2 depending on each variable’s units.

InteractiveCoordinate descent step by step
optimum
Profile in β1\beta_1 con β2=1.60\beta_2 = 1.60 fixed: 12u2−c1u+λ∣u∣\tfrac12 u^2 - c_1u + \lambda\abs{u}
Soft threshold S(c,λ)S(c, \lambda) and c1c_1 of this step
  • coordinate path
  • exact optimum
  • profile without penalty (its minimum is cjc_j)
  • thresholds ±λ\pm\lambda
start
0.45
0.60
Updated coordinate(none yet)
Partial correlation c1c_10.540
New β1=S(c1,λ)\beta_1 = S(c_1, \lambda)0.090
Current β\vb{\beta}(−0.400, 1.600)
F(β)−F(β^)F(\vb{\beta}) - F(\hat{\vb{\beta}})1.5873
Optimum β^\hat{\vb{\beta}}(1.050, 0.000)
Explicit model: F(β)=12(β−β^MCO)⊤R(β−β^MCO)+λ∥β∥1F(\vb{\beta}) = \frac12(\vb{\beta} - \hat{\vb{\beta}}_{\text{MCO}})\T\mat{R}(\vb{\beta} - \hat{\vb{\beta}}_{\text{MCO}}) + \lambda\norm{\vb{\beta}}_1 with two variables of correlation ρ\rho. Each step updates one coordinate (1, 2, 1, 2...) and moves the point parallel to an axis. Below, the one-dimensional profile minimized at that step (the dashed parabola is the same profile without penalty, with vertex at partial correlation cjc_j) and where cjc_j falls in soft thresholding. Play the animation and watch the fourth step; then drag the start, raise ρ\rho to 0.9, and count steps.

Initially (β^MCO=(1.5,0)\hat{\vb{\beta}}_{\text{MCO}} = (1.5, 0), ρ=0.6\rho = 0.6, λ=0.45\lambda = 0.45, starting at (−0.4,1.6)(-0.4, 1.6)), the first step sets β1=S(0.54,0.45)=0.09\beta_1 = S(0.54, 0.45) = 0.09, the second β2=S(0.846,0.45)=0.396\beta_2 = S(0.846, 0.45) = 0.396, and the third β1=0.812\beta_1 = 0.812. On the fourth, partial correlation of x2x_2 has fallen to c2=0.413≤λc_2 = 0.413 \le \lambda and thresholding sends it to exact zero: the profile minimum is at the kink of λ∣u∣\lambda\abs{u}. The fifth step takes β1\beta_1 to optimum 1.051.05 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 ρ\rho 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 Fλ(β)−Fλ(β^)F_\lambda(\vb{\beta}) - F_\lambda(\hat{\vb{\beta}}) 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 λ\lambda 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 λ\lambda, so λ\lambda can be chosen by cross-validation. The regularization path is that family, calculated on a decreasing grid

λk=λmax⁡ εk/(K−1),k=0,…,K−1,\lambda_k = \lambda_{\max}\,\eps^{k/(K-1)}, \qquad k = 0, \dots, K - 1,

with K=100K = 100 by default in glmnet and scikit-learn. The ratio ε\eps is 10−310^{-3} in scikit-learn and, in glmnet, 10−410^{-4} if n>pn > p and 10−210^{-2} if n<pn < p (then the problem becomes underdetermined near λ=0\lambda = 0). 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 λk−1\lambda_{k-1} starts the fit at λk\lambda_k. Nearby λ\lambda values have nearby solutions, so each λ\lambda needs few passes. Start at λmax⁡\lambda_{\max}, where the solution 0\vb{0} 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 jj in advance at λk\lambda_k if ∣xj⊤r^(λk−1)∣/n<2λk−λk−1\abs{\vb{x}_j\T\hat{\vb{r}}(\lambda_{k-1})}/n < 2\lambda_k - \lambda_{k-1}. 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 α=1\alpha = 1 (we derive the update in the elastic-net section; here it suffices that it is soft thresholding divided by 1+λ(1−α)1 + \lambda(1 - \alpha)). 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.

[ ]Lasso and elastic net by coordinate descentBrowser
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 2×10−62\times 10^{-6} for coefficients up to 25 (lasso) and 6×10−86\times 10^{-8} (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 λ\lambda values). The L2 part adds λ(1−α)I\lambda(1 - \alpha)\mat{I} to the quadratic matrix X⊤X/n\mat{X}\T\mat{X}/n and improves conditioning, needed here: s1 and s2 have correlation 0.8970.897, so curvature along their difference is only 1−0.897=0.1031 - 0.897 = 0.103 (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 λ\lambda‘s initial transient; the linear convergence tail, dominant with tol=10−8\text{tol} = 10^{-8} and correlated columns, is the same. This is what you saw in coordinate methods, and why glmnet combines warm starts with an active set.

Elastic net

Lasso has three limitations Zou and Hastie (2005) noted when proposing elastic net:

  1. If p>np > n, it selects at most nn variables (when the solution is unique), even if more are relevant.
  2. Among highly correlated variables it tends to keep one and zero the rest; which one depends on sample details.
  3. If n>pn > p 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 λ(1−α)2βj2\frac{\lambda(1-\alpha)}{2}\beta_j^2 to the profile for coordinate jj, becoming 12(1+λ(1−α))βj2−cjβj+λα∣βj∣\frac12(1 + \lambda(1 - \alpha))\beta_j^2 - c_j\beta_j + \lambda\alpha\abs{\beta_j}. Its minimum is
βj←S(cj,λα)1+λ(1−α):\beta_j \leftarrow \frac{S(c_j, \lambda\alpha)}{1 + \lambda(1 - \alpha)}:

soft thresholding at level λα\lambda\alpha followed by ridge-like shrinkage.

  • Optimality conditions and λmax⁡\lambda_{\max}. 1nxj⊤r^=λαsign⁡(β^j)+λ(1−α)β^j\frac1n\vb{x}_j\T\hat{\vb{r}} = \lambda\alpha\operatorname{sign}(\hat\beta_j) + \lambda(1 - \alpha)\hat\beta_j if β^j≠0\hat\beta_j \neq 0, and ∣1nxj⊤r^∣≤λα\abs{\frac1n\vb{x}_j\T\hat{\vb{r}}} \le \lambda\alpha if β^j=0\hat\beta_j = 0. Since the L2 term has zero gradient at 0\vb{0}, the empty model is a solution if and only if λ≥λmax⁡(α)=∥X⊤y∥∞/(nα)\lambda \ge \lambda_{\max}(\alpha) = \norm{\mat{X}\T\vb{y}}_\infty/(n\alpha).
  • Augmented data. With X~=[Xnλ(1−α) Ip]\tilde{\mat{X}} = \begin{bmatrix} \mat{X} \\ \sqrt{n\lambda(1 - \alpha)}\,\mat{I}_p \end{bmatrix} and y~=[y0]\tilde{\vb{y}} = \begin{bmatrix} \vb{y} \\ \vb{0} \end{bmatrix}, 12n∥y~−X~β∥2=12n∥y−Xβ∥2+λ(1−α)2∥β∥2\frac{1}{2n}\norm{\tilde{\vb{y}} - \tilde{\mat{X}}\vb{\beta}}^2 = \frac{1}{2n}\norm{\vb{y} - \mat{X}\vb{\beta}}^2 + \frac{\lambda(1-\alpha)}{2}\norm{\vb{\beta}}^2: elastic net is lasso at level λα\lambda\alpha on n+pn + p rows (Zou and Hastie’s lemma 1 in their parameterization). X~\tilde{\mat{X}} has rank pp, so the objective is strictly convex, the solution unique, and it can have up to pp nonzero coefficients even if p>np > n. 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 x1=x2\vb{x}_1 = \vb{x}_2. For lasso, any split (β1,β2)(\beta_1, \beta_2) with the same sign and sum gives the same fit and penalty ∣β1∣+∣β2∣=∣β1+β2∣\abs{\beta_1} + \abs{\beta_2} = \abs{\beta_1 + \beta_2}: infinitely many solutions, and coordinate descent from zero keeps the first variable visited (the second’s partial correlation then no longer exceeds λ\lambda). Elastic net with α<1\alpha < 1 has a unique solution, and swapping β1\beta_1 and β2\beta_2 does not change the objective, so that solution satisfies β^1=β^2\hat\beta_1 = \hat\beta_2: equal division. Nearly identical columns yield nearly equal division, which can be quantified.

Proof

Since β^i\hat\beta_i and β^j\hat\beta_j are nonzero and have the same sign ss, optimality gives 1nxi⊤r^=λαs+λ(1−α)β^i\frac1n\vb{x}_i\T\hat{\vb{r}} = \lambda\alpha s + \lambda(1 - \alpha)\hat\beta_i and likewise for jj. Subtracting, λ(1−α)(β^i−β^j)=1n(xi−xj)⊤r^\lambda(1 - \alpha)(\hat\beta_i - \hat\beta_j) = \frac1n(\vb{x}_i - \vb{x}_j)\T\hat{\vb{r}}, and Cauchy–Schwarz gives ∣β^i−β^j∣≤∥xi−xj∥ ∥r^∥/(nλ(1−α))\abs{\hat\beta_i - \hat\beta_j} \le \norm{\vb{x}_i - \vb{x}_j}\,\norm{\hat{\vb{r}}}/(n\lambda(1 - \alpha)). With standardized columns, ∥xi−xj∥2=2n−2xi⊤xj=2n(1−ρij)\norm{\vb{x}_i - \vb{x}_j}^2 = 2n - 2\vb{x}_i\T\vb{x}_j = 2n(1 - \rho_{ij}). Also ∥r^∥≤∥y∥\norm{\hat{\vb{r}}} \le \norm{\vb{y}}, because the objective at β^\hat{\vb{\beta}} is no greater than at 0\vb{0}, which is ∥y∥2/(2n)\norm{\vb{y}}^2/(2n), and the penalty is nonnegative. Combining gives ∣β^i−β^j∣≤2n(1−ρij) ∥y∥/(nλ(1−α))\abs{\hat\beta_i - \hat\beta_j} \le \sqrt{2n(1 - \rho_{ij})}\,\norm{\vb{y}}/(n\lambda(1 - \alpha)), as claimed.

∎

As ρij→1\rho_{ij} \to 1, the difference tends to zero: nearly identical variables receive nearly identical coefficients. Lasso (α=1\alpha = 1) has no such bound. The figure shows a model where three highly correlated variables have exactly the same effect.

InteractivePaths with correlated variables
Lasso (α=1\alpha = 1)
−1.0−0.50.00.51.01.5λmaxλmax/10λmax/100λmax/1000
Elastic net (α=0.50\alpha = 0.50)
−1.0−0.50.00.51.01.5λmaxλmax/10λmax/100λmax/1000
  • x1x_1 (group)
  • x2x_2 (group)
  • x3x_3 (group)
  • x4x_4 (effect 1.5)
  • x5x_5 (effect −1)
  • x6,x7,x8x_6, x_7, x_8 (no effect)
0.95
1
0.50
0.60
Lasso: β^1,β^2,β^3\hat\beta_1, \hat\beta_2, \hat\beta_3 in this sample0.00, 1.08, 1.25
Lasso, 30 samples: active group variables (mean)2.63
Lasso, 30 samples: within-group standard deviation0.463
Lasso: largest is x1,x2,x3x_1, x_2, x_3 (times out of 30)4 / 13 / 13
Elastic net: β^1,β^2,β^3\hat\beta_1, \hat\beta_2, \hat\beta_3 in this sample0.56, 0.65, 0.64
Elastic net, 30 samples: active group variables3.00
Elastic net, 30 samples: within-group standard deviation0.039
Group sum: lasso, elastic net (truth 3)2.33, 1.85
With ρ=0.95\rho = 0.95 lasso gives the group mean dispersion 0.46 versus 0.04 for elastic net: which variable carries the weight depends on the sample, not the symmetric model.
Explicit model: n=100n = 100, x1,x2,x3x_1, x_2, x_3 correlated at ρ\rho, independent x4,…,x8x_4, \dots, x_8, and y=x1+x2+x3+1.5x4−x5+1.5εy = x_1 + x_2 + x_3 + 1.5x_4 - x_5 + 1.5\eps. Paths use warm-start coordinate descent at 60 λ\lambda values (from λmax⁡\lambda_{\max} to λmax⁡/1000\lambda_{\max}/1000, each method using its own). Readouts repeat fitting on 30 samples from the same model and measure, at the dashed line, how many group variables remain active and how much their coefficients differ. Change seed at ρ=0.95\rho = 0.95 and see which group variable carries the lasso weight; then lower ρ\rho to 0.5.

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 λ=λmax⁡/4\lambda = \lambda_{\max}/4 for lasso and the same L1 part (equal λα\lambda\alpha) for elastic net with α=0.5\alpha = 0.5.

[ ]A correlated group: lasso versus elastic netBrowser
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 ρ=0.5\rho = 0.5 both methods keep all three variables active and differ little (within-group standard deviation 0.1880.188 versus 0.1010.101). At ρ=0.99\rho = 0.99, lasso keeps an average 1.651.65 of three active with within-group standard deviation 0.8300.830; elastic net always keeps all three, with 0.0210.021. The group variable with the largest lasso coefficient is x1x_1, x2x_2, or x3x_3 in 4, 8, and 8 of 20 samples: sampling chance selects it. In the last sample lasso gives (0,0.884,1.141)(0, 0.884, 1.141) and elastic net (0.535,0.553,0.553)(0.535, 0.553, 0.553). The grouping theorem’s bound explains the difference: with 1−ρ=0.011 - \rho = 0.01, factor 2(1−ρ)=0.14\sqrt{2(1 - \rho)} = 0.14 forces elastic net to give nearly equal coefficients. At the other extreme, ridge (the limit α→0\alpha \to 0) distributes equally well but does not zero any no-effect variables x6x_6, x7x_7, and x8x_8: elastic net takes the best of both, and its α\alpha is therefore selected by cross-validation with λ\lambda.

Double shrinkage

The sum of group coefficients shows elastic net’s price. Truth is 3; lasso gives 2.212.21 on average at ρ=0.99\rho = 0.99 and elastic net 1.761.76. Both shrink, elastic net more. In the orthonormal case its solution is S(zj,λα)/(1+λ(1−α))S(z_j, \lambda\alpha)/(1 + \lambda(1 - \alpha)): 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 1+λ21 + \lambda_2 (in their parameterization; 1+λ(1−α)1 + \lambda(1 - \alpha) in ours with standardized columns). glmnet and scikit-learn do not apply that correction: they return the naive version and let cross-validation choose λ\lambda and α\alpha 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 y∣β∼N(Xβ,σ2In)\vb{y} \given \vb{\beta} \sim \Normal(\mat{X}\vb{\beta}, \sigma^2\mat{I}_n) and independent βj\beta_j with density 12be−∣βj∣/b\frac{1}{2b}e^{-\abs{\beta_j}/b},

−log⁡p(β∣y)=12σ2∥y−Xβ∥2+1b∥β∥1+cte.-\log p(\vb{\beta} \given \vb{y}) = \frac{1}{2\sigma^2}\norm{\vb{y} - \mat{X}\vb{\beta}}^2 + \frac1b\norm{\vb{\beta}}_1 + \text{cte}.

Multiplying by σ2/n\sigma^2/n, which does not change the minimizer, the MAP estimator is lasso with λ=σ2/(nb)\lambda = \sigma^2/(nb): a more concentrated prior (smaller scale bb) 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 exp⁡{−c(α∣β∣+1−α2β2)}\exp\{-c(\alpha\abs{\beta} + \frac{1-\alpha}{2}\beta^2)\}, 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, P(βj=0∣y)=0\Pr(\beta_j = 0 \given \vb{y}) = 0: 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 λ\lambda where active set AA and signs sA\vb{s}_A do not change, and suppose XA\mat{X}_A (active columns) has full rank. Active optimality conditions, 1nXA⊤(y−XAβA)=λsA\frac1n\mat{X}_A\T(\vb{y} - \mat{X}_A\vb{\beta}_A) = \lambda\vb{s}_A, give

β^A(λ)=(XA⊤XA)−1(XA⊤y−nλ sA),\hat{\vb{\beta}}_A(\lambda) = (\mat{X}_A\T\mat{X}_A)^{-1}\big(\mat{X}_A\T\vb{y} - n\lambda\,\vb{s}_A\big),

an affine function of λ\lambda. The lasso path is piecewise linear, with knots at λ\lambda values where an event occurs: an inactive variable reaches ∣xj⊤r^∣/n=λ\abs{\vb{x}_j\T\hat{\vb{r}}}/n = \lambda and enters, or an active coefficient reaches zero and leaves. Both times follow from linear equations in λ\lambda, 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 pp in the worst case, as Mairal and Yu proved in 2012), each requiring a factorization update, while each point on a warm-start λ\lambda grid costs a few cheap passes.

Lasso degrees of freedom

The degrees of freedom of a fit y^\hat{\vb{y}} are df=1σ2∑iCov⁡(y^i,yi)\mathrm{df} = \frac{1}{\sigma^2}\sum_i\Cov(\hat y_i, y_i). For ridge this was ∑jdj2/(dj2+λ)\sum_j d_j^2/(d_j^2 + \lambda). Lasso is adaptive (it chooses variables by looking at y\vb{y}), so one might expect extra degrees of freedom, as with best subset, whose df\mathrm{df} exceeds its number of chosen variables (Ye, 1998). The result is cleaner:

The proof idea uses Stein’s lemma: if y^(y)\hat{\vb{y}}(\vb{y}) is Lipschitz, ∑iCov⁡(y^i,yi)=σ2E[∑i∂y^i/∂yi]\sum_i\Cov(\hat y_i, y_i) = \sigma^2\E[\sum_i \partial\hat y_i/\partial y_i]. The lasso fit is continuous and piecewise linear in y\vb{y} and, for almost every y\vb{y}, AA and sA\vb{s}_A are locally constant. There, by the preceding formula, y^=HAy−nλXA(XA⊤XA)−1sA\hat{\vb{y}} = \mat{H}_A\vb{y} - n\lambda\mat{X}_A(\mat{X}_A\T\mat{X}_A)^{-1}\vb{s}_A, with HA\mat{H}_A the projection onto col⁡(XA)\col(\mat{X}_A). The second term does not depend on y\vb{y}, so divergence is tr⁡HA=∣A∣\tr\mat{H}_A = \abs{A}. The hard part is proving local constancy, not the calculation. The cell checks the calculation by finite differences.

[ ]The Jacobian of the lasso fit is a projectorBrowser
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 3.00003.0000, the Jacobian agrees with projection HA\mat{H}_A to 10−910^{-9}, 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 y\vb{y} adds degrees of freedom; shrinking coefficients toward zero by the fixed amount nλ(XA⊤XA)−1sAn\lambda(\mat{X}_A\T\mat{X}_A)^{-1}\vb{s}_A removes them. Practically, the result gives a cheap information criterion for choosing λ\lambda: Cp=∥y−y^∥2+2σ2∣A∣C_p = \norm{\vb{y} - \hat{\vb{y}}}^2 + 2\sigma^2\abs{A}.

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 SS be the true support of β∗\vb{\beta}^* and C=X⊤X/n\mat{C} = \mat{X}\T\mat{X}/n the correlation matrix, partitioned into blocks CSS\mat{C}_{SS}, CScS\mat{C}_{S^cS}.

Proof

Suppose β^\hat{\vb{\beta}} has support SS and signs s\vb{s}. Since 1nX⊤r^=C(β∗−β^)\frac1n\mat{X}\T\hat{\vb{r}} = \mat{C}(\vb{\beta}^* - \hat{\vb{\beta}}), active conditions give CSS(βS∗−β^S)=λs\mat{C}_{SS}(\vb{\beta}^*_S - \hat{\vb{\beta}}_S) = \lambda\vb{s}, namely β^S=βS∗−λCSS−1s\hat{\vb{\beta}}_S = \vb{\beta}^*_S - \lambda\mat{C}_{SS}^{-1}\vb{s}. Inactive conditions give ∣CjS(βS∗−β^S)∣=λ∣CjSCSS−1s∣≤λ\abs{\mat{C}_{jS}(\vb{\beta}^*_S - \hat{\vb{\beta}}_S)} = \lambda\abs{\mat{C}_{jS}\mat{C}_{SS}^{-1}\vb{s}} \le \lambda for j∉Sj \notin S, the stated condition. Conversely, if it holds, take λ>0\lambda > 0 small enough that βS∗−λCSS−1s\vb{\beta}^*_S - \lambda\mat{C}_{SS}^{-1}\vb{s} has signs s\vb{s} (such a value exists because no component of βS∗\vb{\beta}^*_S is zero). That vector, completed with zeros, satisfies all optimality conditions, sufficient by convexity.

∎

The quantity CScSCSS−1s\mat{C}_{S^cS}\mat{C}_{SS}^{-1}\vb{s} 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 ≤1−η\le 1 - \eta for some η>0\eta > 0) suffices with regularity conditions, and the weak version (≤1\le 1) 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.

InteractiveThe irrepresentability condition
Population lasso path (no noise): β^j(λ)\hat\beta_j(\lambda) with λ\lambda decreasing to the right
−1.0−0.50.00.51.0λ/λmax = 10.750.500.250.00
  • β^1\hat\beta_1 (true 1)
  • β^2\hat\beta_2 (true 1)
  • β^3\hat\beta_3 (true 0)
0.60
True coefficients β∗\vb{\beta}^*
∣C3SCSS−1sign⁡(βS∗)∣\abs{\mat{C}_{3S}\mat{C}_{SS}^{-1}\operatorname{sign}(\vb{\beta}^*_S)}1.200
Population: does any λ>0\lambda > 0 give exact support?no
Population: x3x_3 enters at λ/λmax⁡\lambda/\lambda_{\max}1.000
200 samples (n=100n = 100, σ=1\sigma = 1): exact support at some λ\lambda46 %
The condition fails (1.20>11.20 > 1): with no noise and infinite data, no λ>0\lambda > 0 gives the correct support. x3x_3 “represents” both x1x_1 and x2x_2.
Explicit model: independent x1x_1 and x2x_2, and x3x_3 correlated at ρ\rho with each (C\mat{C} positive definite if ρ<1/2\rho < 1/\sqrt 2); β∗=(1,±1,0)\vb{\beta}^* = (1, \pm 1, 0). Above, the exact population path (no noise, infinite data). The irrepresentability quantity is ρ∣1±1∣\rho\abs{1 \pm 1}. Readouts also show 200 finite samples with n=100n = 100 and noise σ=1\sigma = 1: the percentage with some path λ\lambda having correct support and signs. Raise ρ\rho from 0.4 to 0.6 with equal signs; then change signs.

The example can be solved by hand. With β∗=(1,1,0)\vb{\beta}^* = (1, 1, 0) and s=(1,1)\vb{s} = (1, 1), CSS=I\mat{C}_{SS} = \mat{I} and C3SCSS−1s=2ρ\mat{C}_{3S}\mat{C}_{SS}^{-1}\vb{s} = 2\rho: the condition fails if ρ>0.5\rho > 0.5. It then fails in the worst way. Since 1nX⊤y=Cβ∗=(1+0,0+1,2ρ)\frac1n\mat{X}\T\vb{y} = \mat{C}\vb{\beta}^* = (1 + 0, 0 + 1, 2\rho) and 2ρ>12\rho > 1, the first variable to enter is x3x_3, the one with no effect. While alone, β^3=2ρ−λ\hat\beta_3 = 2\rho - \lambda. The other two enter together at λ=(1−2ρ2)/(1−ρ)\lambda = (1 - 2\rho^2)/(1 - \rho) (0.7 at ρ=0.6\rho = 0.6), and from then on, with β^1=β^2\hat\beta_1 = \hat\beta_2 by symmetry, active conditions for all three give

β^3(λ)=(2ρ−1)λ1−2ρ2>0para todo λ>0,\hat\beta_3(\lambda) = \frac{(2\rho - 1)\lambda}{1 - 2\rho^2} > 0 \quad \text{para todo } \lambda > 0,

so x3x_3 never leaves: it tends to zero with λ\lambda but vanishes for no positive λ\lambda. With β∗=(1,−1,0)\vb{\beta}^* = (1, -1, 0) and the same ρ\rho, the quantity is ρ∣1−1∣=0\rho\abs{1 - 1} = 0 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 ρ=0.6\rho = 0.6, 46% of samples do have some λ\lambda with correct support. Repeat the proof’s reasoning with sample data. Let κ=C^3SC^SS−1s\kappa = \hat{\mat{C}}_{3S}\hat{\mat{C}}_{SS}^{-1}\vb{s} be sample irrepresentability and η=z3−C^3SC^SS−1zS\eta = z_3 - \hat{\mat{C}}_{3S}\hat{\mat{C}}_{SS}^{-1}\vb{z}_S, with z=X⊤y/n\vb{z} = \mat{X}\T\vb{y}/n, be sample partial correlation of x3x_3 with response, which would be 0 without noise. The x3x_3 condition for the candidate with support SS is ∣η+κλ∣≤λ\abs{\eta + \kappa\lambda} \le \lambda. If κ>1\kappa > 1, it holds for some λ>0\lambda > 0 only if η<0\eta < 0, then for λ≥∣η∣/(κ−1)\lambda \ge \abs{\eta}/(\kappa - 1): noise randomly pushes x3x_3‘s partial correlation against its bias and a λ\lambda on the noise scale exploits it. This is a coin toss that does not improve with more data. The cell checks it.

[ ]Irrepresentability with noise: who succeeds and whyBrowser
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 ρ=0.2\rho = 0.2 (population quantity 0.4), all samples have some λ\lambda with correct support, and at ρ=0.4\rho = 0.4 91% do; failures are samples where noise raised sample κ\kappa above 1. At ρ=0.6\rho = 0.6 mean sample κ\kappa is 1.211.21 and 49% succeed. The division is exact: among samples with κ>1\kappa > 1, all with η<0\eta < 0 succeed and none with η>0\eta > 0 do. Since η\eta is zero-centered noise for any nn, that half does not disappear with more data, but cannot be exploited either: knowing which λ\lambda to choose would require knowing the support. Zhao and Yu study λ\lambda dominating noise (λn→∞\lambda\sqrt{n} \to \infty in our scale), to which the proof’s argument applies directly.

Choosing λ by cross-validation selects too much

The λ\lambda minimizing prediction error is not the one recovering support. Good prediction favors small λ\lambda (soft-threshold bias costs error), and small λ\lambda admits spurious variables with tiny coefficients. Meinshausen and Bühlmann (2006) proved that prediction-optimal λ\lambda does not generally yield consistent selection. The next lab measures this.

Remedies

  • Relaxed lasso (Meinshausen, 2007): use lasso with a λ\lambda to choose support AλA_\lambda, then refit on it with a smaller penalty ϕλ\phi\lambda with ϕ∈[0,1]\phi \in [0, 1], choosing (λ,ϕ)(\lambda, \phi) 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 ϕ β^λlasso+(1−ϕ) β^AλMCO\phi\,\hat{\vb{\beta}}^{\text{lasso}}_\lambda + (1 - \phi)\,\hat{\vb{\beta}}^{\text{MCO}}_{A_\lambda}, 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 λ∑jwj∣βj∣\lambda\sum_j w_j\abs{\beta_j} with weights wj=1/∣β~j∣γw_j = 1/\abs{\tilde\beta_j}^\gamma from an initial estimate β~\tilde{\vb{\beta}}, so large coefficients are penalized little. With fixed pp 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 (±1\pm 1, spaced 50 positions apart). Variables follow an AR(1) process, corr⁡(xj,xk)=ρ∣j−k∣\operatorname{corr}(x_j, x_k) = \rho^{\abs{j - k}}, so each relevant variable has correlated neighbors. For each ρ\rho, fit LassoCV and ElasticNetCV (with α=0.5\alpha = 0.5) using 5-fold cross-validation on a grid of 20 λ\lambda values from λmax⁡\lambda_{\max} to λmax⁡/100\lambda_{\max}/100 (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.

[ ]Support recovery with p = 500 and n = 100Browser
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 ρ≤0.5\rho \le 0.5, 9 at ρ=0.9\rho = 0.9), 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 λ\lambda 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 λ\lambda is chosen by cross-validation, lasso tends to select a small λ\lambda 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 (λ,ϕ)(\lambda, \phi) with 5-fold cross-validation, and compares it with pure lasso (ϕ=1\phi = 1, with λ\lambda chosen by the same validation) on 10 problems (n=100n = 100, p=50p = 50, 5 nonzero coefficients, noise σ=2\sigma = 2), measuring error on 2,000 test points.

[ ]Relaxed lasso versus cross-validated lassoBrowser
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 16.216.2 variables, over three times the 5 true ones, with test error 4.974.97 at noise variance 4. Relaxed lasso keeps 5.65.6 variables, reduces error to 4.544.54, and wins in 7 of 10 problems. All chose ϕ=0\phi = 0: pure least squares on support from a λ\lambda between 1.81.8 and 5.95.9 times larger than lasso’s, because a small λ\lambda 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 λ\lambda gives 5.545.54, worse than lasso itself, because it includes that support’s spurious variables without shrinkage (at least 16.2−5=11.216.2 - 5 = 11.2 on average). Bias is also visible in coefficients: that of x1x_1, truly 3, is 2.592.59 with lasso and 2.872.87 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).

[ ]LassoCV and ElasticNetCV in a pipelineBrowser
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 =0.846= 0.846 and keeps 8 of 10 variables (excluding age and s2). ElasticNetCV, among four mixtures, selects l1_ratio =1= 1, pure lasso, with the same validation error. This is unsurprising: with n=442n = 442, p=10p = 10, and one highly correlated pair there are no groups to distribute. Elastic net pays off when pp 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-learnglmnet (R)
Objective12nRSS+alpha⋅l1_ratio∥β∥1+alpha(1−l1_ratio)2∥β∥22\frac{1}{2n}\mathrm{RSS} + \texttt{alpha}\cdot\texttt{l1\_ratio}\norm{\vb{\beta}}_1 + \frac{\texttt{alpha}(1 - \texttt{l1\_ratio})}{2}\norm{\vb{\beta}}_2^212nRSS+λ(1−α2∥β∥22+α∥β∥1)\frac{1}{2n}\mathrm{RSS} + \lambda\big(\frac{1-\alpha}{2}\norm{\vb{\beta}}_2^2 + \alpha\norm{\vb{\beta}}_1\big)
Our λ\lambdaalphalambda
Our α\alphal1_ratioalpha
Standardization of X\mat{X}none: do it in the pipelinestandardize=TRUE by default; returns coefficients on original scale
Responseunchangedwith family="gaussian", internally standardized (variance using 1/n1/n) to compute its λ\lambda grid
Grid100 values, ε=10−3\eps = 10^{-3}nlambda = 100, lambda.min.ratio 10−410^{-4} if n>pn > p, otherwise 10−210^{-2}
Cross-validationLassoCV, ElasticNetCV (5 folds by default)cv.glmnet (10 folds), with lambda.min and lambda.1se

Ridge(alpha=a) minimizes RSS+a∥β∥2\mathrm{RSS} + a\norm{\vb{\beta}}^2 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 y\vb{y} if reproducing results in another program. lambda.1se is the ridge lesson’s one-standard-error rule: the largest λ\lambda with validation error within one standard error of the minimum, giving sparser models with little predictive loss.

Common mistakes

Exercises

NumericHow many survive?
With an orthonormal design (X⊤X/n=I\mat{X}\T\mat{X}/n = \mat{I}), the least-squares estimate is β^MCO=(3,−0.5,1.2)\hat{\vb{\beta}}_{\text{MCO}} = (3, -0.5, 1.2). How many nonzero coefficients does lasso have with λ=1\lambda = 1?
NumericWhere the elastic net path starts
With standardized columns, the correlations with the response are X⊤y/n=(0.8,−1.4,0.3)\mat{X}\T\vb{y}/n = (0.8, -1.4, 0.3). What is the smallest λ\lambda for which elastic net with α=0.5\alpha = 0.5 gives the empty model?
NumericTwo copies of the same variable
A problem has only two identical standardized columns, x1=x2=x\vb{x}_1 = \vb{x}_2 = \vb{x}, with x⊤y/n=1\vb{x}\T\vb{y}/n = 1. You fit elastic net with λ=0.2\lambda = 0.2 and α=0.5\alpha = 0.5. What is β^1\hat\beta_1?
NumericThe λ of a Laplace prior
In a linear model with Gaussian noise of standard deviation σ=2\sigma = 2 and n=100n = 100 observations, you put a Laplace prior of scale b=0.05b = 0.05 on each coefficient. What lasso λ\lambda, in the scale 12n∥y−Xβ∥2+λ∥β∥1\frac{1}{2n}\norm{\vb{y} - \mat{X}\vb{\beta}}^2 + \lambda\norm{\vb{\beta}}_1, gives the MAP estimator?
QuizTwo identical variables
Two columns of X\mat{X} are identical and the variable has a real effect. What does elastic net do with a mixture 0<α<10 < \alpha < 1?
QuizThe same lasso on another scale
You fit scikit-learn's Lasso(alpha=0.1) with n=200n = 200. A paper writes lasso as min⁡β∥y−Xβ∥2+λ∥β∥1\min_{\vb{\beta}} \norm{\vb{y} - \mat{X}\vb{\beta}}^2 + \lambda\norm{\vb{\beta}}_1. What λ\lambda in the paper gives exactly the same solution?
QuizA variable sneaks in
In the irrepresentability figure's example, x1⊥x2x_1 \perp x_2, corr⁡(x3,x1)=corr⁡(x3,x2)=0.6\operatorname{corr}(x_3, x_1) = \operatorname{corr}(x_3, x_2) = 0.6 and β∗=(1,1,0)\vb{\beta}^* = (1, 1, 0), with no noise and infinitely many observations. Which statement is true?
QuizValidation that looks too good
With n=100n = 100 and p=2000p = 2000, you select 15 variables using 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 R2R^2 of 0.6. What do you conclude?
QuizWhat can be said about lasso
Which statements hold for lasso with fixed λ>0\lambda > 0 and standardized X\mat{X}?

More than one answer may be correct.

ProofSoft thresholding with orthonormal design
Prove: If X⊤X/n=I\mat{X}\T\mat{X}/n = \mat{I}, the lasso solution is β^j=sign⁡(zj)(∣zj∣−λ)+\hat\beta_j = \operatorname{sign}(z_j)(\abs{z_j} - \lambda)_+, with z=β^MCO=X⊤y/n\vb{z} = \hat{\vb{\beta}}_{\text{MCO}} = \mat{X}\T\vb{y}/n.
0
Start with Fλ(β)=12n∥y−Xβ∥2+λ∥β∥1F_\lambda(\vb{\beta}) = \frac{1}{2n}\norm{\vb{y} - \mat{X}\vb{\beta}}^2 + \lambda\norm{\vb{\beta}}_1 with λ>0\lambda > 0.

Step 1 of 4. What form does FλF_\lambda take with X⊤X/n=I\mat{X}\T\mat{X}/n = \mat{I}?

ProofWhen lasso selects nothing
Prove: β^=0\hat{\vb{\beta}} = \vb{0} is the lasso solution if and only if λ≥λmax⁡=max⁡j∣xj⊤y∣/n\lambda \ge \lambda_{\max} = \max_j\abs{\vb{x}_j\T\vb{y}}/n.
0
Fλ(β)=12n∥y−Xβ∥2+λ∥β∥1F_\lambda(\vb{\beta}) = \frac{1}{2n}\norm{\vb{y} - \mat{X}\vb{\beta}}^2 + \lambda\norm{\vb{\beta}}_1 with λ>0\lambda > 0.

Step 1 of 4. What condition characterizes a minimum of FλF_\lambda?

CodeLasso by coordinate descent
Implement lasso_cd(X, y, lam, tol=1e-10, max_pasadas=20000), minimizing 12n∥y−Xβ∥2+λ∥β∥1\frac{1}{2n}\norm{\vb{y} - \mat{X}\vb{\beta}}^2 + \lambda\norm{\vb{\beta}}_1 without an intercept and with columns not necessarily standardized, using cyclic coordinate descent. Maintain the residual r=y−Xβ\vb{r} = \vb{y} - \mat{X}\vb{\beta} and update it in O(n)\bigO(n) 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 λ\lambda, including p>np > n.
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 b
Shift+Enter to run

Summary

Key idea
Lasso replaces ridge’s L2 ball with the L1 ball, whose corners lie on the axes: this is why it sets coefficients exactly to zero. Optimality conditions (all active variables have correlation λ\lambda with the residual, inactive ones less) explain it, soft thresholding computes it coordinate by coordinate, and elastic net stabilizes it for correlated variables. As an estimator it is excellent; as a variable selector it is reliable only under conditions that must be checked.
  • Geometry: the constrained solution lands on a diamond corner for a positive-area set of positions of β^MCO\hat{\vb{\beta}}_{\text{MCO}} (a wedge), whereas the L2 ball touches the axes only on a zero-area set.
  • Optimality conditions: 1nxj⊤r^=λsign⁡(β^j)\frac1n\vb{x}_j\T\hat{\vb{r}} = \lambda\operatorname{sign}(\hat\beta_j) for active variables and ≤λ\le \lambda in absolute value for inactive ones; the empty model is optimal if and only if λ≥λmax⁡=∥X⊤y∥∞/n\lambda \ge \lambda_{\max} = \norm{\mat{X}\T\vb{y}}_\infty/n.
  • With orthonormal design: hard thresholding (best subset), soft thresholding (lasso) and proportional shrinkage (ridge). Soft thresholding has bounded risk but subtracts λ\lambda from large coefficients.
  • Coordinate descent: βj←S(cj,λα)/(1+λ(1−α))\beta_j \leftarrow S(c_j, \lambda\alpha)/(1 + \lambda(1 - \alpha)) with partial correlation cj=1nxj⊤r+βjc_j = \frac1n\vb{x}_j\T\vb{r} + \beta_j and the residual updated in O(n)\bigO(n); the path is traversed from λmax⁡\lambda_{\max} using warm starts, an active set and screening rules.
  • Elastic net adds an L2 part: a unique solution, up to pp variables with p>np > n, 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 λ\lambda chosen by cross-validation. Remedies include relaxed lasso, adaptive lasso, stability selection and selective inference.