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:
- Run the setup block once at the top of your script. Every exercise assumes its names exist.
- Read the task and the expected output. Copy the starter code below the setup and replace each to-do comment with your code.
- Run the script and compare your output with the expected output.
- 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, becausepartial_dependencein 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 pltimport numpy as npimport pandas as pdimport shapfrom sklearn.compose import ColumnTransformerfrom sklearn.ensemble import ( GradientBoostingClassifier, GradientBoostingRegressor, RandomForestClassifier, RandomForestRegressor,)from sklearn.inspection import ( PartialDependenceDisplay, partial_dependence, permutation_importance,)from sklearn.linear_model import LinearRegression, LogisticRegressionfrom sklearn.metrics import r2_score, roc_auc_scorefrom sklearn.model_selection import train_test_splitfrom sklearn.pipeline import Pipeline, make_pipelinefrom sklearn.preprocessing import OneHotEncoder, StandardScalerfrom 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
Section titled “Warm-up”M43-W01 · Global or local?
Section titled “M43-W01 · Global or local?”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.
global | permutation importance on the test setlocal | SHAP waterfall for that customerglobal | partial dependence plot of sqftlocal | ICE curve of sqft for that houseglobal | permutation importance of regionlocal | top 3 SHAP values of that customerglobal questions: 3questions = [ "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 onesHint 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 == 3global | permutation importance on the test setlocal | SHAP waterfall for that customerglobal | partial dependence plot of sqftlocal | ICE curve of sqft for that houseglobal | permutation importance of regionlocal | top 3 SHAP values of that customerglobal questions: 3How it works:
- 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.
- Question 4 is a what-if for one house: an ICE curve answers it exactly, because it changes only
sqftfor that row. sum()over booleans counts theTruevalues, becauseTruecounts 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”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.
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)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.177tenure_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:
- Logistic regression is linear in the log-odds, so a coefficient is a change in log-odds.
np.expturns it into a factor on the odds. - An odds ratio below 1 lowers the odds; above 1 raises them.
ratio - 1is the relative change. - 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)).
M43-W03 · Standardize before you compare
Section titled “M43-W03 · Standardize before you compare”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.
raw: sqft 0.00047, has_pool 0.225sqft 0.336distance_to_center_km -0.250condition 0.111dtype: float64lin = 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 valueHint 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"raw: sqft 0.00047, has_pool 0.225sqft 0.336distance_to_center_km -0.250condition 0.111dtype: float64How it works:
- The raw coefficient of
sqftis per square foot, so it is tiny. The coefficient ofhas_poolis for a full 0-to-1 step. Raw sizes say nothing about importance. - 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. - 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.
M43-W04 · Importances of a shallow tree
Section titled “M43-W04 · Importances of a shallow tree”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.
sqft 0.695distance_to_center_km 0.305dtype: float64sum: 1.0unused: ['bedrooms', 'bathrooms', 'year_built', 'condition', 'has_pool', 'garage_spaces']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 featuresHint 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 unusedsqft 0.695distance_to_center_km 0.305dtype: float64sum: 1.0unused: ['bedrooms', 'bathrooms', 'year_built', 'condition', 'has_pool', 'garage_spaces']How it works:
- A tree of depth 3 has at most 7 splits. This one splits only on size and distance.
- Impurity importances are scaled to sum to 1, so each value is a share of the total impurity reduction.
- A feature with no split gets exactly 0. The tree ignores
has_poolandcondition, 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.
M43-W05 · Shuffle one column by hand
Section titled “M43-W05 · Shuffle one column by hand”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.
baseline R²: 0.751sqft shuffled: -0.060importance of sqft: 0.810lin = 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 dropHint 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 - scoreprint(f"baseline R²: {baseline:.3f}")print(f"sqft shuffled: {score:.3f}")print(f"importance of sqft: {drop:.3f}")assert drop > 0.3assert not shuffled["sqft"].equals(Xh_test["sqft"])assert sorted(shuffled["sqft"]) == sorted(Xh_test["sqft"])baseline R²: 0.751sqft shuffled: -0.060importance of sqft: 0.810How it works:
- The baseline is the model’s normal test score.
- Shuffling keeps the values of
sqftbut assigns them to random houses. The link between size and price is gone, and so is the link between size and the other features. - 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”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.
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.0assert stump.tree_.feature[0] == 0sqft: 0.7058condition: 0.0000has_pool: 0.0000How it works:
- The stump splits once, on
sqft, the feature with the largest error reduction.stump.tree_.feature[0] == 0confirms that the root split uses column 0. - Shuffling
conditionorhas_poolchanges columns that the model never reads, so every prediction stays the same and the score drop is exactly 0. - 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”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.
PD: [12.5246 12.9935 13.4623]steps: [0.4689 0.4689]coef x 1000: 0.4689lin = 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")] * 1000print("PD:", curve.round(4))print("steps:", steps.round(4))print(f"coef x 1000: {coef_step:.4f}")assert np.allclose(steps, coef_step)PD: [12.5246 12.9935 13.4623]steps: [0.4689 0.4689]coef x 1000: 0.4689How it works:
- The PDP sets
sqftto the grid value in every test row and averages the predictions. - In a linear model, changing
sqftby 1,000 changes every prediction by exactlycoef * 1000, whatever the other features are. So the PDP is a straight line with that slope. - 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”For a linear model with independent features, the SHAP value of feature is , where 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.
{'sqft': 1400.0, 'condition': 3.0, 'has_pool': 0.0}sqft -0.228condition -0.001has_pool -0.029dtype: float64base 12.9141 + sum -0.2576 = 12.6565prediction: 12.6565cols = ["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 predictionHint 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){'sqft': 1400.0, 'condition': 3.0, 'has_pool': 0.0}sqft -0.228condition -0.001has_pool -0.029dtype: float64base 12.9141 + sum -0.2576 = 12.6565prediction: 12.6565How it works:
- The mean prediction of a linear model equals the prediction at the mean row, so the base value is .
- Subtracting the base value from the prediction leaves : one term per feature. Each term is that feature’s SHAP value.
- A feature at its average value gets a SHAP value of 0. Here the small house has a negative
sqftvalue: 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”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.
log-odds: 3.620probability: 0.974wrong (added to a probability): 5.707base = -1.964phi = 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) + sumHint 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.964phi = 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 < 1assert wrong > 1log-odds: 3.620probability: 0.974wrong (added to a probability): 5.707How it works:
- The base value plus the SHAP values gives the model’s raw output, 3.620 log-odds.
- The sigmoid maps log-odds to a probability between 0 and 1: about 97%.
- 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”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.
noise on train: 0.0256noise on test: -0.0028test std: 0.0022rng = 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 compareHint 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])noise on train: 0.0256noise on test: -0.0028test std: 0.0022How it works:
- On the training set, shuffling
noisebreaks splits that the trees used to memorize individual rows, so the training R² drops. - On the test set, those memorized splits never helped, so shuffling the noise costs nothing within its standard deviation.
- 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”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.
coef_per_sd odds_ratiotenure_months -1.396 0.248support_tickets 0.526 1.692monthly_charges 0.372 1.450logins_last_30d -0.281 0.755model = LogisticRegression(max_iter=1000)model.fit(X_train[NUM_COLS], y_train) # bug: raw unitscoefs = 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 againHint 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) coef_per_sd odds_ratiotenure_months -1.396 0.248support_tickets 0.526 1.692monthly_charges 0.372 1.450logins_last_30d -0.281 0.755How it works:
- Without scaling,
total_charges(tens to thousands) gets a tiny coefficient andhas_autopay(0 or 1) a large one, whatever their real roles. Raw logistic regression on such ranges can also converge slowly. - After scaling, each coefficient is the change in log-odds for a one-standard-deviation step, so the sizes are comparable.
np.expturns 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”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.
half 1: sqft +0.253, listed +0.265, sum 0.518half 2: sqft +1.046, listed -0.526, sum 0.520correlation: 0.9996rng = 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 sumHint 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) // 2results = {}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.1half 1: sqft +0.253, listed +0.265, sum 0.518half 2: sqft +1.046, listed -0.526, sum 0.520correlation: 0.9996How it works:
- The two size columns correlate almost perfectly. The model can shift weight from one to the other with almost no change in fit.
- So the individual coefficients depend on small accidents of the sample: they differ between the halves, and one of them can even turn negative.
- 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.
M43-C04 · A random id in a churn forest
Section titled “M43-C04 · A random id in a churn forest”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).
mdi_rank perm_ranktotal_charges 1 5tenure_months 2 1monthly_charges 3 2random_id 4 8age 5 4avg_session_minutes 6 9logins_last_30d 7 3support_tickets 8 6has_autopay 9 7random_id permutation importance: 0.0004rng = 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 importanceHint 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"] mdi_rank perm_ranktotal_charges 1 5tenure_months 2 1monthly_charges 3 2random_id 4 8age 5 4avg_session_minutes 6 9logins_last_30d 7 3support_tickets 8 6has_autopay 9 7random_id permutation importance: 0.0004How it works:
- 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.
- 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).
- 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.
M43-C05 · Choose the scoring metric
Section titled “M43-C05 · Choose the scoring metric”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.
accuracy: tenure_months 0.023, support_tickets 0.020, contract 0.018, logins_last_30d 0.016roc_auc: contract 0.065, tenure_months 0.050, monthly_charges 0.034, logins_last_30d 0.027gbm = make_gbm().fit(X_train, y_train)# TODO: permutation importance with accuracy and with roc_auc# TODO: print the top 4 of eachHint 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"accuracy: tenure_months 0.023, support_tickets 0.020, contract 0.018, logins_last_30d 0.016roc_auc: contract 0.065, tenure_months 0.050, monthly_charges 0.034, logins_last_30d 0.027How it works:
- Accuracy uses the 0.5 threshold. Most customers are far from it, so shuffling a feature flips few labels and the drops are small.
- 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).
- The two metrics also order the features differently:
contractmatters most for the ranking,tenure_monthsfor 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”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.
tenure alone: 0.2015total_charges alone: 0.0058both together: 0.1614def 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 pairHint 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_ctenure alone: 0.2015total_charges alone: 0.0058both together: 0.1614How it works:
- 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.
- Shuffling
total_chargesalone costs little, because tenure and monthly charges still carry its information. - Shuffling tenure alone costs more than shuffling both. The logistic model offsets a negative tenure weight against a positive
total_chargesweight (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. - 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”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.
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.099first tenure below 0.15: 24gbm = 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.15Hint 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] 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.099first tenure below 0.15: 24How it works:
partial_dependenceworks on the whole pipeline: it changes the raw column, and the encoder and model run as usual.- 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_dependenceuses brute force here, because aPipelineis not a tree model, so each value is an average over the test rows. - 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”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.
Change in log-odds from 0 to 4 tickets:contractmonth-to-month 2.384one-year 0.375two-year 0.328dtype: float64gbm = 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 contractHint 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"]Change in log-odds from 0 to 4 tickets:contractmonth-to-month 2.384one-year 0.375two-year 0.328dtype: float64How it works:
- Each ICE line changes only the ticket count of one customer and keeps the rest of the row.
- 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.
- 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”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.
implausible rows at tenure 60: 900 of 1250share: 72.0%real customers with tenure >= 60: 85tenure_grid = 60# TODO: expected = monthly_charges * tenure_grid# TODO: implausible = total_charges < 0.5 * expected; print the count and shareHint 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 = 60expected = X_test["monthly_charges"] * tenure_gridimplausible = X_test["total_charges"] < 0.5 * expectedprint(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.5implausible rows at tenure 60: 900 of 1250share: 72.0%real customers with tenure >= 60: 85How it works:
- 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.
- 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.
- 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”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_estimatorandax=. - The left panel shows one PDP line for
year_built; the right panel shows 50 thin centered ICE lines and a dashed average forcondition. - The script prints the test R² of the model and the correlation between
year_builtandcondition, which equal the Output in the solution.
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=Trueplt.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) >= 2plt.show()test R²: 0.858corr(year_built, condition): 0.42
How it works:
- Each
from_estimatorcall draws on the axes you pass, so one figure holds both panels. - The
year_builtcurve is flat for older houses and rises for newer ones, with the steepest rise for new builds. For gradient boosting withkind="average", scikit-learn picks the fastmethod="recursion". It averages over the training data that reached each tree node (it usesXh_testonly 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 onXh_test. year_builtandconditioncorrelate 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.- 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”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.
typical price 406,016, predicted 395,534sqft = 1400: -19.9%distance_to_center_km = 1.7: +13.2%year_built = 2015: +4.7%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) - 1Hint 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])typical price 406,016, predicted 395,534sqft = 1400: -19.9%distance_to_center_km = 1.7: +13.2%year_built = 2015: +4.7%How it works:
- 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) × …. np.exp(phi) - 1is 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.- 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.
M43-C12 · Group one-hot SHAP values
Section titled “M43-C12 · Group one-hot SHAP values”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.
(300, 12)Truecontract 0.521tenure_months 0.437monthly_charges 0.367age 0.297support_tickets 0.289dtype: float64gbm = 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().Tmargin = 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)(300, 12)Truecontract 0.521tenure_months 0.437monthly_charges 0.367age 0.297support_tickets 0.289dtype: float64How it works:
next(..., name)returns the first matching text column, or the name itself for numeric columns.- Transposing makes the columns into rows, so
groupby(level=0)can sum rows with the same label. Transposing back restores one row per customer. - 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”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.
logistic mean std ranktenure_months 0.194 0.010 1support_tickets 0.046 0.013 2monthly_charges 0.031 0.007 3boosting mean std rankcontract 0.065 0.009 1tenure_months 0.051 0.005 2monthly_charges 0.034 0.005 3logit = 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 functionHint 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))logistic mean std ranktenure_months 0.194 0.010 1support_tickets 0.046 0.013 2monthly_charges 0.031 0.007 3boosting mean std rankcontract 0.065 0.009 1tenure_months 0.051 0.005 2monthly_charges 0.034 0.005 3How it works:
- The function takes everything that varies (model, data, metric, repeats) as parameters and fixes the seed, so all tables are reproducible.
- It returns data, not printed text, so the caller can sort, merge or plot the tables.
- The logistic model sees only numeric columns, so
contractcannot 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?”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.
spearman directiontenure_months -0.97 higher → less risklogins_last_30d -0.90 higher → less riskhas_autopay -0.86 higher → less riskavg_session_minutes -0.73 higher → less risktotal_charges -0.71 higher → less riskage -0.38 mixedmonthly_charges 0.84 higher → more risksupport_tickets 0.92 higher → more riskgbm = 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 correlationHint 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" spearman directiontenure_months -0.97 higher → less risklogins_last_30d -0.90 higher → less riskhas_autopay -0.86 higher → less riskavg_session_minutes -0.73 higher → less risktotal_charges -0.71 higher → less riskage -0.38 mixedmonthly_charges 0.84 higher → more risksupport_tickets 0.92 higher → more riskHow it works:
- 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.
- Spearman correlation uses ranks, so it catches any monotonic relation, curved or not.
- “Mixed” flags features whose effect is not monotonic, or is weak, for example
age. Check its shape withshap.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.
Challenge
Section titled “Challenge”M43-X01 · Catch a leaky feature with explanations
Section titled “M43-X01 · Catch a leaky feature with explanations”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.
ROC-AUC clean 0.838, with the flag 0.974retention_call_logged 0.272contract 0.007total_charges 0.006dtype: float64dominant: ['retention_call_logged']rng = np.random.default_rng(42)keep = rng.random(len(customers)) < 0.9flag = 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.9flag = 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.05ROC-AUC clean 0.838, with the flag 0.974retention_call_logged 0.272contract 0.007total_charges 0.006dtype: float64dominant: ['retention_call_logged']How it works:
- 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.
- Permutation importance shows where the jump comes from: one feature holds most of the importance, far ahead of the real drivers.
flag_dominantturns 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.
M43-X02 · A ChurnExplainer class
Section titled “M43-X02 · A ChurnExplainer class”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.
contract 0.521tenure_months 0.437monthly_charges 0.367age 0.297dtype: float64C04542 risk 0.97: support_tickets = 9; tenure_months = 3; logins_last_30d = 3class 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 classHint 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)) == 3assert ce.explain(row).shape == (1, 12)contract 0.521tenure_months 0.437monthly_charges 0.367age 0.297dtype: float64C04542 risk 0.97: support_tickets = 9; tenure_months = 3; logins_last_30d = 3How it works:
- The explainer is built once in
__init__; every method reuses it. explainholds the only copy of the encoding and grouping logic.global_importanceandreasonsbuild on it, so a fix in one place fixes all.reasonskeeps 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”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.
mean_abs_shap perm_alonetenure_months 0.282 0.017tenure_days 0.171 0.003mean |SHAP of the twins added per row|: 0.4350permutation, both shuffled: 0.0588X_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 togetherHint 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() mean_abs_shap perm_alonetenure_months 0.282 0.017tenure_days 0.171 0.003mean |SHAP of the twins added per row|: 0.4350permutation, both shuffled: 0.0588How it works:
- 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_monthsgets 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. - 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.
- 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.
M43-X04 · How stable is the ranking?
Section titled “M43-X04 · How stable is the ranking?”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.
best worstcontract 1 1tenure_months 2 2monthly_charges 3 5support_tickets 3 5logins_last_30d 3 6age 4 6payment_method 7 7has_autopay 8 10plan 8 10avg_session_minutes 8 12region 9 11total_charges 10 12unstable: ['logins_last_30d', 'avg_session_minutes']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 > 2Hint 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 best worstcontract 1 1tenure_months 2 2monthly_charges 3 5support_tickets 3 5logins_last_30d 3 6age 4 6payment_method 7 7has_autopay 8 10plan 8 10avg_session_minutes 8 12region 9 11total_charges 10 12unstable: ['logins_last_30d', 'avg_session_minutes']How it works:
- Two halves of the test set show the effect of the data sample; two seeds show the effect of the shuffles.
- The top features keep their places. Features in the middle, with similar importances, swap ranks between runs.
- 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.
M43-X05 · Answer three stakeholders
Section titled “M43-X05 · Answer three stakeholders”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.
1. Top drivers (ROC-AUC drop): contract, tenure_months, monthly_charges2. C04542: support_tickets = 9; tenure_months = 3; logins_last_30d = 33. Region: 1.6% of the total mean |SHAP|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).indexprint("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.05assert top3.index[0] == "contract"1. Top drivers (ROC-AUC drop): contract, tenure_months, monthly_charges2. C04542: support_tickets = 9; tenure_months = 3; logins_last_30d = 33. Region: 1.6% of the total mean |SHAP|How it works:
- Question 1 is global and about what predicts churn on new data: permutation importance on the test set with ROC-AUC.
- Question 2 is local: grouped SHAP values of one customer, positive pushes only, in plain feature names.
- 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.