Skip to content

43. Interpretability — Exercises

These exercises practice every idea of the interpretability lesson. They use data/customers.csv (churn) and data/houses.csv (house prices), described in the data dictionary.

How to work:

  1. Run the setup block once at the top of your script. Every exercise assumes its names exist.
  2. Read the task and the expected output. Copy the starter code below the setup and replace each to-do comment with your code.
  3. Run the script and compare your output with the expected output.
  4. Stuck? Open one hint at a time. Open the solution only after a real attempt.

Each solution ends with assert statements that check the result. Add the same checks to your own code.

The setup loads both datasets and makes the train/test splits of the lesson. Two details matter for this module:

  • The numeric churn columns are cast to float, because partial_dependence in scikit-learn 1.9 rejects integer columns.
  • The house exercises use the eight numeric columns without blanks (H_COLS), so that linear models and gradient boosting accept them directly. The target is log price.

make_gbm() builds the churn pipeline of the lesson: one-hot encoding of the text columns, then gradient boosting.

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,
GradientBoostingRegressor,
RandomForestClassifier,
RandomForestRegressor,
)
from sklearn.inspection import (
PartialDependenceDisplay,
partial_dependence,
permutation_importance,
)
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.metrics import r2_score, roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.tree import DecisionTreeRegressor
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].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
)
houses = pd.read_csv("data/houses.csv")
H_COLS = [
"sqft", "bedrooms", "bathrooms", "year_built", "condition",
"distance_to_center_km", "has_pool", "garage_spaces",
]
Xh = houses[H_COLS].astype(float)
yh = np.log(houses["price"])
Xh_train, Xh_test, yh_train, yh_test = train_test_split(
Xh, yh, test_size=0.25, random_state=42
)
def make_gbm(n_estimators: int = 100) -> Pipeline:
"""One-hot encode the text columns, then fit gradient boosting for churn."""
encode = ColumnTransformer(
[("cat", OneHotEncoder(sparse_output=False), CAT_COLS)],
remainder="passthrough",
verbose_feature_names_out=False,
).set_output(transform="pandas")
model = GradientBoostingClassifier(
n_estimators=n_estimators, max_depth=3, random_state=42
)
return Pipeline([("encode", encode), ("model", model)])
Warm-up

Choose a method and justify it: six people ask questions about the churn and house models. Label each question "global" or "local" and store the method you would use. Print one line per question, then the number of global questions.

Expected output
global | permutation importance on the test set
local | SHAP waterfall for that customer
global | partial dependence plot of sqft
local | ICE curve of sqft for that house
global | permutation importance of region
local | top 3 SHAP values of that customer
global questions: 3
Starter
questions = [
"Which features drive churn across all customers?",
"Why did customer C04542 get a 97% churn score?",
"How does predicted price change with sqft on average?",
"How would this house's price change if it were 500 sqft larger?",
"Does the model rely on region at all?",
"Which three facts raised this customer's score?",
]
# TODO: a list of (scope, method) pairs in the same order
# TODO: print "scope | method" per question, then the count of global ones
Hint 1

“Across all customers”, “on average” and “at all” describe the whole model: global. “This customer” and “this house” describe one row: local.

Hint 2

Global methods: permutation importance, mean absolute SHAP, partial dependence. Local methods: a SHAP waterfall, an ICE curve.

Solution
questions = [
"Which features drive churn across all customers?",
"Why did customer C04542 get a 97% churn score?",
"How does predicted price change with sqft on average?",
"How would this house's price change if it were 500 sqft larger?",
"Does the model rely on region at all?",
"Which three facts raised this customer's score?",
]
answers = [
("global", "permutation importance on the test set"),
("local", "SHAP waterfall for that customer"),
("global", "partial dependence plot of sqft"),
("local", "ICE curve of sqft for that house"),
("global", "permutation importance of region"),
("local", "top 3 SHAP values of that customer"),
]
for scope, method in answers:
print(f"{scope:6} | {method}")
n_global = sum(scope == "global" for scope, _ in answers)
print("global questions:", n_global)
assert len(answers) == len(questions)
assert n_global == 3
Output
global | permutation importance on the test set
local | SHAP waterfall for that customer
global | partial dependence plot of sqft
local | ICE curve of sqft for that house
global | permutation importance of region
local | top 3 SHAP values of that customer
global questions: 3

How it works:

  1. A question about the whole model or about averages needs a global explanation. A question about one customer or one house needs a local explanation.
  2. Question 4 is a what-if for one house: an ICE curve answers it exactly, because it changes only sqft for that row.
  3. sum() over booleans counts the True values, because True counts as 1.

Alternative: mean absolute SHAP also answers questions 1 and 5. It measures how far region moves the predictions, while permutation importance measures how much the test score needs it.

M43-W02 · From coefficients to odds ratios

Section titled “M43-W02 · From coefficients to odds ratios”
Warm-up

A logistic regression on standardized churn features has these coefficients: tenure_months −1.024, support_tickets 0.543 and contract_two-year −1.730 (reference category: month-to-month). Convert each one to an odds ratio and to a percent change in the odds.

Expected output
tenure_months: odds ratio 0.359 (-64% odds)
support_tickets: odds ratio 1.721 (+72% odds)
contract_two-year: odds ratio 0.177 (-82% odds)
Starter
coefs = {"tenure_months": -1.024, "support_tickets": 0.543, "contract_two-year": -1.730}
# TODO: odds ratio = exp(coef); percent change = odds ratio - 1
# TODO: print "name: odds ratio 0.359 (-64% odds)"
Hint 1

np.exp(coef) turns a log-odds coefficient into an odds ratio.

Hint 2

The format spec :+.0% shows a fraction as a signed percent: f"{-0.641:+.0%}" gives -64%.

Solution
coefs = {"tenure_months": -1.024, "support_tickets": 0.543, "contract_two-year": -1.730}
ratios = {}
for name, coef in coefs.items():
ratios[name] = float(np.exp(coef))
print(f"{name}: odds ratio {ratios[name]:.3f} ({ratios[name] - 1:+.0%} odds)")
assert ratios["support_tickets"] > 1 > ratios["tenure_months"]
assert round(ratios["contract_two-year"], 3) == 0.177
Output
tenure_months: odds ratio 0.359 (-64% odds)
support_tickets: odds ratio 1.721 (+72% odds)
contract_two-year: odds ratio 0.177 (-82% odds)

How it works:

  1. Logistic regression is linear in the log-odds, so a coefficient is a change in log-odds. np.exp turns it into a factor on the odds.
  2. An odds ratio below 1 lowers the odds; above 1 raises them. ratio - 1 is the relative change.
  3. For the standardized numeric features, “one unit” means one standard deviation. For contract_two-year, it means “two-year instead of month-to-month”.

Alternative: NumPy converts all coefficients at once: np.exp(pd.Series(coefs)).

Warm-up

Fit a LinearRegression on Xh_train and yh_train (log price). Print the raw coefficients of sqft and has_pool. Then multiply every coefficient by its feature’s standard deviation in Xh_train to get the effect of a one-standard-deviation step, and print the top three by absolute size.

Expected output
raw: sqft 0.00047, has_pool 0.225
sqft 0.336
distance_to_center_km -0.250
condition 0.111
dtype: float64
Starter
lin = LinearRegression().fit(Xh_train, yh_train)
raw = pd.Series(lin.coef_, index=H_COLS)
# TODO: print the raw coefficients of sqft and has_pool
# TODO: per_sd = raw * standard deviation; print the top 3 by absolute value
Hint 1

Xh_train.std() returns one standard deviation per column, aligned by column name with raw.

Hint 2

series.sort_values(key=abs, ascending=False) sorts by size and ignores the sign.

Solution
lin = LinearRegression().fit(Xh_train, yh_train)
raw = pd.Series(lin.coef_, index=H_COLS)
print(f"raw: sqft {raw['sqft']:.5f}, has_pool {raw['has_pool']:.3f}")
per_sd = (raw * Xh_train.std()).sort_values(key=abs, ascending=False)
print(per_sd.head(3).round(3))
assert abs(raw["has_pool"]) > abs(raw["sqft"])
assert per_sd.index[0] == "sqft"
Output
raw: sqft 0.00047, has_pool 0.225
sqft 0.336
distance_to_center_km -0.250
condition 0.111
dtype: float64

How it works:

  1. The raw coefficient of sqft is per square foot, so it is tiny. The coefficient of has_pool is for a full 0-to-1 step. Raw sizes say nothing about importance.
  2. Multiplying by the standard deviation gives the change in log price for a typical step in each feature. This equals the coefficient you would get after StandardScaler.
  3. On that common scale, size matters most, then distance (negative: farther is cheaper).

Alternative: fit make_pipeline(StandardScaler(), LinearRegression()) and read pipe[-1].coef_. The values match per_sd up to the small difference between the sample and population standard deviation.

Warm-up

Fit a DecisionTreeRegressor(max_depth=3, random_state=42) on Xh_train, yh_train. Print its non-zero feature_importances_, the sum of all importances and the names of the features the tree never uses.

Expected output
sqft 0.695
distance_to_center_km 0.305
dtype: float64
sum: 1.0
unused: ['bedrooms', 'bathrooms', 'year_built', 'condition', 'has_pool', 'garage_spaces']
Starter
tree = DecisionTreeRegressor(max_depth=3, random_state=42).fit(Xh_train, yh_train)
importances = pd.Series(tree.feature_importances_, index=H_COLS)
# TODO: print the non-zero importances, their sum and the unused features
Hint 1

A boolean mask selects rows of a Series: importances[importances > 0].

Hint 2

