Skip to content
E
Educatum

Why is L1 supposed to lead to sparsity than L2?

Curated by Educatum AI teamLast updated:
Regularization Techniques
Direct Answer

L1 regularization induces sparsity because its constraint region is a cross-polytope (a diamond in 2D) with sharp corners lying directly on the coordinate axes, where one or more weights equal zero. Expanding elliptical loss contours are much more likely to hit a sharp axial corner of the L1 diamond than to intersect a smooth L2 hypersphere exactly on an axis. Analytically, L1's constant subgradient magnitude pushes small weights all the way to zero, whereas L2's gradient fades proportionally toward zero.

Study Card: Why L1 Regularization Leads to Sparsity

Direct Answer

L1 regularization (Lasso) produces sparse parameter vectors (many weights equal to exact 00) whereas L2 regularization (Ridge) shrinks weights toward 00 without zeroing them out. This difference arises from both optimization geometry and gradient dynamics:

  1. Constrained Geometry: Minimizing empirical loss plus a penalty is equivalent via Lagrangian duality to minimizing loss inside a norm ball:

    • L1 constraint: ∑j=1p∣βj∣≤s\sum_{j=1}^p |\beta_j| \le s defines a diamond (cross-polytope in Rp\mathbb{R}^p) whose sharp vertices sit on the coordinate axes where one or more coefficients are zero. As the elliptical contours of the unregularized loss expand outward from the OLS optimum, they typically first touch a corner of the diamond.
    • L2 constraint: ∑j=1pβj2≤s\sum_{j=1}^p \beta_j^2 \le s defines a smooth circle (hypersphere in Rp\mathbb{R}^p—not an ellipse) with no corners; an expanding ellipse almost never strikes the circle at an exact axis point.
  2. Subgradients and KKT Conditions: In the penalized objective L(β)+λ∑j∣βj∣\mathcal{L}(\boldsymbol{\beta}) + \lambda \sum_j |\beta_j|, the L1 subgradient has constant magnitude λ\lambda anywhere βj≠0\beta_j \neq 0, setting β^j=0\hat{\beta}_j = 0 whenever the unregularized gradient at zero satisfies ∣∂L∂βj∣≤λ\left|\frac{\partial \mathcal{L}}{\partial \beta_j}\right| \le \lambda (yielding soft-thresholding). By contrast, L2’s penalty gradient 2λβj2\lambda \beta_j diminishes linearly as βj→0\beta_j \to 0, shrinking weights asymptotically rather than zeroing them.

Key Terms

  • Sparsity: A parameter vector containing many exact zeros, enabling automatic feature selection and compact models.
  • L1 Penalty: λ∑j=1p∣βj∣\lambda \sum_{j=1}^{p} |\beta_j| (non-differentiable at βj=0\beta_j = 0, forming sharp vertices on axes).
  • L2 Penalty: λ∑j=1pβj2\lambda \sum_{j=1}^{p} \beta_j^2 (smooth everywhere with a spherical constraint boundary).
  • Soft-Thresholding: Closed-form proximal step Sλ(z)=sign⁡(z)max⁡(∣z∣−λ,0)S_{\lambda}(z) = \operatorname{sign}(z)\max(|z| - \lambda, 0) induced by L1 penalties.
  • Subgradient: Generalization of the derivative to convex non-differentiable functions (for ∣β∣|\beta|, the subdifferential at 00 is [−1,1][-1, 1]).

Example

Consider regression with two parameters β1\beta_1 and β2\beta_2, where β1\beta_1 predicts the target strongly and β2\beta_2 corresponds to noise (so the unregularized minimum sits near (β^1,β^2)≈(3.0,0.2)(\hat{\beta}_1, \hat{\beta}_2) \approx (3.0, 0.2)). Because the elliptical MSE contours reach a tight L1 diamond ∣β1∣+∣β2∣≤s|\beta_1| + |\beta_2| \le s at its horizontal vertex (β1=s,β2=0)(\beta_1 = s, \beta_2 = 0), Lasso sets β2=0\beta_2 = 0 exactly. Under an L2 circle β12+β22≤s\beta_1^2 + \beta_2^2 \le s, the smooth tangency stays slightly off the β1\beta_1-axis, keeping β2\beta_2 small but non-zero.

