Chapter 9 of 42 · ~17 min read & lab+60 XP
Chapter 9 · Machine Learning

Feature Selection: Correlation Filters, Mutual Information, RFE & L1

Why more columns can actually hurt accuracy, and how Filter, Wrapper (RFE), and Embedded (Lasso/Tree) selection prune noise cleanly

What Is It?

Feature Selection identifies and keeps only the most informative input columns while dropping noisy, constant, or redundant features before final training.

Why Is It Required?

Feeding 500 noisy columns into a model slows inference, invites overfitting (Curse of Dimensionality), inflates cloud bills, and makes models harder to debug.

Everyday Analogy: Packing only the 10 clothes you will actually wear for a trip instead of dragging your entire closet through airport security.
Why ML Engineers & Data Scientists Actually Need This

Cutting a 300-feature table down to the top 25 features often IMPROVES test accuracy while making inference 10× faster.

ML / AI Engineer

Fewer features mean fewer upstream database joins, lower feature-store latency, and fewer broken pipelines in production.

Data Scientist

Pruning collinear and noise features stabilizes model explanations (SHAP) and prevents models from memorizing random correlations.

Interview & Debug Edge

Common interview trap: 'If you select the top 10 features correlated with y on all rows and THEN run 5-fold CV, why is your CV score optimistically biased?'

Step 0 · Test Your Gut Before Any Math!

Which feature selection family automatically zeros out irrelevant feature weights during model training itself?

What You Will Master in This Chapter
  • Compare the 3 families of feature selection: Filter (fast, model-agnostic), Wrapper (RFE, model-specific), and Embedded (Lasso L1 & Tree Importance).
  • Explain why Mutual Information catches non-linear relationships that Pearson Correlation misses completely.
  • Avoid the #1 selection mistake: running feature selection on the full dataset BEFORE Cross-Validation (Selection Bias Leakage).
  • Combine variance thresholds, correlation pruning, and permutation importance in a practical workflow.
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 2
I(X; Y)Say aloud:“Mutual Information”
Plain-English Meaning
Measures how much knowing feature X reduces uncertainty about Y — captures BOTH linear and non-linear patterns.
Everyday Example
For y = x², Pearson r = 0, but Mutual Information I(X; Y) is huge!
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

More features are NOT always better. Every irrelevant column is an extra opportunity for your model to find a spurious coincidence on the training set. Feature Selection strips away dead weight using three progressively smarter tiers: Filters (fast statistics), Wrappers (trial-and-error subsets), and Embedded (built into Lasso/Trees).

1. The 3 Families of Feature Selection

  1. Filter Methods (Fastest, Model-Agnostic):
    • Variance Threshold: Drop constant or near-constant columns (0 information).
    • Pearson / Spearman Correlation: Drop features with near-zero signal or drop one of two features with ∣r∣>0.95|r| > 0.95.
    • Mutual Information: Catches non-linear relationships (y=x2y = x^2, sinusoids) that Pearson misses!
  2. Wrapper Methods (Accurate, Slower):
    • Forward / Backward Stepwise Selection and RFE (Recursive Feature Elimination) repeatedly train your actual estimator on shrinking subsets.
  3. Embedded Methods (Best Speed-Accuracy Tradeoff):
    • Lasso (L1) drives weak linear weights to exact zero; Tree / Permutation Importance ranks features by real validation drop.

2. The Silent Killer: Selection-Before-CV Leakage

Never pick the "top 20 features" using the full dataset and then run Cross-Validation! Even on 100% pure random noise, picking the 20 columns that happened to correlate with y across all rows produces fake 85% CV accuracy. Fix: Put your feature selector (SelectKBest, SelectFromModel, or RFE) inside a Scikit-Learn Pipeline so it re-selects strictly inside every training fold!

“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

Feature Selection keeps a subset of your original columns (age, income), preserving full human interpretability. PCA blends all columns into new synthetic axes (PC1 = 0.4·age + 0.7·income...), losing direct column names.

Interactive Visual Lab
Lab Challenge: Watch how L1 Lasso regularization automatically zeros out noisy features along the regularization path.
Interactive Animation • Regularization Paths

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!

Regularization Strength λ (0.0 → 3.0)
0%
λ = 0.00 | Zeros: 0
At λ = 0.00: exact zero weights = 0 / 4. Lasso's sharp L1 diamond corners delete weak/noisy features completely!
Intuition Takeaway: Prune constant/redundant columns with fast Filters (Variance, Correlation, Mutual Info), refine with Embedded L1/Permutation Importance, and ALWAYS run selection inside each CV fold.
Production NumPy & PyTorch Code Patterns
import numpy as np

# Fast Filter Selection: Drop Near-Constant + Rank by |Pearson r| on Train Split
rng = np.random.default_rng(42)
N = 200
x_signal = rng.normal(size=N)
x_noise = rng.normal(size=N)
x_const = np.ones(N) * 7.0
y = 3.0 * x_signal + rng.normal(scale=0.5, size=N)

X = np.column_stack([x_signal, x_noise, x_const])
names = ["signal_feat", "pure_noise", "constant_col"]

for j, name in enumerate(names):
    var = np.var(X[:, j])
    if var < 1e-6:
        print(f"{name:14s} | DROPPED (zero variance)")
        continue
    r = np.corrcoef(X[:, j], y)[0, 1]
    status = "KEEP" if abs(r) >= 0.2 else "DROP (low signal)"
    print(f"{name:14s} | var={var:.2f} | |r|={abs(r):.3f} -> {status}")
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Using Pearson correlation to drop features for a non-linear model like Random Forest or XGBoost.
Best Practice: Pearson only detects straight-line relationships; use Mutual Information or Permutation Importance for non-linear models.
Chapter Mastery Check (+60 XP)
Score: 0 / 1
1If you run feature selection on the entire dataset BEFORE splitting into train/test folds, what happens?

Apply What You Learned — Solve Matching Coding Problems