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:
- Which features drive the model’s churn scores, and how sure are we of that ranking?
- How does the predicted risk change with tenure and with support tickets, and does the ticket effect depend on the contract?
- For each customer on this week’s call list, which three facts raised the score?
- 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.
Dataset
Section titled “Dataset”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”.
Requirements
Section titled “Requirements”Your script must:
- Fit a
Pipelinewith a one-hot encoder for the text columns andGradientBoostingClassifier(n_estimators=200, max_depth=3, learning_rate=0.05, random_state=42). Print the test ROC-AUC. - Compute permutation importance on the test set with
scoring="roc_auc",n_repeats=5andrandom_state=42, on the raw columns. Print the table with mean and standard deviation, and draw a bar chart with error bars. - Draw partial dependence and centered ICE curves for
tenure_monthsandsupport_tickets. - Measure the ticket effect per contract type: the average change in log-odds from 0 to 4 tickets, from ICE values.
- Compute SHAP values with
shap.TreeExplainerfor 500 test customers. Check additivity againstdecision_functionwithnp.allclose, and draw a beeswarm plot. - 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. - Print a note for the retention team of at most 12 lines, with the top drivers, the interaction, and at least three caveats.
- End with
assertchecks: additivity, the shape of the call list and the stability of the top feature.
Step plan
Section titled “Step plan”-
Load and split. Read the CSV, fill the 10 blanks, cast the numeric columns to
floatand split with the lesson’s settings. -
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). -
Global importance. Run
permutation_importanceon the pipeline with the rawX_test. Sort by the mean. Plot the top 8 withbarhandxerr. -
Shapes and interactions. Draw
PartialDependenceDisplay.from_estimator(..., kind="both", centered=True, subsample=80)for the two features. Then compute ICE values ofsupport_ticketsat 0 and 4 withresponse_method="decision_function"and average the change per contract. -
SHAP. Encode a 500-row sample with
pipeline["encode"].transform, explain it, check additivity, draw the beeswarm withshow=False, then callplt.show(). -
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. -
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:
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport 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: assertsRubric
Section titled “Rubric”| 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 |
Stretch goals
Section titled “Stretch goals”- Second seed. Repeat the permutation importance with
random_state=0and 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.Explanationwith 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 onereport.htmlfile.
Reference solution
Section titled “Reference solution”Reference solution
The solution runs as one script, explain_churn.py. The blocks below are its parts in order.
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport shapfrom sklearn.compose import ColumnTransformerfrom sklearn.ensemble import GradientBoostingClassifierfrom sklearn.inspection import ( PartialDependenceDisplay, partial_dependence, permutation_importance,)from sklearn.metrics import roc_auc_scorefrom sklearn.model_selection import train_test_splitfrom sklearn.pipeline import Pipelinefrom 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}")test ROC-AUC: 0.837perm = 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() 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.0028payment_method 0.0084 0.0016total_charges 0.0022 0.0020avg_session_minutes 0.0011 0.0010has_autopay 0.0002 0.0001plan -0.0001 0.0001region -0.0008 0.0009
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))Change in log-odds from 0 to 4 tickets, by contract:contractmonth-to-month 2.221one-year 0.643two-year 0.445dtype: float64
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()base value: -1.964 log-odds; additivity holds: Truecontract 0.521tenure_months 0.445monthly_charges 0.356age 0.296support_tickets 0.270logins_last_30d 0.202dtype: float64
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).indexcontrib_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}")customer risk reasonsC04816 0.98 1 month(s) of tenure; 5 support tickets; age 66C04542 0.97 9 support tickets; 3 month(s) of tenure; 3 logins in 30 daysC04642 0.96 2 logins in 30 days; 2 month(s) of tenure; age 21C04165 0.95 4 support tickets; 5 month(s) of tenure; month-to-month contractC04795 0.94 1 month(s) of tenure; pays 110.49 a month; 3 logins in 30 daysC04881 0.94 1 month(s) of tenure; 4 support tickets; pays 103.43 a monthC04761 0.94 1 month(s) of tenure; pays 101.11 a month; age 70C04825 0.93 4 support tickets; 1 month(s) of tenure; 3 logins in 30 daysC04720 0.92 5 support tickets; 2 month(s) of tenure; month-to-month contractC04574 0.91 2 month(s) of tenure; 4 support tickets; pays 93.49 a monthtop3 = 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 additiveassert call_list.shape == (10, 3)assert call_list["risk"].is_monotonic_decreasingassert len(note) <= 12assert importance.index[0] == "contract"assert importance["mean"].iloc[0] - 2 * importance["std"].iloc[0] > importance[ "mean"].iloc[1]CHURN MODEL: WHAT IT LOOKS ATRanking 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:
- 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.
- 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.
- 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.
- 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.
- Part 5 turns the largest positive contributions into sentences. The templates keep the wording consistent across customers and avoid model jargon.
- 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.