Code Implementation

import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import Lasso, Ridge

# 1. Visualize MSE loss contours vs. L1 (diamond) and L2 (circle) constraint regions
rng = np.random.default_rng(42)
n = 100
x1 = rng.normal(size=n)
x2 = rng.normal(size=n)
y = 3.0 * x1 + 0.4 * x2 + rng.normal(scale=0.5, size=n)

b1_vals = np.linspace(-1, 5, 120)
b2_vals = np.linspace(-3, 3, 120)
B1, B2 = np.meshgrid(b1_vals, b2_vals)
# Vectorized MSE surface over (b1, b2)
Z = np.mean((y[:, None, None] - (B1[None, :, :] * x1[:, None, None] + B2[None, :, :] * x2[:, None, None])) ** 2, axis=0)

fig, axes = plt.subplots(1, 2, figsize=(12, 5))
budgets = [1.5, 2.5]

# L1 Diamond plot
axes[0].contour(B1, B2, Z, levels=20, cmap="viridis")
for s in budgets:
    axes[0].plot(s * np.array([-1, 0, 1, 0, -1]), s * np.array([0, 1, 0, -1, 0]), "r-", lw=2, label=f"L1 budget s={s}")
axes[0].axhline(0, color="grey", lw=0.6)
axes[0].axvline(0, color="grey", lw=0.6)
axes[0].set_xlim(-1.5, 4.5)
axes[0].set_ylim(-3.0, 3.0)
axes[0].set_aspect("equal")
axes[0].set_title("L1 (Lasso): Loss Contours vs. Diamond Constraint")
axes[0].set_xlabel(r"$\beta_1$")
axes[0].set_ylabel(r"$\beta_2$")
axes[0].legend()
axes[0].grid(True, alpha=0.3)

# L2 Circle plot
axes[1].contour(B1, B2, Z, levels=20, cmap="viridis")
theta = np.linspace(0, 2 * np.pi, 200)
for s in budgets:
    axes[1].plot(s * np.cos(theta), s * np.sin(theta), "b-", lw=2, label=f"L2 radius sqrt(s)={s}")
axes[1].axhline(0, color="grey", lw=0.6)
axes[1].axvline(0, color="grey", lw=0.6)
axes[1].set_xlim(-1.5, 4.5)
axes[1].set_ylim(-3.0, 3.0)
axes[1].set_aspect("equal")
axes[1].set_title("L2 (Ridge): Loss Contours vs. Circle Constraint")
axes[1].set_xlabel(r"$\beta_1$")
axes[1].set_ylabel(r"$\beta_2$")
axes[1].legend()
axes[1].grid(True, alpha=0.3)

plt.tight_layout()
plt.show()

# 2. Demonstrate exact sparsity on 2 features (1 informative, 1 pure noise)
X_2d = np.column_stack([x1, rng.normal(size=n)])
y_sparse = 3.0 * X_2d[:, 0] + rng.normal(scale=0.5, size=n)

lasso = Lasso(alpha=0.2).fit(X_2d, y_sparse)
ridge = Ridge(alpha=5.0).fit(X_2d, y_sparse)
print("True weights:   [3.0, 0.0]")
print("Lasso weights: ", np.round(lasso.coef_, 4))
print("Ridge weights: ", np.round(ridge.coef_, 4))
  • Lagrange Multipliers / KKT Optimality: Formally connect constrained norm budgets ≤s\le s to penalized multipliers λ\lambda.
  • Coordinate Descent & Proximal Gradient (ISTA): Standard efficient solvers for non-smooth L1 objectives using soft-thresholding.
  • Elastic Net: Combines L1 and L2 to preserve sparsity while sharing weights evenly among correlated features (where pure Lasso arbitrarily selects one).
  • Basis Pursuit: Compressed sensing optimization finding sparse solutions to underdetermined linear systems via L1 minimization.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.