Skip to content

43. Interpretability

A churn model flags customer C04542 with a 97% churn risk. The retention agent who calls this customer asks one question: “Why?” The product manager asks a second one: “What drives churn across all our customers?” A good score on the test set answers neither question. This module gives you the tools that do.

Interpretability is the degree to which a person can understand why a model makes its predictions. You use it to debug a model, to find data leakage, to earn the trust of the people who act on the predictions, to meet legal duties such as explaining a credit refusal, and to learn something about the problem itself. The lesson uses the two main datasets of the course: data/customers.csv for churn and data/houses.csv for house prices. The data dictionary describes every column.

  • Tell global explanations (how the model behaves overall) from local explanations (why it made one prediction), and choose the right one for a question.
  • Read linear model coefficients on standardized features and logistic regression odds ratios, and recognize when correlated features make them unstable.
  • Explain why impurity-based tree importance favors continuous and high-cardinality features, and replace it with permutation importance on a held-out set.
  • Draw partial dependence plots and ICE curves with PartialDependenceDisplay, and spot the interactions and impossible rows that an average can hide.
  • Compute SHAP values with shap.TreeExplainer, check that they add up to the prediction, and read beeswarm and waterfall plots.
  • Use explanations responsibly: they describe the model, not the world, and they are not causal.

A model with a good test score can still be wrong for the wrong reasons. It can lean on a column that leaks the target, on an id that happens to correlate with time, or on a pattern that holds only in the training period. Explanations make these problems visible before the model reaches production.

Reason Question Example
Debugging Does the model use sensible features? A churn model that relies on customer_id has found a leak.
Trust Do the people who act on it agree with its logic? A retention agent sees that “9 support tickets” drives a risk score.
Compliance Can we justify one decision to the person it affects? A lender must give the main reasons for a credit refusal.
Discovery What does the model say about the problem? The model adds more value for size in Lakeview than in Cedar Park (Example 4).

Some models are intrinsically interpretable: you can read their logic directly. A linear model has one coefficient per feature, and a shallow decision tree is a short list of rules. Other models, such as random forests and gradient boosting, are black boxes: they are too large to read, so you explain them post hoc, after training, with separate tools.

A global explanation describes how the model behaves over the whole dataset: which features matter most and how the prediction changes with each feature. A local explanation describes one prediction: why the model gave this customer this score.

Global Local
Question “What drives churn?” “Why is C04542 at 97%?”
Audience data scientists, product managers, auditors the person affected, the agent who calls them
Methods in this module coefficients, impurity and permutation importance, partial dependence, mean absolute SHAP ICE curves, SHAP values of one row (waterfall plot)

A second distinction is about scope. A model-specific method works for one family of models, such as coefficients for linear models or impurity importance for trees. A model-agnostic method treats the model as a black box: it only calls predict or predict_proba, so it works for any model. Permutation importance, partial dependence and ICE are model-agnostic. SHAP is a general idea with fast, model-specific algorithms; this module uses the one for trees.

flowchart TD
    Q{"Question about the model"} --> G["Global:<br/>how does it behave overall?"]
    Q --> L["Local:<br/>why this prediction?"]
    G --> G1["Which features matter?<br/>permutation importance,<br/>mean |SHAP|"]
    G --> G2["How does the prediction<br/>change with a feature?<br/>partial dependence"]
    L --> L1["Which features pushed<br/>this score up or down?<br/>SHAP waterfall"]
    L --> L2["What if one feature changed?<br/>ICE curve"]

The lesson page runs top to bottom in one namespace. The first block loads every library of the page and the churn data. It makes the same stratified train/test split as the data dictionary baseline.

total_charges is blank for 10 brand-new customers who signed up in December 2024 and have tenure_months 0. scikit-learn’s GradientBoostingClassifier rejects blanks, so the block fills them. With no completed month of tenure, 0 is a reasonable value; it is a choice, not a recorded fact.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import shap
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import GradientBoostingClassifier, RandomForestRegressor
from sklearn.inspection import (
PartialDependenceDisplay,
partial_dependence,
permutation_importance,
)
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
customers = pd.read_csv("data/customers.csv")
customers["total_charges"] = customers["total_charges"].fillna(0.0)
num_cols = [
"age", "tenure_months", "monthly_charges", "total_charges",
"support_tickets", "logins_last_30d", "avg_session_minutes", "has_autopay",
]
cat_cols = ["region", "plan", "contract", "payment_method"]
X = customers[num_cols + cat_cols]
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
)
print(X_train.shape, X_test.shape)
Output
(3750, 12) (1250, 12)

A linear model predicts with a weighted sum: y^=b+w1x1+w2x2+⋯+wpxp\hat{y} = b + w_1 x_1 + w_2 x_2 + \dots + w_p x_p. Each coefficient wjw_j says how much the prediction changes when feature xjx_j grows by one unit and every other feature stays the same. This “all else equal” reading makes linear models the classic interpretable model.

Two rules make the reading correct:

  1. Compare coefficients only on standardized features. A raw coefficient depends on the unit. The coefficient of sqft per square foot is tiny, and the coefficient of has_pool (0 or 1) is large, but that says nothing about which feature matters more. After StandardScaler, every numeric feature has mean 0 and standard deviation 1. A standardized coefficient is then the effect of a one-standard-deviation step, and steps of the same “size” are comparable.
  2. Read logistic regression coefficients as odds ratios. Logistic regression is linear in the log-odds log⁡p1−p\log\frac{p}{1-p}. A one-unit step in xjx_j multiplies the odds by ewje^{w_j}, the odds ratio. An odds ratio of 1.72 means “72% higher odds”, and 0.36 means “64% lower odds”. An odds ratio is not a ratio of probabilities (module 36 shows why).

For a one-hot encoded column such as contract_two-year, the coefficient compares the category with the reference category, the level that drop="first" removed (here month-to-month).

Every split in a decision tree reduces the impurity of the node: the Gini impurity or entropy for classification, the squared error for regression. A tree model’s feature_importances_ adds up the impurity reductions of all splits on each feature, weighted by the number of training rows that reach the split, and scales the totals to sum to 1. A forest averages this over its trees. The method is also called mean decrease in impurity (MDI).

MDI is free: the model computes it during training. It has two serious flaws:

  • It is measured on the training data. A deep tree splits on noise to fit the training rows, and MDI credits the noise feature for that “reduction”.
  • It favors features with many possible split points. A continuous feature or an id with thousands of distinct values offers thousands of thresholds. Some of them separate the training rows well by chance. A 0/1 flag offers one threshold. So a random continuous column can get a higher importance than a real binary feature.

Module 33 warned about this bias. Example 2 measures it with two random columns.

