Skip to content

43. Interpretability — Mini-project

The retention team will start to use the churn model next month. Every Monday, the team calls the customers with the highest churn risk. Before the launch, the head of retention asks you for an explanation pack: a short set of outputs that shows what the model has learned, how far its explanations can be trusted, and what an agent should say about each customer on the call list.

The pack must answer four questions:

  1. Which features drive the model’s churn scores, and how sure are we of that ranking?
  2. How does the predicted risk change with tenure and with support tickets, and does the ticket effect depend on the contract?
  3. For each customer on this week’s call list, which three facts raised the score?
  4. What must the team not conclude from these explanations?

The project uses every part of module 43: permutation importance on held-out data, partial dependence and ICE curves, SHAP values with an additivity check, grouping of one-hot columns, plain-language reasons and responsible communication.

data/customers.csv: 5,000 subscription customers, one row each, with the target churned (19.3% churn). The data dictionary describes the 15 columns. Use the 12 features of the lesson: 8 numeric (age, tenure_months, monthly_charges, total_charges, support_tickets, logins_last_30d, avg_session_minutes, has_autopay) and 4 text (region, plan, contract, payment_method).

total_charges is blank for 10 brand-new customers with tenure_months 0. Fill these blanks with 0. Cast the numeric columns to float so that partial_dependence accepts them.

Use the lesson’s split: train_test_split(test_size=0.25, stratify=y, random_state=42). The test set (1,250 customers) stands in for “this week’s customers”.

Your script must:

  1. Fit a Pipeline with a one-hot encoder for the text columns and GradientBoostingClassifier(n_estimators=200, max_depth=3, learning_rate=0.05, random_state=42). Print the test ROC-AUC.
  2. Compute permutation importance on the test set with scoring="roc_auc", n_repeats=5 and random_state=42, on the raw columns. Print the table with mean and standard deviation, and draw a bar chart with error bars.
  3. Draw partial dependence and centered ICE curves for tenure_months and support_tickets.
  4. Measure the ticket effect per contract type: the average change in log-odds from 0 to 4 tickets, from ICE values.
  5. Compute SHAP values with shap.TreeExplainer for 500 test customers. Check additivity against decision_function with np.allclose, and draw a beeswarm plot.
  6. Build the call list: the 10 test customers with the highest churn probability, each with customer_id, risk and three reasons in plain words, from SHAP values grouped to the original features.
  7. Print a note for the retention team of at most 12 lines, with the top drivers, the interaction, and at least three caveats.
  8. End with assert checks: additivity, the shape of the call list and the stability of the top feature.
  1. Load and split. Read the CSV, fill the 10 blanks, cast the numeric columns to float and split with the lesson’s settings.

  2. Fit the model. Build the pipeline with set_output(transform="pandas") on the encoder, so that SHAP gets column names. Check the test ROC-AUC (about 0.84).

  3. Global importance. Run permutation_importance on the pipeline with the raw X_test. Sort by the mean. Plot the top 8 with barh and xerr.

  4. Shapes and interactions. Draw PartialDependenceDisplay.from_estimator(..., kind="both", centered=True, subsample=80) for the two features. Then compute ICE values of support_tickets at 0 and 4 with response_method="decision_function" and average the change per contract.

  5. SHAP. Encode a 500-row sample with pipeline["encode"].transform, explain it, check additivity, draw the beeswarm with show=False, then call plt.show().

  6. Call list. Rank the test set by predict_proba. Explain the top 10, group the one-hot columns, keep the positive contributions and turn the top 3 into phrases with a dict of templates.

  7. The note. Write it from your results, not from memory: insert the numbers with f-strings. State what the explanations are and what they are not.

A skeleton to start from:

explain_churn.py (starter)
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import shap
# TODO: scikit-learn imports
# --- Data ---
# TODO: load, fill total_charges, cast numeric columns to float, split
# --- Model ---
# TODO: pipeline with OneHotEncoder (set_output pandas) + GradientBoostingClassifier
# --- 1. Global importance ---
# TODO: permutation_importance on the test set, table and bar chart
# --- 2. Partial dependence, ICE and the ticket x contract interaction ---
# TODO: PartialDependenceDisplay, then partial_dependence(kind="individual")
# --- 3. SHAP ---
# TODO: TreeExplainer, additivity check, beeswarm
# --- 4. Call list ---
# TODO: top 10 risk customers with 3 reasons each
# --- 5. Note for the retention team ---
# TODO: print at most 12 lines
# --- Self-checks ---
# TODO: asserts
Criterion Points Full points when
Model and split 2 The pipeline, split and ROC-AUC match the requirements
Permutation importance 3 Computed on the test set, raw columns, ROC-AUC, 5 repeats; table and chart with error bars
Partial dependence and ICE 3 Both features drawn with centered ICE; the ticket effect is measured per contract in log-odds
SHAP 3 Explains encoded rows; additivity checked with np.allclose; beeswarm drawn with show=False and one plt.show()
Call list 3 10 customers, sorted by risk, with three plain-language reasons from grouped SHAP values
Note for the team 3 Numbers come from the results; at least three caveats, including “not causal”
Code quality 2 Clear names, helper functions, no repeated blocks, random_state=42 everywhere
Self-checks 1 Meaningful assert statements at the end
Total 20 16 or more: you are ready for module 44
  • Second seed. Repeat the permutation importance with random_state=0 and on each half of the test set. Mark the features whose rank moves by more than 2 places as “uncertain” in the note.
  • Counterfactuals. For each customer on the call list, compute the model’s risk if the contract were one-year. Show it as “model’s what-if”, with a warning that it is not a prediction of the customer’s behavior.
  • Grouped beeswarm. Build a shap.Explanation with the grouped values and numeric data (encode each text feature as its share of churners in the training set) and draw a beeswarm with 12 rows.
  • Leakage guard. Add a check that fails when one feature holds more than half of the total permutation importance (see exercise M43-X01).
  • HTML report. Save the three figures and the call list (DataFrame.to_html) into one report.html file.
Reference solution

The solution runs as one script, explain_churn.py. The blocks below are its parts in order.