importances.index[importances == 0].tolist() lists the unused features.

Solution
tree = DecisionTreeRegressor(max_depth=3, random_state=42).fit(Xh_train, yh_train)
importances = pd.Series(tree.feature_importances_, index=H_COLS)
print(importances[importances > 0].round(3))
print("sum:", round(importances.sum(), 6))
unused = importances.index[importances == 0].tolist()
print("unused:", unused)
assert np.isclose(importances.sum(), 1.0)
assert "sqft" not in unused
Output
sqft 0.695
distance_to_center_km 0.305
dtype: float64
sum: 1.0
unused: ['bedrooms', 'bathrooms', 'year_built', 'condition', 'has_pool', 'garage_spaces']

How it works:

  1. A tree of depth 3 has at most 7 splits. This one splits only on size and distance.
  2. Impurity importances are scaled to sum to 1, so each value is a share of the total impurity reduction.
  3. A feature with no split gets exactly 0. The tree ignores has_pool and condition, although they affect price: with only 7 splits, the tree spends them on the strongest features.

Alternative: sklearn.tree.export_text(tree, feature_names=H_COLS) prints the splits as rules, so you can see where each importance comes from.

Warm-up

Fit a LinearRegression on Xh_train, yh_train. Compute the test R². Then shuffle the sqft column of a copy of Xh_test with rng = np.random.default_rng(42) and compute the R² again. Print both scores and the drop: the permutation importance of sqft from one shuffle.

Expected output
baseline R²: 0.751
sqft shuffled: -0.060
importance of sqft: 0.810
Starter
lin = LinearRegression().fit(Xh_train, yh_train)
rng = np.random.default_rng(42)
# TODO: baseline R² on the test set
# TODO: shuffled copy of Xh_test (only sqft), R² again, print the drop
Hint 1

lin.score(X, y) returns R². Xh_test.copy() gives a copy that you can change safely.

Hint 2

shuffled["sqft"] = rng.permutation(shuffled["sqft"].to_numpy()) shuffles one column.

Solution
lin = LinearRegression().fit(Xh_train, yh_train)
rng = np.random.default_rng(42)
baseline = lin.score(Xh_test, yh_test)
shuffled = Xh_test.copy()
shuffled["sqft"] = rng.permutation(shuffled["sqft"].to_numpy())
score = lin.score(shuffled, yh_test)
drop = baseline - score
print(f"baseline R²: {baseline:.3f}")
print(f"sqft shuffled: {score:.3f}")
print(f"importance of sqft: {drop:.3f}")
assert drop > 0.3
assert not shuffled["sqft"].equals(Xh_test["sqft"])
assert sorted(shuffled["sqft"]) == sorted(Xh_test["sqft"])
Output
baseline R²: 0.751
sqft shuffled: -0.060
importance of sqft: 0.810

How it works:

  1. The baseline is the model’s normal test score.
  2. Shuffling keeps the values of sqft but assigns them to random houses. The link between size and price is gone, and so is the link between size and the other features.
  3. The model is not retrained. The drop in R² measures how much this fitted model relies on sqft.

Alternative: permutation_importance(lin, Xh_test, yh_test, n_repeats=5, random_state=42) does the same for every column and repeats each shuffle 5 times.

M43-W06 · Predict the output: an unused feature

Section titled “M43-W06 · Predict the output: an unused feature”
Warm-up

Predict the output: a decision stump (max_depth=1) is fitted on three house features. Then permutation importance runs on the test set. Before you run the code, predict which importances are exactly 0.0 and why.

Acceptance criteria:

  • Write your prediction for each of the three features first, then run the code.
  • Your prediction of which values are exactly 0.0 matches the Output in the solution.
Starter
cols = ["sqft", "condition", "has_pool"]
stump = DecisionTreeRegressor(max_depth=1, random_state=42)
stump.fit(Xh_train[cols], yh_train)
perm = permutation_importance(
stump, Xh_test[cols], yh_test, n_repeats=3, random_state=42
)
for name, value in zip(cols, perm.importances_mean, strict=True):
print(f"{name}: {value:.4f}")
Hint 1

A stump makes exactly one split, on one feature.

Hint 2

If the model never reads a column, shuffling that column cannot change any prediction.

Solution
cols = ["sqft", "condition", "has_pool"]
stump = DecisionTreeRegressor(max_depth=1, random_state=42)
stump.fit(Xh_train[cols], yh_train)
perm = permutation_importance(
stump, Xh_test[cols], yh_test, n_repeats=3, random_state=42
)
for name, value in zip(cols, perm.importances_mean, strict=True):
print(f"{name}: {value:.4f}")
assert perm.importances_mean[1] == 0.0 and perm.importances_mean[2] == 0.0
assert stump.tree_.feature[0] == 0
Output
sqft: 0.7058
condition: 0.0000
has_pool: 0.0000

How it works:

  1. The stump splits once, on sqft, the feature with the largest error reduction. stump.tree_.feature[0] == 0 confirms that the root split uses column 0.
  2. Shuffling condition or has_pool changes columns that the model never reads, so every prediction stays the same and the score drop is exactly 0.
  3. Permutation importance is model-agnostic: it does not look inside the tree, yet it finds the same answer.

Alternative: stump.feature_importances_ gives [1, 0, 0] here. For a stump, impurity and permutation importance agree on which features are unused; they disagree on deep trees with noise.

M43-W07 · Partial dependence of a linear model

Section titled “M43-W07 · Partial dependence of a linear model”
Warm-up

Fit a LinearRegression on Xh_train, yh_train. Compute the partial dependence of sqft at 1,000, 2,000 and 3,000 sqft with partial_dependence(..., custom_values=...) on Xh_test. Print the three values and the step between them, and check that the step equals the coefficient times 1,000.

Expected output
PD: [12.5246 12.9935 13.4623]
steps: [0.4689 0.4689]
coef x 1000: 0.4689
Starter
lin = LinearRegression().fit(Xh_train, yh_train)
grid = {"sqft": np.array([1000.0, 2000.0, 3000.0])}
# TODO: result = partial_dependence(lin, Xh_test, ["sqft"], custom_values=grid)
# TODO: print the average curve and its steps; compare with lin.coef_
Hint 1

result["average"][0] is the curve for the first (and only) feature.

Hint 2

np.diff(curve) gives the differences between neighbors. H_COLS.index("sqft") finds the coefficient’s position.

Solution
lin = LinearRegression().fit(Xh_train, yh_train)
grid = {"sqft": np.array([1000.0, 2000.0, 3000.0])}
result = partial_dependence(lin, Xh_test, ["sqft"], custom_values=grid)
curve = result["average"][0]
steps = np.diff(curve)
coef_step = lin.coef_[H_COLS.index("sqft")] * 1000
print("PD:", curve.round(4))
print("steps:", steps.round(4))
print(f"coef x 1000: {coef_step:.4f}")
assert np.allclose(steps, coef_step)
Output
PD: [12.5246 12.9935 13.4623]
steps: [0.4689 0.4689]
coef x 1000: 0.4689

How it works:

  1. The PDP sets sqft to the grid value in every test row and averages the predictions.
  2. In a linear model, changing sqft by 1,000 changes every prediction by exactly coef * 1000, whatever the other features are. So the PDP is a straight line with that slope.
  3. ICE curves of a linear model without interactions are parallel lines. Partial dependence becomes interesting for models with curves and interactions.

Alternative: pass kind="individual" to see that all 750 ICE curves have the same step: np.allclose(np.diff(ice, axis=1), coef_step).

M43-W08 · SHAP values of a linear model by hand

Section titled “M43-W08 · SHAP values of a linear model by hand”
Warm-up

For a linear model with independent features, the SHAP value of feature jj is wj(xj−xˉj)w_j (x_j - \bar{x}_j), where xˉj\bar{x}_j is the mean of the background data, and the base value is the mean prediction. Fit a LinearRegression on Xh_train with only sqft, condition and has_pool. Compute the SHAP values of the first test house with Xh_train as background, and check that base value plus SHAP values equals the prediction.

Expected output
{'sqft': 1400.0, 'condition': 3.0, 'has_pool': 0.0}
sqft -0.228
condition -0.001
has_pool -0.029
dtype: float64
base 12.9141 + sum -0.2576 = 12.6565
prediction: 12.6565
Starter
cols = ["sqft", "condition", "has_pool"]
lin = LinearRegression().fit(Xh_train[cols], yh_train)
house = Xh_test[cols].iloc[[0]]
# TODO: base = mean prediction on Xh_train[cols]
# TODO: phi = lin.coef_ * (house - Xh_train[cols].mean())
# TODO: print phi, base, base + phi.sum() and the model's prediction
Hint 1

lin.predict(Xh_train[cols]).mean() is the base value.

Hint 2

house.iloc[0] - Xh_train[cols].mean() gives a Series of deviations; multiply it by lin.coef_.

Solution
cols = ["sqft", "condition", "has_pool"]
lin = LinearRegression().fit(Xh_train[cols], yh_train)
house = Xh_test[cols].iloc[[0]]
base = lin.predict(Xh_train[cols]).mean()
phi = lin.coef_ * (house.iloc[0] - Xh_train[cols].mean())
prediction = lin.predict(house)[0]
print(house.iloc[0].to_dict())
print(phi.round(4))
print(f"base {base:.4f} + sum {phi.sum():.4f} = {base + phi.sum():.4f}")
print(f"prediction: {prediction:.4f}")
assert np.isclose(base + phi.sum(), prediction)
Output
{'sqft': 1400.0, 'condition': 3.0, 'has_pool': 0.0}
sqft -0.228
condition -0.001
has_pool -0.029
dtype: float64
base 12.9141 + sum -0.2576 = 12.6565
prediction: 12.6565

