Objective
Fewer features means less variance and a model you can reason about; interpretation tells you whether the model learned something economic or something accidental. You should be able to compare selection methods, compute permutation importance and Shapley values for simple models, and explain why importances mislead when features are correlated.
Three families of feature selection
| Family | How it works | Examples | Pros and cons |
|---|---|---|---|
| Filter | Score each feature against the target, independently of any model | Correlation, rank IC, mutual information, univariate t-tests | Fast and hard to overfit; ignores interactions and redundancy |
| Wrapper | Search over subsets, scoring each by a model's validation error | Forward/backward stepwise, recursive feature elimination (RFE) | Captures interactions; expensive, and the search itself overfits |
| Embedded | Selection happens inside model fitting | Lasso, elastic net, tree importances, early-stopped boosting | Efficient; inherits the model's biases |
Two rules regardless of method. First, selection is part of fitting: it must happen inside each cross-validation training fold, or the CV score is contaminated (a filter run on the full sample is a textbook leak). Second, correlation filters miss non-linear relationships: a feature can have zero correlation with the target and still determine it, which mutual information or a tree would catch.
Impurity importance versus permutation importance
Impurity importance (mean decrease in impurity, MDI, the feature_importances_ attribute of scikit-learn trees) sums the impurity reductions from all splits on a feature, weighted by the samples reaching each split, averaged over trees. It is free to compute but has two biases:
- It is measured on the training data, so it rewards features the model used to fit noise.
- It favours features with many possible split points (continuous variables, high-cardinality categories), because more candidate thresholds give more chances to find a split that reduces impurity by luck.
Permutation importance (mean decrease in accuracy, MDA): on held-out data, shuffle one feature's column, breaking its link with the target, and measure how much the score drops. Model-agnostic and computed out of sample, so a pure-noise feature scores about zero. Its costs: repeated predictions, noise in the estimate, and a specific failure with correlated features (below).
import numpy as np
from sklearn.ensemble import RandomForestRegressor
from sklearn.inspection import permutation_importance
rng = np.random.default_rng(1)
n = 4000
signal = rng.normal(size=n)
X = np.column_stack([
signal, # the only real feature
rng.normal(size=n), # continuous noise
rng.integers(0, 2, size=n), # binary noise
])
y = 0.3 * signal + rng.normal(size=n) # best possible R^2 is about 8%
train, test = slice(0, 3000), slice(3000, None)
rf = RandomForestRegressor(n_estimators=300, min_samples_leaf=50, random_state=0)
rf.fit(X[train], y[train])
print(f"test R^2 {rf.score(X[test], y[test]):.3f}")
perm = permutation_importance(rf, X[test], y[test], n_repeats=20, random_state=0)
for name, mdi, pm in zip(["signal", "cont_noise", "binary_noise"],
rf.feature_importances_, perm.importances_mean):
print(f"{name:13s} impurity {mdi:.2f} permutation {pm:+.3f}")
test R^2 0.076
signal impurity 0.75 permutation +0.171
cont_noise impurity 0.23 permutation +0.007
binary_noise impurity 0.02 permutation -0.003
The continuous noise column receives almost a quarter of the impurity importance, ten times the binary noise column, though both are equally useless. Out of sample, permutation importance puts both near zero. In a low signal-to-noise problem, impurity importance mostly measures how easily a feature can be used to fit noise.
Worked example
permutation importance for a linear model
The model is with , and has variance 4. (a) By how much does the expected squared error rise when is permuted on a large test set? (b) Now the dataset contains an exact copy and the model splits the coefficient, . What is each feature's permutation importance?
Show solutionHide solution
(a) Permuting replaces by an independent copy with the same distribution. The prediction error changes from to . The extra term is independent of the original error when is the true regression, so the MSE rises by
(b) Permuting alone adds , so the rise is for each copy. The two importances sum to 1, half the importance of the single feature. Duplicating a feature makes it look a quarter as important, and dropping either copy and refitting would cost nothing at all because the other copy takes over.
A simulation with a million draws gives and . The lesson for correlated features: permutation importance splits credit between them and understates the group, while drop-column importance can make each look worthless. Assess correlated features as a group (permute them together, or cluster features first and compute importance per cluster).
Partial dependence and ICE
The partial dependence of model on feature averages the prediction over the data while fixing :
Plotting against shows the average marginal effect: a straight line for a linear term, a step for a tree threshold, a flattening curve for a saturating effect.
Two failure modes. Interactions cancel: for with symmetric around zero, , a flat line, though matters enormously. Individual conditional expectation (ICE) curves, one curve per observation, reveal this: half slope up, half slope down. Correlated features again force evaluation at unrealistic points; accumulated local effects (ALE) plots average only over nearby observations to avoid it.
SHAP values
SHAP explains a single prediction by distributing among the features, using the Shapley value from cooperative game theory. Let be the expected prediction when the features in are fixed at their values in and the rest are averaged out. Feature 's attribution averages its marginal contribution over all orders in which features can be added:
It is the unique attribution with these properties: the sum to (local accuracy), a feature that never changes the output gets zero, and symmetric features get equal shares. Exact computation is exponential in the number of features; TreeSHAP computes it exactly for tree ensembles in polynomial time, and KernelSHAP approximates it for any model.
For a linear model with independent features, , so SHAP reduces to "coefficient times deviation from average". Its value is in non-linear models, where it attributes interactions too. Averaging over a dataset gives a global importance measure that is computed per prediction and is usually more stable than impurity importance; it is still descriptive of the model, not causal, and still sensitive to correlated features.
Worked example
Shapley values by hand
Features are independent with means , . (a) For at , compute . (b) For with , , at , compute .
Show solutionHide solution
(a) Linear model: and . Check local accuracy: and , so .
(b) With independent features, , , , . With two features each order has weight :
They sum to . In general for the product, : the interaction effect is split between the two features according to the averaging over orders, which is a convention, not a fact about the world.
Multicollinearity
When features are highly correlated, the data cannot say which one carries the effect.
- Linear models. The variance of is inflated by the variance inflation factor , where is from regressing on the other features. Two features with correlation have , , so each coefficient's standard error is times larger than with uncorrelated features. Coefficients can flip sign between samples while predictions barely change. Ridge stabilises them by spreading weight; lasso picks one more or less arbitrarily, and which one can change from fold to fold.
- Trees. A forest chooses among correlated features almost at random at each split, so impurity importance is diluted across them; boosting tends to concentrate on whichever was picked first.
- Interpretation. Permutation importance splits credit or creates impossible rows, PD and SHAP evaluate unrealistic combinations, and individual importances become unstable.
Practical response: decide what question you are asking. If it is "does this group of information help?", cluster correlated features (for example by hierarchical clustering on ) and measure importance per cluster. If it is "which single variable?", accept that the data may not be able to answer it.
Knowledge check
A random forest's impurity importances rank a 10,000-level stock-identifier feature first. Permutation importance on a later test period puts it near zero. What is the best explanation?
Knowledge check
For a linear model with independent features of means and , what is the SHAP value of at ?
Knowledge check
A model is with symmetric around zero and independent of . What does the partial dependence plot of look like?
Key takeaways
- Filter methods are fast and robust, wrappers capture interactions but overfit their own search, embedded methods are efficient but inherit model biases; always select inside the CV folds.
- Impurity importance is in sample and favours high-cardinality, continuous features; use held-out permutation importance instead.
- Permuting in raises MSE by ; correlated copies split that credit, so assess correlated features as groups.
- Partial dependence shows average effects and hides interactions; ICE curves reveal them.
- SHAP distributes by Shapley values; for linear models with independent features .
- Multicollinearity inflates coefficient variance by the VIF and makes every single-feature importance unstable.
Practice problems
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).