Regularization Mastery: Ridge (L2), Lasso (L1) & ElasticNet
Why L1 diamonds create exact zeros, L2 smoothness on collinear features, ElasticNet grouping, unpenalized intercepts & Feature Selection
Regularization adds a penalty on the size of model weights (L2 for Ridge, L1 for Lasso, both for ElasticNet) directly into the loss function.
Without regularization, models with many or correlated features assign huge, unstable weights that memorize training noise and collapse on new data.
Without regularization, wide real-world datasets (500+ features) overfit brutally and collinear weights explode to ±100,000!
L2 Weight Decay in AdamW (training every LLM!) is literally Ridge Regularization applied to billions of Transformer weights.
Lasso & ElasticNet turn messy 200-column business tables into clean, interpretable 12-feature models executives can actually trust.
'Why does L1 create sparsity while L2 doesn't?', 'Why shouldn't you regularize the intercept b?', and 'Ridge vs. Lasso vs. ElasticNet?' appear in almost every ML interview!
You forget to standardize your features before running Ridge Regression: Feature A is in meters (0–2) and Feature B is in millimeters (0–2,000). What happens under L2 penalty λ(w_A² + w_B²)?
- Explain geometrically why L1 (Lasso) drives irrelevant weights to EXACT 0.00 while L2 (Ridge) shrinks correlated weights together smoothly.
- Combine both with ElasticNet when you have groups of strongly correlated features AND want sparsity.
- Never make the classic mistake of penalizing the intercept term b₀ or forgetting to scale features before L1/L2!
- Compare Filter, Wrapper (RFE), and Embedded Feature Selection methods.
Regularization puts a speed limit (budget) on your model's weights so it can't twist wildly to chase training noise: Loss = Data Fit + λ · Complexity Penalty. Turn λ = 0 and you get raw OLS; turn λ up and you trade a tiny pinch of Bias for a massive drop in Variance!
1. The Geometry of Sparsity: L1 Diamond vs. L2 Circle
Imagine inflating an oval balloon (your MSE error contour) until it first touches a fence around the origin:
- L1 Lasso Fence (Sharp Diamond): The corners stick straight out along the coordinate axes! The balloon almost always bumps a sharp corner where one weight equals EXACT
0.00! - L2 Ridge Fence (Smooth Circle): No corners anywhere! The balloon almost always touches a curvy side where both weights stay small and non-zero!
Slide λ below to watch Lasso delete noisy features right before your eyes!
Answering Our Opening Hook: Collinear Features Under Ridge vs. Lasso
- Ridge (L2): Splits credit evenly between correlated features
X₁andX₂(because — strictly smaller L2 penalty!). Super stable! - Lasso (L1): Arbitrarily picks ONE of
X₁orX₂and zeroes out the other (because ). - ElasticNet: Combines both — zeroes out junk features while keeping correlated signal groups together!
Given weight vector w = [3, −1, 0, 2] and λ = 0.5, compute both the L1 penalty λ‖w‖₁ and the L2 penalty λ‖w‖₂².
2. Regularization Paths & Unpenalized Intercepts
Watch out for the #1 implementation bug in Ridge Regression from scratch: NEVER penalize the intercept b! If house prices average $500,000, penalizing b² drags every single house prediction down toward $0! Center y first or zero out the intercept slot in your penalty matrix P = λ · diag(0, 1, 1, ..., 1)!
Bayesian Connection (Remember Probability Ch 8!)
- Ridge (L2) = MAP estimation with a Gaussian Prior !
- Lasso (L1) = MAP estimation with a Laplace Prior !
Pause & Check: Why must you ALWAYS standardize features (StandardScaler) BEFORE fitting Ridge or Lasso?
3. Feature Selection: Filter vs. Wrapper vs. Embedded
When you have 500 candidate features, dropping the 450 junk ones speeds up inference, reduces overfitting, and makes models explainable. Three classic strategies:
- Filter Methods (Mutual Info, Correlation, ): score each feature independently before training. Blazing fast, misses feature interactions.
- Wrapper Methods (Recursive Feature Elimination — RFE): retrain the model repeatedly dropping the weakest feature. Accurate, computationally heavy.
- Embedded Methods (Lasso L1, ElasticNet, Tree/GBDT Importance): select features automatically inside training — best real-world balance!
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
NEVER guess λ by hand! Search across a log-spaced grid like [1e-4, 1e-3, 1e-2, 0.1, 1, 10, 100] using Cross-Validation (RidgeCV / LassoCV in scikit-learn does this automatically in one line!).
Sweep λ from 0 → 3: Watch Lasso Drop Noisy Weights to Exact Zero
Toggle Lasso (L1 Sparsity) vs. Ridge (L2 Smooth Shrinkage) while the path sweeps live!
Genomics & Wide Healthcare Tables (d >> n)
When 20,000 genes predict outcomes for 400 patients, ElasticNet selects clean sparse biomarkers without crashing.
LLM AdamW Weight Decay (L2)
Decoupled L2 weight decay prevents billion-parameter Transformer weights from growing unboundedly during pretraining.
Quantitative Finance Alpha Factors
Ridge stabilizes highly correlated macroeconomic & technical indicators where raw OLS weights flip signs wildly.
Interpretable Credit Risk Models
Regulated banks use Lasso/Ridge to keep scorecards sparse, auditable, and resilient to collinear borrower metrics.
import numpy as np
# Exact Closed-Form Ridge Regression with UNPENALIZED Intercept!
def fit_ridge_closed_form(X: np.ndarray, y: np.ndarray, lam: float) -> tuple[np.ndarray, float]:
n, d = X.shape
X_aug = np.column_stack([np.ones(n), X]) # Col 0 = intercept
reg = lam * np.eye(d + 1)
reg[0, 0] = 0.0 # NEVER penalize intercept!
theta = np.linalg.solve(X_aug.T @ X_aug + reg, X_aug.T @ y)
return theta[1:], float(theta[0])
b inside (XᵀX + λI).reg[0, 0] = 0.0 (or mean-center X and y first!) so the intercept is never shrunk toward 0!StandardScaler before Ridge/Lasso.StandardScaler() + RidgeCV() inside a single Pipeline!