Skip to content
E
Educatum

Why L1 and L2 are Commonly Used for Regularization

Curated by Educatum AI teamLast updated:
Regularization TechniquesRegularization
Direct Answer

L1 and L2 norms dominate regularization because they strike the optimal balance between statistical usefulness, convexity, and computational tractability. Ideal sparsity (L0 pseudo-norm) requires NP-hard combinatorial subset search, whereas L1 is its tightest convex relaxation and yields sparse models efficiently, and squared L2 is strictly convex, smooth everywhere, and admits a closed-form linear solution in Ridge regression. Probabilistically, L1 and L2 correspond directly to Laplace and Gaussian MAP priors.

Study Card: Why L1 and L2 are Commonly Used for Regularization

Direct Answer

Among infinitely many vector penalties (L0,LpL_0, L_p for 0<p<10 < p < 1, L1,L2,L∞L_1, L_2, L_\infty), L1 and L2 dominate machine learning because they pair complementary regularization behavior with tractable convex optimization:

  • Why not L0L_0 or LpL_p (0<p<10 < p < 1)? The L0L_0 pseudo-norm (∥w∥0\|\mathbf{w}\|_0, counting non-zeros; not a true norm because it violates homogeneity) directly enforces sparsity, but subset selection is combinatorial and NP-hard in general. Fractional penalties (0<p<10 < p < 1) are non-convex with many local optima.
  • Why L1? The L1 norm (∥w∥1=∑j∣wj∣\|\mathbf{w}\|_1 = \sum_j |w_j|) is the tightest convex relaxation of L0L_0 on unit-bounded weights, enabling fast global optimization (coordinate descent, proximal gradient) while still inducing exact zeros.
  • Why L2? The squared L2 penalty (∥w∥22=∑jwj2\|\mathbf{w}\|_2^2 = \sum_j w_j^2) is smooth, differentiable everywhere, strictly convex, rotationally invariant, and—in Ridge linear regression—yields the closed-form solution β^ridge=(X⊤X+λI)−1X⊤y\hat{\boldsymbol{\beta}}_{\text{ridge}} = (X^\top X + \lambda I)^{-1} X^\top \mathbf{y} that stabilizes ill-conditioned matrices.
  • Why not L∞L_\infty? While convex, max⁡j∣wj∣\max_j |w_j| penalizes only the largest-magnitude coordinate(s), offering weak control over remaining weights and tending to push weights toward uniform magnitudes rather than sparsity.
  • Bayesian MAP equivalence: Adding L2 corresponds to a zero-mean Gaussian prior on weights, while adding L1 corresponds to a sharper Laplace prior.

Key Terms

  • Convexity: Ensures local optima are global optima, enabling reliable convergence.
  • L0L_0 Pseudo-Norm: Counts non-zero parameters; ideal theoretically for sparsity but NP-hard to optimize at scale.
  • L∞L_\infty Norm: max⁡j∣wj∣\max_j |w_j|; convex but non-smooth and penalizes only extreme coordinates.
  • Ridge Closed-Form Solution: (X⊤X+λI)−1X⊤y(X^\top X + \lambda I)^{-1} X^\top \mathbf{y} (for linear regression), always invertible whenever λ>0\lambda > 0.
  • MAP Estimation: Maximum A Posteriori inference unifying empirical loss minimization with prior weight regularization.

Example

Consider fitting a model with 1,000 candidate features where only 10 truly matter. Exhaustive L0L_0 search would require evaluating (100010)>1023\binom{1000}{10} > 10^{23} subsets—completely infeasible. L1 (Lasso) solves a single convex problem in milliseconds to select a sparse active subset, while L2 (Ridge) cleanly regularizes correlated features in closed form (for linear regression) or via smooth gradients (for neural networks). By contrast, L∞L_\infty primarily caps the largest single coefficient while leaving smaller noisy weights unpenalized.

Code Implementation

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

# Generate zero-intercept data so fit_intercept=False compares L1, L2, and L-inf fairly
rng = np.random.default_rng(0)
X = rng.normal(size=(120, 2))
y = 3.0 * X[:, 0] + rng.normal(scale=0.5, size=120)

lasso = Lasso(alpha=0.1, fit_intercept=False).fit(X, y)
ridge = Ridge(alpha=10.0, fit_intercept=False).fit(X, y)


def l_infinity_loss(beta, X, y, alpha):
    residuals = y - X @ beta
    return 0.5 * np.sum(residuals ** 2) + alpha * np.max(np.abs(beta))


# Use derivative-free Powell method because max(|beta|) is non-smooth
res_inf = minimize(l_infinity_loss, np.zeros(2), args=(X, y, 10.0), method="Powell")

print("True weights:        [3.0, 0.0]")
print("Lasso (L1) weights: ", np.round(lasso.coef_, 4))
print("Ridge (L2) weights: ", np.round(ridge.coef_, 4))
print("L-infinity weights: ", np.round(res_inf.x, 4))

# Visualize 2D geometry: L1 norm vs. Squared L2 (Ridge penalty) vs. L-inf norm
b1 = np.linspace(-2, 2, 80)
b2 = np.linspace(-2, 2, 80)
B1, B2 = np.meshgrid(b1, b2)

L1 = np.abs(B1) + np.abs(B2)
L2_sq = B1 ** 2 + B2 ** 2
L_inf = np.maximum(np.abs(B1), np.abs(B2))

fig = plt.figure(figsize=(15, 4.5))
for idx, (Z, title) in enumerate([
    (L1, "L1 Norm (|b1| + |b2|)"),
    (L2_sq, "Squared L2 Penalty (b1^2 + b2^2)"),
    (L_inf, "L-infinity Norm (max(|b1|, |b2|))"),
], start=1):
    ax = fig.add_subplot(1, 3, idx, projection="3d")
    ax.plot_surface(B1, B2, Z, cmap="viridis", alpha=0.85)
    ax.set_title(title)
    ax.set_xlabel("b1")
    ax.set_ylabel("b2")

plt.tight_layout()
plt.show()
  • Optimization Solvers: Smooth squared L2 supports standard gradient descent, L-BFGS, or closed-form linear solves; non-smooth L1 uses coordinate descent or proximal gradient methods.
  • Elastic Net: Bridges L1 and L2 when correlated predictors cause pure L1 to be unstable.
  • Matrix Conditioning: Adding λI\lambda I to X⊤XX^\top X lifts eigenvalues from σi2\sigma_i^2 to σi2+λ\sigma_i^2 + \lambda, fixing multicollinearity.
  • Regularization Path: Tracing coefficients across λ\lambda values shows how L1 enters features sequentially while L2 shrinks all weights continuously.
View all →

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