Permutation importance asks a direct question: how much worse does the model score when one feature carries no information? To remove the information without retraining, it shuffles the column. The shuffle keeps the column’s values but breaks their link to the target and to the other features.

  1. Score the fitted model on a held-out set: the baseline score ss.
  2. For feature jj, shuffle its column, score again and get sjs_{j}. The importance is the drop s−sjs - s_{j}.
  3. Repeat the shuffle n_repeats times and report the mean and the standard deviation of the drops.
  4. Put the column back and move on to the next feature.
importancej=s−1K∑k=1Ksj,k\text{importance}_j = s - \frac{1}{K}\sum_{k=1}^{K} s_{j,k}

Here KK is n_repeats and sj,ks_{j,k} is the score after shuffle kk of feature jj. scikit-learn’s sklearn.inspection.permutation_importance(model, X, y, n_repeats=5, random_state=42, scoring=...) does all of this. It uses the model’s default score (R² for a regressor, accuracy for a classifier) unless you pass scoring.

Rules for good permutation importance:

  • Use a held-out set. On the training set, the importance shows what the model memorized. On the test set, it shows what generalizes.
  • Choose the metric you care about. For churn, scoring="roc_auc" measures ranking quality. Accuracy barely moves when only 19% of customers churn.
  • Permute raw columns, not one-hot columns. Pass the whole Pipeline and the raw X_test. Then one shuffle moves the whole contract column, and no row ends up with two contracts at once.
  • Watch correlated features. When two features carry the same information, shuffling one costs little because the model still has the other. Both can look unimportant, although together they matter.

An importance near 0, or slightly negative, means the model does not need the feature on this data. A negative value is noise: the shuffled column happened to score a little better.

Importance tells you how much a feature matters. It does not tell you how the prediction changes with it. A partial dependence plot (PDP) shows the average prediction as a function of one feature. For each grid value vv of feature jj, it sets column jj to vv in every row, predicts, and averages:

PDj(v)=1n∑i=1nf^(xi,1,…,xi,j=v,…,xi,p)\text{PD}_j(v) = \frac{1}{n}\sum_{i=1}^{n} \hat{f}\left(x_{i,1}, \dots, x_{i,j} = v, \dots, x_{i,p}\right)

An individual conditional expectation (ICE) curve is the same computation without the average: one curve per row. It shows how the prediction for one house or one customer would change if only this feature changed. The PDP is the average of the ICE curves. A centered ICE plot shifts every curve to start at 0, so that you compare slopes instead of levels.

PartialDependenceDisplay.from_estimator(model, X, features, kind=...) draws them: kind="average" for the PDP, "individual" for ICE curves and "both" for both. partial_dependence(...) returns the numbers instead of a plot.

Both functions take a method argument. method="brute" computes the formula above: it changes column jj in the rows of the X you pass and averages the predictions. For tree models (forests, gradient boosting, single trees) with kind="average", the default method="auto" picks method="recursion" instead. Recursion is fast, but it walks the trees and averages over the training data that reached each node; it uses your X only to build the grid. So its curve can differ from the brute-force average over X. For gradient boosting, recursion also leaves out the model’s constant starting value, so the curve sits around 0. ICE curves (kind="individual" or "both") always use brute force. Pass method="brute" when you want the formula above on a given dataset.

Two caveats:

  • An average hides interactions. If house size adds 40% in one neighborhood and 120% in another, the PDP shows one middle curve that fits neither. ICE curves that fan out or cross reveal the interaction: the effect of one feature depends on another.
  • Correlated features create impossible rows. Setting distance_to_center_km to 1 km for every house creates suburban houses in the city center. The model never saw such rows, so its predictions there are guesses. Read a PDP only where the data has support. The rug marks on the x-axis (the deciles of the feature) show where that is.

SHAP (SHapley Additive exPlanations) splits one prediction into one contribution per feature. Methods that split a prediction (or a score) among the features are called feature attribution methods. It comes from cooperative game theory. There, a Shapley value is the fair share of a team’s payout for one player: the player’s added value, averaged over every order in which the players could join the team. In SHAP, the players are the features and the payout is the prediction minus the average prediction.

The result is an exact sum. For row xx with pp features:

f^(x)=ϕ0+∑j=1pϕj(x)\hat{f}(x) = \phi_0 + \sum_{j=1}^{p} \phi_j(x)
  • ϕ0\phi_0 is the base value: the model’s average output over the background data (for trees, the training data).
  • ϕj(x)\phi_j(x) is the SHAP value of feature jj for this row: how far feature jj moved this prediction away from the base value. Positive values push the prediction up, negative values push it down.

This additivity property (also called local accuracy) makes SHAP values easy to communicate: start at the average, add each feature’s push, and you arrive at the prediction. Shapley values also give zero to a feature that the model never uses and equal shares to two features that play exactly the same role.

Exact Shapley values need 2p2^p model calls per row, which is too slow for most models. shap.TreeExplainer uses the structure of tree ensembles to compute exact values in milliseconds. It works with scikit-learn forests and gradient boosting, XGBoost and LightGBM.

Call Returns or draws
explainer = shap.TreeExplainer(model) an explainer for a fitted tree model
sv = explainer(X) an Explanation: sv.values (rows × features), sv.base_values, sv.data, sv.feature_names
shap.plots.beeswarm(sv, show=False) global: one dot per row and feature, colored by the feature value
shap.plots.bar(sv, show=False) global: mean absolute SHAP value per feature
shap.plots.waterfall(sv[i], show=False) local: how row i goes from the base value to its prediction
shap.plots.scatter(sv[:, "tenure_months"], show=False) one feature’s SHAP value against its value (a dependence plot)

The shap plots draw on the current matplotlib figure and call plt.show() themselves unless you pass show=False. Pass show=False, then add a title or save the figure, then call plt.show() once.

Method Scope Works for Measures Main weakness
Coefficients global linear models effect of one unit (or one SD) step unstable with correlated features; linear effects only
Impurity importance (MDI) global trees training impurity reduction biased toward continuous and high-cardinality features; training data
Permutation importance global any model drop in a test score correlated features share or hide importance; slower
Partial dependence global any model average prediction vs one feature hides interactions; impossible rows
ICE curves local any model prediction vs one feature, per row cluttered; same impossible rows
SHAP local and global any (fast for trees) additive contributions to one prediction correlated features share credit; easy to over-read as causal

Every method on this page explains the model, not the world. A large SHAP value for support_tickets means the model leans on tickets. It does not mean that tickets cause churn, or that closing tickets faster will keep customers. Tickets may only signal an unhappy customer. To learn what an action would do, you need an experiment, such as the A/B tests of module 29.

When you present explanations to people who are not data scientists:

  • Say what the number is. “Moves the churn score up”, not “causes churn”. Give units: log-odds, percent of price, points of ROC-AUC.
  • Show uncertainty. Report the spread of permutation importance over repeats, and check that a ranking survives a second random seed.
  • Name the caveats. Correlated features share credit. Partial dependence outside the data range is a guess.
  • Check for proxies. A model without a protected attribute (such as age or ethnicity) can still use a proxy feature: a feature that stands in for it, such as a postcode. Look at the explanations for such features before you deploy.
  • Keep it short. A retention agent needs three reasons in plain words, not a beeswarm plot.

