Feature Selection
After this lesson, you will be able to:
- Explain why fewer features often mean better generalization, faster training, and easier explainability, and why dumping every available column into a model is a beginner mistake
- Apply filter methods (variance threshold, correlation filter, mutual information, chi-squared, ANOVA F-test) to score features against a target before any model training
- Use wrapper methods (Recursive Feature Elimination, sequential forward/backward selection) when accuracy matters more than compute and you can afford repeated model fits
- Use embedded methods (L1/Lasso, tree feature importance, Boruta) that select features as a side effect of fitting, and know why permutation importance beats Gini importance for any tree-based model
Before you start
Don't worry if "filter vs wrapper vs embedded" sounds bureaucratic — once you see them in code, the trade-off (speed vs accuracy vs how-much-do-you-trust-your-model) becomes obvious.
#Less Is More: Why Features Are Not Free
p grows, the volume of feature space grows exponentially. With finite data n, your samples become sparse in that space, distance metrics break down, and any model with enough capacity will find spurious patterns. The classic warning sign: training accuracy keeps climbing as you add features while validation accuracy plateaus or drops. That gap is overfitting, and it grows with every useless feature you keep.#Filter Methods: Score Features Without a Model
n × p), parallelizable, and a great first pass on any dataset with hundreds or thousands of columns.#Variance Threshold
The cheapest filter of all: drop any feature whose values barely change. A feature with variance near zero is a constant in disguise — it cannot help any model split groups apart.
Why does a threshold such as 0.16 mean "drop a 0/1 column that is the same value in more than 80% of rows"? Open the derivation.
#Correlation Filter
|r| exceeds 0.95 (or whatever threshold makes sense). They carry the same information; keeping both adds compute without adding signal and destabilizes linear-model coefficients.#Mutual Information: The Workhorse Filter
r ≈ 0.mutual_info_classif) and regression (mutual_info_regression). Spend the 60 seconds it takes to run on every new dataset.Why this sum is a KL divergence, and why it also equals H(X) minus H(X given Y), is derived in Information Theory & Entropy, in the Math track.
#Chi-Squared and ANOVA F-test
chi2) — it tests whether the joint distribution of feature and target differs from independence.Where does the chi-squared score come from, and how is it related to correlation? Open the derivation, which works the smallest case: a 0/1 feature against a 0/1 target.
f_classif) — it tests whether the feature's mean differs across target classes.The F score for a numeric feature compares how far apart the class means are with how spread out the values are inside each class. Open the derivation for the exact bookkeeping.
These are faster than mutual information but assume linear-ish relationships. Use them when you have thousands of features and need a rapid pre-filter; use mutual information when you can spend the extra seconds.
You have a tabular classification dataset with 10,000 features and only 500 samples. What should be your FIRST step before any modeling?
p >> n), you are deep in the curse-of-dimensionality regime. Wrapper methods (RFE-CV) require fitting your model hundreds of times — each fit overfits because of the sample shortage, so the rankings are noise. Embedded methods like XGBoost still need to look at all 10,000 features; some will look "important" by random chance. PCA destroys interpretability and may not even reduce overfitting. The right first move is a fast filter: rank by mutual information, keep the top 200-500, then apply wrapper or embedded selection on the survivors.#Wrapper Methods: Use the Model Itself
O(p) times or worse).#Recursive Feature Elimination (RFE)
The standard wrapper. Algorithm:
- Train your chosen model on all
pfeatures. - Rank features by importance (model coefficient magnitude, tree feature importance).
- Drop the bottom
kfeatures. - Repeat until you reach the target feature count.
RFECV) automatically picks the optimal feature count by tracking validation score across removal steps. The price: you fit your model p / k times for each CV fold. On a Random Forest with 1000 features and 5-fold CV, that is hundreds of fits.How many model fits do these wrappers cost? Open the derivation to count them for RFE, forward selection and trying every subset.
#Sequential Forward / Backward Selection
- Forward: Start with zero features. At each step, add the feature that most improves CV score. Stop when no addition helps.
- Backward: Start with all features. At each step, drop the feature whose removal most improves (or least hurts) CV score. Stop when removal hurts.
feature_a × feature_b is informative but neither alone is). They are also expensive. Use them when accuracy is paramount and compute is cheap — production deployment, final Kaggle submission, regulated medical work.#Embedded Methods: Selection During Training
Embedded methods bake feature selection into model fitting itself. No separate scoring phase, no model-fits-per-feature explosion — just train the model and read off which features it kept.
#L1 Regularization (Lasso) for Linear Models
Why L1 sets a weight to exactly zero, and how strong the data's pull must be for a weight to survive, is derived in Regularization: L1, L2, and ElasticNet, in the Classical ML track.
Try it: leave the toggle on L1 and see which coefficient lands exactly on zero, flip to L2 to compare, then shrink the budget and watch the path.
Two important details:
- Scale your features first. L1 penalizes coefficient magnitudes, so unscaled features (one in dollars, one in cents) get unfair penalties. Always run
StandardScalerbefore Lasso. - Use
LassoCVto pickα. It runs cross-validation across a path ofαvalues and picks the one minimizing CV error. Settingαby hand is guesswork.
ElasticNet blends L1 and L2 penalties and works better when features are correlated — L1 alone tends to arbitrarily pick one feature from a correlated group, while ElasticNet shares weight more stably.#Tree-Based Feature Importance
feature_importances_ attribute after fitting. These are usually Gini importance (for classification) or mean decrease in impurity — the average improvement to split criterion that each feature provides, weighted by how often it is used.#Boruta and SHAP-Based Selection
- Boruta wraps a Random Forest and compares each real feature's importance against a "shadow" feature (the same column with values shuffled). A feature passes if it consistently beats its shadow. Aggressive but principled.
- SHAP-based selection uses SHAP values (game-theoretic feature attributions) to rank features by total contribution magnitude. Slower than Gini, more honest, and explains why the model uses each feature.
#Putting It Together: The Recommended Workflow
Most production ML teams converge on a layered approach:
- Cheap filter sweep. Variance threshold (drop near-constants) → correlation filter (drop near-duplicates) → mutual information ranking (keep top 30-50% by MI score). Takes seconds.
- Embedded selection during training. Fit a regularized linear model (Lasso) or a gradient-boosted tree on the survivors. Read off coefficients or feature importances.
- Permutation importance audit on the validation set. Confirm that "important" features actually generalize. Drop any feature whose permutation importance is statistically indistinguishable from zero.
- Wrapper only if accuracy critical. RFE-CV on the survivors of step 3 — maybe 30 features down to the optimal 12.
This sequence cuts compute aggressively early (filter) and reserves the expensive analysis for the small surviving feature set (wrapper).
(Reminder: scaling matters for L1-based selection. Without it, large-magnitude features dominate the penalty term and small-magnitude features get unfairly zeroed out regardless of predictive value.)
#Try It Yourself
Tests: Verify that mutual information, L1 coefficients, and permutation importance agree on the most predictive features. Verify that the top-5 model performs at least as well as the all-features model.
#When Selection Goes Wrong
A few sharp edges worth memorizing:
- Selection inside the CV fold. If you select features (filter, wrapper, or embedded) using the full dataset and then cross-validate, your CV scores are optimistic by exactly the amount the selection used the held-out folds. Always wrap selection in a
Pipelinethat lives insidecross_val_score. - Correlated features confuse importance. If
feature_aandfeature_bare 95% correlated, one model fit may give all the weight toaand another tob, even though both are equally useful. Usepermutation_importancewithn_repeats >= 10to average across runs, or group correlated features and treat them as a unit. - Train/serve skew of the feature set. The feature list is a contract. If your training pipeline selects different features than the serving pipeline expects (e.g., because selection ran on different data), predictions silently break. The selected feature list must be versioned and checked at inference time.
#Key Takeaways
- Fewer features almost always beat more features. Every irrelevant column adds compute, hurts generalization (curse of dimensionality), complicates monitoring, and gives the model another chance to overfit to noise; selection is a real first-class step, not a polish task
- Filter, wrapper, embedded are speed/accuracy/honesty trade-offs. Filter (mutual information, ANOVA) is fast and model-agnostic; wrapper (RFE) is accurate but expensive; embedded (Lasso, tree importance) is the practical default because it piggy-backs on training you would do anyway
- Mutual information is the highest-leverage filter. It captures non-linear relationships that Pearson correlation misses, runs in seconds, and works for both classification and regression; run it on every new dataset before doing anything else
- Permutation importance beats Gini importance for trees. Gini is biased toward high-cardinality features and can rank noise features above genuine signal; permutation importance is unbiased, model-agnostic, computed on a held-out set, and only requires re-scoring (not re-fitting)
- Selection must live inside the CV loop. Scoring features against the target on the full dataset and then cross-validating leaks the test set into the model; wrap selection in a sklearn
Pipelineso it runs fresh inside each fold
#Quick Check
You have a dataset with 5,000 features and 800 samples. What is the best opening move?