How it works:

  1. The mean prediction of a linear model equals the prediction at the mean row, so the base value is b+∑jwjxˉjb + \sum_j w_j \bar{x}_j.
  2. Subtracting the base value from the prediction b+∑jwjxjb + \sum_j w_j x_j leaves ∑jwj(xj−xˉj)\sum_j w_j (x_j - \bar{x}_j): one term per feature. Each term is that feature’s SHAP value.
  3. A feature at its average value gets a SHAP value of 0. Here the small house has a negative sqft value: it is below the average size.

Alternative: shap.LinearExplainer(lin, shap.maskers.Independent(Xh_train[cols], max_samples=len(Xh_train))) computes the same values. With a plain DataFrame as background, the explainer keeps only 100 rows, prints a message about it, and its means differ slightly.

M43-W09 · From SHAP values to a probability

Section titled “M43-W09 · From SHAP values to a probability”
Warm-up

A churn explainer gives base value −1.964 (log-odds) and these SHAP values for one customer: [1.713, 1.311, 1.105, 0.842, 0.639, 0.455, -0.394, -0.087]. Compute the model output in log-odds and the churn probability. Then show what goes wrong if someone adds the SHAP values to the base probability.

Expected output
log-odds: 3.620
probability: 0.974
wrong (added to a probability): 5.707
Starter
base = -1.964
phi = np.array([1.713, 1.311, 1.105, 0.842, 0.639, 0.455, -0.394, -0.087])
# TODO: log-odds = base + sum; probability = sigmoid(log-odds)
# TODO: the wrong way: sigmoid(base) + sum
Hint 1

The sigmoid is 1 / (1 + np.exp(-z)).

Hint 2

SHAP values of a gradient boosting classifier are in log-odds. Add them in log-odds, then convert once.

Solution
base = -1.964
phi = np.array([1.713, 1.311, 1.105, 0.842, 0.639, 0.455, -0.394, -0.087])
def sigmoid(z: float) -> float:
return float(1 / (1 + np.exp(-z)))
log_odds = base + phi.sum()
proba = sigmoid(log_odds)
wrong = sigmoid(base) + phi.sum()
print(f"log-odds: {log_odds:.3f}")
print(f"probability: {proba:.3f}")
print(f"wrong (added to a probability): {wrong:.3f}")
assert 0 < proba < 1
assert wrong > 1
Output
log-odds: 3.620
probability: 0.974
wrong (added to a probability): 5.707

How it works:

  1. The base value plus the SHAP values gives the model’s raw output, 3.620 log-odds.
  2. The sigmoid maps log-odds to a probability between 0 and 1: about 97%.
  3. Adding log-odds contributions to a probability mixes units and gives an impossible “probability” above 1.

Alternative: scipy.special.expit(log_odds) is a fast, numerically safe sigmoid.

M43-C01 · Fix the bug: importance on the training set

Section titled “M43-C01 · Fix the bug: importance on the training set”
Core

Fix the bug: a colleague adds a column of random numbers to the house features, fits a forest and computes permutation importance. The noise column looks useful. Fix the code so that the importance measures what generalizes, and print the noise column’s importance on both sets.

Expected output
noise on train: 0.0256
noise on test: -0.0028
test std: 0.0022
Starter
rng = np.random.default_rng(42)
Xn_train = Xh_train.assign(noise=rng.normal(size=len(Xh_train)))
Xn_test = Xh_test.assign(noise=rng.normal(size=len(Xh_test)))
forest = RandomForestRegressor(n_estimators=50, random_state=42)
forest.fit(Xn_train, yh_train)
perm = permutation_importance(
forest, Xn_train, yh_train, n_repeats=5, random_state=42 # bug
)
print(f"noise importance: {perm.importances_mean[-1]:.4f}")
# TODO: compute it on the test set as well, and compare
Hint 1

The forest grows its trees until the leaves are pure, so it memorizes the training rows, noise included.

Hint 2

Pass Xn_test, yh_test to permutation_importance.

Solution
rng = np.random.default_rng(42)
Xn_train = Xh_train.assign(noise=rng.normal(size=len(Xh_train)))
Xn_test = Xh_test.assign(noise=rng.normal(size=len(Xh_test)))
forest = RandomForestRegressor(n_estimators=50, random_state=42)
forest.fit(Xn_train, yh_train)
on_train = permutation_importance(
forest, Xn_train, yh_train, n_repeats=5, random_state=42
)
on_test = permutation_importance(
forest, Xn_test, yh_test, n_repeats=5, random_state=42
)
print(f"noise on train: {on_train.importances_mean[-1]:.4f}")
print(f"noise on test: {on_test.importances_mean[-1]:.4f}")
print(f"test std: {on_test.importances_std[-1]:.4f}")
assert on_train.importances_mean[-1] > 5 * abs(on_test.importances_mean[-1])
Output
noise on train: 0.0256
noise on test: -0.0028
test std: 0.0022

How it works:

  1. On the training set, shuffling noise breaks splits that the trees used to memorize individual rows, so the training R² drops.
  2. On the test set, those memorized splits never helped, so shuffling the noise costs nothing within its standard deviation.
  3. The bug is not in the function call but in the data: permutation importance reports what the model needs on the data you pass.

Alternative: use a validation split from the training data when the test set must stay untouched until the very end, as in model selection.

M43-C02 · Fix the bug: ranking unscaled coefficients

Section titled “M43-C02 · Fix the bug: ranking unscaled coefficients”
Core

Fix the bug: a script ranks churn drivers by the size of logistic regression coefficients fitted on raw numeric features. Ranks by raw coefficients depend on the units. Put a StandardScaler before the model, rank the standardized coefficients by absolute value and print the top four as odds ratios per standard deviation.

Expected output
coef_per_sd odds_ratio
tenure_months -1.396 0.248
support_tickets 0.526 1.692
monthly_charges 0.372 1.450
logins_last_30d -0.281 0.755
Starter
model = LogisticRegression(max_iter=1000)
model.fit(X_train[NUM_COLS], y_train) # bug: raw units
coefs = pd.Series(model.coef_[0], index=NUM_COLS)
print(coefs.sort_values(key=abs, ascending=False).head(4))
# TODO: scale inside a pipeline, then rank again
Hint 1

make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)) scales inside the model, so the test set is scaled with the training statistics.

Hint 2

The fitted logistic regression is the last step: pipe[-1].coef_[0].

Solution
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
pipe.fit(X_train[NUM_COLS], y_train)
coefs = pd.Series(pipe[-1].coef_[0], index=NUM_COLS)
top = coefs.sort_values(key=abs, ascending=False).head(4)
table = pd.DataFrame({"coef_per_sd": top, "odds_ratio": np.exp(top)})
print(table.round(3))
assert table.index[0] == "tenure_months"
assert (table["odds_ratio"] < 1).equals(table["coef_per_sd"] < 0)
Output
coef_per_sd odds_ratio
tenure_months -1.396 0.248
support_tickets 0.526 1.692
monthly_charges 0.372 1.450
logins_last_30d -0.281 0.755

How it works:

  1. Without scaling, total_charges (tens to thousands) gets a tiny coefficient and has_autopay (0 or 1) a large one, whatever their real roles. Raw logistic regression on such ranges can also converge slowly.
  2. After scaling, each coefficient is the change in log-odds for a one-standard-deviation step, so the sizes are comparable.
  3. np.exp turns each into an odds ratio. Tenure has the strongest effect: one standard deviation more tenure divides the odds by about four (odds ratio 0.248).

Alternative: keep the raw model and multiply each raw coefficient by its feature’s standard deviation. The ranking matches the scaled model’s when the model converges; the pipeline is simpler and safer.

M43-C03 · Interpret a result: twin features

Section titled “M43-C03 · Interpret a result: twin features”
Core

Interpret a result: add sqft_listed, the size from the sales listing (the true size plus a rounding error with a standard deviation of 20 sqft), to a linear model with sqft and condition. Fit the model on two halves of the training set. Print both coefficients from each half and their sum, and explain what you see.

Expected output
half 1: sqft +0.253, listed +0.265, sum 0.518
half 2: sqft +1.046, listed -0.526, sum 0.520
correlation: 0.9996
Starter
rng = np.random.default_rng(42)
data = Xh_train[["sqft", "condition"]].assign(
sqft_listed=Xh_train["sqft"] + rng.normal(0, 20, size=len(Xh_train))
)
half = len(data) // 2
# TODO: fit LinearRegression on data[:half] and on data[half:]
# TODO: print the sqft and sqft_listed coefficients (x 1000) and their sum
Hint 1

data.iloc[:half] and yh_train.iloc[:half] select the first half; use iloc[half:] for the second.

Hint 2

Multiply the coefficients by 1,000 to read them as “log price per 1,000 sqft”.

Solution
rng = np.random.default_rng(42)
data = Xh_train[["sqft", "condition"]].assign(
sqft_listed=Xh_train["sqft"] + rng.normal(0, 20, size=len(Xh_train))
)
half = len(data) // 2
results = {}
for name, rows in [("half 1", slice(0, half)), ("half 2", slice(half, None))]:
model = LinearRegression().fit(data.iloc[rows], yh_train.iloc[rows])
coef = pd.Series(model.coef_, index=data.columns) * 1000
results[name] = coef
print(
f"{name}: sqft {coef['sqft']:+.3f}, listed {coef['sqft_listed']:+.3f}, "
f"sum {coef['sqft'] + coef['sqft_listed']:.3f}"
)
print(f"correlation: {data['sqft'].corr(data['sqft_listed']):.4f}")
sums = [c["sqft"] + c["sqft_listed"] for c in results.values()]
assert abs(sums[0] - sums[1]) < 0.1
Output
half 1: sqft +0.253, listed +0.265, sum 0.518
half 2: sqft +1.046, listed -0.526, sum 0.520
correlation: 0.9996

