Sub topic 2
Setting up: a held-out split and a score to track
Permutation importance and partial dependence both depend on decisions you make before you call either function. You must choose which rows the model is judged on, and which number counts as "the score". This chapter covers those two choices and builds the model that the rest of the tutorial reuses.
I assume you can train a scikit-learn estimator and call fit, predict, and score. I also assume you know what R² and accuracy measure, and that you are comfortable with pandas DataFrames.
Why the data you evaluate on matters
Permutation importance asks a simple question. If a feature's values are scrambled, how much worse does the model score? The answer is only as meaningful as the baseline score it is measured against.
A flexible model such as a random forest can memorize its training rows. Its score on those rows is inflated. If you measure importance there, you measure how much the model relies on a feature to reproduce what it memorized. You do not measure how much the feature helps it predict new cases. Chapter 6 compares the two readings in detail. For now, the rule is to decide on a held-out set first and compute everything from it.
A held-out set is a slice of the data that the model never sees during fitting. In this tutorial it is the test split from train_test_split.
The running example
The tutorial uses the California housing dataset. It has 20,640 rows, eight numeric features, and a continuous target, the median house value of a district. It is large enough for stable estimates and small enough to run in seconds. fetch_california_housing downloads the data on first use and caches it.
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
X, y = fetch_california_housing(as_frame=True, return_X_y=True)
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("rows (train / test):", len(X_train), "/", len(X_test))
print(f"R^2 on train: {model.score(X_train, y_train):.3f}")
print(f"R^2 on test: {model.score(X_test, y_test):.3f}")train_test_split holds out 25% of the rows by default, which gives 15,480 training rows and 5,160 test rows. Setting random_state makes the split reproducible. Reproducibility matters here because a different split gives slightly different importances, and you want to be able to tell a real change from a re-split.
You should see a train R² near 0.97 and a test R² near 0.80. The exact digits can vary with library versions. The gap is the point. The model looks nearly perfect on data it has seen and noticeably worse on data it has not. The test score is the honest one.
as_frame=True keeps X as a DataFrame. That keeps the column names attached, which you need later to label importances and to pick features by name for partial dependence plots.
Choosing the score to track
model.score uses the estimator's default metric. For regressors that is R², and for classifiers it is accuracy. Permutation importance reports a drop in whichever score you choose, so the metric changes what "important" means. A feature that matters for mean squared error may matter less for mean absolute error, because squared error weights large mistakes more heavily.
Pick the metric that matches how the model will be judged in practice. Common choices:
| Task | Metric (scikit-learn name) | Notes |
|---|---|---|
| Regression | `r2` | Scale-free, 1.0 is perfect, can be negative. |
| Regression | `neg_mean_absolute_error` | In target units, less sensitive to outliers. |
| Regression | `neg_root_mean_squared_error` | In target units, punishes large errors. |
| Classification | `accuracy` | Misleading when classes are imbalanced. |
| Classification | `balanced_accuracy` | Averages recall across classes. |
| Classification | `roc_auc` | Needs `predict_proba` or `decision_function`. |
The "neg" prefix is a scikit-learn convention. Tools such as cross-validation and grid search always maximize a score. Error metrics, where lower is better, are therefore negated so that higher is still better. Permutation importance follows the same convention. Importance is the baseline score minus the shuffled score, so a useful feature produces a positive number under every metric in the table.
You can evaluate any metric by name with get_scorer. This block continues from the previous one and reuses model and the test split.
from sklearn.metrics import get_scorer
for name in ["r2", "neg_mean_absolute_error", "neg_root_mean_squared_error"]:
scorer = get_scorer(name)
print(f"{name:<30} {scorer(model, X_test, y_test):.3f}")A scorer is a callable with the signature scorer(estimator, X, y). This is the same signature that permutation_importance calls internally, and you can pass the same strings to its scoring argument. Passing a list of names computes the importance under several metrics in one run, which is a cheap way to check whether your ranking depends on the metric.
Check the baseline before explaining it
Importance and dependence describe what the model learned. They say nothing about whether it learned something good. If the test score is poor, the explanations are explanations of a poor model. A feature can rank first simply because the model leans on it heavily and is still wrong.
Run a short sanity check before any inspection:
- Compare the test score with a trivial baseline.
DummyRegressorpredicts the training mean and scores an R² of about 0 on test data.DummyClassifierpredicts the majority class. If your model barely beats these, stop and fix the model first. - Compare the train and test scores. A large gap, as above, is a sign of overfitting. That is not a reason to abandon inspection. It is a reason to read results with the cautions in chapter 6.
- Look at the size of the test set. Each importance estimate is an average over test rows, so a small test set makes the estimate noisy. A few hundred rows is thin. Several thousand is comfortable.
Pitfalls in building the split
The default random split is correct only when rows are independent and identically distributed. Several common data shapes break that assumption, and a leaky split produces an optimistic baseline and misleading importances.
- Time series. A random split puts future rows in the training set and past rows in the test set. Split by time instead, for example with
TimeSeriesSplitor a cutoff date, so the test period comes after the training period. - Grouped rows. Several rows from the same patient, customer, or house can land on both sides of the split. The model then recognizes the group, and the test score is inflated. Use
GroupShuffleSplitorGroupKFoldso each group stays on one side. - Preprocessing before the split. Fitting a scaler, imputer, or encoder on the full dataset leaks test statistics into training. Split first, then fit preprocessing on the training part only. A
Pipelinedoes this for you and enforces the order. - Target-derived features. A column computed from the target, or recorded after the outcome, will dominate the importance ranking. If one feature has a suspiciously huge score drop, ask how it was produced before celebrating.
What to carry forward
The rest of the tutorial uses these objects from the code above: X_train, X_test, y_train, y_test, and the fitted model. They give you three fixed ingredients:
- A model that was fitted on the training split only.
- A held-out set of 5,160 rows for every importance and dependence computation.
- A named metric whose test value, the baseline, is the reference for all score drops.
Next you will see why the importances that come with the forest are not a substitute for this procedure, and then you will build permutation importance on top of this setup.
Exercise
A colleague builds a model on hourly sensor readings from 40 machines. They use train_test_split with the default shuffle and report a test R² of 0.98. Then they compute permutation importance on the test set, and one feature, machine_id, ranks first by a wide margin. Give two reasons to distrust this setup and say how you would change the split.
Show answer
The rows are neither independent nor evenly mixed. Hourly readings from the same machine are strongly related to each other and to neighbouring hours, so a random split puts near-duplicates of every test row into the training set. The model can look up the machine and time neighbourhood, which inflates the 0.98 and makes machine_id look important because the model uses it to recall the machine, not because it generalizes. Hourly readings are also a time series, so a random split trains on the future to predict the past. To fix this, split by time with a cutoff date or TimeSeriesSplit. If the goal is to predict new machines, hold out whole machines with GroupShuffleSplit on machine_id. Then recompute the baseline score and the importances on the new held-out set.