MLDay 26 of 50Trees and Ensembles
Explain a Model's Predictions
The D25 model flags a customer as likely to miss next month's card payment, and the bank cuts their limit. "The boosted trees said so" won't satisfy the customer or a regulator. It won't help you either, the day the model goes wrong.
The idea
You can answer two questions about any model without opening it up.
- Which features matter? Shuffle one column of the test set, so its values land on random rows. The model still runs, but that feature now carries no information. Score the model again. The permutation importance of the feature is how much the score drops. A big drop means the model leans on it; no drop means it ignores it.
- How does a feature move the predictions? Give every row the same value of that feature, predict, and average. Repeat for a range of values. This partial dependence curve shows how the average prediction changes as the feature changes, with every other column left as it was.
Do both on held-out rows: the test set from D06. On training rows, a model gets credit for noise it memorized.
Tree models also have a built-in score, impurity importance: how much each feature's splits cut Gini impurity (D23) during training. It's free, but biased. It's measured on the training rows, and it favours columns with many distinct values, because they offer more splits to overfit. Below, a forest ranks a column of pure random numbers second of 24.
A tiny example
A toy model predicts "default" when a customer is 2 or more months late on a payment. It ignores age.
| Customer | Months late | Age | Truth | Prediction |
|---|---|---|---|---|
| A | 3 | 25 | default | default |
| B | 0 | 41 | paid | paid |
| C | 2 | 33 | default | default |
| D | 0 | 52 | paid | paid |
It gets 4 of 4 right. Now shuffle the months-late column, so A, B, C and D get 0, 2, 3 and 0. A becomes "paid" (wrong), B becomes "default" (wrong), and C and D stay right. Accuracy falls from 1.0 to 0.5, so months late has an importance of 0.5. Shuffle the age column instead: no prediction changes, so age's importance is 0.
The formula
Permutation importance is the average score lost over several shuffles.
| Symbol | Meaning |
|---|---|
| the importance of feature | |
| the model's score on the untouched test set; here ROC-AUC (D13) | |
how many times the column is shuffled (n_repeats, 5 by default) |
|
| the score after the -th shuffle of column |
Worked: the D25 model scores . PAY_0 is the latest repayment status (1 = one month late, 2 = two
months late, and so on). Five shuffles of it average a ROC-AUC of 0.696, so .
Partial dependence is an average prediction with one feature pinned to a value.
| Symbol | Meaning |
|---|---|
| the average predicted chance of default when feature equals for everyone | |
| the number of test rows (6,000) | |
| the model's predicted chance of default for one row | |
| row 's features; only feature changes |
Worked: set PAY_0 to 1 for all 6,000 test customers, and the average prediction is 0.239. Set it to 2 and it's
0.591: the second month late more than doubles the risk.
Try it
Shuffle a column: what does the credit model lean on?
The model is fixed: p = σ(w · x + b), and it predicts 1 when p > 0.5. Shuffle a feature's column to scramble it across the rows, and see how much accuracy the model loses without it.
b = -1.5accuracy before shuffling 12 of 12 (100%)
| feature | weight w | shuffle | accuracy after | drop |
|---|---|---|---|---|
| months late | 2 | – | – | |
| credit limit ($10k) | -0.25 | – | – | |
| age (years) | 0 | – | – |
No column shuffled yet.
The fixed model gets all 12 customers right (1 = default). Guess the ranking, then press Shuffle on each row. Months late costs 41.7 points of accuracy. Credit limit costs 25.0, though its weight is 8 times smaller: limits span 1 to 20, so the weight's size alone misleads. Age costs nothing. Press Shuffle again on credit limit and you get 8.3, then 16.7: one shuffle is noisy, so scikit-learn averages several.
In code
permutation_importance shuffles each test column 5 times. partial_dependence with method="brute" pins one
feature to each value you give it and averages predict_proba.
# script_id: day_026_explaining_models/explain
import os
from pathlib import Path
import numpy as np
import pandas as pd
from sklearn.ensemble import HistGradientBoostingClassifier, RandomForestClassifier
from sklearn.inspection import partial_dependence, permutation_importance
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
df = pd.read_csv(DATA_DIR / "credit_default" / "default_of_credit_card_clients.csv")
df = df.drop(columns="ID").rename(columns={"default payment next month": "default"})
X, y = df.drop(columns="default").astype(float), df["default"] # partial_dependence rejects int columns
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)
model = HistGradientBoostingClassifier(random_state=42).fit(X_tr, y_tr) # the D25 model
print(f"test ROC-AUC: {roc_auc_score(y_te, model.predict_proba(X_te)[:, 1]):.3f}")
r = permutation_importance(model, X_te, y_te, scoring="roc_auc", n_repeats=5, random_state=42)
imp = pd.DataFrame({"drop": r.importances_mean, "spread": r.importances_std}, index=X.columns)
print(imp.sort_values("drop", ascending=False).head(4).round(3))
pdp = partial_dependence(model, X_te, ["PAY_0"], method="brute", response_method="predict_proba",
custom_values={"PAY_0": [-1, 0, 1, 2, 3]})
print("PAY_0 -1..3, average p(default):", pdp["average"][0].round(3))
print("BILL_AMT1 vs BILL_AMT2 correlation:", round(X["BILL_AMT1"].corr(X["BILL_AMT2"]), 2))
test ROC-AUC: 0.781
drop spread
PAY_0 0.085 0.002
LIMIT_BAL 0.022 0.001
BILL_AMT1 0.020 0.003
PAY_AMT2 0.011 0.002
PAY_0 -1..3, average p(default): [0.181 0.174 0.239 0.591 0.594]
BILL_AMT1 vs BILL_AMT2 correlation: 0.95
The latest repayment status matters about four times as much as the credit limit (LIMIT_BAL). The small spread
says five shuffles agree. The average risk barely moves from −1 to 0, rises at one month late, and jumps at two.
The credit limit is a smooth number, so its curve is easier to read as a chart:
# script_id: day_026_explaining_models/explain
import matplotlib.pyplot as plt
from sklearn.inspection import PartialDependenceDisplay
FIG_DIR = Path(os.environ.get("ML_FIG_DIR", "figures"))
FIG_DIR.mkdir(exist_ok=True)
fig, ax = plt.subplots(figsize=(6, 4))
PartialDependenceDisplay.from_estimator(model, X_te, ["LIMIT_BAL"], method="brute",
response_method="predict_proba", ax=ax)
ax.set_title("Default risk falls as the credit limit rises, then levels off")
fig.tight_layout()
fig.savefig(FIG_DIR / "pd_limit_bal.png", dpi=120)
plt.close(fig)