How it works:

  1. The two size columns correlate almost perfectly. The model can shift weight from one to the other with almost no change in fit.
  2. So the individual coefficients depend on small accidents of the sample: they differ between the halves, and one of them can even turn negative.
  3. Their sum, the total effect of size, is stable. Report the combined effect, or keep only one of the twins.

Alternative: Ridge(alpha=...) with standardized features shrinks the twins toward equal, stable shares. The shares are still a modeling choice, not a fact about the houses.

Core

Add random_id, a random number from 0 to 4,999 per customer, to the numeric churn features. Fit a RandomForestClassifier(n_estimators=100, random_state=42) on the eight numeric features plus the id. Print the rank of random_id by impurity importance and by permutation importance on the test set (scoring="roc_auc", n_repeats=5).

Expected output
mdi_rank perm_rank
total_charges 1 5
tenure_months 2 1
monthly_charges 3 2
random_id 4 8
age 5 4
avg_session_minutes 6 9
logins_last_30d 7 3
support_tickets 8 6
has_autopay 9 7
random_id permutation importance: 0.0004
Starter
rng = np.random.default_rng(42)
ids = pd.Series(rng.permutation(len(X)), index=X.index)
cols = NUM_COLS + ["random_id"]
Xi_train = X_train[NUM_COLS].assign(random_id=ids)
Xi_test = X_test[NUM_COLS].assign(random_id=ids)
# TODO: fit the forest, rank by feature_importances_ and by permutation importance
Hint 1

.assign(random_id=ids) aligns the Series by index, so each customer keeps the same id in both sets.

Hint 2

series.rank(ascending=False) gives rank 1 to the largest value.

Solution
rng = np.random.default_rng(42)
ids = pd.Series(rng.permutation(len(X)), index=X.index)
cols = NUM_COLS + ["random_id"]
Xi_train = X_train[NUM_COLS].assign(random_id=ids)
Xi_test = X_test[NUM_COLS].assign(random_id=ids)
forest = RandomForestClassifier(n_estimators=100, random_state=42)
forest.fit(Xi_train, y_train)
mdi = pd.Series(forest.feature_importances_, index=cols)
perm = permutation_importance(
forest, Xi_test, y_test, scoring="roc_auc", n_repeats=5, random_state=42
)
perm_s = pd.Series(perm.importances_mean, index=cols)
ranks = pd.DataFrame(
{
"mdi_rank": mdi.rank(ascending=False).astype(int),
"perm_rank": perm_s.rank(ascending=False).astype(int),
}
)
print(ranks.sort_values("mdi_rank"))
print(f"random_id permutation importance: {perm_s['random_id']:.4f}")
assert ranks.loc["random_id", "mdi_rank"] < ranks.loc["random_id", "perm_rank"]
Output
mdi_rank perm_rank
total_charges 1 5
tenure_months 2 1
monthly_charges 3 2
random_id 4 8
age 5 4
avg_session_minutes 6 9
logins_last_30d 7 3
support_tickets 8 6
has_autopay 9 7
random_id permutation importance: 0.0004

How it works:

  1. The id has 5,000 distinct values, so it offers thousands of split points. Deep trees use them to separate training customers, and impurity importance credits the id for it.
  2. On the test set, the id carries no signal, so shuffling it does not lower the ROC-AUC. Its permutation rank falls near the bottom (8 of 9).
  3. Real ids are not always pure noise. In customers.csv, ids grow with the signup date, so a real id would carry tenure information. Check what a high-cardinality column encodes before you drop or trust it.

Alternative: drop the id and refit: if the test ROC-AUC stays the same, the model never needed it.

Core

Choose a method and justify it: fit make_gbm() on the churn training set. Compute permutation importance on the test set twice, once with scoring="accuracy" and once with scoring="roc_auc" (n_repeats=5, random_state=42). Print the top four features of each, and decide which metric suits a retention team that calls the 200 riskiest customers.

Expected output
accuracy: tenure_months 0.023, support_tickets 0.020, contract 0.018, logins_last_30d 0.016
roc_auc: contract 0.065, tenure_months 0.050, monthly_charges 0.034, logins_last_30d 0.027
Starter
gbm = make_gbm().fit(X_train, y_train)
# TODO: permutation importance with accuracy and with roc_auc
# TODO: print the top 4 of each
Hint 1

Pass the whole pipeline and the raw X_test, so each shuffle moves one original column.

Hint 2

A loop over ["accuracy", "roc_auc"] avoids repeating the call.

Solution
gbm = make_gbm().fit(X_train, y_train)
tops = {}
for metric in ["accuracy", "roc_auc"]:
perm = permutation_importance(
gbm, X_test, y_test, scoring=metric, n_repeats=5, random_state=42
)
s = pd.Series(perm.importances_mean, index=X_test.columns)
tops[metric] = s.sort_values(ascending=False).head(4)
print(f"{metric}:", ", ".join(f"{k} {v:.3f}" for k, v in tops[metric].items()))
assert tops["roc_auc"].iloc[0] > tops["accuracy"].iloc[0]
assert tops["roc_auc"].index[0] == "contract"
Output
accuracy: tenure_months 0.023, support_tickets 0.020, contract 0.018, logins_last_30d 0.016
roc_auc: contract 0.065, tenure_months 0.050, monthly_charges 0.034, logins_last_30d 0.027

How it works:

  1. Accuracy uses the 0.5 threshold. Most customers are far from it, so shuffling a feature flips few labels and the drops are small.
  2. ROC-AUC measures the ranking of all customers. The team calls the 200 riskiest, so the ranking is what matters: choose ROC-AUC (or average precision).
  3. The two metrics also order the features differently: contract matters most for the ranking, tenure_months for the labels at 0.5.

Alternative: scoring="average_precision" focuses on the top of the ranking, which suits a team with a fixed call budget even better.

M43-C06 · Permute a group of columns together

Section titled “M43-C06 · Permute a group of columns together”
Core

Interpret a result: write a function group_importance(model, X, y, cols, n_repeats, seed) that shuffles all columns in cols with the same row permutation and returns the mean drop in test ROC-AUC. Use a scaled logistic regression on the numeric churn features. Compare tenure_months alone, total_charges alone and both together, and explain why the pair is not more important than tenure alone.

Expected output
tenure alone: 0.2015
total_charges alone: 0.0058
both together: 0.1614
Starter
def group_importance(model, X, y, cols, n_repeats=5, seed=42) -> float:
rng = np.random.default_rng(seed)
base = roc_auc_score(y, model.predict_proba(X)[:, 1])
drops = []
# TODO: for each repeat, one permutation applied to all cols at once
return float(np.mean(drops))
logit = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
logit.fit(X_train[NUM_COLS], y_train)
# TODO: print the importance of each column alone and of the pair
Hint 1

order = rng.permutation(len(X)) gives one permutation. X[cols].to_numpy()[order] reorders the rows of all those columns together.

Hint 2

Write into a copy: shuffled = X.copy(), then shuffled[cols] = X[cols].to_numpy()[order].

Solution
def group_importance(model, X, y, cols, n_repeats=5, seed=42) -> float:
"""Mean ROC-AUC drop when the columns in cols are shuffled together."""
rng = np.random.default_rng(seed)
base = roc_auc_score(y, model.predict_proba(X)[:, 1])
drops = []
for _ in range(n_repeats):
order = rng.permutation(len(X))
shuffled = X.copy()
shuffled[cols] = X[cols].to_numpy()[order]
drops.append(base - roc_auc_score(y, model.predict_proba(shuffled)[:, 1]))
return float(np.mean(drops))
logit = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
logit.fit(X_train[NUM_COLS], y_train)
Xt = X_test[NUM_COLS]
alone_t = group_importance(logit, Xt, y_test, ["tenure_months"])
alone_c = group_importance(logit, Xt, y_test, ["total_charges"])
both = group_importance(logit, Xt, y_test, ["tenure_months", "total_charges"])
print(f"tenure alone: {alone_t:.4f}")
print(f"total_charges alone: {alone_c:.4f}")
print(f"both together: {both:.4f}")
assert alone_t > both > alone_c
Output
tenure alone: 0.2015
total_charges alone: 0.0058
both together: 0.1614

How it works:

  1. One permutation per repeat, applied to every column of the group, keeps the pair’s values together within each row. Only their link to the target and to the other features breaks.
  2. Shuffling total_charges alone costs little, because tenure and monthly charges still carry its information.
  3. Shuffling tenure alone costs more than shuffling both. The logistic model offsets a negative tenure weight against a positive total_charges weight (lesson, Example 1). A shuffled tenure next to the customer’s real total charges makes a row that cannot exist, such as 70 months with 90 in total charges, and the model scores such rows badly. Shuffling both keeps each row’s pair consistent and measures only the loss of information.
  4. So single-column permutation importance of a correlated feature can be inflated by impossible rows as well as deflated by a partner that covers it. Group the features that measure the same thing, and report their joint importance.

Alternative: permutation_importance in scikit-learn 1.9 has no option for groups. Another way is to replace the pair by one feature before you fit, for example avg_charge = total_charges / (tenure_months + 1) next to tenure_months. Then the standard function permutes features that are far less correlated.

M43-C07 · Read a partial dependence curve as numbers

Section titled “M43-C07 · Read a partial dependence curve as numbers”
Core