Example 1 — Rank churn drivers with standardized coefficients

Section titled “Example 1 — Rank churn drivers with standardized coefficients”

Goal: Fit a logistic regression on the churn data, rank its standardized coefficients as odds ratios, and test how far you can trust them when two features are correlated.

Step 1 — Fit a scaled logistic regression

Section titled “Step 1 — Fit a scaled logistic regression”
def make_logit(numeric: list[str]) -> Pipeline:
"""Scale the numbers, one-hot encode the text columns, fit a logistic model."""
preprocess = ColumnTransformer(
[
("num", StandardScaler(), numeric),
("cat", OneHotEncoder(drop="first", sparse_output=False), cat_cols),
],
verbose_feature_names_out=False,
)
return make_pipeline(preprocess, LogisticRegression(max_iter=1000))
logit = make_logit(num_cols).fit(X_train, y_train)
auc = roc_auc_score(y_test, logit.predict_proba(X_test)[:, 1])
print(f"test ROC-AUC: {auc:.3f}")
Output
test ROC-AUC: 0.813

The pipeline standardizes the eight numeric columns and one-hot encodes the four text columns. LogisticRegression uses an L2 penalty by default (C=1.0), so its coefficients are slightly shrunk toward 0. The score matches the data dictionary baseline, so the model is worth explaining.

Step 2 — Rank the coefficients as odds ratios

Section titled “Step 2 — Rank the coefficients as odds ratios”
names = logit[:-1].get_feature_names_out()
coefs = pd.Series(logit[-1].coef_[0], index=names)
table = pd.DataFrame({"coef": coefs, "odds_ratio": np.exp(coefs)})
print(table.sort_values("coef", key=abs, ascending=False).head(9))
Output
coef odds_ratio
contract_two-year -1.730 0.177
contract_one-year -1.058 0.347
tenure_months -1.024 0.359
support_tickets 0.543 1.721
monthly_charges 0.429 1.536
payment_method_electronic_check 0.372 1.450
plan_standard -0.367 0.693
logins_last_30d -0.278 0.757
total_charges 0.270 1.310

key=abs sorts by size and ignores the sign. A two-year contract multiplies the churn odds by 0.177 compared with month-to-month (the reference category), an 82% cut. One standard deviation more tenure cuts the odds by 64%. One standard deviation more support tickets raises them by 72%. Their directions agree with the headline churn rates in the data dictionary. Then comes a surprise: total_charges has an odds ratio above 1. Do customers who paid more churn more?

Step 3 — Translate one coefficient into real units

Section titled “Step 3 — Translate one coefficient into real units”
scaler = logit[0].named_transformers_["num"]
sd = pd.Series(scaler.scale_, index=num_cols)
per_ticket = coefs["support_tickets"] / sd["support_tickets"]
print(f"1 SD of support_tickets = {sd['support_tickets']:.2f} tickets")
print(f"odds ratio per extra ticket: {np.exp(per_ticket):.3f}")
Output
1 SD of support_tickets = 1.16 tickets
odds ratio per extra ticket: 1.597

The scaler stores each feature’s standard deviation in scale_. Dividing the standardized coefficient by it gives the coefficient per original unit. Each extra support ticket multiplies the churn odds by 1.597, about 60% higher odds, with all other features held fixed. Stakeholders understand “per ticket” better than “per standard deviation”.

pair = customers[["tenure_months", "total_charges", "monthly_charges"]]
print(pair.corr().round(3))
Output
tenure_months total_charges monthly_charges
tenure_months 1.000 0.865 -0.001
total_charges 0.865 1.000 0.378
monthly_charges -0.001 0.378 1.000

total_charges is roughly monthly_charges × tenure_months, so it correlates 0.865 with tenure. The coefficient of total_charges answers a question about customers who cannot exist: “with the same tenure and the same monthly charges, what if a customer had paid more in total?” Because total_charges is close to monthly_charges × tenure_months, the linear model uses it as a correction term next to its two parts and offsets it against the tenure weight. Its sign has no stand-alone meaning. It is not a statement about loyal, high-paying customers.

Step 5 — Refit without the correlated feature

Section titled “Step 5 — Refit without the correlated feature”
logit_small = make_logit([c for c in num_cols if c != "total_charges"])
logit_small.fit(X_train, y_train)
auc_small = roc_auc_score(y_test, logit_small.predict_proba(X_test)[:, 1])
coefs_small = pd.Series(
logit_small[-1].coef_[0], index=logit_small[:-1].get_feature_names_out()
)
rows = ["tenure_months", "total_charges", "monthly_charges"]
compare = pd.DataFrame({"with": coefs[rows], "without": coefs_small.reindex(rows)})
print(f"test ROC-AUC without total_charges: {auc_small:.3f}")
print(compare)
Output
test ROC-AUC without total_charges: 0.813
with without
tenure_months -1.024 -0.769
total_charges 0.270 NaN
monthly_charges 0.429 0.481

The score is unchanged, so total_charges adds almost nothing. Yet the tenure coefficient changes from −1.024 to −0.769. Part of the tenure effect had been offset by the positive total_charges weight. The same model quality fits two different stories.

rng = np.random.default_rng(42)
draws = []
for _ in range(20):
idx = rng.integers(0, len(X_train), size=len(X_train))
model = make_logit(num_cols).fit(X_train.iloc[idx], y_train.iloc[idx])
draws.append(model[-1].coef_[0])
boot = pd.DataFrame(draws, columns=names)
watch = ["tenure_months", "total_charges", "monthly_charges", "support_tickets"]
print(boot[watch].agg(["mean", "std", "min", "max"]))
trade = boot["tenure_months"].corr(boot["total_charges"])
print(f"correlation of the tenure and total_charges coefficients: {trade:.2f}")
Output
tenure_months total_charges monthly_charges support_tickets
mean -1.117 0.342 0.405 0.539
std 0.217 0.214 0.111 0.043
min -1.566 -0.066 0.224 0.434
max -0.757 0.734 0.565 0.622
correlation of the tenure and total_charges coefficients: -0.93

A bootstrap refits the model on 20 resamples of the training rows, drawn with replacement. A stable coefficient barely moves: support_tickets stays between 0.434 and 0.622. The correlated pair does not. The total_charges coefficient varies more than tenfold, and one draw flips its sign. The tenure coefficient is just as unstable (standard deviation 0.217, range −1.566 to −0.757). The last line shows why: across the draws, the two coefficients correlate at −0.93, so the model trades weight between them. Report the sign of a coefficient only when its bootstrap range (with more draws, a 95% percentile interval) stays on one side of 0, and report its size only when that range is narrow.