Now the forest from D24, given one extra column of random numbers:
# script_id: day_026_explaining_models/explain
rng = np.random.default_rng(42)
X_tr_n = X_tr.assign(noise=rng.random(len(X_tr))) # pure noise: no link to default
X_te_n = X_te.assign(noise=rng.random(len(X_te)))
forest = RandomForestClassifier(n_estimators=300, n_jobs=-1, random_state=42).fit(X_tr_n, y_tr)
impurity = pd.Series(forest.feature_importances_, index=X_tr_n.columns).sort_values(ascending=False)
print("impurity importance, top 3:", impurity.head(3).round(3).to_dict())
perm = permutation_importance(forest, X_te_n, y_te, scoring="roc_auc", n_repeats=5, random_state=42, n_jobs=-1)
print(f"noise, permutation importance on test: {perm.importances_mean[-1]:.4f}")
impurity importance, top 3: {'PAY_0': 0.098, 'noise': 0.07, 'AGE': 0.057}
noise, permutation importance on test: -0.0003
The forest split on the noise again and again to memorize training rows, so impurity ranks it second. On the test set, shuffling it costs nothing.
Quick check
Quick check
1. Shuffling a feature drops test ROC-AUC from 0.85 to 0.72. What is its permutation importance?
2. Why compute permutation importance on the test set, not the training set?
3. A forest's impurity importance ranks a random-number column second. What does that tell you?
Next
D27 tunes this model's settings on a fixed compute budget.
Data: Default of Credit Card Clients (UCI Machine Learning Repository, dataset 350), CC BY 4.0; cite Yeh, I.-C. and Lien, C.-H. (2009), "The comparisons of data mining techniques for the predictive accuracy of probability of default of credit card clients", Expert Systems with Applications 36(2).