MML204

Lasso Regression

⏱7 min read👁️Eye-Care Reading Mode

What you'll learn

  • Why Lasso (Least Absolute Shrinkage and Selection Operator) uniquely performs automatic feature selection.
  • How the geometry of the L1L_1 diamond constraint produces exact zeros (βj=0\beta_j = 0), unlike the smooth L2L_2 circle of Ridge.
  • Why the non-differentiable absolute value function prevents a closed-form matrix inverse and necessitates subgradients.
  • The Karush-Kuhn-Tucker (KKT) optimality conditions governing sparse solutions.
  • The closed-form Soft-Thresholding Operator S(z,t)=sign(z)max⁡(∣z∣−t,0)\mathcal{S}(z, t) = \text{sign}(z)\max(|z| - t, 0).
  • How the Coordinate Descent algorithm solves Lasso by cycling through one parameter at a time.
  • How to determine the all-zero threshold λmax⁡\lambda_{\max} and select the optimal hyperparameter via cross-validation.

Explained in detail

1. The Big Picture: What is Lasso Regression?

In machine learning and statistics, we often encounter datasets with dozens or hundreds of candidate features, many of which may be irrelevant, noisy, or redundant.

While Ordinary Least Squares (OLS) assigns a non-zero weight to every available feature, and Ridge Regression shrinks coefficients toward zero without ever discarding any, Lasso Regression (Least Absolute Shrinkage and Selection Operator) accomplishes two tasks simultaneously:

  1. Regularization: It prevents overfitting by shrinking coefficient magnitudes.
  2. Feature Selection: It drives uninformative or redundant coefficients to exactly zero, producing a sparse, interpretable model.

The Lasso objective function is:

J(β)=∑i=1n(yi−∑j=1pXijβj)2⏟RSS (Data Mismatch)+λ∑j=1p∣βj∣⏟L1 Penalty (Sparsity)J(\boldsymbol{\beta}) = \underbrace{\sum_{i=1}^{n} \left( y_i - \sum_{j=1}^{p} X_{ij}\beta_j \right)^2}_{\text{RSS (Data Mismatch)}} + \underbrace{\lambda \sum_{j=1}^{p} |\beta_j|}_{L_1\text{ Penalty (Sparsity)}}

In matrix notation:

J(β)=∥y−Xβ∥22+λ∥β∥1J(\boldsymbol{\beta}) = \|\mathbf{y} - \mathbf{X}\boldsymbol{\beta}\|_2^2 + \lambda \|\boldsymbol{\beta}\|_1

where λ≥0\lambda \ge 0 is the regularization tuning parameter.

Penalty LevelValue of λ\lambdaModel Behavior
No Regularizationλ=0\lambda = 0Penalty vanishes; equivalent to unregularized OLS.
Moderate Regularizationλ>0\lambda > 0Weak features are pruned to exact zero; informative features are shrunk.
Maximum Thresholdλ≥λmax⁡\lambda \ge \lambda_{\max}The penalty is so dominant that all coefficients become zero (null model).

2. The L1L_1 Penalty and Geometric Intuition

To understand why Lasso produces exact zeros while Ridge does not, we examine the problem from a constrained optimization perspective (Lagrangian duality):

min⁡βRSS(β)subject to∑j=1p∣βj∣≤s\min_{\boldsymbol{\beta}} \text{RSS}(\boldsymbol{\beta}) \quad \text{subject to} \quad \sum_{j=1}^{p} |\beta_j| \le s

where ss is an allowable coefficient budget inversely related to λ\lambda.

Comparison between L1 diamond geometry and L2 circular geometry

In 2D parameter space (β1,β2)(\beta_1, \beta_2):

  • The OLS Contours (Blue Ellipses): Centered at the unconstrained minimum β^OLS\hat{\boldsymbol{\beta}}_{\text{OLS}}. Each ellipse traces parameter combinations that share identical Residual Sum of Squares.
  • The L2L_2 Constraint (Ridge Circle): The constraint β12+β22≤s\beta_1^2 + \beta_2^2 \le s is a smooth sphere/circle. The expanding ellipse touches the circle along its smooth curved edge, retaining non-zero values for both parameters.
  • The L1L_1 Constraint (Lasso Diamond): The constraint ∣β1∣+∣β2∣≤s|\beta_1| + |\beta_2| \le s is a rotated square (diamond) whose sharp corners (vertices) lie precisely on the coordinate axes: (±s,0)and(0,±s)(\pm s, 0) \quad \text{and} \quad (0, \pm s)