Common mistakes:

  • Ranking raw coefficients of unscaled features. The ranking then reflects the units, not the importance.
  • Reading an odds ratio as a probability ratio. An odds ratio of 1.72 does not mean “72% more likely to churn”.
  • Forgetting the reference category. contract_two-year is compared with month-to-month, not with “no contract”.
  • Trusting the sign of a coefficient that has a strongly correlated partner. Check the correlations and bootstrap the coefficients first.

Example 2 — Catch impurity importance ranking random noise

Section titled “Example 2 — Catch impurity importance ranking random noise”

Goal: Add two columns of pure noise to the house data, fit a random forest for log price and see where its built-in feature_importances_ ranks them.

Step 1 — Add a random number and a random flag

Section titled “Step 1 — Add a random number and a random flag”
houses = pd.read_csv("data/houses.csv")
X_h = pd.get_dummies(
houses.drop(columns=["house_id", "sold_date", "price"]),
columns=["neighborhood"],
dtype=float,
).astype(float)
rng = np.random.default_rng(42)
X_h["random_number"] = rng.normal(size=len(X_h))
X_h["random_flag"] = rng.integers(0, 2, size=len(X_h)).astype(float)
y_h = np.log(houses["price"])
Xh_train, Xh_test, yh_train, yh_test = train_test_split(
X_h, y_h, test_size=0.25, random_state=42
)
print(X_h.shape)
Output
(3000, 20)

random_number is continuous: 3,000 distinct values. random_flag is a coin flip: two values. Neither has anything to do with price. The target is log price, because price is right-skewed. astype(float) makes every column a float, which partial dependence needs later. The 90 blanks in each of lot_sqft and school_rating stay as NaN: random forests in scikit-learn 1.9 handle missing values natively.

forest = RandomForestRegressor(n_estimators=100, random_state=42)
forest.fit(Xh_train, yh_train)
print(f"R² train: {forest.score(Xh_train, yh_train):.3f}")
print(f"R² test: {forest.score(Xh_test, yh_test):.3f}")
Output
R² train: 0.984
R² test: 0.900

The forest grows every tree until its leaves are pure. It fits the training set almost perfectly and the test set well. The gap shows that it has memorized part of the training noise.

mdi = pd.Series(forest.feature_importances_, index=X_h.columns)
mdi = mdi.sort_values(ascending=False)
ranks = pd.DataFrame({"mdi": mdi.round(4), "rank": range(1, len(mdi) + 1)})
print(ranks.head(14))
print(ranks.loc[["random_number", "random_flag"]])
Output
mdi rank
sqft 0.475 1
school_rating 0.205 2
distance_to_center_km 0.150 3
condition 0.042 4
year_built 0.034 5
neighborhood_Maple Grove 0.021 6
lot_sqft 0.017 7
random_number 0.013 8
neighborhood_Lakeview 0.010 9
bathrooms 0.008 10
neighborhood_Oak Hill 0.005 11
bedrooms 0.004 12
garage_spaces 0.004 13
neighborhood_Westfield 0.003 14
mdi rank
random_number 0.013 8
random_flag 0.002 17

The importances sum to 1. random_number ranks above bathrooms, bedrooms, garage_spaces, has_pool and most neighborhood columns, although it is pure noise by construction. random_flag ranks far lower than random_number, although both are pure noise. Its two values offer one threshold; the continuous column offers thousands. This is the bias of impurity importance.

Common mistakes:

  • Reading feature_importances_ as “how much the model needs this feature”. It measures training impurity reduction, which includes fitted noise.
  • Comparing the importance of a 0/1 flag with that of a continuous feature. The comparison is biased toward the continuous feature.
  • Dropping features because their MDI is below some cut-off. Check with permutation importance on held-out data first.

Example 3 — Measure permutation importance on held-out data

Section titled “Example 3 — Measure permutation importance on held-out data”

Goal: Replace impurity importance with permutation importance on the test set, compare it with the training set, and see what a duplicated feature does to it.

Step 1 — Permute each column of the test set

Section titled “Step 1 — Permute each column of the test set”
perm = permutation_importance(
forest, Xh_test, yh_test, n_repeats=5, random_state=42
)
perm_test = pd.DataFrame(
{"mean": perm.importances_mean, "std": perm.importances_std},
index=X_h.columns,
).sort_values("mean", ascending=False)
fmt = "{:.4f}".format
print(perm_test.head(8).to_string(float_format=fmt))
print(perm_test.loc[["random_number", "random_flag"]].to_string(float_format=fmt))
Output
mean std
sqft 0.6417 0.0171
distance_to_center_km 0.2213 0.0193
school_rating 0.1097 0.0065
condition 0.0647 0.0042
year_built 0.0306 0.0026
neighborhood_Maple Grove 0.0288 0.0032
neighborhood_Lakeview 0.0225 0.0021
neighborhood_Oak Hill 0.0039 0.0004
mean std
random_number -0.0002 0.0008
random_flag 0.0002 0.0002

The default score of a regressor is R², so each value is a drop in test R². Shuffling sqft costs about 0.64 points of R²: without size, the model is lost. The two noise columns cost nothing within their standard deviation. The order also changes: distance_to_center_km now ranks above school_rating.

perm_tr = permutation_importance(
forest, Xh_train, yh_train, n_repeats=5, random_state=42
)
side = pd.DataFrame(
{"train": perm_tr.importances_mean, "test": perm.importances_mean},
index=X_h.columns,
)
print(side.loc[["sqft", "lot_sqft", "random_number", "random_flag"]].to_string(
float_format=fmt
))
Output
train test
sqft 0.7033 0.6417
lot_sqft 0.0154 0.0030
random_number 0.0095 -0.0002
random_flag 0.0015 0.0002

On the training rows, shuffling random_number hurts: the trees memorized it. On the test rows, it does not. lot_sqft shows the same pattern in a milder form. Permutation importance on the training set inherits the overfitting that you wanted to detect, so always use held-out data.

Step 3 — Plot the importances with their spread

Section titled “Step 3 — Plot the importances with their spread”
top = perm_test.head(10).iloc[::-1]
fig, ax = plt.subplots(figsize=(7, 4))
ax.barh(top.index, top["mean"], xerr=top["std"], color="tab:blue")
ax.set_xlabel("Drop in test R² when the column is shuffled")
ax.set_title("Permutation importance, house price forest")
fig.tight_layout()
plt.show()
Horizontal bar chart: sqft has by far the largest drop in R², about 0.65, followed by distance to center, school rating and condition; the other bars are short.
Permutation importance on the test set. The error bars show the standard deviation over 5 shuffles.

iloc[::-1] reverses the order, so the largest bar is at the top. The error bars are tiny for this model, so the ranking is stable. Always show them: with small test sets they can overlap.

Step 4 — Add a duplicate of the most important feature