explain_churn.py (part 1: data and model)
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
from sklearn.inspection import (
PartialDependenceDisplay,
partial_dependence,
permutation_importance,
)
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
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"]
customers = pd.read_csv("data/customers.csv")
customers["total_charges"] = customers["total_charges"].fillna(0.0)
X = customers[NUM_COLS + CAT_COLS].astype(dict.fromkeys(NUM_COLS, float))
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
)
encode = ColumnTransformer(
[("cat", OneHotEncoder(sparse_output=False), CAT_COLS)],
remainder="passthrough",
verbose_feature_names_out=False,
).set_output(transform="pandas")
model = GradientBoostingClassifier(
n_estimators=200, max_depth=3, learning_rate=0.05, random_state=42
)
pipe = Pipeline([("encode", encode), ("model", model)]).fit(X_train, y_train)
risk = pd.Series(pipe.predict_proba(X_test)[:, 1], index=X_test.index)
auc = roc_auc_score(y_test, risk)
print(f"test ROC-AUC: {auc:.3f}")
Output
test ROC-AUC: 0.837
explain_churn.py (part 2: permutation importance)
perm = permutation_importance(
pipe, X_test, y_test, scoring="roc_auc", n_repeats=5, random_state=42
)
importance = pd.DataFrame(
{"mean": perm.importances_mean, "std": perm.importances_std},
index=X_test.columns,
).sort_values("mean", ascending=False)
print(importance.to_string(float_format="{:.4f}".format))
top8 = importance.head(8).iloc[::-1]
fig, ax = plt.subplots(figsize=(7, 4))
ax.barh(top8.index, top8["mean"], xerr=top8["std"], color="tab:blue")
ax.set_xlabel("Drop in test ROC-AUC when the column is shuffled")
ax.set_title("What the churn model needs (permutation importance)")
fig.tight_layout()
plt.show()
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
payment_method 0.0084 0.0016
total_charges 0.0022 0.0020
avg_session_minutes 0.0011 0.0010
has_autopay 0.0002 0.0001
plan -0.0001 0.0001
region -0.0008 0.0009
Horizontal bar chart of the drop in ROC-AUC: contract is largest at about 0.065, then tenure_months, monthly_charges, logins_last_30d, support_tickets and age, with payment_method and total_charges small.
Permutation importance of the churn model on the test set, with the standard deviation over 5 shuffles.
explain_churn.py (part 3: partial dependence and ICE)
fig, axes = plt.subplots(1, 2, figsize=(10, 3.8))
PartialDependenceDisplay.from_estimator(
pipe,
X_test,
["tenure_months", "support_tickets"],
kind="both",
centered=True,
subsample=80,
random_state=42,
ax=axes,
)
fig.suptitle("Change in churn probability (centered ICE curves and average)")
fig.tight_layout()
plt.show()
ice = partial_dependence(
pipe,
X_test,
["support_tickets"],
kind="individual",
custom_values={"support_tickets": np.array([0.0, 4.0])},
response_method="decision_function",
)
lines = ice["individual"][0]
ticket_effect = pd.Series(lines[:, 1] - lines[:, 0], index=X_test.index)
by_contract = ticket_effect.groupby(X_test["contract"]).mean()
print("Change in log-odds from 0 to 4 tickets, by contract:")
print(by_contract.round(3))
Output
Change in log-odds from 0 to 4 tickets, by contract:
contract
month-to-month 2.221
one-year 0.643
two-year 0.445
dtype: float64
Two panels of centered ICE curves. Left: churn probability falls steeply over the first six months of tenure and then stays roughly flat. Right: probability rises with support tickets; some curves climb steeply while many stay almost flat.
Centered ICE curves and their average for tenure (left) and support tickets (right).
explain_churn.py (part 4: SHAP values)
def original_feature(column: str) -> str:
"""Map an encoded column such as 'contract_two-year' back to 'contract'."""
return next((c for c in CAT_COLS if column.startswith(f"{c}_")), column)
explainer = shap.TreeExplainer(pipe["model"])
def grouped_shap(rows: pd.DataFrame) -> tuple[pd.DataFrame, np.ndarray]:
"""SHAP values per original feature, and the base values."""
sv = explainer(pipe["encode"].transform(rows))
groups = [original_feature(c) for c in sv.feature_names]
values = pd.DataFrame(sv.values, columns=groups, index=rows.index)
return values.T.groupby(level=0).sum().T, sv.base_values
sample = X_test.sample(500, random_state=42)
sv_sample = explainer(pipe["encode"].transform(sample))
grouped, base = grouped_shap(sample)
additive = np.allclose(base + grouped.sum(axis=1), pipe.decision_function(sample))
print(f"base value: {base[0]:.3f} log-odds; additivity holds: {additive}")
print(grouped.abs().mean().sort_values(ascending=False).head(6).round(3))
shap.plots.beeswarm(sv_sample, max_display=10, show=False)
plt.title("How each feature moves the churn score (500 test customers)")
plt.show()
Output
base value: -1.964 log-odds; additivity holds: True
contract 0.521
tenure_months 0.445
monthly_charges 0.356
age 0.296
support_tickets 0.270
logins_last_30d 0.202
dtype: float64
Beeswarm plot: short tenure, a month-to-month contract, high monthly charges, many support tickets and few logins push churn scores up; long tenure and a two-year contract push them down.
SHAP beeswarm of the churn model, in log-odds.
explain_churn.py (part 5: call list)
TEMPLATES = {
"support_tickets": "{:g} support tickets",
"tenure_months": "{:g} month(s) of tenure",
"logins_last_30d": "{:g} logins in 30 days",
"contract": "{} contract",
"monthly_charges": "pays {:.2f} a month",
"payment_method": "pays by {}",
"age": "age {:g}",
"total_charges": "paid {:.2f} in total",
"avg_session_minutes": "{:g} min per session",
"has_autopay": "autopay = {:g}",
"region": "{} region",
"plan": "{} plan",
}
def reasons(contrib: pd.Series, row: pd.Series, k: int = 3) -> str:
"""The k largest positive contributions as plain phrases."""
top = contrib[contrib > 0].nlargest(k).index
return "; ".join(TEMPLATES[f].format(row[f]) for f in top)
top10 = risk.nlargest(10).index
contrib_top, _ = grouped_shap(X_test.loc[top10])
call_list = pd.DataFrame(
{
"customer_id": customers.loc[top10, "customer_id"],
"risk": risk[top10].round(2),
"reasons": [reasons(contrib_top.loc[i], X_test.loc[i]) for i in top10],
}
)
print("customer risk reasons")
for row in call_list.itertuples(index=False):
print(f"{row.customer_id} {row.risk:.2f} {row.reasons}")
Output
customer risk reasons
C04816 0.98 1 month(s) of tenure; 5 support tickets; age 66
C04542 0.97 9 support tickets; 3 month(s) of tenure; 3 logins in 30 days
C04642 0.96 2 logins in 30 days; 2 month(s) of tenure; age 21
C04165 0.95 4 support tickets; 5 month(s) of tenure; month-to-month contract
C04795 0.94 1 month(s) of tenure; pays 110.49 a month; 3 logins in 30 days
C04881 0.94 1 month(s) of tenure; 4 support tickets; pays 103.43 a month
C04761 0.94 1 month(s) of tenure; pays 101.11 a month; age 70
C04825 0.93 4 support tickets; 1 month(s) of tenure; 3 logins in 30 days
C04720 0.92 5 support tickets; 2 month(s) of tenure; month-to-month contract
C04574 0.91 2 month(s) of tenure; 4 support tickets; pays 93.49 a month
explain_churn.py (part 6: note and self-checks)
top3 = importance.index[:3].tolist()
mtm = by_contract["month-to-month"]
others = by_contract.drop("month-to-month").mean()
note = [
"CHURN MODEL: WHAT IT LOOKS AT",
f"Ranking quality: test ROC-AUC {auc:.3f}.",
f"Top drivers (permutation importance): {', '.join(top3)}.",
f"Extra tickets matter most on month-to-month: +{mtm:.2f} log-odds for 0->4,",
f" versus +{others:.2f} on longer contracts.",
"Each call-list reason names the facts that raised the model's score.",
"CAVEATS",
"- The model shows patterns, not causes: fixing tickets may not stop churn.",
"- Tenure and total charges overlap; their credit is shared between them.",
"- Ranks below the top 3 are close and can swap with new data.",
"- Test any retention offer with an A/B test before rolling it out.",
]
print("\n".join(note))
assert additive
assert call_list.shape == (10, 3)
assert call_list["risk"].is_monotonic_decreasing
assert len(note) <= 12
assert importance.index[0] == "contract"
assert importance["mean"].iloc[0] - 2 * importance["std"].iloc[0] > importance[
"mean"
].iloc[1]
Output
CHURN MODEL: WHAT IT LOOKS AT
Ranking quality: test ROC-AUC 0.837.
Top drivers (permutation importance): contract, tenure_months, monthly_charges.
Extra tickets matter most on month-to-month: +2.22 log-odds for 0->4,
versus +0.54 on longer contracts.
Each call-list reason names the facts that raised the model's score.
CAVEATS
- The model shows patterns, not causes: fixing tickets may not stop churn.
- Tenure and total charges overlap; their credit is shared between them.
- Ranks below the top 3 are close and can swap with new data.
- Test any retention offer with an A/B test before rolling it out.

How it works:

  1. Part 1 builds one pipeline, so that permutation importance and partial dependence can work on raw columns, and SHAP can work on the encoded columns that the trees use.
  2. Part 2 measures what the model needs on unseen customers. Error bars show the spread over 5 shuffles. The last assert checks that the top feature’s lead is larger than twice its standard deviation, so “contract matters most” is stable against shuffle noise. It says nothing about a different sample of customers; the “Second seed” stretch goal and exercise M43-X04 test that.
  3. Part 3 shows the shapes. The centered ICE curves for tickets split into steep and flat groups. The per-contract average in log-odds names the interaction behind the split: month-to-month customers react far more to extra tickets.
  4. Part 4 checks additivity before anything else uses the SHAP values. Grouping the one-hot columns keeps the sums exact and gives one value per original feature.
  5. Part 5 turns the largest positive contributions into sentences. The templates keep the wording consistent across customers and avoid model jargon.
  6. Part 6 writes the note from the computed numbers, so it stays correct when the model is retrained. The caveats state what the explanations are not: causes, separable effects of correlated features, or a final ranking of the middle features.