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.
What you will learn
Section titled “What you will learn”- 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.
Prerequisites
Section titled “Prerequisites”- 33. Feature engineering: scaling, one-hot encoding, multicollinearity, impurity-based importance and data leakage.
- 34. scikit-learn workflow:
Pipeline,ColumnTransformerandtrain_test_split. - 35. Regression and 36. Classification: linear and logistic regression, random forests, gradient boosting, log-odds and odds ratios.
- 38. Ensembles: how forests and boosting combine many trees.
- 29. Statistics and probability: correlation versus causation.
- The datasets
data/customers.csvanddata/houses.csv, described in the data dictionary.
Concepts
Section titled “Concepts”Why explain a model
Section titled “Why explain a model”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.
Global and local explanations
Section titled “Global and local explanations”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 data and models for this page
Section titled “The data and models for this page”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 pltimport numpy as npimport pandas as pdimport shapfrom sklearn.compose import ColumnTransformerfrom sklearn.ensemble import GradientBoostingClassifier, RandomForestRegressorfrom sklearn.inspection import ( PartialDependenceDisplay, partial_dependence, permutation_importance,)from sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import roc_auc_scorefrom sklearn.model_selection import train_test_splitfrom sklearn.pipeline import Pipeline, make_pipelinefrom 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)(3750, 12) (1250, 12)Linear model coefficients
Section titled “Linear model coefficients”A linear model predicts with a weighted sum: . Each coefficient says how much the prediction changes when feature 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:
- Compare coefficients only on standardized features. A raw coefficient depends on the unit. The coefficient of
sqftper square foot is tiny, and the coefficient ofhas_pool(0 or 1) is large, but that says nothing about which feature matters more. AfterStandardScaler, 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. - Read logistic regression coefficients as odds ratios. Logistic regression is linear in the log-odds . A one-unit step in multiplies the odds by , 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).
Impurity-based importance in trees
Section titled “Impurity-based importance in trees”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
Section titled “Permutation importance”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.
- Score the fitted model on a held-out set: the baseline score .
- For feature , shuffle its column, score again and get . The importance is the drop .
- Repeat the shuffle
n_repeatstimes and report the mean and the standard deviation of the drops. - Put the column back and move on to the next feature.
Here is n_repeats and is the score after shuffle of feature . 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
Pipelineand the rawX_test. Then one shuffle moves the wholecontractcolumn, 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.
Partial dependence and ICE curves
Section titled “Partial dependence and ICE curves”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 of feature , it sets column to in every row, predicts, and averages:
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 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_kmto 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 values
Section titled “SHAP values”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 with features:
- is the base value: the model’s average output over the background data (for trees, the training data).
- is the SHAP value of feature for this row: how far feature 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 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.
Choosing a method
Section titled “Choosing a method”| 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 |
Use explanations responsibly
Section titled “Use explanations responsibly”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.
Worked examples
Section titled “Worked examples”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}")test ROC-AUC: 0.813The 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)) coef odds_ratiocontract_two-year -1.730 0.177contract_one-year -1.058 0.347tenure_months -1.024 0.359support_tickets 0.543 1.721monthly_charges 0.429 1.536payment_method_electronic_check 0.372 1.450plan_standard -0.367 0.693logins_last_30d -0.278 0.757total_charges 0.270 1.310key=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}")1 SD of support_tickets = 1.16 ticketsodds ratio per extra ticket: 1.597The 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”.
Step 4 — Spot the correlated pair
Section titled “Step 4 — Spot the correlated pair”pair = customers[["tenure_months", "total_charges", "monthly_charges"]]print(pair.corr().round(3)) tenure_months total_charges monthly_chargestenure_months 1.000 0.865 -0.001total_charges 0.865 1.000 0.378monthly_charges -0.001 0.378 1.000total_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)test ROC-AUC without total_charges: 0.813 with withouttenure_months -1.024 -0.769total_charges 0.270 NaNmonthly_charges 0.429 0.481The 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.
Step 6 — Bootstrap the coefficients
Section titled “Step 6 — Bootstrap the coefficients”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}") tenure_months total_charges monthly_charges support_ticketsmean -1.117 0.342 0.405 0.539std 0.217 0.214 0.111 0.043min -1.566 -0.066 0.224 0.434max -0.757 0.734 0.565 0.622correlation of the tenure and total_charges coefficients: -0.93A 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-yearis 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)(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.
Step 2 — Fit the forest
Section titled “Step 2 — Fit the forest”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}")R² train: 0.984R² test: 0.900The 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.
Step 3 — Read the impurity importances
Section titled “Step 3 — Read the impurity importances”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"]]) mdi ranksqft 0.475 1school_rating 0.205 2distance_to_center_km 0.150 3condition 0.042 4year_built 0.034 5neighborhood_Maple Grove 0.021 6lot_sqft 0.017 7random_number 0.013 8neighborhood_Lakeview 0.010 9bathrooms 0.008 10neighborhood_Oak Hill 0.005 11bedrooms 0.004 12garage_spaces 0.004 13neighborhood_Westfield 0.003 14 mdi rankrandom_number 0.013 8random_flag 0.002 17The 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}".formatprint(perm_test.head(8).to_string(float_format=fmt))print(perm_test.loc[["random_number", "random_flag"]].to_string(float_format=fmt)) mean stdsqft 0.6417 0.0171distance_to_center_km 0.2213 0.0193school_rating 0.1097 0.0065condition 0.0647 0.0042year_built 0.0306 0.0026neighborhood_Maple Grove 0.0288 0.0032neighborhood_Lakeview 0.0225 0.0021neighborhood_Oak Hill 0.0039 0.0004 mean stdrandom_number -0.0002 0.0008random_flag 0.0002 0.0002The 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.
Step 2 — Compare with the training set
Section titled “Step 2 — Compare with the training set”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)) train testsqft 0.7033 0.6417lot_sqft 0.0154 0.0030random_number 0.0095 -0.0002random_flag 0.0015 0.0002On 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()
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)) mdi permutationsqft 0.238 0.157sqm 0.239 0.153distance_to_center_km 0.150 0.220sqm 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.
Step 1 — Draw partial dependence plots
Section titled “Step 1 — Draw partial dependence plots”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()
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()
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()) - 1print("Predicted price change from 1,500 to 3,000 sqft:")print(uplift.sort_values().map("{:+.0%}".format))Predicted price change from 1,500 to 3,000 sqft:neighborhoodOld Town +42%Cedar Park +43%Westfield +45%Downtown +53%Maple Grove +56%Riverside +79%Oak Hill +121%Lakeview +126%dtype: strcustom_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)) min median maxneighborhoodDowntown 0.2 0.9 4.6Old Town 0.2 1.5 4.9Riverside 1.1 4.0 7.8Lakeview 3.7 7.5 11.1Oak Hill 5.1 9.0 12.7Maple Grove 7.7 11.0 14.7Westfield 10.1 13.5 16.7Cedar Park 13.2 15.9 20.2Each 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 aValueError; 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}")test ROC-AUC: 0.837Trees 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")Explanation (500, 22)base value: -1.964 log-oddsThe 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.
Step 3 — Check additivity
Section titled “Step 3 — Check additivity”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}")base + SHAP = log-odds: Truesigmoid(sum) = probability: Truesigmoid(base value) = 0.123mean predicted probability = 0.177The 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.
Step 4 — Read the beeswarm plot
Section titled “Step 4 — Read the beeswarm plot”shap.plots.beeswarm(sv, max_display=10, show=False)plt.title("SHAP values of the churn model (500 test customers)")plt.show()
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))tenure_months 0.445contract_month-to-month 0.440monthly_charges 0.356age 0.296support_tickets 0.270logins_last_30d 0.202payment_method_electronic_check 0.193contract_two-year 0.128dtype: float64The 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=Falseand 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")afterfit. The model was then fitted on a NumPy array without column names, and a laterpredicton 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.
Step 1 — Find the riskiest customer
Section titled “Step 1 — Find the riskiest customer”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())C04542 P(churn) = 0.974age 18tenure_months 3monthly_charges 31.33total_charges 89.95support_tickets 9logins_last_30d 3avg_session_minutes 11.3has_autopay 0region Northplan basiccontract month-to-monthpayment_method credit_cardThe 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().Tprint(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))(500, 12)Truesupport_tickets 1.713tenure_months 1.311logins_last_30d 1.105age 0.842contract 0.639total_charges 0.455monthly_charges -0.394Name: 4541, dtype: float64The 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.
Step 3 — Draw the waterfall plot
Section titled “Step 3 — Draw the waterfall plot”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()
A waterfall plot shows how one prediction is built. It reads from the bottom up. It starts at the base value , adds one bar per feature and ends at this customer’s output . 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}")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 daysThe 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})")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 = 0to 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)) mean stdcontract 0.0619 0.0073tenure_months 0.0468 0.0040monthly_charges 0.0344 0.0043logins_last_30d 0.0254 0.0037support_tickets 0.0242 0.0056age 0.0237 0.0028The 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.
Step 2 — Put both rankings side by side
Section titled “Step 2 — Put both rankings side by side”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}") mean_abs_shap perm_auc_drop shap_rank perm_rankcontract 0.5205 0.0619 1 1tenure_months 0.4446 0.0468 2 2monthly_charges 0.3564 0.0344 3 3age 0.2958 0.0237 4 6support_tickets 0.2701 0.0242 5 5logins_last_30d 0.2020 0.0254 6 4payment_method 0.1993 0.0084 7 7total_charges 0.1002 0.0022 8 8avg_session_minutes 0.0421 0.0011 9 9region 0.0384 -0.0008 10 12has_autopay 0.0274 0.0002 11 10plan 0.0003 -0.0001 12 11Spearman rank correlation: 0.951The 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.
Pitfalls
Section titled “Pitfalls”| 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 |
Where this is used beyond data science
Section titled “Where this is used beyond data science”- 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.
Summary
Section titled “Summary”- 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.
Self-check questions
Section titled “Self-check questions”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 . 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: , 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.
Track your progress
Section titled “Track your progress”Next steps
Section titled “Next steps”- 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.