Section titled “Step 4 — Add a duplicate of the most important feature”
X_dup = X_h.assign(sqm=X_h["sqft"] * 0.0929)
Xd_train, Xd_test = X_dup.loc[Xh_train.index], X_dup.loc[Xh_test.index]
forest_dup = RandomForestRegressor(n_estimators=100, random_state=42)
forest_dup.fit(Xd_train, yh_train)
perm_dup = permutation_importance(
forest_dup, Xd_test, yh_test, n_repeats=5, random_state=42
)
dup = pd.DataFrame(
{
"mdi": forest_dup.feature_importances_,
"permutation": perm_dup.importances_mean,
},
index=X_dup.columns,
)
print(dup.loc[["sqft", "sqm", "distance_to_center_km"]].round(4))
Output
mdi permutation
sqft 0.238 0.157
sqm 0.239 0.153
distance_to_center_km 0.150 0.220

sqm is the same size in square meters, so it carries exactly the same information. The forest now splits on either column. MDI splits the credit roughly in half. The permutation importance of each twin collapses (0.157 + 0.153 is far below the 0.642 that sqft had alone), because the other twin covers it when one is shuffled. Neither feature looks as important as size really is. With correlated features, permute them together, or drop one before you explain.

Common mistakes:

  • Running permutation importance on the training set. It then rewards memorized noise.
  • Using one shuffle (n_repeats=1). You cannot see whether a difference between two features is larger than the noise.
  • Concluding that a feature is useless because its permutation importance is small, when a correlated partner carries the same information.

Example 4 — Read partial dependence and ICE curves for house prices

Section titled “Example 4 — Read partial dependence and ICE curves for house prices”

Goal: Show how the forest’s predicted price changes with size, distance and condition, and use ICE curves to find out whether the effect of size is the same in every neighborhood.

fig, axes = plt.subplots(1, 3, figsize=(10, 3.4), sharey=True)
PartialDependenceDisplay.from_estimator(
forest,
Xh_test,
["sqft", "distance_to_center_km", "condition"],
method="brute",
ax=axes,
)
fig.suptitle("Partial dependence of log price")
fig.tight_layout()
plt.show()
Three partial dependence panels: log price rises steadily with sqft from about 12.45 to 13.35; it stays flat with distance up to about 10 km, then drops sharply near 12 km; it rises with condition from 1 to 5.
Partial dependence of predicted log price on three features (brute force over the test set). The tick marks at the bottom are the deciles of each feature.

method="brute" makes each panel do exactly what the formula says: it replaces one column in all 750 test rows with a grid value, predicts, and averages. Without it, the forest would use the faster recursion method, which averages over the training data instead. Price rises with size and condition. The distance curve is flat to about 10 km and then drops. That drop is suspicious: distance is tied to the neighborhood, so this curve mixes two effects (Step 4).

Step 2 — Draw centered ICE curves for size

Section titled “Step 2 — Draw centered ICE curves for size”
fig, ax = plt.subplots(figsize=(6.5, 4))
PartialDependenceDisplay.from_estimator(
forest,
Xh_test,
["sqft"],
kind="both",
centered=True,
subsample=60,
random_state=42,
ax=ax,
)
ax.set_title("Centered ICE curves for sqft (60 houses)")
fig.tight_layout()
plt.show()
Sixty thin ICE lines start at zero and fan out as sqft grows: one group climbs to about 1.3 to 1.5 in log price, another levels off near 0.5; the dashed average lies between the groups.
Centered ICE curves: one line per house, all shifted to start at 0. The dashed line is the partial dependence.

kind="both" draws the ICE curves and their average. subsample=60 keeps the plot readable. centered=True shifts every curve to start at 0. The curves split into two groups: for some houses, extra size adds much more value than for others. The average line describes almost no house. This fan shape is the signature of an interaction.

Step 3 — Measure the size effect per neighborhood

Section titled “Step 3 — Measure the size effect per neighborhood”
grid = {"sqft": np.array([1500.0, 3000.0])}
ice = partial_dependence(
forest, Xh_test, ["sqft"], kind="individual", custom_values=grid
)
lines = ice["individual"][0]
gain = pd.Series(lines[:, 1] - lines[:, 0], index=Xh_test.index)
hood = houses.loc[Xh_test.index, "neighborhood"]
uplift = np.exp(gain.groupby(hood).mean()) - 1
print("Predicted price change from 1,500 to 3,000 sqft:")
print(uplift.sort_values().map("{:+.0%}".format))
Output
Predicted price change from 1,500 to 3,000 sqft:
neighborhood
Old Town +42%
Cedar Park +43%
Westfield +45%
Downtown +53%
Maple Grove +56%
Riverside +79%
Oak Hill +121%
Lakeview +126%
dtype: str

custom_values sets the grid to exactly two sizes. ice["individual"][0] has one row per house and one column per grid value. The difference is a change in log price, so np.exp(...) - 1 turns it into a percent. Doubling the size adds about 43% in Cedar Park and about 126% in Lakeview. The model has learned a size × neighborhood interaction; one PDP line could never show this.

Step 4 — Check where the distance curve has data

Section titled “Step 4 — Check where the distance curve has data”
spread = houses.groupby("neighborhood")["distance_to_center_km"].agg(
["min", "median", "max"]
)
print(spread.sort_values("median").round(1))
Output
min median max
neighborhood
Downtown 0.2 0.9 4.6
Old Town 0.2 1.5 4.9
Riverside 1.1 4.0 7.8
Lakeview 3.7 7.5 11.1
Oak Hill 5.1 9.0 12.7
Maple Grove 7.7 11.0 14.7
Westfield 10.1 13.5 16.7
Cedar Park 13.2 15.9 20.2

Each neighborhood sits in its own distance band. The PDP at 1 km includes Cedar Park houses moved into the city center, a row that the data has never seen. The drop near 12 km is where the expensive Lakeview and Oak Hill bands end and the cheaper Westfield and Cedar Park bands begin. The curve reflects neighborhood prices more than the cost of distance. A PDP of a feature that is strongly tied to another feature describes impossible rows.

Common mistakes:

  • Passing integer columns to partial_dependence. scikit-learn 1.9 raises a ValueError; cast to float first.
  • Reading a flat PDP as “no effect”. Opposite effects in two groups can average to a flat line. Draw ICE curves.
  • Reading the curve far outside the rug marks. There the model extrapolates.
  • Forgetting the units: this PDP is in log price. Convert differences with np.exp(diff) - 1.

Example 5 — Explain the churn model globally with SHAP

Section titled “Example 5 — Explain the churn model globally with SHAP”

Goal: Fit a gradient boosting churn model, compute SHAP values for 500 test customers, check that they add up to the model output, and read the beeswarm plot.

Step 1 — Fit a gradient boosting pipeline