Why Corners Cause Exact Zeros

Because the diamond constraint has sharp pointy corners aligned with the coordinate axes, the expanding elliptical RSS contours have a very high mathematical probability of first making contact with the boundary at a corner!

When contact occurs at the corner (s,0)(s, 0), parameter β2\beta_2 is strictly zero:

β^1=s,β^2=0\hat{\beta}_1 = s, \qquad \hat{\beta}_2 = 0

Feature x2x_2 is completely pruned from the model!


3. Optimization: Why Doesn't Lasso Have a Matrix Inverse?

Students often ask: Why can we invert a matrix to solve Ridge β^Ridge=(XTX+λI)−1XTy\hat{\boldsymbol{\beta}}_{\text{Ridge}} = (\mathbf{X}^T\mathbf{X} + \lambda \mathbf{I})^{-1}\mathbf{X}^T\mathbf{y}, but cannot do the same for Lasso?

The answer lies in calculus. The absolute value function ∣x∣|x| has a sharp, non-differentiable corner (kink) at x=0x = 0:

ddx∣x∣={+1,x>0−1,x<0undefined,x=0\frac{d}{dx}|x| = \begin{cases} +1, & x > 0 \\ -1, & x < 0 \\ \text{undefined}, & x = 0 \end{cases}

Because the derivative does not exist at zero, we cannot differentiate the objective using standard calculus to set up a linear system of equations.

Subgradients

For non-differentiable convex functions, we generalize the derivative using subgradients. A scalar gg is a subgradient of a convex function ff at point xx if the line with slope gg passing through (x,f(x))(x, f(x)) lies everywhere on or below the graph of ff.

For the absolute value function f(x)=∣x∣f(x) = |x|, the subdifferential is:

∂∣x∣={{+1},x>0[−1,1],x=0{−1},x<0\partial |x| = \begin{cases} \{+1\}, & x > 0 \\ [-1, 1], & x = 0 \\ \{-1\}, & x < 0 \end{cases}

At the sharp corner x=0x = 0, any slope between −1-1 and +1+1 is a valid subgradient! This continuous interval [−1,1][-1, 1] is the exact mathematical mechanism that allows solutions to lock onto zero across a wide range of data configurations.

The subgradient optimality condition for Lasso is:

0∈2XT(Xβ^−y)+λ∂∥β^∥1\mathbf{0} \in 2\mathbf{X}^T(\mathbf{X}\hat{\boldsymbol{\beta}} - \mathbf{y}) + \lambda \partial \|\hat{\boldsymbol{\beta}}\|_1

4. Karush-Kuhn-Tucker (KKT) Optimality Conditions

Let xj\mathbf{x}_j denote the jj-th column of X\mathbf{X}, and let r=y−Xβ^\mathbf{r} = \mathbf{y} - \mathbf{X}\hat{\boldsymbol{\beta}} denote the final residual vector. The jj-th coordinate condition from the subgradient equation is:

0∈−2xjTr+λ∂∣β^j∣0 \in -2\mathbf{x}_j^T\mathbf{r} + \lambda \partial |\hat{\beta}_j|

Evaluating the three cases of the subdifferential ∂∣β^j∣\partial |\hat{\beta}_j| yields the Coordinate-wise KKT Conditions:

2xjTr=λ,if β^j>02xjTr=−λ,if β^j<0∣2xjTr∣≤λ,if β^j=0\begin{aligned} 2\mathbf{x}_j^T\mathbf{r} &= \lambda, &\quad &\text{if } \hat{\beta}_j > 0 \\ 2\mathbf{x}_j^T\mathbf{r} &= -\lambda, &\quad &\text{if } \hat{\beta}_j < 0 \\ |2\mathbf{x}_j^T\mathbf{r}| &\le \lambda, &\quad &\text{if } \hat{\beta}_j = 0 \end{aligned}
💡

The KKT Threshold Intuition: For a feature to have a non-zero coefficient, its sample correlation with the residual (2xjTr2\mathbf{x}_j^T\mathbf{r}) must hit the upper or lower boundary ±λ\pm \lambda. If its correlation falls within the interior deadband [−λ,λ][-\lambda, \lambda], the feature is not informative enough to justify its L1L_1 penalty cost, and its coefficient remains locked at exact zero!


5. The Soft-Thresholding Operator

When predictors are orthogonal (XTX=I\mathbf{X}^T\mathbf{X} = \mathbf{I}), the multivariate Lasso problem uncouples into pp independent scalar minimization problems. Each coordinate solution is given by the Soft-Thresholding Operator:

S(z,t)=sign(z)max⁡(∣z∣−t,0)\mathcal{S}(z, t) = \text{sign}(z) \max(|z| - t, 0)

Equivalently written piecewise:

S(z,t)={z−t,z>t0,−t≤z≤tz+t,z<−t\mathcal{S}(z, t) = \begin{cases} z - t, & z > t \\ 0, & -t \le z \le t \\ z + t, & z < -t \end{cases}

Soft-thresholding operator with threshold t = 2 showing the deadband where values are zeroed

Notice how soft-thresholding operates:

  1. Deadband [−t,t][-t, t]: Any input whose magnitude is less than or equal to tt is snapped strictly to zero!
  2. Outside the Deadband: Inputs exceeding tt in magnitude are preserved, but shrunk toward zero by a constant offset of tt.

6. The Coordinate Descent Algorithm

Because we cannot solve for all pp coefficients simultaneously in one matrix inversion, how do modern libraries (like scikit-learn and glmnet) solve Lasso? They use Coordinate Descent.

Flowchart of the coordinate descent optimization loop

The Core Idea

Instead of updating all parameters at once, Coordinate Descent minimizes the objective with respect to one coordinate βj\beta_j at a time, while keeping all other p−1p - 1 coordinates fixed at their current values.

Let rj\mathbf{r}_j be the partial residual calculated by removing the effect of feature jj:

rj=y−∑k≠jxkβk=y−Xβ+xjβj\mathbf{r}_j = \mathbf{y} - \sum_{k \ne j} \mathbf{x}_k \beta_k = \mathbf{y} - \mathbf{X}\boldsymbol{\beta} + \mathbf{x}_j \beta_j

The single-coordinate subproblem reduces to:

min⁡βj∥rj−xjβj∥22+λ∣βj∣\min_{\beta_j} \|\mathbf{r}_j - \mathbf{x}_j \beta_j\|_2^2 + \lambda |\beta_j|

This univariate problem has a closed-form solution given directly by soft-thresholding!

The Coordinate Update Formula

βjnew=S(xjTrj, λ2)xjTxj\beta_j^{\text{new}} = \frac{\mathcal{S}\left(\mathbf{x}_j^T\mathbf{r}_j, \, \frac{\lambda}{2}\right)}{\mathbf{x}_j^T\mathbf{x}_j}

When features are standardized so that xjTxj=1\mathbf{x}_j^T\mathbf{x}_j = 1, the update simplifies to:

βjnew=S(xjTrj, λ2)\beta_j^{\text{new}} = \mathcal{S}\left(\mathbf{x}_j^T\mathbf{r}_j, \, \frac{\lambda}{2}\right)

Numerical Example

Suppose for feature jj, xjTrj=7\mathbf{x}_j^T\mathbf{r}_j = 7, xjTxj=4\mathbf{x}_j^T\mathbf{x}_j = 4, and penalty λ=2\lambda = 2 (so threshold t=λ/2=1t = \lambda/2 = 1):

S(7,1)=7−1=6  ⟹  βjnew=64=1.5\mathcal{S}(7, 1) = 7 - 1 = 6 \implies \beta_j^{\text{new}} = \frac{6}{4} = 1.5

If instead the correlation was weak, say xjTrj=0.6\mathbf{x}_j^T\mathbf{r}_j = 0.6:

S(0.6,1)=0  ⟹  βjnew=0.0\mathcal{S}(0.6, 1) = 0 \implies \beta_j^{\text{new}} = 0.0

The coefficient is instantly pruned!

The algorithm repeatedly cycles through coordinates j=1,2,…,pj = 1, 2, \dots, p until the maximum coefficient change falls below a convergence tolerance ϵ\epsilon (e.g., 10−410^{-4}).


7. Practical Modeling: Scaling and Choosing λ\lambda

Mandatory Feature Standardization

Because the L1L_1 penalty sums the raw absolute values ∑∣βj∣\sum |\beta_j|, features measured in large units (e.g., house price in millions vs. number of bathrooms) will have arbitrarily small coefficients and escape penalization.

Always standardize features using training set statistics:

zij=xij−xˉjsjz_{ij} = \frac{x_{ij} - \bar{x}_j}{s_j}

The All-Zero Threshold (λmax⁡\lambda_{\max})

At what penalty value do all coefficients become zero? Using the KKT conditions at β=0\boldsymbol{\beta} = \mathbf{0}, every coordinate condition ∣2xjTy∣≤λ|2\mathbf{x}_j^T\mathbf{y}| \le \lambda must hold. Thus:

λmax⁡=2max⁡j=1,…,p∣xjTy∣\lambda_{\max} = 2 \max_{j=1,\dots,p} |\mathbf{x}_j^T\mathbf{y}|

Any λ≥λmax⁡\lambda \ge \lambda_{\max} yields the trivial null model β^=0\hat{\boldsymbol{\beta}} = \mathbf{0}. Effective grids for hyperparameter search typically span logarithmically from λmax⁡\lambda_{\max} down to 10−4λmax⁡10^{-4}\lambda_{\max}.

Cross-Validation Workflow

We select the optimal λ\lambda using KK-Fold Cross-Validation:

Five-fold cross-validation workflow: training on 4 folds, testing on 1 holdout

Regularization path showing coefficients dropping to zero one by one

  1. Regularization Path: As λ\lambda is decreased from λmax⁡\lambda_{\max}, features enter the active set one by one.
  2. λmin\lambda_{\text{min}} vs λ1se\lambda_{\text{1se}}: We can select the λ\lambda with the absolute lowest cross-validation error (λmin\lambda_{\text{min}}), or use the 1-Standard-Error rule (λ1se\lambda_{\text{1se}})—the simplest (sparsest) model whose error is within one standard error of the minimum.

8. Strengths & Limitations of Lasso

Strengths

  • Interpretability: Prunes irrelevant features, leaving a compact, readable formula.
  • High-Dimensional Regression (p>np > n): When there are more features than observations, OLS is undefined. Lasso can select at most nn predictors and provides stable estimates.

Limitations & Motivation for Elastic Net

  1. Correlated Predictor Selection: When two features are strongly collinear (r≈0.99r \approx 0.99), Lasso tends to arbitrarily select one and zero out the other.
  2. Constraint on Active Set: If p>np > n, Lasso can never select more than nn variables.
  3. Over-Shrinkage of Large Slopes: Because the penalty subtracts a constant offset tt from all surviving coefficients, true large signals may suffer excess bias.

These limitations motivate Elastic Net, which combines both L1L_1 (Lasso) and L2L_2 (Ridge) penalties: λ1∥β∥1+λ2∥β∥22\lambda_1 \|\boldsymbol{\beta}\|_1 + \lambda_2 \|\boldsymbol{\beta}\|_2^2.

Figure 3.5: Lasso Diamond Geometry & Exact Sparsity

β̂_Lasso:[2.57, 0.04]ᵀ
Active Features:2 of 2
||β̂||₁ (L1):2.61
Model State:Dense Model
Lasso Regularization Penalty (λ = 3.5)3.50
010

Interactive Lasso Regularization. The sharp corners of the L₁ diamond constraint ||β||₁ ≤ s lie directly on coordinate axes. When the expanding RSS contour touches a corner, the corresponding parameter drops exactly to zero (automatic feature selection).

What to try

  • Move the λ\lambda Slider:
    • In Diamond L1L_1 Geometry View: Watch the amber diamond shrink as λ\lambda increases. Notice the moment contact hits the horizontal axis corner (β2\beta_2 drops to exact 0.000.00 while β1\beta_1 remains active).
    • Toggle "+ Compare Ridge Circle": See how the green circular L2L_2 boundary touches the ellipse along a curve, keeping both parameters non-zero, while Lasso snaps to the corner.
  • Switch to "Soft Thresholding":
    • Examine the red shaded deadband [−λ2,+λ2][-\frac{\lambda}{2}, +\frac{\lambda}{2}]. Notice how any input within this window is clamped to zero.
  • Switch to "Regularization Paths":
    • Watch β2\beta_2 intersect the horizontal axis at λ≈3.4\lambda \approx 3.4 and remain flat at zero.

Key ideas at a glance

Summary Reference Table

Feature / PropertyOrdinary Least SquaresRidge (L2L_2)Lasso (L1L_1)
Penalty TermNoneλ∑βj2\lambda \sum \beta_j^2$\lambda \sum
Constraint ShapeNoneSmooth circle / sphereSharp diamond / octahedron
Analytical SolutionYes: (XTX)−1XTy(\mathbf{X}^T\mathbf{X})^{-1}\mathbf{X}^T\mathbf{y}Yes: (XTX+λI)−1XTy(\mathbf{X}^T\mathbf{X} + \lambda \mathbf{I})^{-1}\mathbf{X}^T\mathbf{y}No closed-form (solved via Coordinate Descent)
DifferentiabilityEverywhere differentiableEverywhere differentiableNon-differentiable at βj=0\beta_j = 0 (uses Subgradients)
Feature SelectionNo (all features non-zero)No (shrinks close to zero, never exact zero)Yes (drives coefficients to exact zero)
Core OptimizerNormal equationsLinear matrix inversionCoordinate Descent & Soft-Thresholding
Handling p>np > nFails (singular matrix)Works (stabilizes matrix)Works (selects at most nn features)
Feature ScalingOptionalMandatoryMandatory

Check your understanding

🧩

Ready to test yourself?

15 questions · explanations shown after


Teach & Solidify

🎓
Feynman Teaching Card

Teach This: Lasso Regression (L1 Regularization)

Core Intuition

Lasso minimizes RSS + λ∑|βⱼ|. Its sharp diamond constraint drives uninformative coefficients to exact zero, performing simultaneous regularization and automatic feature selection via Coordinate Descent.

Key Concepts to Explain

  • 1Lasso uses an L₁ penalty: ∑|βⱼ|.
  • 2Sharp diamond corners on the axes make tangency occur at exact zero (sparsity).
  • 3The kink at zero requires subgradient calculus: ∂|0| = [-1, 1].
  • 4KKT conditions require |2xⱼᵀr| ≤ λ for a coefficient to remain zero.
  • 5Coordinate Descent optimizes one feature at a time using the closed-form Soft-Thresholding Operator.
  • 6Features must be standardized, and λ is tuned via K-fold cross-validation.

⚠️ What Most Students Get Confused About

Believing Lasso has a closed-form matrix formula like Ridge. Because the absolute value is non-differentiable at zero, Lasso cannot be solved with a simple matrix inverse; it must be solved iteratively via Coordinate Descent.

✍️
Active Recall Practice

Explain Lasso Regression in your own words

Imagine you are explaining this idea to a friend or classmate with no math background. Writing it out forces your brain to bridge gaps in your intuition.

Saved locally on your device

Resources & GitHub

🎯

Mastered this concept?

Tick this box when you feel confident explaining it.

📁
Study Notes & Files3 files

Topic Resources

GitHub↗
📕

Lasso_Regression.pdf

PDF Note

537.3 KB · Modified Latest

📐

Lasso_Regression_Notes.tex

LaTeX Source

26.4 KB · Modified Latest

📝

Lasso_Regression_Summary.md

Markdown Note

2.0 KB · Modified Latest

Was this clear?