Skip to content
LeetQuant
QR06 Machine Learning and Model Validation

QR06 · Machine Learning and Model Validation · Lesson 5 of 5

Feature Selection and Interpretability

Filter, wrapper and embedded selection, permutation versus impurity importance and their biases, partial dependence, SHAP values from the Shapley definition, and how multicollinearity distorts all of them.

18 min

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

FamilyHow it worksExamplesPros and cons
FilterScore each feature against the target, independently of any modelCorrelation, rank IC, mutual information, univariate t-testsFast and hard to overfit; ignores interactions and redundancy
WrapperSearch over subsets, scoring each by a model's validation errorForward/backward stepwise, recursive feature elimination (RFE)Captures interactions; expensive, and the search itself overfits
EmbeddedSelection happens inside model fittingLasso, elastic net, tree importances, early-stopped boostingEfficient; 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 y^=βx\hat y = \beta x with β=0.5\beta = 0.5, and xx has variance 4. (a) By how much does the expected squared error rise when xx is permuted on a large test set? (b) Now the dataset contains an exact copy x2=x1=xx_2 = x_1 = x and the model splits the coefficient, y^=0.25x1+0.25x2\hat y = 0.25 x_1 + 0.25 x_2. What is each feature's permutation importance?

Show solution

(a) Permuting replaces xx by an independent copy x′x' with the same distribution. The prediction error changes from y−βxy - \beta x to (y−βx)+β(x−x′)(y - \beta x) + \beta(x - x'). The extra term is independent of the original error when y^\hat y is the true regression, so the MSE rises by