Section titled “Step 1 — Fit a gradient boosting pipeline”
encode = ColumnTransformer(
[("cat", OneHotEncoder(sparse_output=False), cat_cols)],
remainder="passthrough",
verbose_feature_names_out=False,
).set_output(transform="pandas")
gbm = Pipeline(
[
("encode", encode),
(
"model",
GradientBoostingClassifier(
n_estimators=200, max_depth=3, learning_rate=0.05, random_state=42
),
),
]
).fit(X_train, y_train)
auc_gbm = roc_auc_score(y_test, gbm.predict_proba(X_test)[:, 1])
print(f"test ROC-AUC: {auc_gbm:.3f}")
Output
test ROC-AUC: 0.837

Trees need no scaling, so the pipeline only one-hot encodes the text columns and passes the numbers through. set_output(transform="pandas"), called before fit, makes the encoder return a DataFrame with column names, which SHAP uses as labels. The model beats the logistic regression of Example 1.

Step 2 — Compute SHAP values for a sample

Section titled “Step 2 — Compute SHAP values for a sample”
X_sample = X_test.sample(500, random_state=42)
X_sample_enc = gbm["encode"].transform(X_sample)
explainer = shap.TreeExplainer(gbm["model"])
sv = explainer(X_sample_enc)
print(type(sv).__name__, sv.values.shape)
print(f"base value: {sv.base_values[0]:.3f} log-odds")
Output
Explanation (500, 22)
base value: -1.964 log-odds

The explainer gets the fitted model (the last pipeline step) and the encoded rows, because the trees split on encoded columns. The result is an Explanation object: it holds one SHAP value per customer and per encoded column, plus the base values, the feature values and the feature names. 500 rows keep the plots readable and the page fast; TreeExplainer itself is fast enough for the whole test set.

margin = gbm.decision_function(X_sample)
rebuilt = sv.base_values + sv.values.sum(axis=1)
proba = gbm.predict_proba(X_sample)[:, 1]
print("base + SHAP = log-odds:", np.allclose(rebuilt, margin))
print("sigmoid(sum) = probability:", np.allclose(1 / (1 + np.exp(-rebuilt)), proba))
print(f"sigmoid(base value) = {1 / (1 + np.exp(-sv.base_values[0])):.3f}")
print(f"mean predicted probability = {proba.mean():.3f}")
Output
base + SHAP = log-odds: True
sigmoid(sum) = probability: True
sigmoid(base value) = 0.123
mean predicted probability = 0.177

The base value plus the row’s SHAP values equals the model’s log-odds for every customer, up to floating-point error, so np.allclose is the right test. The sigmoid of that sum is the predicted probability. The sigmoid of the base value is not the average probability: the base value is an average of log-odds, and the sigmoid of an average is not the average of the sigmoids.

shap.plots.beeswarm(sv, max_display=10, show=False)
plt.title("SHAP values of the churn model (500 test customers)")
plt.show()
Beeswarm plot with tenure_months, contract_month-to-month and monthly_charges at the top. Low tenure (blue) has positive SHAP values up to about 1.8; month-to-month (red) pushes risk up; high charges and many tickets (red) push risk up; few logins (blue) push risk up.
Beeswarm plot: one dot per customer and feature. The x-position is the SHAP value in log-odds; the color is the feature value.

A beeswarm plot shows every SHAP value at once. Each row of the plot is a feature, sorted by mean absolute SHAP value. Each dot is a customer. Dots to the right raised that customer’s churn score; dots to the left lowered it. Red means a high feature value. Low tenure (blue) pushes risk up; a month-to-month contract (red, value 1) pushes it up; many support tickets push it up; few logins push it up. The last row adds up the remaining 13 encoded columns.

Step 5 — Rank the features by mean absolute SHAP

Section titled “Step 5 — Rank the features by mean absolute SHAP”
mean_abs = pd.Series(np.abs(sv.values).mean(axis=0), index=sv.feature_names)
print(mean_abs.sort_values(ascending=False).head(8).round(3))
Output
tenure_months 0.445
contract_month-to-month 0.440
monthly_charges 0.356
age 0.296
support_tickets 0.270
logins_last_30d 0.202
payment_method_electronic_check 0.193
contract_two-year 0.128
dtype: float64

The mean absolute SHAP value is a global importance: the average size of a feature’s push, in log-odds. Use the absolute value, because positive and negative pushes would cancel in a plain mean. shap.plots.bar(sv) draws the same ranking.

Common mistakes:

  • Passing raw text columns to the explainer. The trees split on the encoded columns, so explain gbm["encode"].transform(X).
  • Adding SHAP values of a classifier to a probability. They are in log-odds.
  • Forgetting show=False and then adding a title. The plot is already shown and closed, so the title lands on a new, empty figure.
  • Calling set_output(transform="pandas") after fit. The model was then fitted on a NumPy array without column names, and a later predict on named data warns “X has feature names, but GradientBoostingClassifier was fitted without feature names”. Call it when you build the transformer.

Example 6 — Explain one customer to the retention team

Section titled “Example 6 — Explain one customer to the retention team”

Goal: Find the riskiest customer in the sample, explain the score with a waterfall plot, and turn the explanation into three sentences for a retention agent.

i = int(proba.argmax())
row_id = X_sample.index[i]
print(customers.loc[row_id, "customer_id"], f"P(churn) = {proba[i]:.3f}")
print(X_sample.loc[row_id].to_string())
Output
C04542 P(churn) = 0.974
age 18
tenure_months 3
monthly_charges 31.33
total_charges 89.95
support_tickets 9
logins_last_30d 3
avg_session_minutes 11.3
has_autopay 0
region North
plan basic
contract month-to-month
payment_method credit_card

The customer is young, three months in, on a month-to-month contract, with 9 support tickets and only 3 logins in the last month.

Step 2 — Group the one-hot columns back into original features

Section titled “Step 2 — Group the one-hot columns back into original features”
def original_feature(column: str) -> str:
"""Map an encoded column such as 'contract_two-year' to 'contract'."""
for cat in cat_cols:
if column.startswith(f"{cat}_"):
return cat
return column
groups = [original_feature(c) for c in sv.feature_names]
encoded = pd.DataFrame(sv.values, columns=groups, index=X_sample.index)
by_feature = encoded.T.groupby(level=0).sum().T
print(by_feature.shape)
print(np.allclose(sv.base_values + by_feature.sum(axis=1), margin))
contrib = by_feature.loc[row_id].sort_values(key=abs, ascending=False)
print(contrib.round(3).head(7))
Output
(500, 12)
True
support_tickets 1.713
tenure_months 1.311
logins_last_30d 1.105
age 0.842
contract 0.639
total_charges 0.455
monthly_charges -0.394
Name: 4541, dtype: float64

The model sees three contract_* columns, but the agent thinks of one contract. Because SHAP values are additive, you can sum the values of the columns that came from one feature. The total is unchanged, as the np.allclose check confirms. Now each original feature has one contribution.