Fit make_gbm() on the churn training set. Compute the partial dependence of the churn probability on tenure_months at 0, 3, 6, 12, 24, 48 and 72 months, on the test set. Print a small table and the first tenure where the average predicted probability falls below 0.15.

Expected output
tenure_months p_churn
0.0 0.413
3.0 0.337
6.0 0.190
12.0 0.167
24.0 0.139
48.0 0.099
72.0 0.099
first tenure below 0.15: 24
Starter
gbm = make_gbm().fit(X_train, y_train)
grid = {"tenure_months": np.array([0.0, 3, 6, 12, 24, 48, 72])}
# TODO: partial_dependence(gbm, X_test, ["tenure_months"], custom_values=grid)
# TODO: table of tenure and average P(churn); first tenure below 0.15
Hint 1

For a classifier, partial_dependence uses predict_proba by default and returns the probability of the positive class.

Hint 2

table.loc[table["p_churn"] < 0.15, "tenure_months"].iloc[0] finds the first tenure below the cut-off.

Solution
gbm = make_gbm().fit(X_train, y_train)
grid = {"tenure_months": np.array([0.0, 3, 6, 12, 24, 48, 72])}
result = partial_dependence(gbm, X_test, ["tenure_months"], custom_values=grid)
table = pd.DataFrame(
{"tenure_months": result["grid_values"][0], "p_churn": result["average"][0]}
)
print(table.round(3).to_string(index=False))
first = table.loc[table["p_churn"] < 0.15, "tenure_months"].iloc[0]
print("first tenure below 0.15:", int(first))
assert table["p_churn"].iloc[0] > 2 * table["p_churn"].iloc[-1]
Output
tenure_months p_churn
0.0 0.413
3.0 0.337
6.0 0.190
12.0 0.167
24.0 0.139
48.0 0.099
72.0 0.099
first tenure below 0.15: 24

How it works:

  1. partial_dependence works on the whole pipeline: it changes the raw column, and the encoder and model run as usual.
  2. The average predicted churn probability falls steeply over the first year (from 0.413 to 0.167) and then flattens: the 48- and 72-month values are equal. partial_dependence uses brute force here, because a Pipeline is not a tree model, so each value is an average over the test rows.
  3. Each number is an average over 1,250 test customers with tenure set to the grid value. It is the model’s answer, not the observed churn rate of customers with that tenure.

Alternative: PartialDependenceDisplay.from_estimator(gbm, X_test, ["tenure_months"]) draws the same curve with a rug of the data.

M43-C08 · ICE curves reveal an interaction

Section titled “M43-C08 · ICE curves reveal an interaction”
Core

Does the model’s response to extra support tickets depend on the contract? Check with ICE values. Fit make_gbm(), compute ICE values of support_tickets at 0 and 4 tickets in log-odds (response_method="decision_function") on the test set, and print the average change per contract type.

Expected output
Change in log-odds from 0 to 4 tickets:
contract
month-to-month 2.384
one-year 0.375
two-year 0.328
dtype: float64
Starter
gbm = make_gbm().fit(X_train, y_train)
grid = {"support_tickets": np.array([0.0, 4.0])}
# TODO: kind="individual", response_method="decision_function"
# TODO: change per customer = value at 4 - value at 0; mean per contract
Hint 1

result["individual"][0] has one row per customer and one column per grid value.

Hint 2

Wrap the change in a Series with index=X_test.index, then groupby(X_test["contract"]).mean().

Solution
gbm = make_gbm().fit(X_train, y_train)
grid = {"support_tickets": np.array([0.0, 4.0])}
result = partial_dependence(
gbm,
X_test,
["support_tickets"],
kind="individual",
custom_values=grid,
response_method="decision_function",
)
lines = result["individual"][0]
change = pd.Series(lines[:, 1] - lines[:, 0], index=X_test.index)
by_contract = change.groupby(X_test["contract"]).mean()
print("Change in log-odds from 0 to 4 tickets:")
print(by_contract.round(3))
assert by_contract["month-to-month"] > 3 * by_contract["two-year"]
Output
Change in log-odds from 0 to 4 tickets:
contract
month-to-month 2.384
one-year 0.375
two-year 0.328
dtype: float64

How it works:

  1. Each ICE line changes only the ticket count of one customer and keeps the rest of the row.
  2. In log-odds, the model adds far more risk for four tickets when the contract is month-to-month. The ICE lines of the two groups have different slopes: an interaction.
  3. Log-odds make the comparison fair. In probabilities, a customer who already has a high risk cannot gain much more, so the same effect would look smaller.

Alternative: draw the curves with PartialDependenceDisplay.from_estimator(..., kind="individual", centered=True) once per contract subset of X_test and compare the slopes visually.

M43-C09 · Interpret a result: impossible rows

Section titled “M43-C09 · Interpret a result: impossible rows”
Core

Interpret a result: a partial dependence of tenure_months at 60 months keeps every customer’s total_charges. But total_charges is about monthly_charges × tenure_months. Count the test customers whose row becomes implausible at tenure 60: their total_charges is less than half of monthly_charges × 60. Print the count and the share.

Expected output
implausible rows at tenure 60: 900 of 1250
share: 72.0%
real customers with tenure >= 60: 85
Starter
tenure_grid = 60
# TODO: expected = monthly_charges * tenure_grid
# TODO: implausible = total_charges < 0.5 * expected; print the count and share
Hint 1

All the columns you need are in X_test. The comparison gives a boolean Series.

Hint 2

mask.sum() counts the True values and mask.mean() gives the share.

Solution
tenure_grid = 60
expected = X_test["monthly_charges"] * tenure_grid
implausible = X_test["total_charges"] < 0.5 * expected
print(f"implausible rows at tenure {tenure_grid}: {implausible.sum()} of {len(X_test)}")
print(f"share: {implausible.mean():.1%}")
print(f"real customers with tenure >= 60: {(X_test['tenure_months'] >= 60).sum()}")
assert implausible.mean() > 0.5
Output
implausible rows at tenure 60: 900 of 1250
share: 72.0%
real customers with tenure >= 60: 85

How it works:

  1. The PDP point at 60 months asks the model about customers with 60 months of tenure but the total charges of their real, shorter tenure.
  2. Most of these rows are impossible: a customer cannot pay for five years and have paid only a few months’ worth. The model never saw such rows, so its predictions there are extrapolations.
  3. Read a PDP of a feature with a strong partner with care. Drop or combine the partner, or check the curve against the observed churn rate by tenure.

Alternative: an accumulated local effects (ALE) plot averages only small changes around the observed values, so it avoids most impossible rows. It is not in scikit-learn; packages such as alibi provide it.

M43-C10 · Draw a PDP and ICE figure for house prices

Section titled “M43-C10 · Draw a PDP and ICE figure for house prices”
Core

Fit a GradientBoostingRegressor(n_estimators=200, max_depth=3, random_state=42) on Xh_train, yh_train. Draw a figure with two panels: the partial dependence of year_built, and centered ICE curves plus the average for condition (subsample=50). Add a title to the figure.

Acceptance criteria:

  • One figure with two panels, made with PartialDependenceDisplay.from_estimator and ax=.
  • The left panel shows one PDP line for year_built; the right panel shows 50 thin centered ICE lines and a dashed average for condition.
  • The script prints the test R² of the model and the correlation between year_built and condition, which equal the Output in the solution.
Starter
gbr = GradientBoostingRegressor(n_estimators=200, max_depth=3, random_state=42)
gbr.fit(Xh_train, yh_train)
fig, axes = plt.subplots(1, 2, figsize=(9, 3.5))
# TODO: left panel: PDP of year_built; right panel: kind="both", centered=True
plt.show()
Hint 1

Call from_estimator twice, with ax=axes[0] and ax=axes[1].

Hint 2

The second call takes kind="both", centered=True, subsample=50, random_state=42.

Solution
gbr = GradientBoostingRegressor(n_estimators=200, max_depth=3, random_state=42)
gbr.fit(Xh_train, yh_train)
print(f"test R²: {gbr.score(Xh_test, yh_test):.3f}")
print(f"corr(year_built, condition): {Xh['year_built'].corr(Xh['condition']):.2f}")
fig, axes = plt.subplots(1, 2, figsize=(9, 3.5))
PartialDependenceDisplay.from_estimator(gbr, Xh_test, ["year_built"], ax=axes[0])
PartialDependenceDisplay.from_estimator(
gbr,
Xh_test,
["condition"],
kind="both",
centered=True,
subsample=50,
random_state=42,
ax=axes[1],
)
fig.suptitle("House price model: year built and condition (log price)")
fig.tight_layout()
assert len(fig.axes) >= 2
plt.show()
Output
test R²: 0.858
corr(year_built, condition): 0.42
Left: partial dependence of log price on year built, flat around -0.1 before 1970 and rising in steps to about 0.18 for houses built around 2020. Right: centered ICE lines for condition that all rise from condition 1 to 5, close together up to condition 3 and spreading a little above it.
Partial dependence of year built (left) and centered ICE curves for condition (right).

How it works:

  1. Each from_estimator call draws on the axes you pass, so one figure holds both panels.
  2. The year_built curve is flat for older houses and rises for newer ones, with the steepest rise for new builds. For gradient boosting with kind="average", scikit-learn picks the fast method="recursion". It averages over the training data that reached each tree node (it uses Xh_test only for the grid), and it leaves out the model’s constant starting value, so the curve sits around 0. Read its shape, not its level. The ICE panel on the right uses brute force on Xh_test.
  3. year_built and condition correlate at 0.42: newer houses tend to be in better condition. So the PDP of either feature also carries part of the other’s effect, and its grid creates year and condition combinations that are rare in the data.
  4. The condition ICE lines rise together and spread only a little, so the condition effect hardly depends on the other features. Compare that with the fanning size curves of the lesson.

