Skip to content

Interpretability

Interpretability tools answer two questions: what drives a model overall (global), and why it gave one prediction (local). This page covers intrinsic explanations (coefficients), model-agnostic tools (permutation importance, partial dependence, ICE) and SHAP. The examples explain churn models fitted on data/customers.csv. The blocks share one session:

import numpy as np
import pandas as pd
import shap
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
pd.set_option("display.width", 100)
pd.set_option("display.precision", 3)
customers = pd.read_csv("data/customers.csv")
features = ["tenure_months", "monthly_charges", "support_tickets", "logins_last_30d",
"avg_session_minutes", "has_autopay", "age"]
X = customers[features].astype(float) # float: partial_dependence rejects int columns
y = customers["churned"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
gbc = GradientBoostingClassifier(n_estimators=150, max_depth=3, random_state=42)
gbc.fit(X_train, y_train)
print(X.shape, round(gbc.score(X_test, y_test), 3))
Output
(5000, 7) 0.837
I want to… Use… Scope
comparable linear coefficients StandardScaler in the pipeline, then pipe[-1].coef_ global
a coefficient in original units coef / pipe[0].scale_ global
odds ratios of a logistic model np.exp(coef) global
percent change in the odds np.exp(coef) - 1 global
uncertainty of a coefficient statsmodels smf.logit(...).fit().conf_int() or a bootstrap global
a tree model’s built-in importance model.feature_importances_ global; training data; biased
what the model needs on new data permutation_importance(model, X_test, y_test, n_repeats=10, random_state=42) global
permutation importance with another metric scoring="roc_auc" global
permute raw columns through preprocessing pass the whole Pipeline and raw X_test global
check importances against noise add a random column; real features must beat it global
the average effect of one feature PartialDependenceDisplay.from_estimator(model, X, ["f"]) global
one curve per row kind="individual" or kind="both" local
compare ICE slopes kind="both", centered=True, subsample=50 local
the numbers behind a PDP partial_dependence(model, X, ["f"], kind="average") global
average over the data I pass method="brute" global
a two-feature interaction plot features=[("f1", "f2")] global
SHAP values of a tree model sv = shap.TreeExplainer(model)(X) local
SHAP values of a linear model shap.LinearExplainer(model, shap.maskers.Independent(X, max_samples=len(X))) local
check SHAP additivity np.allclose(sv.base_values + sv.values.sum(1), raw_output) local
global SHAP importance np.abs(sv.values).mean(axis=0) or shap.plots.bar(sv, show=False) global
every row and feature in one plot shap.plots.beeswarm(sv, show=False) global
explain one prediction shap.plots.waterfall(sv[i], show=False) local
SHAP against a feature value shap.plots.scatter(sv[:, "f"], color=sv, show=False) global
SHAP for a pipeline TreeExplainer(pipe[-1])(pipe[:-1].transform(X)) local
one SHAP value per original column sum the one-hot columns of each feature either
a what-if for one row change a copy of the row, call predict_proba again local
Question Method Needs labels Watch out
What does the model need to score well on new data? permutation importance yes correlated features hide each other
How much does each feature move the predictions? mean absolute SHAP no correlated features share credit
What is the average effect of a feature? PDP no averages hide opposite effects
Does the effect differ between rows? ICE, centered no impossible rows with correlated features
Why this one prediction? SHAP waterfall no log-odds for boosting classifiers
Size and sign of an effect in a linear model standardized coefficient, odds ratio — collinearity, regularization
A quick look during development feature_importances_ — training data; favors continuous features
logit = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
logit.fit(X_train, y_train)
coef = pd.Series(logit[-1].coef_[0], index=features) # log-odds per 1 SD
table = pd.DataFrame({
"coef_per_sd": coef,
"odds_ratio_per_sd": np.exp(coef),
"odds_ratio_per_unit": np.exp(coef / logit[0].scale_), # original units
})
print(table.sort_values("coef_per_sd", key=abs, ascending=False).round(3))
Output
coef_per_sd odds_ratio_per_sd odds_ratio_per_unit
tenure_months -1.133 0.322 0.945
support_tickets 0.528 1.696 1.578
monthly_charges 0.437 1.547 1.019
logins_last_30d -0.282 0.754 0.966
has_autopay -0.216 0.806 0.649
age -0.102 0.903 0.992
avg_session_minutes -0.068 0.934 0.991
Model A coefficient means Turn it into
linear regression change in y^\hat y per unit of xjx_j, the others fixed per SD: fit on scaled data; per unit: coef / scale_
logistic regression change in the 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 category
log target change in ln⁡y\ln y per unit percent effect np.exp(coef) - 1
interaction x1:x2 the slope of x1 changes with x2 read slopes at chosen x2 values

Tenure has an odds ratio of 0.32 per SD: each extra SD of tenure (about 20 months) cuts the odds of churn to about a third, the other features fixed. Per month, the ratio is 0.945: about 5.5% lower odds. Odds are not probabilities: the change in probability depends on the starting point. Before you trust a coefficient, check correlations (X.corr() above about 0.8 makes coefficients unstable), compare models with the same penalty (C, alpha) and bootstrap the sign.

from sklearn.inspection import permutation_importance
rng = np.random.default_rng(42)
X_noise_train = X_train.assign(noise=rng.normal(size=len(X_train))) # no signal
X_noise_test = X_test.assign(noise=rng.normal(size=len(X_test)))
gbc_noise = GradientBoostingClassifier(n_estimators=150, max_depth=3, random_state=42)
gbc_noise.fit(X_noise_train, y_train)
perm = permutation_importance(gbc_noise, X_noise_test, y_test, scoring="roc_auc",
n_repeats=10, random_state=42)
imp = pd.DataFrame({
"impurity (train)": gbc_noise.feature_importances_,
"permutation (test AUC)": perm.importances_mean,
"perm_std": perm.importances_std,
}, index=X_noise_train.columns)
print(imp.sort_values("permutation (test AUC)", ascending=False).round(3))
Output
impurity (train) permutation (test AUC) perm_std
tenure_months 0.415 0.138 0.018
monthly_charges 0.144 0.033 0.006
age 0.110 0.031 0.005
support_tickets 0.089 0.026 0.007
logins_last_30d 0.113 0.026 0.004
has_autopay 0.012 0.001 0.001
noise 0.084 -0.001 0.002
avg_session_minutes 0.033 -0.002 0.002
Impurity (MDI) feature_importances_ Permutation permutation_importance
Measures split gains in the training data score drop when a column is shuffled
Data training rows held-out rows
Models trees only any fitted model or pipeline
Units shares that sum to 1 points of the metric (AUC, R²)
Cost free n_features × n_repeats predictions
Bias favors continuous and many-valued columns; noise gets credit correlated features hide each other
Can be negative no yes: the column hurts or is noise
permutation_importance argument Advice
X, y held-out data, never the training set
scoring "roc_auc", "average_precision" for rare classes; default model.score
n_repeats 5–10; report importances_std
random_state fix it for repeatable tables
max_samples lower it for large test sets

The pure-noise column gets 8% of the impurity importance, more than has_autopay, but no permutation importance. Impurity importance is computed on the training rows, where the trees split on noise.

from sklearn.inspection import partial_dependence
grid = {"tenure_months": np.array([1.0, 6.0, 12.0, 24.0, 48.0])}
pdp_brute = partial_dependence(gbc, X_test, ["tenure_months"], custom_values=grid,
method="brute") # averages over X_test
pdp_rec = partial_dependence(gbc, X_test, ["tenure_months"], custom_values=grid,
method="recursion") # trees: training data, no constant
print(pdp_brute["grid_values"][0], pdp_brute["average"][0].round(3)) # probability
print(pdp_rec["average"][0].round(3)) # raw log-odds scale for boosting classifiers
ice = partial_dependence(gbc, X_test, ["tenure_months"], custom_values=grid,
kind="individual")
print(ice["individual"][0].shape) # rows x grid points
Output
[ 1. 6. 12. 24. 48.] [0.565 0.222 0.17 0.121 0.054]
[ 1.894 0.011 -0.395 -0.835 -1.776]
(1250, 5)
method= Averages over Output for a boosting classifier Use
"auto" (default) recursion for trees with kind="average", otherwise brute depends on the choice quick plots
"brute" the X you pass predict_proba the honest average; any model; ICE
"recursion" the training data (tree structure) log-odds without the initial constant fast; trees only; levels differ

Plotting template:

import matplotlib.pyplot as plt
from sklearn.inspection import PartialDependenceDisplay
fig, axes = plt.subplots(1, 3, figsize=(12, 3.5))
PartialDependenceDisplay.from_estimator(gbc, X_test, ["tenure_months"], ax=axes[0])
PartialDependenceDisplay.from_estimator( # ICE: one line per row, plus the average
gbc, X_test, ["logins_last_30d"], kind="both", centered=True, subsample=50,
random_state=42, ax=axes[1],
)
PartialDependenceDisplay.from_estimator( # two-way interaction (contour)
gbc, X_test, [("tenure_months", "monthly_charges")], ax=axes[2],
)
fig.tight_layout()
plt.show()
Argument Values Note
features ["f"], [("f1", "f2")] a tuple draws a two-way PDP
kind "average", "individual", "both" ICE needs method="brute" (chosen automatically)
centered True every ICE line starts at 0: compare slopes
subsample int or fraction ICE lines drawn
grid_resolution, percentiles 100, (0.05, 0.95) grid between the 5th and 95th percentile
custom_values {"f": array} your own grid
categorical_features names or a mask one point per category
response_method "predict_proba", "decision_function" log-odds for classifiers

Read a PDP as “the model’s average prediction if every row had this value”. Parallel ICE lines mean no interaction; fanning or crossing lines mean the effect depends on other features.

SHAP (SHapley Additive exPlanations) splits each prediction into one contribution per feature. The parts add up exactly:

f(x)=ϕ0+∑j=1pϕj(x)f(x) = \phi_0 + \sum_{j=1}^{p} \phi_j(x)
explainer = shap.TreeExplainer(gbc)
sv = explainer(X_test) # an Explanation object
print(sv.values.shape, round(float(sv.base_values[0]), 3))
log_odds = gbc.decision_function(X_test) # the output TreeExplainer explains here
print(np.allclose(sv.base_values + sv.values.sum(axis=1), log_odds)) # additivity
row = 0
p = 1 / (1 + np.exp(-(sv.base_values[row] + sv.values[row].sum()))) # sigmoid
print(round(float(p), 4), round(float(gbc.predict_proba(X_test.iloc[[row]])[0, 1]), 4))
top = pd.Series(sv.values[row], index=features).sort_values(key=abs, ascending=False)
print(top.head(3).round(3)) # the top reasons for one customer, in log-odds
mean_abs = pd.Series(np.abs(sv.values).mean(axis=0), index=features)
print(mean_abs.sort_values(ascending=False).head(3).round(3))
Output
(1250, 7) -1.943
True
0.058 0.058
support_tickets -0.389
age -0.264
monthly_charges -0.158
dtype: float64
tenure_months 0.742
monthly_charges 0.377
support_tickets 0.338
dtype: float64

The base value −1.943 is the mean log-odds; its sigmoid (0.125) is not the churn rate (0.193). Convert only the full sum, as above.

Model Explainer Output space of the SHAP values Shape of sv.values
GradientBoostingRegressor, forest regressors TreeExplainer(model) prediction units (n, p)
GradientBoostingClassifier (binary) TreeExplainer(model) log-odds (decision_function) (n, p)
XGBoost, LightGBM classifiers TreeExplainer(model) log-odds (raw margin) (n, p)
RandomForestClassifier TreeExplainer(model) probability (n, p, n_classes): pick [:, :, 1]
linear models LinearExplainer(model, masker) the model’s raw output (n, p)
any model shap.Explainer(model.predict_proba, masker) as given; slow depends
a Pipeline TreeExplainer(pipe[-1])(pipe[:-1].transform(X)) as above encoded columns
Explanation part Holds
sv.values SHAP values
sv.base_values ϕ0\phi_0 per row: the average model output on the background
sv.data, sv.feature_names the explained rows and the column names
sv[i] one row, for waterfall
sv[:, "f"] one feature, for scatter

Plotting template (show=False, then your labels, then one plt.show()):

import matplotlib.pyplot as plt
shap.plots.beeswarm(sv, max_display=10, show=False) # every row, colored by value
plt.show()
shap.plots.bar(sv, show=False) # mean |SHAP| per feature
plt.show()
shap.plots.waterfall(sv[0], max_display=8, show=False) # one prediction
plt.title("Customer 0, log-odds of churn")
plt.show()
shap.plots.scatter(sv[:, "tenure_months"], color=sv, show=False) # dependence
plt.show()
Say Avoid
“The model’s churn score rises with support tickets” “Support tickets cause churn”
units: log-odds, probability points, AUC points a unitless “importance 0.27”
the spread over repeats, folds or seeds single numbers with false precision
original features (one-hot columns summed) payment_method_credit_card = 0
three reasons in plain words for one customer a full SHAP table
correlated groups and sparse regions silent caveats
an experiment to test an action a what-if score promised as an outcome
Trap Symptom Fix
feature_importances_ as the final answer a pure-noise column gets credit permutation importance on held-out data
permutation importance on the training set memorized noise looks important use the test or validation set
correlated features each looks unimportant when permuted alone; SHAP splits credit permute groups; report correlated features together
permuting one-hot columns one by one impossible rows (two categories at once) pass the pipeline and raw columns
integer columns in partial_dependence ValueError (scikit-learn 1.9) X.astype(float) before fitting
method="auto" on trees the PDP level differs from the mean prediction method="brute" to average over your X
a flat PDP “no effect” claimed draw ICE: opposite effects can cancel
PDP far from the data effects in regions with no rows read only between the 5th and 95th percentile
SHAP of a boosting classifier read as probability contributions do not add to predict_proba they are log-odds: sum, then apply the sigmoid
sigmoid of base_values read as the churn rate a number off from y.mean() it is the mean log-odds, not the mean probability
forest classifier SHAP shape a 3-D array select the positive class: sv[:, :, 1]
SHAP on a log target effects in log units contributions multiply on the original scale
shap plots without show=False plt.title lands on a new empty figure show=False, then plt.show()
LinearExplainer(model, X) with more than 100 rows a subsampling message on the output shap.maskers.Independent(X, max_samples=len(X))
explanations read causally wrong business decisions explanations describe the model; test actions with experiments
explaining a weak model confident stories about noise check the test score before explaining