explanation = shap.Explanation(
values=contrib.to_numpy(),
base_values=sv.base_values[i],
data=X_sample.loc[row_id, contrib.index].to_numpy(),
feature_names=list(contrib.index),
)
shap.plots.waterfall(explanation, max_display=8, show=False)
plt.title(f"Why {customers.loc[row_id, 'customer_id']} is high risk")
plt.show()
Waterfall plot that starts at the base value -1.964 log-odds and climbs to 3.614: support_tickets 9 adds 1.71, tenure 3 adds 1.31, logins 3 adds 1.1, age 18 adds 0.84, month-to-month contract adds 0.64; monthly charges 31.33 subtract 0.39.
Waterfall plot for the riskiest customer, in log-odds. Red bars push the score up, blue bars push it down.

A waterfall plot shows how one prediction is built. It reads from the bottom up. It starts at the base value E[f(X)]E[f(X)], adds one bar per feature and ends at this customer’s output f(x)f(x). shap.Explanation builds the object by hand from the grouped values, so the labels show the original values, such as month-to-month = contract. Low monthly charges are the only large factor that lowers this customer’s risk.

Step 4 — Write the reasons in plain words

Section titled “Step 4 — Write the reasons in plain words”
labels = {
"support_tickets": "opened {} support tickets",
"tenure_months": "has been a customer for only {} months",
"logins_last_30d": "logged in only {} times in the last 30 days",
"age": "is {} years old",
"contract": "is on a {} contract",
}
reasons = [
labels[f].format(X_sample.loc[row_id, f]) for f in contrib.index[:3] if f in labels
]
print(f"Churn risk {proba[i]:.0%}. Main reasons, the customer:")
for reason in reasons:
print(f"- {reason}")
Output
Churn risk 97%. Main reasons, the customer:
- opened 9 support tickets
- has been a customer for only 3 months
- logged in only 3 times in the last 30 days

The agent gets the risk and the three largest pushes as one sentence. It names the facts the model reacted to, not causes. “Opened 9 tickets” invites the agent to ask what went wrong; it does not promise that fixing tickets will keep the customer.

Step 5 — Ask a what-if question, carefully

Section titled “Step 5 — Ask a what-if question, carefully”
what_if = X_sample.loc[[row_id]].assign(contract="one-year")
p_new = gbm.predict_proba(what_if)[0, 1]
print(f"model's risk on a one-year contract: {p_new:.3f} (was {proba[i]:.3f})")
Output
model's risk on a one-year contract: 0.814 (was 0.974)

The model’s score drops when only the contract changes. This is a what-if query: one changed input and the model’s new output, the same as one point of an ICE curve. It is not a full counterfactual explanation, which searches for the smallest change to the input that changes the model’s decision; here the risk stays far above 0.5. Either way, it describes the model, not the customer. A customer who accepts a one-year offer may still leave: the tickets and the low usage remain. Only an experiment can measure the real effect of an offer.

Common mistakes:

  • Showing raw one-hot names such as payment_method_credit_card = 0 to a non-technical reader. Group them first.
  • Giving the agent the full SHAP table. Three reasons in plain words are enough.
  • Presenting a what-if score as a promise. A change of contract does not change the customer’s history or intent.

Example 7 — Compare SHAP and permutation importance

Section titled “Example 7 — Compare SHAP and permutation importance”

Goal: Rank the 12 original churn features with permutation importance on the test set and with mean absolute SHAP, and explain where the two rankings differ.

Step 1 — Compute permutation importance on raw columns

Section titled “Step 1 — Compute permutation importance on raw columns”
perm_gbm = permutation_importance(
gbm, X_test, y_test, scoring="roc_auc", n_repeats=5, random_state=42
)
perm_auc = pd.Series(perm_gbm.importances_mean, index=X_test.columns)
perm_sd = pd.Series(perm_gbm.importances_std, index=X_test.columns)
perm_table = pd.DataFrame({"mean": perm_auc, "std": perm_sd})
top6 = perm_table.sort_values("mean", ascending=False).head(6)
print(top6.to_string(float_format="{:.4f}".format))
Output
mean std
contract 0.0619 0.0073
tenure_months 0.0468 0.0040
monthly_charges 0.0344 0.0043
logins_last_30d 0.0254 0.0037
support_tickets 0.0242 0.0056
age 0.0237 0.0028

The pipeline is the model here, so X_test keeps its 12 raw columns. Each shuffle moves a whole feature, such as contract, through the encoder. The score is ROC-AUC, so each value is a drop in AUC points.

shap_rank = by_feature.abs().mean()
compare = pd.DataFrame({"mean_abs_shap": shap_rank, "perm_auc_drop": perm_auc})
compare["shap_rank"] = compare["mean_abs_shap"].rank(ascending=False).astype(int)
compare["perm_rank"] = compare["perm_auc_drop"].rank(ascending=False).astype(int)
print(compare.sort_values("shap_rank").to_string(float_format="{:.4f}".format))
rho = compare["mean_abs_shap"].corr(compare["perm_auc_drop"], method="spearman")
print(f"Spearman rank correlation: {rho:.3f}")
Output
mean_abs_shap perm_auc_drop shap_rank perm_rank
contract 0.5205 0.0619 1 1
tenure_months 0.4446 0.0468 2 2
monthly_charges 0.3564 0.0344 3 3
age 0.2958 0.0237 4 6
support_tickets 0.2701 0.0242 5 5
logins_last_30d 0.2020 0.0254 6 4
payment_method 0.1993 0.0084 7 7
total_charges 0.1002 0.0022 8 8
avg_session_minutes 0.0421 0.0011 9 9
region 0.0384 -0.0008 10 12
has_autopay 0.0274 0.0002 11 10
plan 0.0003 -0.0001 12 11
Spearman rank correlation: 0.951

The two methods agree on the top three (contract, tenure, monthly charges) and on the weak tail. The Spearman rank correlation compares the orders, not the values. Small swaps in the middle, such as age and logins_last_30d, are normal: the permutation drops of logins, tickets and age lie within 0.002 of each other, and the methods answer different questions.

Step 3 — Explain the difference between the two

Section titled “Step 3 — Explain the difference between the two”
Mean absolute SHAP Permutation importance
Question How far does the feature move the predictions? How much does the test score need the feature?
Data any rows, no labels needed labeled held-out rows
Unit model output (log-odds here) score points (ROC-AUC here)
Correlated partner shares credit with it can look unimportant, because the partner covers it
Local view yes, one value per row no

age is rank 4 by SHAP and rank 6 by permutation. The permutation drops of logins_last_30d, support_tickets and age lie within 0.002 of each other, well inside their standard deviations from Step 1, so ranks 4–6 are a tie within noise. total_charges gets small values from both methods, because tenure and monthly charges carry most of its information. When the two rankings disagree strongly, look for correlated features or for overfitting.

Common mistakes:

  • Comparing the raw numbers of the two methods. Their units differ; compare ranks.
  • Permuting one-hot columns separately, which creates customers with two contracts.
  • Expecting a perfect match. Two good methods that answer different questions give similar but not identical rankings.