E[β2(x−x′)2]=2β2Var⁡(x)=2×0.25×4=2.\mathbb{E}\big[\beta^2 (x - x')^2\big] = 2\beta^2 \operatorname{Var}(x) = 2 \times 0.25 \times 4 = 2 .

(b) Permuting x1x_1 alone adds β2(x−x′)\tfrac{\beta}{2}(x - x'), so the rise is 2(β/2)2Var⁡(x)=β2Var⁡(x)/2=0.52(\beta/2)^2 \operatorname{Var}(x) = \beta^2 \operatorname{Var}(x)/2 = 0.5 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 2.002.00 and 0.500.50. 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 ff on feature jj averages the prediction over the data while fixing xjx_j:

PDj(v)=1n∑i=1nf(v,  xi,−j).\text{PD}_j(v) = \frac1n \sum_{i=1}^{n} f\big(v,\; x_{i,-j}\big) .

Plotting PDj\text{PD}_j against vv 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 f=x1x2f = x_1 x_2 with x2x_2 symmetric around zero, PD1(v)=v⋅xˉ2≈0\text{PD}_1(v) = v \cdot \bar x_2 \approx 0, a flat line, though x1x_1 matters enormously. Individual conditional expectation (ICE) curves, one curve f(v,xi,−j)f(v, x_{i,-j}) 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 f(x)−E[f]f(x) - \mathbb{E}[f] among the features, using the Shapley value from cooperative game theory. Let v(S)v(S) be the expected prediction when the features in SS are fixed at their values in xx and the rest are averaged out. Feature ii's attribution averages its marginal contribution over all orders in which features can be added:

ϕi=∑S⊆N∖{i}∣S∣! (∣N∣−∣S∣−1)!∣N∣! [v(S∪{i})−v(S)].\phi_i = \sum_{S \subseteq N \setminus \{i\}} \frac{|S|!\,(|N| - |S| - 1)!}{|N|!}\,\big[v(S \cup \{i\}) - v(S)\big] .

It is the unique attribution with these properties: the ϕi\phi_i sum to f(x)−E[f]f(x) - \mathbb{E}[f] (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, ϕi=βi(xi−E[xi])\phi_i = \beta_i (x_i - \mathbb{E}[x_i]), so SHAP reduces to "coefficient times deviation from average". Its value is in non-linear models, where it attributes interactions too. Averaging ∣ϕi∣|\phi_i| 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 E[x1]=0.5\mathbb{E}[x_1] = 0.5, E[x2]=1\mathbb{E}[x_2] = 1. (a) For f(x)=1+2x1−3x2f(x) = 1 + 2x_1 - 3x_2 at x=(2,0)x = (2, 0), compute ϕ1,ϕ2\phi_1, \phi_2. (b) For g(x)=x1x2g(x) = x_1 x_2 with E[x1]=1\mathbb{E}[x_1] = 1, E[x2]=0\mathbb{E}[x_2] = 0, at x=(2,3)x = (2, 3), compute ϕ1,ϕ2\phi_1, \phi_2.

Show solution

(a) Linear model: ϕ1=2(2−0.5)=3\phi_1 = 2(2 - 0.5) = 3 and ϕ2=−3(0−1)=3\phi_2 = -3(0 - 1) = 3. Check local accuracy: f(x)=1+4−0=5f(x) = 1 + 4 - 0 = 5 and E[f]=1+1−3=−1\mathbb{E}[f] = 1 + 1 - 3 = -1, so f(x)−E[f]=6=ϕ1+ϕ2f(x) - \mathbb{E}[f] = 6 = \phi_1 + \phi_2.

(b) With independent features, v(∅)=E[x1]E[x2]=0v(\varnothing) = \mathbb{E}[x_1]\mathbb{E}[x_2] = 0, v({1})=x1E[x2]=0v(\{1\}) = x_1 \mathbb{E}[x_2] = 0, v({2})=E[x1]x2=3v(\{2\}) = \mathbb{E}[x_1] x_2 = 3, v({1,2})=6v(\{1,2\}) = 6. With two features each order has weight 12\tfrac12:

ϕ1=12[(v({1})−v(∅))+(v({1,2})−v({2}))]=12[0+3]=1.5,\phi_1 = \tfrac12\big[(v(\{1\}) - v(\varnothing)) + (v(\{1,2\}) - v(\{2\}))\big] = \tfrac12[0 + 3] = 1.5, ϕ2=12[(v({2})−v(∅))+(v({1,2})−v({1}))]=12[3+6]=4.5.\phi_2 = \tfrac12\big[(v(\{2\}) - v(\varnothing)) + (v(\{1,2\}) - v(\{1\}))\big] = \tfrac12[3 + 6] = 4.5 .

They sum to 6=g(x)−E[g]6 = g(x) - \mathbb{E}[g]. In general for the product, ϕ1=12(x1−μ1)(x2+μ2)\phi_1 = \tfrac12 (x_1 - \mu_1)(x_2 + \mu_2): 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 β^j\hat\beta_j is inflated by the variance inflation factor VIFj=1/(1−Rj2)\text{VIF}_j = 1/(1 - R_j^2), where Rj2R_j^2 is from regressing xjx_j on the other features. Two features with correlation 0.90.9 have R2=0.81R^2 = 0.81, VIF≈5.26\text{VIF} \approx 5.26, so each coefficient's standard error is 5.26≈2.29\sqrt{5.26} \approx 2.29 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 1−∣ρ∣1 - |\rho|) 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 f(x)=4+3x1−x2f(x) = 4 + 3x_1 - x_2 with independent features of means E[x1]=1\mathbb{E}[x_1] = 1 and E[x2]=2\mathbb{E}[x_2] = 2, what is the SHAP value of x1x_1 at x=(3,5)x = (3, 5)?

Knowledge check

A model is f=x1x2f = x_1 x_2 with x2x_2 symmetric around zero and independent of x1x_1. What does the partial dependence plot of x1x_1 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 xx in y^=βx\hat y = \beta x raises MSE by 2β2Var⁡(x)2\beta^2\operatorname{Var}(x); 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 f(x)−E[f]f(x) - \mathbb{E}[f] by Shapley values; for linear models with independent features ϕi=βi(xi−E[xi])\phi_i = \beta_i(x_i - \mathbb{E}[x_i]).
  • Multicollinearity inflates coefficient variance by the VIF 1/(1−Rj2)1/(1 - R_j^2) and makes every single-feature importance unstable.

Practice problems

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).