43. Interpretability — Cheat sheet
The essentials of module 43 on one page. Every runnable block on this page is checked against its output. The blocks run in order and use scikit-learn’s bundled diabetes dataset (442 patients, 10 float features, target: disease progression after one year), so they run in seconds.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Scope |
|---|---|---|
| compare linear coefficients fairly | StandardScaler in a Pipeline, then pipe[-1].coef_ |
global |
| read a logistic coefficient | np.exp(coef): odds ratio per unit (or per SD) |
global |
| convert a standardized coefficient to real units | coef / scaler.scale_ |
global |
| get a tree model’s built-in importance | model.feature_importances_ (MDI, training data, biased) |
global |
| measure what the model needs on new data | permutation_importance(model, X_test, y_test, n_repeats=5, random_state=42) |
global |
| use another metric | permutation_importance(..., scoring="roc_auc") |
global |
| permute raw columns through preprocessing | pass the whole Pipeline and raw X_test |
global |
| see the average effect of one feature | PartialDependenceDisplay.from_estimator(model, X, ["f"]) |
global |
| see the effect per row | from_estimator(..., kind="individual") or kind="both" |
local |
| compare ICE slopes | from_estimator(..., kind="both", centered=True, subsample=50) |
local |
| get the numbers behind a PDP or ICE | partial_dependence(model, X, ["f"], kind="average" or "individual") |
either |
| choose the grid | partial_dependence(..., custom_values={"f": np.array([...])}) |
either |
| explain a classifier in log-odds | partial_dependence(..., response_method="decision_function") |
either |
| explain a tree model’s predictions | explainer = shap.TreeExplainer(model); sv = explainer(X) |
local |
| check SHAP additivity | np.allclose(sv.base_values + sv.values.sum(axis=1), raw_output) |
local |
| plot global SHAP importance | shap.plots.beeswarm(sv, show=False) or shap.plots.bar(sv, show=False) |
global |
| explain one prediction | shap.plots.waterfall(sv[i], show=False) |
local |
| plot one feature’s SHAP values | shap.plots.scatter(sv[:, "f"], show=False) |
global |
| combine one-hot SHAP columns | sum the columns per original feature (additivity keeps totals) | either |
| test a model’s what-if | change one column of a row copy, call predict_proba again |
local |
Setup for the snippets
Section titled “Setup for the snippets”import matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport shapfrom sklearn.datasets import load_diabetesfrom sklearn.ensemble import GradientBoostingRegressorfrom sklearn.inspection import ( PartialDependenceDisplay, partial_dependence, permutation_importance,)from sklearn.linear_model import LinearRegressionfrom sklearn.model_selection import train_test_splitfrom sklearn.pipeline import make_pipelinefrom sklearn.preprocessing import StandardScaler
pd.set_option("display.width", 100)pd.set_option("display.precision", 3)
X, y = load_diabetes(return_X_y=True, as_frame=True)X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.25, random_state=42)gbr = GradientBoostingRegressor(n_estimators=150, max_depth=3, random_state=42)gbr.fit(X_train, y_train)print(X.shape, f"test R² {gbr.score(X_test, y_test):.3f}")(442, 10) test R² 0.409Coefficients
Section titled “Coefficients”lin = make_pipeline(StandardScaler(), LinearRegression()).fit(X_train, y_train)coef = pd.Series(lin[-1].coef_, index=X.columns) # change per 1 SD of the featureprint(coef.sort_values(key=abs, ascending=False).head(3).round(1)) # s1, s2 correlateper_unit = coef / lin[0].scale_ # back to the original unitsprint(f"bmi per unit: {per_unit['bmi']:.1f}")s1 -44.1s5 33.4bmi 25.1dtype: float64bmi per unit: 532.0| Model | Coefficient means | Turn it into |
|---|---|---|
| linear regression | change in per unit of , others fixed | per SD: coef * sd; per unit: coef / sd after scaling |
| logistic regression | change in log-odds per unit | odds ratio np.exp(coef); percent np.exp(coef) - 1 |
one-hot column (drop="first") |
difference from the reference category | name the reference in every report |
| log target | change in | percent effect np.exp(coef) - 1 |
Checks before you trust a coefficient:
- Standardize, or compare per-SD effects only.
- Check correlations between features:
X.corr(). Pairs above about 0.8 make coefficients unstable. - Bootstrap: refit on resampled rows and look at the spread and the sign.
- Regularization (
Ridge,Lasso, the defaultC=1.0ofLogisticRegression) shrinks coefficients; compare models with the same penalty.
Impurity-based importance (MDI)
Section titled “Impurity-based importance (MDI)”mdi = pd.Series(gbr.feature_importances_, index=X.columns)print(mdi.sort_values(ascending=False).head(3).round(3))print(f"sum: {mdi.sum():.1f}") # MDI always sums to 1bmi 0.361s5 0.209bp 0.109dtype: float64sum: 1.0| Property | Detail |
|---|---|
| Computed from | impurity reductions of all splits, on the training data |
| Sums to | 1 |
| Bias | favors continuous and high-cardinality features (many split points) |
| Cost | free, computed during fit |
| Sanity check | add a random column rng.normal(size=n); real features should beat it |
Permutation importance
Section titled “Permutation importance”perm = permutation_importance(gbr, X_test, y_test, n_repeats=5, random_state=42)table = pd.DataFrame( {"mean": perm.importances_mean, "std": perm.importances_std}, index=X.columns)print(table.sort_values("mean", ascending=False).head(4).round(3))print(perm.importances.shape) # one column per repeat mean stds5 0.286 0.065bmi 0.251 0.064sex 0.054 0.013bp 0.039 0.048(10, 5)| Parameter | Meaning | Advice |
|---|---|---|
X, y |
data to permute and score | held-out data, never the training set |
scoring |
metric; default is model.score |
"roc_auc" or "average_precision" for imbalanced classes |
n_repeats |
shuffles per feature | 5–10; report the std |
random_state |
seed of the shuffles | fix it for reproducible tables |
max_samples |
fraction or number of rows per repeat | lower it for large test sets |
n_jobs |
parallel workers | leave unset in small scripts |
Result attributes: importances_mean, importances_std, importances (features × repeats).
Partial dependence and ICE
Section titled “Partial dependence and ICE”pd_res = partial_dependence( gbr, X_test, ["bmi"], custom_values={"bmi": np.array([-0.05, 0.0, 0.05])})print(pd_res["grid_values"][0], pd_res["average"][0].round(1)) # recursion, no constantice = partial_dependence(gbr, X_test, ["bmi"], kind="individual", grid_resolution=5)print(ice["individual"][0].shape) # (rows, grid points)[-0.05 0. 0.05] [-20.8 -20.3 21.3](111, 5)fig, axes = plt.subplots(1, 2, figsize=(9, 3.2))PartialDependenceDisplay.from_estimator(gbr, X_test, ["bmi"], ax=axes[0])PartialDependenceDisplay.from_estimator( gbr, X_test, ["s5"], kind="both", centered=True, subsample=40, random_state=42, ax=axes[1],)fig.tight_layout()plt.show()
| Argument | Values | Note |
|---|---|---|
features |
["f"], [("f1", "f2")] |
a tuple draws a two-way PDP (contour) |
kind |
"average", "individual", "both" |
ICE needs the slower brute-force method |
centered |
True / False |
start every curve at 0 to compare slopes |
subsample |
int or fraction | number of ICE lines to draw |
grid_resolution |
default 100 | grid points between percentiles |
percentiles |
default (0.05, 0.95) |
grid range; avoids the sparse tails |
custom_values |
{"f": array} |
your own grid |
categorical_features |
names or mask | one point per category |
response_method |
"auto", "predict_proba", "decision_function" |
log-odds for classifiers |
method |
"auto", "recursion", "brute" |
"auto" picks recursion for tree models with kind="average". Recursion: tree models only; averages over the training data, not X; for gradient boosting it also omits the initial constant. "brute" averages over X |
explainer = shap.TreeExplainer(gbr)sv = explainer(X_test)print(type(sv).__name__, sv.values.shape, round(float(sv.base_values[0]), 1))print(np.allclose(sv.base_values + sv.values.sum(axis=1), gbr.predict(X_test)))mean_abs = pd.Series(np.abs(sv.values).mean(axis=0), index=sv.feature_names)print(mean_abs.sort_values(ascending=False).head(3).round(1))Explanation (111, 10) 154.3Truebmi 25.1s5 23.0bp 14.0dtype: float64Explanation attribute |
Holds |
|---|---|
sv.values |
SHAP values, shape (rows, features) |
sv.base_values |
per row (the average model output) |
sv.data |
the feature values that were explained |
sv.feature_names |
column names |
sv[i] |
one row, for waterfall |
sv[:, "bmi"] |
one feature, for scatter |
| Model | Explainer | Output explained |
|---|---|---|
| sklearn forests and gradient boosting, XGBoost, LightGBM | shap.TreeExplainer(model) |
regressor: prediction; boosting classifier: log-odds; forest classifier: probability |
| linear models | shap.LinearExplainer(model, masker) |
prediction; value for independent features |
| any model | shap.Explainer(model.predict, masker) |
slow; keep the data small |
a Pipeline |
explain pipe[-1] on pipe[:-1].transform(X) |
trees split on encoded columns |
shap.plots.waterfall(sv[0], max_display=6, show=False)plt.title("One patient")plt.show()
| Plot | Shows | Call |
|---|---|---|
| beeswarm | every row and feature; color = feature value | shap.plots.beeswarm(sv, max_display=10, show=False) |
| bar | mean absolute SHAP per feature | shap.plots.bar(sv, show=False) |
| waterfall | one prediction from base value to output | shap.plots.waterfall(sv[i], show=False) |
| scatter | SHAP value vs feature value (dependence) | shap.plots.scatter(sv[:, "f"], color=sv, show=False) |
Plot rule: pass show=False, add titles or labels, then call plt.show() once.
Choosing a method
Section titled “Choosing a method”| Question | Method | Why |
|---|---|---|
| Which features does the model need on new data? | permutation importance on held-out data | measures loss of score; model-agnostic |
| How far does each feature move the predictions? | mean absolute SHAP | additive, per row, no labels needed |
| What is the average effect of one feature? | PDP | simple curve; check with ICE |
| Does the effect differ between rows? | ICE, centered | fan or crossing lines reveal interactions |
| Why this one prediction? | SHAP waterfall, top reasons | exact decomposition of the output |
| What is the size and sign of an effect in a linear model? | standardized coefficient or odds ratio | intrinsic, if features are not strongly correlated |
| Quick look during development | feature_importances_ |
free, but biased; never the final word |
Communicating explanations
Section titled “Communicating explanations”| Do | Avoid |
|---|---|
| “The model’s score rises with support tickets” | “Support tickets cause churn” |
| give units: log-odds, percent of price, points of ROC-AUC | unitless “importance 0.27” |
| show the spread over repeats or seeds | single numbers with false precision |
| group one-hot columns into original features | payment_method_credit_card = 0 |
| three reasons in plain words for one customer | a full SHAP table |
| name correlated groups and extrapolated regions | silent caveats |
| test an action with an experiment | promise a what-if score as an outcome |
Gotchas
Section titled “Gotchas”feature_importances_is computed on the training data and ranks random continuous columns above real binary features.- Permutation importance on the training set rewards memorized noise. Use held-out data.
- Correlated features hide each other in permutation importance, share credit in SHAP, and create impossible rows in partial dependence. Shuffling one of an offsetting pair can also inflate its importance.
- Permuting one-hot columns separately creates rows with two categories at once. Permute raw columns through the pipeline.
partial_dependenceraises aValueErrorfor integer columns in scikit-learn 1.9. Cast to float before fitting.- A flat PDP does not prove “no effect”. Opposite effects can cancel; draw ICE curves.
- For tree models,
kind="average"defaults to therecursionmethod, which averages over the training data, not over theXyou pass. For gradient boosting it also leaves out the starting constant, so the level differs from the average prediction. Passmethod="brute"to average overX. - SHAP values of a boosting classifier are in log-odds. Add them, then apply the sigmoid. The sigmoid of the base value is not the mean predicted probability.
- On a log target, SHAP contributions add in log units and multiply on the original scale.
- shap plots call
plt.show()themselves by default. Withoutshow=False, a laterplt.titlelands on a new empty figure. - Explain the encoded rows for a pipeline:
explainer(pipe[:-1].transform(X)). shap.LinearExplainer(model, X)with more than 100 background rows prints a subsampling message and uses only 100 rows. Passshap.maskers.Independent(X, max_samples=len(X))for exact means and a silent run.- No explanation method is causal. Explanations describe the model, not the world.