Alternative: pass both features in one call, ["year_built", "condition"], with kind="both". Both panels then get ICE lines.

M43-C11 · Explain one house price in percent

Section titled “M43-C11 · Explain one house price in percent”
Core

Fit a GradientBoostingRegressor(n_estimators=200, max_depth=3, random_state=42) on Xh_train, yh_train (log price). Explain the first test house with shap.TreeExplainer. Check additivity, convert the predicted log price to a price, and print the three largest contributions as percent effects on the price.

Expected output
typical price 406,016, predicted 395,534
sqft = 1400: -19.9%
distance_to_center_km = 1.7: +13.2%
year_built = 2015: +4.7%
Starter
gbr = GradientBoostingRegressor(n_estimators=200, max_depth=3, random_state=42)
gbr.fit(Xh_train, yh_train)
house = Xh_test.iloc[[0]]
# TODO: explainer = shap.TreeExplainer(gbr); sv = explainer(house)
# TODO: check base + sum == gbr.predict(house); print the price
# TODO: top 3 contributions as exp(phi) - 1
Hint 1

The model predicts log price, so SHAP values are in log price. np.exp(phi) - 1 turns one contribution into a percent effect on the price.

Hint 2

pd.Series(sv.values[0], index=H_COLS) labels the values; sort with key=abs.

Solution
gbr = GradientBoostingRegressor(n_estimators=200, max_depth=3, random_state=42)
gbr.fit(Xh_train, yh_train)
house = Xh_test.iloc[[0]]
sv = shap.TreeExplainer(gbr)(house)
phi = pd.Series(sv.values[0], index=H_COLS)
base = sv.base_values[0]
log_pred = base + phi.sum()
print(f"typical price {np.exp(base):,.0f}, predicted {np.exp(log_pred):,.0f}")
for name, value in phi.sort_values(key=abs, ascending=False).head(3).items():
print(f"{name} = {house.iloc[0][name]:g}: {np.exp(value) - 1:+.1%}")
assert np.isclose(log_pred, gbr.predict(house)[0])
Output
typical price 406,016, predicted 395,534
sqft = 1400: -19.9%
distance_to_center_km = 1.7: +13.2%
year_built = 2015: +4.7%

How it works:

  1. On log price, contributions add in log units. On the price scale they multiply: the price is exp(base) × exp(phi_1) × exp(phi_2) × ….
  2. np.exp(phi) - 1 is the percent effect of one feature on the price, given the others. The percents multiply, so they do not add up to the total change.
  3. The base value is the average log price, so np.exp(base) is a typical (geometric mean) price, not the arithmetic mean price.

Alternative: fit the model on the price itself to get SHAP values in currency that add up. The model is then worse, because the price is right-skewed.

Core

Fit make_gbm() and compute SHAP values for 300 test customers (X_test.sample(300, random_state=42)). Sum the values of each feature’s one-hot columns, so that each of the 12 original features gets one value per customer. Check that additivity still holds, and print the five largest mean absolute grouped values.

Expected output
(300, 12)
True
contract 0.521
tenure_months 0.437
monthly_charges 0.367
age 0.297
support_tickets 0.289
dtype: float64
Starter
gbm = make_gbm().fit(X_train, y_train)
sample = X_test.sample(300, random_state=42)
sv = shap.TreeExplainer(gbm["model"])(gbm["encode"].transform(sample))
# TODO: map each encoded name to its original feature
# TODO: group, check additivity, print the top 5 mean |SHAP|
Hint 1

An encoded name such as contract_two-year starts with contract_. Numeric columns keep their names.

Hint 2

pd.DataFrame(sv.values, columns=groups).T.groupby(level=0).sum().T sums columns with the same group name.

Solution
gbm = make_gbm().fit(X_train, y_train)
sample = X_test.sample(300, random_state=42)
sv = shap.TreeExplainer(gbm["model"])(gbm["encode"].transform(sample))
def original(name: str) -> str:
return next((c for c in CAT_COLS if name.startswith(f"{c}_")), name)
groups = [original(n) for n in sv.feature_names]
grouped = pd.DataFrame(sv.values, columns=groups).T.groupby(level=0).sum().T
margin = gbm.decision_function(sample)
print(grouped.shape)
print(np.allclose(sv.base_values + grouped.sum(axis=1), margin))
print(grouped.abs().mean().sort_values(ascending=False).head(5).round(3))
assert grouped.shape == (300, 12)
Output
(300, 12)
True
contract 0.521
tenure_months 0.437
monthly_charges 0.367
age 0.297
support_tickets 0.289
dtype: float64

How it works:

  1. next(..., name) returns the first matching text column, or the name itself for numeric columns.
  2. Transposing makes the columns into rows, so groupby(level=0) can sum rows with the same label. Transposing back restores one row per customer.
  3. Summing is allowed because SHAP values are additive: the grouped values still add up to the model output.

Alternative: sv.values @ M, where M is a 0/1 matrix from encoded columns to original features, does the grouping as one matrix product.

M43-C13 · Refactor: one function for importance tables

Section titled “M43-C13 · Refactor: one function for importance tables”
Core

Refactor: the starter computes permutation importance for one model with copy-pasted lines. Turn it into a function importance_table(model, X, y, scoring="roc_auc", n_repeats=5) that returns a DataFrame with mean, std and rank, sorted by mean. Use it for a scaled logistic regression on the numeric churn features and for make_gbm(), and print the top three of each.

Expected output
logistic
mean std rank
tenure_months 0.194 0.010 1
support_tickets 0.046 0.013 2
monthly_charges 0.031 0.007 3
boosting
mean std rank
contract 0.065 0.009 1
tenure_months 0.051 0.005 2
monthly_charges 0.034 0.005 3
Starter
logit = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
logit.fit(X_train[NUM_COLS], y_train)
r = permutation_importance(logit, X_test[NUM_COLS], y_test, scoring="roc_auc",
n_repeats=5, random_state=42)
df = pd.DataFrame({"mean": r.importances_mean, "std": r.importances_std},
index=NUM_COLS).sort_values("mean", ascending=False)
df["rank"] = range(1, len(df) + 1)
print(df.head(3))
# TODO: the same lines again for make_gbm() ... turn them into a function
Hint 1

The column names come from X.columns, so the function does not need a separate list.

Hint 2

Return the DataFrame; let the caller decide what to print.

Solution
def importance_table(
model, X: pd.DataFrame, y: pd.Series, scoring: str = "roc_auc", n_repeats: int = 5
) -> pd.DataFrame:
"""Permutation importance on held-out data as a ranked table."""
result = permutation_importance(
model, X, y, scoring=scoring, n_repeats=n_repeats, random_state=42
)
table = pd.DataFrame(
{"mean": result.importances_mean, "std": result.importances_std},
index=X.columns,
).sort_values("mean", ascending=False)
table["rank"] = range(1, len(table) + 1)
return table
logit = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
logit.fit(X_train[NUM_COLS], y_train)
gbm = make_gbm().fit(X_train, y_train)
tables = {
"logistic": importance_table(logit, X_test[NUM_COLS], y_test),
"boosting": importance_table(gbm, X_test, y_test),
}
for name, table in tables.items():
print(name)
print(table.head(3).round(4))
assert list(tables["boosting"]["rank"]) == list(range(1, 13))
Output
logistic
mean std rank
tenure_months 0.194 0.010 1
support_tickets 0.046 0.013 2
monthly_charges 0.031 0.007 3
boosting
mean std rank
contract 0.065 0.009 1
tenure_months 0.051 0.005 2
monthly_charges 0.034 0.005 3

How it works:

  1. The function takes everything that varies (model, data, metric, repeats) as parameters and fixes the seed, so all tables are reproducible.
  2. It returns data, not printed text, so the caller can sort, merge or plot the tables.
  3. The logistic model sees only numeric columns, so contract cannot appear in its table. Comparing the two tables shows what the text columns add.

Alternative: sklearn.inspection.permutation_importance accepts a list of metrics, scoring=["roc_auc", "average_precision"], and then returns one result per metric in a dict.

M43-C14 · Which way does each feature push?

Section titled “M43-C14 · Which way does each feature push?”
Core

A beeswarm plot shows direction by color. Compute it as a number instead. Fit make_gbm(), compute SHAP values for 300 test customers, and for each numeric feature compute the Spearman correlation between the feature value and its SHAP value. Print a table with the correlation and a direction label: “higher → more risk”, “higher → less risk”, or “mixed” when the absolute correlation is below 0.5.

Expected output
spearman direction
tenure_months -0.97 higher → less risk
logins_last_30d -0.90 higher → less risk
has_autopay -0.86 higher → less risk
avg_session_minutes -0.73 higher → less risk
total_charges -0.71 higher → less risk
age -0.38 mixed
monthly_charges 0.84 higher → more risk
support_tickets 0.92 higher → more risk
Starter
gbm = make_gbm().fit(X_train, y_train)
sample = X_test.sample(300, random_state=42)
sv = shap.TreeExplainer(gbm["model"])(gbm["encode"].transform(sample))
values = pd.DataFrame(sv.values, columns=sv.feature_names, index=sample.index)
# TODO: for each column in NUM_COLS, Spearman corr of sample[col] and values[col]
# TODO: label the direction and print the table sorted by correlation
Hint 1

sample[col].corr(values[col], method="spearman") gives one correlation.

Hint 2

np.select([r >= 0.5, r <= -0.5], ["higher → more risk", "higher → less risk"], "mixed") labels a whole array.

