Skip to content
E
Educatum

L1 VS L2

Curated by Educatum AI teamLast updated:
Regularization TechniquesRegularization
Direct Answer

L1 (Lasso) and L2 (Ridge) regularization prevent overfitting by adding a weight penalty to the training loss. L1 penalizes the sum of absolute weights and drives irrelevant coefficients to exactly zero for automatic feature selection, whereas L2 penalizes the sum of squared weights to shrink all coefficients smoothly toward zero without eliminating them.

Study Card: L1 vs L2 Regularization

Direct Answer

L1 (Lasso) and L2 (Ridge) regularization reduce overfitting by adding a complexity penalty to the empirical loss function:

LL1(β)=Loss(β)+λ∑j=1p∣βj∣,LL2(β)=Loss(β)+λ∑j=1pβj2\mathcal{L}_{\text{L1}}(\beta) = \text{Loss}(\beta) + \lambda \sum_{j=1}^{p} |\beta_j|, \qquad \mathcal{L}_{\text{L2}}(\beta) = \text{Loss}(\beta) + \lambda \sum_{j=1}^{p} \beta_j^2

L1 regularization adds a penalty proportional to the absolute value of the coefficients (λ∥β∥1\lambda \|\beta\|_1), creating a diamond-shaped constraint region whose corners lie on the coordinate axes; this promotes sparsity by driving weak coefficients to exact zero. L2 regularization adds a penalty proportional to the square of the coefficients (λ∥β∥22\lambda \|\beta\|_2^2), creating a smooth hyperspherical constraint that shrinks all coefficients toward zero proportionally, strongly dampening large weights while keeping features non-zero. Because both penalties depend on parameter magnitudes, features should be standardized beforehand.

Key Terms

  • Sparsity: The property of a model having many coefficients equal to zero, enabling implicit feature selection.
  • L1 Norm (∥β∥1\|\beta\|_1): Sum of absolute coefficient values ∑j∣βj∣\sum_j |\beta_j|, whose constant subgradient magnitude away from zero pushes small coefficients all the way to zero.
  • L2 Norm Squared (∥β∥22\|\beta\|_2^2): Sum of squared coefficient values ∑jβj2\sum_j \beta_j^2, whose gradient 2λβj2\lambda \beta_j shrinks large weights aggressively while letting small weights approach zero asymptotically.
  • Feature Selection: Identifying and retaining a subset of informative features while discarding irrelevant ones.
  • Coefficient Shrinkage: Constraining parameter magnitudes to reduce model variance and sensitivity to noise.

Example

Consider a linear regression model with 100 features predicting sales based on advertising spend across channels, where many channels have negligible impact:

  • L1 Regularization (Lasso): Sets coefficients for uninformative channels (e.g., radio or billboard ads) to exactly 0.0, leaving a compact, interpretable model:
    • Example coefficients with L1: [1.2, 0.0, 3.5, 0.0, 0.8, ..., 0.0]
  • L2 Regularization (Ridge): Shrinks all coefficients toward zero and spreads weight across correlated channels, without forcing them to exact zero:
    • Example coefficients with L2: [1.1, 0.2, 3.2, 0.1, 0.7, ..., 0.1]

Numerically, for two coefficients β1=10\beta_1 = 10 and β2=2\beta_2 = 2 with λ=0.5\lambda = 0.5, the L1 penalty is 0.5(∣10∣+∣2∣)=60.5(|10| + |2|) = 6, while the L2 penalty is 0.5(102+22)=520.5(10^2 + 2^2) = 52. L2 penalizes large magnitudes quadratically, yielding strong shrinkage on dominant coefficients.

Code Implementation

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

# Generate synthetic data with many features, only a few being relevant
np.random.seed(42)
n_samples, n_features = 50, 100
X = np.random.randn(n_samples, n_features)
true_coef = np.zeros(n_features)
true_coef[:5] = np.random.randn(5)  # Only first 5 features are relevant
y = X.dot(true_coef) + 0.5 * np.random.randn(n_samples)

# Split data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Fit Lasso (L1) regression
lasso = Lasso(alpha=0.1)  # alpha controls regularization strength
lasso.fit(X_train, y_train)

# Fit Ridge (L2) regression
ridge = Ridge(alpha=1.0)
ridge.fit(X_train, y_train)

# Plot coefficients
plt.figure(figsize=(10, 6))
plt.plot(lasso.coef_, label='Lasso (L1) Coefficients', marker='o')
plt.plot(ridge.coef_, label='Ridge (L2) Coefficients', marker='x')
plt.plot(true_coef, label='True Coefficients', marker='*')

plt.xlabel('Coefficient Index')
plt.ylabel('Coefficient Value')
plt.title('Lasso vs Ridge Coefficients')
plt.legend()
plt.grid(True)

# Annotate the plot with sparsity information
lasso_sparsity = np.sum(lasso.coef_ == 0)
ridge_sparsity = np.sum(ridge.coef_ == 0)
plt.text(0.6, 0.8, f'Lasso Sparsity (zero coefs): {lasso_sparsity}', transform=plt.gca().transAxes)
plt.text(0.6, 0.75, f'Ridge Sparsity (zero coefs): {ridge_sparsity}', transform=plt.gca().transAxes)

plt.show()
  • Elastic Net Regularization: Combines L1 and L2 penalties (λ1∥β∥1+λ2∥β∥22\lambda_1 \|\beta\|_1 + \lambda_2 \|\beta\|_2^2), preserving sparsity while avoiding L1’s instability among strongly correlated features (and overcoming Lasso’s limit of selecting at most nn features when p>np > n).
  • Bias-Variance Tradeoff: Both L1 and L2 trade a small increase in bias for substantial variance reduction; L2 is particularly effective against multicollinearity.
  • Gradient Descent & Proximal Updates: L2 adds a smooth 2λβ2\lambda \beta term to gradients (weight decay), whereas L1 is non-differentiable at 0 and typically optimized with subgradients, coordinate descent, or soft-thresholding proximal steps.
  • Feature Importance: Lasso yields sparse models directly, though correlated features can make which feature gets non-zero weight arbitrary.
  • Regularization Strength (λ\lambda / alpha): Tuned via cross-validation; note that the intercept term is customarily excluded from both L1 and L2 penalties.
  • Bayesian Interpretation: In MAP estimation with Gaussian errors, L1 corresponds to a Laplace prior and L2 corresponds to a zero-mean Gaussian prior.
View all →

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