Sub topic 2
Setting up: a held-out split and a score to track
This chapter assumes you can train a scikit-learn model with fit, predict and score, and that you know what R² and accuracy measure. It also assumes basic NumPy and pandas. Everything later in the tutorial builds on the model and split created here.
Why the setup matters
Permutation importance and partial dependence both query a trained model from the outside. Neither looks at the model's internals. Both depend on two choices you make before running them:
- Which rows the model is evaluated on.
- Which score measures "how well the model does."
If you pick these carelessly, every later result inherits the problem. A feature can look important only because the model memorized it in the training rows.
The held-out split
A held-out set is a portion of the data that the model never sees during fit. Scores on it estimate how the model behaves on new data. Scores on the training rows are optimistic, because a flexible model can fit those rows almost perfectly.
Permutation importance measures the drop in a score. That drop should reflect what the model has learned that generalizes. On the training rows, it can also reflect noise the model memorized. The next chapters return to this. For now, create the split once and reuse it.
Building the model and the baseline
The example uses the California housing data. The target is median house value, so this is a regression task. The code fits a random forest and prints three numbers.
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error
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(f"Train R^2: {model.score(X_train, y_train):.3f}")
print(f"Test R^2: {model.score(X_test, y_test):.3f}")
print(f"Test MAE: {mean_absolute_error(y_test, model.predict(X_test)):.3f}")Expect the train R² to be clearly higher than the test R². That gap is normal for a random forest, which fits the training rows very closely. The test R² is the baseline score. Permutation importance shuffles a feature and measures how far the score falls below this baseline.
Setting random_state in both the split and the model makes the numbers reproducible. This matters later, because you will compare importances across runs.
Choosing the score
model.score uses a default metric. For regressors it is R², and for classifiers it is accuracy. The default is a reasonable start, but the metric defines what "important" means. A feature that matters for R² can matter less for mean absolute error, because R² penalizes large errors more heavily.
Choose the metric that matches the decision the model supports. For an imbalanced classification problem, accuracy can hide poor behavior on the rare class, so you might track ROC AUC or F1 instead. The metric also needs a direction. R² and accuracy rise as the model improves, while MAE falls. Scikit-learn's scorer names handle this by negating error metrics, for example "neg_mean_absolute_error".
Common errors
- Fitting on all the data, then splitting. The held-out rows then influenced the model, and the score is no longer an honest estimate.
- Running preprocessing on the full dataset first. Scalers and imputers should be fit on the training split only. A
Pipelinekeeps this correct, and you can pass the whole pipeline to the inspection tools. - Changing the split between experiments. Importances from different splits are not directly comparable.
- Using a tiny test set. A small test set gives a noisy baseline, so importance differences between features may be noise.
Exercise
You fit a model on the full dataset and then compute permutation importance on the training rows. Name two problems with this setup for interpreting the importances.
Show answer
First, there is no held-out data, so the baseline score is optimistic and cannot show whether the model generalizes. Second, importances computed on training rows can credit features the model used to memorize noise, so they overstate how much those features matter for new data.