Mistake Symptom Fix
Ranking raw coefficients of unscaled features sqft looks negligible, a 0/1 flag looks huge Standardize first, or convert to a meaningful step
Trusting coefficients of correlated features Sign flips between bootstrap samples; “paying more raises churn” Check correlations, bootstrap, drop or combine one of the pair
Using feature_importances_ as the truth Random noise ranks above real features Use permutation importance on a held-out set
Permutation importance on the training set Noise columns look useful Permute the test or validation set
n_repeats=1 Rankings change with the seed Use 5 or more repeats and show the standard deviation
Permuting one-hot columns one by one Rows with two contracts; importance split over dummies Permute raw columns through a Pipeline
Integer columns in partial_dependence ValueError: ... integer data Cast to float before fitting: X.astype(float)
Reading only the PDP One average line hides opposite effects Add ICE curves (kind="both", centered=True)
PDP of a feature tied to another Strange drops or jumps outside the data’s support Check the joint distribution; read only near the rug marks
Adding classifier SHAP values to a probability Probabilities above 1 or below 0 Add in log-odds, then apply the sigmoid
Explaining encoded rows with raw data Shape error or wrong feature names Pass pipeline[:-1].transform(X) to the explainer
Calling a shap plot without show=False The title or the save lands on an empty figure Pass show=False, customize, then call plt.show() once
Presenting explanations as causes “Close tickets faster and churn will fall” Say “the model reacts to”; test actions with an experiment
  • Marketing attribution: ad platforms split the credit for a sale among the channels a customer touched (search, email, social). Shapley values are a standard way to make that split fair.
  • Cloud cost allocation: a shared database serves several teams. Shapley-style splitting charges each team its fair share of the cost, the same idea as SHAP’s split of a prediction.
  • Software performance: profilers attribute run time to functions, and ablation tests switch off one component (a cache, a feature flag) to measure how much a metric drops. That is permutation importance applied to a system.
  • Regulated decisions: credit, insurance and hiring tools must give the main reasons for an adverse decision. Local explanations such as SHAP waterfalls produce those reason lists.
  • Global explanations describe the whole model; local explanations describe one prediction. Choose by the question and the audience.
  • Linear coefficients are readable only on standardized features. Logistic coefficients become odds ratios with np.exp. Correlated features make coefficients unstable: check the correlations and bootstrap.
  • Impurity importance (feature_importances_) is computed on the training data and favors continuous and high-cardinality features. A random noise column exposes the bias.
  • Permutation importance shuffles one column of a held-out set and measures the score drop. Use several repeats, the metric you care about and raw columns through a Pipeline. Correlated features hide each other.
  • Partial dependence shows the average effect of one feature; ICE curves show it per row and reveal interactions. Both create impossible rows when features are correlated.
  • SHAP values split one prediction into additive contributions: base value plus SHAP values equals the model output. For classifiers that output is in log-odds. Beeswarm plots give the global view, waterfall plots the local one.
  • Explanations describe the model, not the world. They are not causal. Communicate them in plain words, with units, uncertainty and caveats.

Q1. A product manager asks which features drive churn across all customers. A retention agent asks why one customer got a high score. Which kind of explanation does each need, and which method would you use?

Answer

The manager needs a global explanation: permutation importance on the test set or mean absolute SHAP values, perhaps with partial dependence plots for the top features. The agent needs a local explanation: the SHAP values of that one customer, shown as a waterfall or as three plain-language reasons.

Q2. A linear regression for house price has a coefficient of 180 for sqft and 25,000 for has_pool. Does a pool matter more than size?

Answer

You cannot tell from raw coefficients. 180 is per square foot, and the standard deviation of sqft is several hundred square feet, so one typical step in size adds far more than 180. Standardize the features (or multiply each coefficient by its feature’s standard deviation) before you compare.

Q3. A logistic regression has a coefficient of −1.73 for contract_two-year, with month-to-month as the reference category. What does that mean?

Answer

The odds ratio is e−1.73≈0.18e^{-1.73} \approx 0.18. A customer on a two-year contract has about 82% lower churn odds than an otherwise identical customer on a month-to-month contract. It is a statement about odds, not probabilities.

Q4. Why can a column of random numbers get a higher feature_importances_ value than a real 0/1 feature?

Answer

Impurity importance is measured on the training data and sums the impurity reductions of every split. A continuous column offers thousands of possible thresholds, and deep trees find some that separate training rows well by chance. A 0/1 feature offers only one threshold. So the noise column collects credit for fitted noise.

Q5. Why should you compute permutation importance on a held-out set, and what does n_repeats control?

Answer

On the training set, the importance includes what the model memorized, so overfitted noise features look useful. On a held-out set, it measures what generalizes. n_repeats is the number of shuffles per feature. The mean of the drops is the importance, and their standard deviation shows whether a difference between features is real.

Q6. sqft and an exact copy sqm are both in a random forest. What happens to the permutation importance of sqft?

Answer

It falls sharply. When sqft is shuffled, the model can still read the size from sqm, so the score barely drops. Both copies look less important than size really is. Permute correlated features together, or drop one before you explain.

Q7. The partial dependence plot of a feature is flat. Can you conclude that the model ignores the feature?

Answer

No. The PDP is an average. If the feature raises the prediction for one group and lowers it for another, the average can be flat. Draw ICE curves: crossing or fanning curves reveal the interaction. Permutation importance would also show that the feature matters.

Q8. For one customer, the base value is −1.96 and the SHAP values sum to 5.58. What is the predicted churn probability?

Answer

The model output is −1.96 + 5.58 = 3.62 log-odds. The probability is the sigmoid: 1/(1+e−3.62)≈0.9741/(1+e^{-3.62}) \approx 0.974, about 97%. You add in log-odds and convert at the end.

Q9. Why can you add up the SHAP values of the three contract_* one-hot columns and call the sum “the contribution of the contract”?

Answer

SHAP values are additive: the base value plus all SHAP values equals the prediction. Summing a group of columns keeps the total unchanged, so the grouped values still add up to the prediction. The sum is the combined push of all the columns that encode the contract.

Q10. A SHAP analysis shows that support_tickets pushes churn risk up. A manager concludes: “If we resolve tickets faster, churn will drop.” What is wrong with this reasoning?

Answer

SHAP explains the model, not the world. The model has learned that customers with many tickets churn more, but tickets may only signal an underlying problem, such as a faulty product. Faster ticket handling may or may not help. Only an experiment, such as an A/B test of a new support process, can measure the causal effect.

Your progress

0 / 4 done

  • Exercises: coefficients, impurity and permutation importance, partial dependence, ICE and SHAP on the churn and house data.
  • Mini-project: build an explanation pack for the churn model that a retention team can use.
  • Cheat sheet: every interpretability call of this module, with its caveats.
  • Next module: 44. ML in production basics turns a trained model into a tested prediction service with FastAPI, pydantic and MLflow.