Sub topic 7
Correlated features: shared and hidden importance
This chapter assumes you can compute permutation importance on a held-out split with scikit-learn, as in the earlier chapters. It also assumes you know what a Pearson or Spearman correlation is. Here you will see why correlated features make permutation importance, and later partial dependence, harder to interpret. You will also learn how to detect the problem and work around it.
The problem in one sentence
Permutation importance measures how much the score drops when one column is shuffled. If a second column carries nearly the same information, the model can lean on it, and the drop is small. The feature looks unimportant even though the information it holds matters a great deal.
Why the importance gets shared
Take two features, A and B, that are almost copies of each other. A model trained on both may use A in some splits and B in others, or blend them. When you shuffle A, B still tells the model most of what A did. The score falls only a little. Shuffling B has the same small effect. Neither feature looks important on its own, although removing both would hurt badly.
The effect depends on the model. A linear model with two collinear inputs may split the weight unpredictably between them. A random forest tends to spread the usage across both. In either case, the importance of the signal is divided among the copies. Gradient boosting often favors whichever feature it happened to pick first, so one copy can look strong and the other weak.
See it happen
The code below adds a noisy copy of MedInc to the California housing data. It then compares permutation importance with and without the copy. The script is self-contained.
import numpy as np
import pandas as pd
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import RandomForestRegressor
from sklearn.inspection import permutation_importance
from sklearn.model_selection import train_test_split
X, y = fetch_california_housing(as_frame=True, return_X_y=True)
rng = np.random.default_rng(0)
# A near-duplicate of MedInc: same values plus a little noise.
X_dup = X.copy()
noise = rng.normal(0, 0.1 * X["MedInc"].std(), size=len(X))
X_dup["MedInc_copy"] = X["MedInc"] + noise
def importance_table(features):
X_train, X_test, y_train, y_test = train_test_split(
features, y, random_state=0
)
model = RandomForestRegressor(n_estimators=100, n_jobs=-1, random_state=0)
model.fit(X_train, y_train)
result = permutation_importance(
model, X_test, y_test, n_repeats=10, random_state=0, n_jobs=-1
)
table = pd.Series(result.importances_mean, index=features.columns)
return model, X_test, y_test, table.sort_values(ascending=False)
_, _, _, original = importance_table(X)
model_dup, X_test_dup, y_test_dup, duplicated = importance_table(X_dup)
print("Original data:")
print(original.head(3).round(3))
print("\nWith a near-copy of MedInc:")
print(duplicated.head(4).round(3))Run it and compare the MedInc rows. In the first table MedInc has a large importance. In the second, that importance is divided between MedInc and MedInc_copy, and each value is much smaller than the original. The model's test score is almost unchanged, because the information has not been lost. It is only spread across two columns. Exact numbers vary with library versions, but the split is the point to look for.
Recovering the hidden importance
If you suspect a group of features carries shared information, permute the group together. Apply the same row shuffle to every column in the group. The rows stay internally consistent, because each row's values for the group still belong together. The group's joint importance appears as a single, larger drop.
def grouped_importance(model, X, y, columns, n_repeats=10, seed=0):
"""Permutation importance for a set of columns shuffled together."""
rng = np.random.default_rng(seed)
baseline = model.score(X, y)
drops = []
for _ in range(n_repeats):
X_perm = X.copy()
order = rng.permutation(len(X_perm))
X_perm[columns] = X_perm[columns].to_numpy()[order]
drops.append(baseline - model.score(X_perm, y))
return np.mean(drops), np.std(drops)
mean, std = grouped_importance(
model_dup, X_test_dup, y_test_dup, ["MedInc", "MedInc_copy"]
)
print(f"Group importance of MedInc + MedInc_copy: {mean:.3f} +/- {std:.3f}")The group value will be close to the original single-feature MedInc importance, and clearly larger than either individual value in the duplicated run. Together, the shared importance is recovered.
Finding the groups
You usually do not know in advance which features overlap. Three checks help.
- Correlation matrix. Compute
X.corr(method="spearman")and look for pairs with absolute values above about 0.8. Spearman catches monotonic relationships that Pearson misses. - Hierarchical clustering on the correlations. Convert the correlation matrix to a distance such as
1 - abs(corr), cluster the features, and cut the tree at a chosen height. Each cluster becomes one group for permutation. - Drop-one comparison. Remove one suspect feature, retrain, and compare the test score. If the score barely changes, other features cover for it.
Correlation only catches pairwise overlap. A feature can also be predicted from a combination of several others. Examples are a total and its parts, or a ratio and its numerator and denominator. Look for these in the feature definitions, not just in the correlation matrix.
In the California data, Latitude and Longitude are strongly (negatively) correlated, and AveRooms and AveBedrms are related as well. Their individual importances should be read with that in mind.
A second problem: impossible rows
Correlation causes another issue that has nothing to do with sharing. When you shuffle one column independently of the others, you create rows that never occur in real data. A house with a very high median income paired with the MedInc_copy of a low-income block is impossible, since the two values are supposed to agree. The model has never seen such a row. Its prediction on it is a guess, and the score drop reflects that guess as much as the feature's real value.
This has two consequences.
- The importance may be inflated or deflated, depending on how the model behaves off the data manifold. Tree models predict constants in empty regions, while linear models extrapolate.
- The size of the effect grows with the correlation. For features with near-zero correlation, the shuffled rows stay plausible and the problem is small.
Grouped permutation reduces this problem for the group's internal correlation, because the group's columns stay aligned with each other. It does not fix correlation between a group and the features outside it.
Effects on partial dependence
Partial dependence (covered in the next chapters) has the same weakness, for a related reason. It sets one feature to a grid value for every row and averages the predictions. If that feature is correlated with another, the modified rows combine values that do not go together, and the average includes predictions for combinations that do not exist. The curve can describe behavior in regions where you have no data. Keep this in mind when you read it, and compare the curve with the data's range and density.
Practical rules
| Situation | What to do |
|---|---|
| Pair of features with correlation above about 0.8 | Report their grouped importance, not only the individual values. |
| Many features with overlapping information | Cluster by correlation and permute each cluster. |
| One feature appears very weak but has a strong correlate | Retrain without the correlate and recheck. |
| Shuffled rows look physically impossible | Treat the importance as approximate and consider conditional methods. |
| Need a stable ranking for a report | Repeat with several random seeds and several train/test splits. |
Conditional permutation, which shuffles a feature only among rows with similar values of its correlates, addresses the impossible-row issue more directly. A later chapter covers it, along with ALE and SHAP.
Summary
Correlated features split permutation importance between them, so each looks weaker than the shared information deserves. They also make shuffled rows unrealistic. To work around this, find groups of related features using correlation and clustering, permute each group together, and read single-feature values for those groups with caution.
Exercise
You train a model with two features, height_cm and height_in, that are exact unit conversions of each other. Permutation importance on the test set gives each of them a very small value, but the model's score is high. A colleague proposes dropping both because they are unimportant. What do you say, and how would you check?
Show answer
Dropping both would be a mistake. Each column is a perfect backup for the other, so shuffling one leaves the model with the same information and the score barely drops. The small values reflect redundancy, not uselessness. To check, permute the two columns together using the same row shuffle and measure the score drop. It should be large. You can also remove only one of the two, retrain, and confirm that the test score stays almost the same.
Exercise
Why does shuffling a single feature that is correlated with others make the importance estimate less trustworthy, even when no backup feature exists in the model?
Show answer
Independent shuffling breaks the relationship between the feature and its correlates, so the shuffled rows contain combinations of values that do not occur in real data. The model must predict on inputs far from its training distribution, and the score drop then partly measures how the model behaves in those unfamiliar regions, not how much it relies on the feature on realistic data.