Feature Selection Mechanism in L1-Regularized Regression
Machine LearningModel answerLast updated
Explain how and why L1 regularization drives coefficients to exactly zero, covering mathematical foundations, practical implications, and trade-offs.
You're building linear regression models for high-dimensional datasets where interpretability and sparsity matter.
Explain how L1 regularization achieves automatic feature selection. Your answer should cover:
- The fundamental difference between L1 and L2 penalties in how they shrink coefficients
- A geometric view of why L1 constraints produce exact zeros
- The mathematical optimality condition that determines when a coefficient becomes zero
- How correlated features affect which variables get selected
- Why feature scaling is critical and what breaks without it
- The approach for tuning the regularization strength and its impact on model complexity
- Scenarios where combining L1 and L2 penalties is advantageous
Provide concrete mathematical intuition alongside practical considerations for model selection and stability.
Hints
Hint 1
Consider what happens to the gradient of |β| as the coefficient approaches zero compared to β²
Hint 2
Visualize the constraint region in 2D: which shape has corners on the axes?
Hint 3
Think about the subgradient at zero: when does the correlation between a feature and residuals justify including that feature?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Feature Selection Through L1 Regularization
Core Mechanism
L1-regularized regression minimizes:
$$\min_\beta ; \frac{1}{2n}|y - X\beta|_2^2 + \lambda \sum_j |\beta_j|$$
The absolute value penalty creates sparsity through a fundamentally different shrinkage pattern than squared penalties.
1. L1 vs L2 Shrinkage Behavior
The key distinction lies in how each penalty's derivative behaves:
L2 penalty ($\frac{\lambda}{2}\beta_j^2$): gradient is $\lambda\beta_j$, proportional to the coefficient itself. As $\beta_j$ shrinks toward zero, the penalty's force weakens proportionally. Coefficients approach but essentially never reach exact zero—they get arbitrarily small instead.
L1 penalty ($\lambda|\beta_j|$): gradient is $\lambda \cdot \text{sign}(\beta_j)$, a constant magnitude regardless of $|\beta_j|$. The penalty applies uniform pressure. If a feature's contribution to reducing loss is weaker than $\lambda$, the penalty overpowers it and drives the coefficient to exactly zero.
For orthogonal predictors ($X^\top X/n = I$), the closed forms clarify this:
- Ridge: $\hat\beta_j = \frac{z_j}{1+\lambda}$ (proportional shrinkage)
- L1: $\hat\beta_j = \text{sign}(z_j) \max(|z_j| - \lambda, 0)$ (soft-thresholding)
The L1 version subtracts $\lambda$ from every coefficient's magnitude and clips negatives to zero.
2. Geometric Perspective
Rewrite as a constrained problem: minimize squared error subject to $\sum_j |\beta_j| \le t$. The solution occurs where loss contours (ellipses centered at the unconstrained optimum) first touch the constraint boundary.
L1 constraint region: a diamond in 2D, cross-polytope in higher dimensions. This polytope has sharp corners sitting on coordinate axes. Most of its surface area concentrates on lower-dimensional faces where multiple coordinates are zero. Generic ellipses typically make first contact at these corners or edges, yielding sparse solutions.
L2 constraint region: a smooth sphere. Tangency happens at interior points with no structural bias toward coordinate planes. All coefficients remain nonzero.
In high dimensions, the L1 polytope's geometry overwhelmingly favors sparse solutions—nearly all boundary points have many zero coordinates.
3. Optimality Condition
Since $|\beta_j|$ is non-differentiable at zero, we use subgradients:
$$\partial|\beta_j| = \begin{cases} {\text{sign}(\beta_j)} & \text{if } \beta_j \ne 0 \ [-1, 1] & \text{if } \beta_j = 0 \end{cases}$$
At optimality, for each feature $j$:
$$\frac{1}{n}x_j^\top (y - X\hat\beta) = \lambda s_j, \quad s_j \in \partial|\hat\beta_j|$$
This yields two regimes:
-
Nonzero coefficient: $\frac{1}{n}x_j^\top r = \lambda \cdot \text{sign}(\hat\beta_j)$. The feature's correlation with residuals $r$ equals exactly $\pm\lambda$.
-
Zero coefficient: $|\frac{1}{n}x_j^\top r| \le \lambda$. The feature's signal is too weak to justify inclusion.
The regularization strength $\lambda$ acts as a threshold: features must correlate with residuals above this level to enter the model. The maximum useful $\lambda$ is $\max_j \frac{1}{n}|x_j^\top y|$ (with centered data), where all coefficients become zero.
4. Correlated Predictors
When features are highly correlated, they capture nearly identical information. L1 regularization is indifferent to how weight distributes among them but prefers concentrated weight (fewer nonzeros).
Consequences:
- Arbitrary selection: from a correlated group, one feature gets picked quasi-randomly while others are zeroed. Small data perturbations change which one survives.
- Instability: selected sets vary substantially across cross-validation folds or bootstrap samples, even when predictions remain stable.
- Theoretical limits: perfect collinearity creates non-unique solutions. With more features than samples ($p > n$), at most $n$ features can be selected (saturation).
For reliable variable selection under correlation, the irrepresentable condition must hold: irrelevant variables cannot be too correlated with relevant ones. Strong pairwise correlation among predictors violates this.
Remedies: group LASSO (when groups are known), stability selection (retain features selected frequently across subsamples), or Elastic Net (covered below).
5. Feature Scaling Requirement
The penalty $\lambda \sum_j |\beta_j|$ weighs all coefficients identically, but coefficient magnitude depends on input scale.
Example: converting temperature from Celsius to Kelvin (shift by 273) doesn't change the coefficient. But converting kilometers to millimeters scales the coefficient by $10^6$, reducing its penalty contribution by the same factor.
Without standardization:
- Small-scale features (e.g., proportions in [0,1]) require large coefficients and face disproportionate penalization, leading to under-selection.
- Large-scale features (e.g., counts in thousands) use small coefficients and escape penalization, causing over-selection.
- Selection reflects measurement units rather than predictive value.
Standard procedure:
- Center all features (subtract means).
- Scale to unit variance (divide by standard deviation).
- Fit intercept separately without penalization, or center the target.
- Transform coefficients back to original scale for interpretation: $\beta_{\text{orig}} = \beta_{\text{scaled}} / \sigma_j$.
Apply scaling within cross-validation folds to prevent data leakage. For categorical dummy variables, group LASSO keeps all levels together rather than treating them independently.
6. Tuning the Regularization Strength
Selection process:
- Compute solutions across a logarithmic grid from $\lambda_{\max}$ (all-zero model) down to $0.001 \lambda_{\max}$, using warm starts for efficiency.
- Evaluate prediction error via K-fold cross-validation on each candidate.
- Choose between two strategies:
- $\lambda_{\min}$: minimizes CV error (more features, better fit).
- One-standard-error rule: largest $\lambda$ within one SE of minimum CV error (sparser, more robust).
Alternative criteria include information criteria (AIC/BIC) using the number of nonzeros as effective degrees of freedom.
Bias-variance trade-off:
- Increasing $\lambda$: more zeros, greater shrinkage of survivors → higher bias, lower variance, better generalization when noise features are present.
- Decreasing $\lambda$: approaches unregularized least squares → low bias, high variance, overfitting risk.
L1 regularization biases even the selected coefficients toward zero by approximately $\lambda$. Cross-validation optimizes prediction and may retain weak features. For unbiased coefficient estimates post-selection, refit ordinary regression on the selected support (though naive inference is invalid; use selective inference methods for valid p-values).
7. When to Use Elastic Net
Elastic Net blends both penalties:
$$\lambda \left[\alpha |\beta|_1 + \frac{1-\alpha}{2}|\beta|_2^2\right], \quad \alpha \in [0,1]$$
Advantages over pure L1:
- Grouped selection: when features are correlated, L2 encourages including the whole group rather than picking one arbitrarily. This improves stability and interpretability when correlations are known to be meaningful.
- Unique solutions: the L2 component enforces strict convexity even with perfect collinearity or $p > n$.
- Better predictions: in highly correlated settings, retaining multiple correlated predictors often improves held-out accuracy compared to the single arbitrary survivor from pure L1.
- No selection limit: unlike L1's $n$-variable cap when $p > n$, Elastic Net can select more than $n$ features.
When to prefer pure L1: when you need maximum sparsity, features are relatively uncorrelated, and interpretation depends on having the smallest possible active set.
Typical Elastic Net usage: $\alpha = 0.5$ or tune $\alpha$ via nested cross-validation. Many practitioners default to Elastic Net as a robust choice that degrades gracefully under correlation.
Summary
L1 regularization achieves feature selection through constant-magnitude shrinkage that drives coefficients exactly to zero when their signal falls below a threshold. This emerges from the geometry of the constraint polytope, the non-differentiability at zero, and the resulting optimality conditions. Practical deployment requires careful standardization, cross-validated tuning, and awareness that correlated features create selection instability—situations where mixing in L2 regularization provides more stable and often more accurate models.