Solution
gbm = make_gbm().fit(X_train, y_train)
sample = X_test.sample(300, random_state=42)
sv = shap.TreeExplainer(gbm["model"])(gbm["encode"].transform(sample))
values = pd.DataFrame(sv.values, columns=sv.feature_names, index=sample.index)
rho = pd.Series(
{c: sample[c].corr(values[c], method="spearman") for c in NUM_COLS}
).sort_values()
direction = np.select(
[rho >= 0.5, rho <= -0.5], ["higher → more risk", "higher → less risk"], "mixed"
)
table = pd.DataFrame({"spearman": rho.round(2), "direction": direction})
print(table)
assert table.loc["tenure_months", "direction"] == "higher → less risk"
assert table.loc["support_tickets", "direction"] == "higher → more risk"
Output
spearman direction
tenure_months -0.97 higher → less risk
logins_last_30d -0.90 higher → less risk
has_autopay -0.86 higher → less risk
avg_session_minutes -0.73 higher → less risk
total_charges -0.71 higher → less risk
age -0.38 mixed
monthly_charges 0.84 higher → more risk
support_tickets 0.92 higher → more risk

How it works:

  1. For each customer, a feature’s SHAP value says how far that feature moved the score. Correlating it with the feature value shows the direction of the effect.
  2. Spearman correlation uses ranks, so it catches any monotonic relation, curved or not.
  3. “Mixed” flags features whose effect is not monotonic, or is weak, for example age. Check its shape with shap.plots.scatter(sv[:, "age"], show=False) before you describe it in words.

Alternative: shap.plots.scatter(sv[:, "age"], show=False) draws one feature’s SHAP values against its values, which shows the shape behind a “mixed” label.

M43-X01 · Catch a leaky feature with explanations

Section titled “M43-X01 · Catch a leaky feature with explanations”
Challenge

A colleague adds retention_call_logged, a flag from the CRM that is 1 when the retention team logged a call. Calls are logged mostly after a customer has asked to cancel, so the flag is recorded after the outcome. Simulate it: the flag equals churned for 90% of customers and is random for the rest (rng = np.random.default_rng(42)). Fit make_gbm() with and without the flag. Write a function flag_dominant(importances, share=0.5) that returns the features with more than half of the total permutation importance, and use it to catch the leak.

Expected output
ROC-AUC clean 0.838, with the flag 0.974
retention_call_logged 0.272
contract 0.007
total_charges 0.006
dtype: float64
dominant: ['retention_call_logged']
Starter
rng = np.random.default_rng(42)
keep = rng.random(len(customers)) < 0.9
flag = np.where(keep, customers["churned"], rng.integers(0, 2, len(customers)))
X_leak = X.assign(retention_call_logged=flag.astype(float))
# TODO: split with the same rows as X_train / X_test
# TODO: fit make_gbm() on both versions; print the test ROC-AUC of each
# TODO: permutation importance (roc_auc) of the leaky model; flag_dominant()
Hint 1

X_leak.loc[X_train.index] and X_leak.loc[X_test.index] reuse the lesson’s split.

Hint 2

make_gbm() passes extra numeric columns through unchanged (remainder="passthrough"), so it works with the new column.

Hint 3

In flag_dominant, clip negative importances to 0 before you divide by the total.

Solution
rng = np.random.default_rng(42)
keep = rng.random(len(customers)) < 0.9
flag = np.where(keep, customers["churned"], rng.integers(0, 2, len(customers)))
X_leak = X.assign(retention_call_logged=flag.astype(float))
XL_train, XL_test = X_leak.loc[X_train.index], X_leak.loc[X_test.index]
def flag_dominant(importances: pd.Series, share: float = 0.5) -> list[str]:
"""Features that hold more than `share` of the total importance."""
positive = importances.clip(lower=0)
return positive.index[positive / positive.sum() > share].tolist()
clean = make_gbm().fit(X_train, y_train)
leaky = make_gbm().fit(XL_train, y_train)
auc_clean = roc_auc_score(y_test, clean.predict_proba(X_test)[:, 1])
auc_leaky = roc_auc_score(y_test, leaky.predict_proba(XL_test)[:, 1])
print(f"ROC-AUC clean {auc_clean:.3f}, with the flag {auc_leaky:.3f}")
perm = permutation_importance(
leaky, XL_test, y_test, scoring="roc_auc", n_repeats=5, random_state=42
)
imp = pd.Series(perm.importances_mean, index=XL_test.columns)
print(imp.sort_values(ascending=False).head(3).round(3))
print("dominant:", flag_dominant(imp))
assert flag_dominant(imp) == ["retention_call_logged"]
assert auc_leaky > auc_clean + 0.05
Output
ROC-AUC clean 0.838, with the flag 0.974
retention_call_logged 0.272
contract 0.007
total_charges 0.006
dtype: float64
dominant: ['retention_call_logged']

How it works:

  1. The flag copies the target for 90% of customers, so the leaky model’s ROC-AUC jumps far above the clean baseline. A jump like this is the first warning sign.
  2. Permutation importance shows where the jump comes from: one feature holds most of the importance, far ahead of the real drivers.
  3. flag_dominant turns the check into a rule you can run in every training pipeline. Then ask when the flag is recorded: after the outcome, so it is not available at prediction time.

Alternative: SHAP shows the same leak: the mean absolute SHAP value of the flag dwarfs every other feature, and its beeswarm row is two tight clusters far from 0.

Challenge

Write a class ChurnExplainer that wraps a fitted churn pipeline. __init__(self, pipeline, cat_cols) stores the pipeline and builds a shap.TreeExplainer. explain(self, X) returns a DataFrame of SHAP values grouped to original features. global_importance(self, X) returns mean absolute grouped values, sorted. reasons(self, row, k=3) returns the k features that push one customer’s risk up the most, as "feature = value" strings. Use it on 300 test customers and on customer C04542.

Expected output
contract 0.521
tenure_months 0.437
monthly_charges 0.367
age 0.297
dtype: float64
C04542 risk 0.97: support_tickets = 9; tenure_months = 3; logins_last_30d = 3
Starter
class ChurnExplainer:
def __init__(self, pipeline: Pipeline, cat_cols: list[str]) -> None:
... # TODO: store; build shap.TreeExplainer(pipeline["model"])
def explain(self, X: pd.DataFrame) -> pd.DataFrame:
... # TODO: encode, compute SHAP, group one-hot columns
def global_importance(self, X: pd.DataFrame) -> pd.Series:
... # TODO: mean |SHAP| per original feature, sorted
def reasons(self, row: pd.DataFrame, k: int = 3) -> list[str]:
... # TODO: top k positive contributions as "feature = value"
gbm = make_gbm().fit(X_train, y_train)
# TODO: use the class
Hint 1

Reuse the grouping from exercise M43-C12 inside explain, with index=X.index on the DataFrame.

Hint 2

reasons explains a one-row DataFrame, keeps the positive values, sorts them in descending order and takes k.

Hint 3

Find C04542 with X.loc[customers["customer_id"] == "C04542"].

Solution
def show(value: object) -> str:
"""Format 9.0 as '9' and leave text unchanged."""
return f"{value:g}" if isinstance(value, float) else str(value)
class ChurnExplainer:
"""SHAP explanations of a churn pipeline, grouped to original features."""
def __init__(self, pipeline: Pipeline, cat_cols: list[str]) -> None:
self.pipeline = pipeline
self.cat_cols = cat_cols
self.explainer = shap.TreeExplainer(pipeline["model"])
def _original(self, name: str) -> str:
return next((c for c in self.cat_cols if name.startswith(f"{c}_")), name)
def explain(self, X: pd.DataFrame) -> pd.DataFrame:
sv = self.explainer(self.pipeline["encode"].transform(X))
groups = [self._original(n) for n in sv.feature_names]
values = pd.DataFrame(sv.values, columns=groups, index=X.index)
return values.T.groupby(level=0).sum().T
def global_importance(self, X: pd.DataFrame) -> pd.Series:
return self.explain(X).abs().mean().sort_values(ascending=False)
def reasons(self, row: pd.DataFrame, k: int = 3) -> list[str]:
contrib = self.explain(row).iloc[0]
top = contrib[contrib > 0].sort_values(ascending=False).head(k)
return [f"{name} = {show(row.iloc[0][name])}" for name in top.index]
gbm = make_gbm().fit(X_train, y_train)
ce = ChurnExplainer(gbm, CAT_COLS)
print(ce.global_importance(X_test.sample(300, random_state=42)).head(4).round(3))
row = X.loc[customers["customer_id"] == "C04542"]
risk = gbm.predict_proba(row)[0, 1]
print(f"C04542 risk {risk:.2f}:", "; ".join(ce.reasons(row)))
assert len(ce.reasons(row)) == 3
assert ce.explain(row).shape == (1, 12)
Output
contract 0.521
tenure_months 0.437
monthly_charges 0.367
age 0.297
dtype: float64
C04542 risk 0.97: support_tickets = 9; tenure_months = 3; logins_last_30d = 3

How it works:

  1. The explainer is built once in __init__; every method reuses it.
  2. explain holds the only copy of the encoding and grouping logic. global_importance and reasons build on it, so a fix in one place fixes all.
  3. reasons keeps only positive contributions, because the agent asks why the risk is high. A second method could list the factors that lower it.

Alternative: return a small dataclass from reasons (feature, value, contribution) instead of strings, and let a separate function format it for each audience.

M43-X03 · SHAP and permutation with a duplicated feature

Section titled “M43-X03 · SHAP and permutation with a duplicated feature”
Challenge

