Sub topic 6
Training data versus test data: what each importance tells you
This chapter assumes you can fit a scikit-learn estimator, call score, and have already run permutation_importance once. It builds on the previous chapters' procedure: score a baseline, shuffle one column, rescore, and take the difference. That procedure never says which rows to score. The choice changes what the number means.
Same procedure, different question
Permutation importance measures how much the model's score falls when one feature's link to the target is broken. The score comes from whatever data you pass in. So the data decides which question you are asking.
| Data passed in | Question answered | Typical use |
|---|---|---|
| Training set | Which features does the fitted model rely on to reproduce the training labels? | Diagnosing overfitting, checking what the model memorized |
| Held-out test set | Which features does the model rely on to make predictions that generalize? | Reporting which features matter for real predictions |
The two questions have different answers when the model overfits. A model that memorizes training rows can depend heavily on a feature that carries no signal. Shuffling that feature wrecks the training score, because the model used it to recognize individual rows. On new data the same feature adds nothing, and shuffling it changes little.
Why training importance inflates
Take a fully grown random forest. Each tree keeps splitting until its leaves are nearly pure. Once the real signal runs out, the splits use whatever feature separates the few remaining rows, including pure noise. The tree is fitting rows, not patterns.
When you shuffle the noise column on the training set, those rows land in the wrong branches and the memorized predictions break. The training score drops, so the noise feature looks important. On the test set the noise feature never helped, so shuffling it changes the score by roughly zero. Because the shuffle is random, the measured change can come out slightly negative.
The test-set number is the one that tracks generalization. The training-set number mixes real signal with memorization, and you cannot separate the two from that number alone.
Measuring it: a noise feature as a control
A column you know is meaningless makes a good control. Add one, fit the model, and compute importance on both splits.
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)
X["Noise"] = rng.normal(size=len(X))
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
model = RandomForestRegressor(n_estimators=100, n_jobs=-1, random_state=0)
model.fit(X_train, y_train)
print(f"R^2 train: {model.score(X_train, y_train):.3f}")
print(f"R^2 test: {model.score(X_test, y_test):.3f}")
def importance_table(model, X, y, label):
result = permutation_importance(
model, X, y, n_repeats=5, random_state=0, n_jobs=-1
)
return pd.Series(result.importances_mean, index=X.columns, name=label)
table = pd.concat(
[
importance_table(model, X_train, y_train, "train"),
importance_table(model, X_test, y_test, "test"),
],
axis=1,
)
table["gap"] = table["train"] - table["test"]
print(table.sort_values("test", ascending=False).round(3))Two things to look at in the output.
- The train R² will be much higher than the test R². That gap is the sign of overfitting, and it tells you the training importances are suspect before you read any of them.
- The
Noiserow should show a larger value intrainthan intest. The test value should sit near zero. Thegapcolumn is the training importance minus the test importance. Features with a large gap are the ones the model leans on for memorization.
I am not quoting exact numbers here. They depend on your scikit-learn version and the random seeds. The pattern is what matters.
Reading the gap
Compare the two columns feature by feature.
- High in both. The feature carries real signal that generalizes. Report it.
- High in train, near zero in test. The model uses the feature to memorize. Treat it as unreliable, and consider regularizing the model (for example,
min_samples_leaformax_depth). - Near zero in both. The model ignores the feature. This says nothing about whether the feature is related to the target. It only says this model does not use it.
- Higher in test than in train. This is uncommon, and it usually means noise from a small test set or a distribution difference between the splits. Check the spread before reading anything into it.
A useful habit is to compute both tables whenever the train and test scores differ noticeably. The importance gap tells you where the overfitting lives, which the score gap alone cannot.
Edge cases and failure modes
A small test set makes the number noisy
The test-set importance is an estimate. With few rows, one unlucky shuffle can move it a lot. The importances_std field from permutation_importance only measures variation across shuffles. It does not capture how the result would change with a different test sample. If the test set is small, repeat the whole evaluation across cross-validation folds and compare rankings between folds.
Reusing the test set for decisions
If you pick features, tune hyperparameters, or choose between models using the test importances, the test set stops being independent. Its scores become optimistic and its importances partly reflect your choices. Do the tuning against a separate validation split, and keep the test set for the final report.
Underfit models
If the model is simple and the train and test scores are close, train and test importances will be similar. Then either choice works, and the training set has a practical advantage: it is larger, so the estimate is less noisy. The warning above applies when the scores diverge, not always.
Distribution shift
Test-set importance only describes the test distribution. If production data differs from your test split, a feature that matters in production may look unimportant in your report. Importance is a statement about a model and a dataset together.
The score matters
The drop is measured in whatever the estimator's score returns, or the scoring argument you pass. For a classifier, accuracy can hide changes in probabilities. A metric such as neg_log_loss can reveal reliance on a feature that accuracy does not. Keep the metric the same across both splits, or the gap column is meaningless.
Impurity importance has the same problem
The built-in feature_importances_ of a tree ensemble is computed entirely from the training data. It sums impurity reductions from the splits that were made. A model that splits on noise to separate memorized rows will credit the noise feature. This is why a noise column often scores noticeably above zero in impurity importance, even when the test-set permutation importance for it is near zero. Held-out permutation importance corrects for this because it measures the effect on predictions for rows the model never saw.
A related option for bagged models is out-of-bag scoring, which evaluates each tree on the rows it did not train on. scikit-learn does not expose out-of-bag permutation importance directly. If you need an unbiased estimate without a separate test set, cross-validation is the portable route.
A short checklist
- Fit on the training split only.
- Print train and test scores. A large gap means train importances need caution.
- Compute permutation importance on the test split. Report the mean and standard deviation.
- If the scores diverge, also compute it on the training split and inspect the per-feature gap.
- Add a random noise column as a sanity check. Anything on the test set that does not clearly beat it is not distinguishable from noise.
Exercise
A gradient-boosted model has train R² of 0.99 and test R² of 0.70. Feature F ranks second in permutation importance on the training set and near the bottom on the test set. What does this tell you, and which ranking would you report as the features that drive predictions?
Show answer
The model is overfit, and it uses F mainly to reproduce training labels, not to predict new rows. Report the test-set ranking, because it measures reliance on features that generalize. Use the training ranking only as evidence of where the overfitting occurs, then consider stronger regularization.
Exercise
You add a pure-noise column and find its test-set importance is -0.002 with a standard deviation of 0.003. Is that a bug? What would you conclude about a real feature with test importance 0.004 and standard deviation 0.003?
Show answer
It is not a bug. Shuffling a useless feature changes the score randomly, so small negative values are expected. The real feature with 0.004 plus or minus 0.003 is not clearly distinguishable from the noise column, so you cannot claim the model relies on it.