Add tenure_days (tenure_months × 30.4) to the churn features. Fit make_gbm() with the twin. Compare, for tenure_months and tenure_days, the mean absolute SHAP value (300 test customers) and the permutation importance (roc_auc, n_repeats=5), each alone and with both shuffled together. Explain what each method does with the twin.

Expected output
mean_abs_shap perm_alone
tenure_months 0.282 0.017
tenure_days 0.171 0.003
mean |SHAP of the twins added per row|: 0.4350
permutation, both shuffled: 0.0588
Starter
X_twin = X.assign(tenure_days=X["tenure_months"] * 30.4)
XT_train, XT_test = X_twin.loc[X_train.index], X_twin.loc[X_test.index]
gbm = make_gbm().fit(XT_train, y_train)
# TODO: mean |SHAP| of both twins on 300 test rows
# TODO: permutation importance of each twin, and of both together
Hint 1

For “both together”, shuffle both columns with one permutation and compute the ROC-AUC drop yourself (see exercise M43-C06).

Hint 2

sv.feature_names contains both twins; take the columns by name from a labeled DataFrame of sv.values.

Solution
X_twin = X.assign(tenure_days=X["tenure_months"] * 30.4)
XT_train, XT_test = X_twin.loc[X_train.index], X_twin.loc[X_test.index]
gbm = make_gbm().fit(XT_train, y_train)
twins = ["tenure_months", "tenure_days"]
sample = XT_test.sample(300, random_state=42)
sv = shap.TreeExplainer(gbm["model"])(gbm["encode"].transform(sample))
shap_df = pd.DataFrame(sv.values, columns=sv.feature_names)
shap_abs = shap_df[twins].abs().mean()
joint = (shap_df["tenure_months"] + shap_df["tenure_days"]).abs().mean()
perm = permutation_importance(
gbm, XT_test, y_test, scoring="roc_auc", n_repeats=5, random_state=42
)
perm_s = pd.Series(perm.importances_mean, index=XT_test.columns)[twins]
rng = np.random.default_rng(42)
base = roc_auc_score(y_test, gbm.predict_proba(XT_test)[:, 1])
drops = []
for _ in range(5):
shuffled = XT_test.copy()
shuffled[twins] = XT_test[twins].to_numpy()[rng.permutation(len(XT_test))]
drops.append(base - roc_auc_score(y_test, gbm.predict_proba(shuffled)[:, 1]))
both = float(np.mean(drops))
print(pd.DataFrame({"mean_abs_shap": shap_abs, "perm_alone": perm_s}).round(4))
print(f"mean |SHAP of the twins added per row|: {joint:.4f}")
print(f"permutation, both shuffled: {both:.4f}")
assert both > perm_s.max()
Output
mean_abs_shap perm_alone
tenure_months 0.282 0.017
tenure_days 0.171 0.003
mean |SHAP of the twins added per row|: 0.4350
permutation, both shuffled: 0.0588

How it works:

  1. The trees split on either twin, so SHAP divides the tenure effect between them. Adding the two SHAP values per customer gives the joint tenure contribution. Its mean absolute value is close to what tenure_months gets without the twin (0.437 in exercise M43-C12). Adding the two separate means would overstate it, because the twins can push in opposite directions for one customer.
  2. Permutation importance of each twin alone is far smaller than tenure’s 0.050 without the twin (exercise M43-C05), because the model still reads tenure from the other twin.
  3. Shuffling both together removes tenure completely, and the drop is clearly larger than for either twin alone. With correlated features, explain groups, not single columns.

Alternative: drop one twin before you explain. If the score does not change, the explanation of the simpler model is the honest one.

Challenge

Fit make_gbm(). Split the test set into two halves (X_test.iloc[::2] and X_test.iloc[1::2]). On each half, compute permutation importance (roc_auc, n_repeats=5) with seeds 0 and 1. Collect the four rankings, and print for each feature its best and worst rank. Report the features whose rank moves by more than 2 places.

Expected output
best worst
contract 1 1
tenure_months 2 2
monthly_charges 3 5
support_tickets 3 5
logins_last_30d 3 6
age 4 6
payment_method 7 7
has_autopay 8 10
plan 8 10
avg_session_minutes 8 12
region 9 11
total_charges 10 12
unstable: ['logins_last_30d', 'avg_session_minutes']
Starter
gbm = make_gbm().fit(X_train, y_train)
halves = {"even": slice(0, None, 2), "odd": slice(1, None, 2)}
ranks = {}
# TODO: for each half and seed, rank features by permutation importance
# TODO: table of best and worst rank; features with worst - best > 2
Hint 1

X_test.iloc[rows] and y_test.iloc[rows] select a half with a slice.

Hint 2

Store each ranking as a Series in a dict, then pd.DataFrame(ranks) makes one column per run; .min(axis=1) and .max(axis=1) give the best and worst rank.

Solution
gbm = make_gbm().fit(X_train, y_train)
halves = {"even": slice(0, None, 2), "odd": slice(1, None, 2)}
ranks = {}
for half, rows in halves.items():
for seed in (0, 1):
perm = permutation_importance(
gbm,
X_test.iloc[rows],
y_test.iloc[rows],
scoring="roc_auc",
n_repeats=5,
random_state=seed,
)
s = pd.Series(perm.importances_mean, index=X_test.columns)
ranks[f"{half}-{seed}"] = s.rank(ascending=False).astype(int)
table = pd.DataFrame(ranks)
summary = pd.DataFrame({"best": table.min(axis=1), "worst": table.max(axis=1)})
print(summary.sort_values(["best", "worst"]))
unstable = summary.index[summary["worst"] - summary["best"] > 2].tolist()
print("unstable:", unstable)
assert summary.loc["contract", "best"] == 1
Output
best worst
contract 1 1
tenure_months 2 2
monthly_charges 3 5
support_tickets 3 5
logins_last_30d 3 6
age 4 6
payment_method 7 7
has_autopay 8 10
plan 8 10
avg_session_minutes 8 12
region 9 11
total_charges 10 12
unstable: ['logins_last_30d', 'avg_session_minutes']

How it works:

  1. Two halves of the test set show the effect of the data sample; two seeds show the effect of the shuffles.
  2. The top features keep their places. Features in the middle, with similar importances, swap ranks between runs.
  3. Report ranks only where they are stable. For the middle group, say “these features matter about equally”.

Alternative: a bootstrap of the test set (resample rows with replacement 20 times) gives a confidence interval for each importance instead of a best and worst rank.

Challenge

Choose a method and justify it: three people ask about the churn model. The head of retention asks: “Which three factors drive churn overall?” A call-center agent asks: “Why is C04542 high risk?” The compliance officer asks: “How much does region influence the scores?” Fit make_gbm(), pick one method per question, and print a one-line answer for each.

Expected output
1. Top drivers (ROC-AUC drop): contract, tenure_months, monthly_charges
2. C04542: support_tickets = 9; tenure_months = 3; logins_last_30d = 3
3. Region: 1.6% of the total mean |SHAP|
Starter
gbm = make_gbm().fit(X_train, y_train)
# TODO: question 1: permutation importance (roc_auc) on the test set, top 3
# TODO: question 2: grouped SHAP values for C04542, top 3 positive
# TODO: question 3: region's share of the total mean |SHAP| (300 test rows)
Hint 1

The head of retention wants a global ranking that reflects predictive value: permutation importance on held-out data.

Hint 2

The compliance officer wants the size of region’s influence on the scores themselves, for all customers: the mean absolute SHAP value of the grouped region feature, as a share of the total.

Solution
gbm = make_gbm().fit(X_train, y_train)
explainer = shap.TreeExplainer(gbm["model"])
def grouped_shap(rows: pd.DataFrame) -> pd.DataFrame:
sv = explainer(gbm["encode"].transform(rows))
groups = [
next((c for c in CAT_COLS if n.startswith(f"{c}_")), n)
for n in sv.feature_names
]
values = pd.DataFrame(sv.values, columns=groups, index=rows.index)
return values.T.groupby(level=0).sum().T
perm = permutation_importance(
gbm, X_test, y_test, scoring="roc_auc", n_repeats=5, random_state=42
)
top3 = pd.Series(perm.importances_mean, index=X_test.columns).nlargest(3)
print("1. Top drivers (ROC-AUC drop):", ", ".join(top3.index))
row = X.loc[customers["customer_id"] == "C04542"]
contrib = grouped_shap(row).iloc[0]
up = contrib[contrib > 0].nlargest(3).index
print("2. C04542:", "; ".join(f"{f} = {row.iloc[0][f]:g}" for f in up))
mean_abs = grouped_shap(X_test.sample(300, random_state=42)).abs().mean()
share = mean_abs["region"] / mean_abs.sum()
print(f"3. Region: {share:.1%} of the total mean |SHAP|")
assert share < 0.05
assert top3.index[0] == "contract"
Output
1. Top drivers (ROC-AUC drop): contract, tenure_months, monthly_charges
2. C04542: support_tickets = 9; tenure_months = 3; logins_last_30d = 3
3. Region: 1.6% of the total mean |SHAP|

How it works:

  1. Question 1 is global and about what predicts churn on new data: permutation importance on the test set with ROC-AUC.
  2. Question 2 is local: grouped SHAP values of one customer, positive pushes only, in plain feature names.
  3. Question 3 is global and about influence on the scores, not on accuracy: region’s share of the mean absolute SHAP. A small share means the model barely moves scores by region. It does not prove fairness: other features could still act as proxies for a protected group, so compliance would also compare scores and error rates across groups.

Alternative: for question 3, refit without region and compare the scores customer by customer. If the scores barely change, region has little influence in practice.