Lesson 19 of 227 min
Feature importance and SHAP
Shuffle a column to see how much a model depends on it, and use SHAP to see how each fact pushed one customer's chance; both say what the model uses, not what causes.
After this lesson you can say which features drove a prediction.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
The chapter's model
Put bank-additional-full.csv from UCI Bank Marketing next to your notebook. The eight word columns become numbers, each word's place in alphabetical order, and the model is told they are categories. That gives lesson 14's boosted trees, and a table shap can read. Keep the same 1,000 calls aside.
import pandas as pd
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import train_test_split
calls = pd.read_csv("bank-additional-full.csv", sep=";")
columns = ["age", "job", "marital", "education", "default", "housing",
"loan", "contact", "campaign", "pdays", "previous", "poutcome"]
words = ["job", "marital", "education", "default", "housing", "loan", "contact", "poutcome"]
X = calls[columns].copy()
for column in words:
X[column] = X[column].map({w: i for i, w in enumerate(sorted(X[column].unique()))})y = calls["y"].eq("yes")
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=1000, stratify=y, random_state=0)
model = HistGradientBoostingClassifier(
categorical_features=words, random_state=0).fit(X_train, y_train)
print(model.n_iter_)45
The trees' own importance
A forest has feature_importances_: how much each column's questions cleaned up the training rows. It is counted on the rows the model learned from, it favors columns with many values, and it says nothing about the score. Here it puts the phone outside its top three. Boosted trees in scikit-learn don't have it. Permutation importance guide
from sklearn.ensemble import RandomForestClassifier
forest = RandomForestClassifier(n_estimators=300, max_depth=10, n_jobs=-1,
random_state=0).fit(X_train, y_train)
own = pd.Series(forest.feature_importances_, X.columns)
print(own.nlargest(3).round(3))pdays 0.311 poutcome 0.188 age 0.165
The whole model in one picture
The chapter's pushes explain one call. Run the explainer on all 1,000 and take the average size of each column's push: a second way to rank columns, in points of chance. beeswarm draws every push of every call, a dot each. The exact explainer tries every order of the twelve facts, so it is slow: many minutes on a laptop.
import numpy as np
import shap
chance = lambda rows: model.predict_proba(rows)[:, 1]
masker = shap.maskers.Independent(X_train.sample(500, random_state=0), max_samples=500)
pushes = shap.Explainer(chance, masker, algorithm="exact")(X_test)
size = pd.Series(np.abs(pushes.values).mean(axis=0), X.columns)
print((100 * size).nlargest(3).round(1))
shap.plots.beeswarm(pushes)contact 2.4 pdays 2.2 age 2.0
Check that the pushes add up
shap.TreeExplainer reads the trees themselves and takes seconds. Its pushes are in log-odds, so they should add up to the log-odds of the model's chance. Here they add up to 0.404, not 1.105: it misreads these trees. The exact explainer's pushes add up to the chance itself, 0.751. Check the sum before you trust any explainer.
fast = shap.TreeExplainer(model)
logit = fast(X_test)
she = list(X_test.index).index(38831)
p = chance(X_test.iloc[[she]])[0]
print(round(logit.base_values[she] + logit.values[she].sum(), 3), round(np.log(p / (1 - p)), 3))
print(round(pushes.base_values[she] + pushes.values[she].sum(), 3), round(p, 3))0.404 1.105 0.751 0.751
Shuffle three columns together
permutation_importance shuffles one column at a time. Columns that say the same thing need a shuffle by hand: mix the rows of all three at once, so they move together, and score the model again.
from sklearn.metrics import roc_auc_score
twins = ["pdays", "previous", "poutcome"]
before = roc_auc_score(y_test, chance(X_test))
rng = np.random.default_rng(0)
falls = []
for _ in range(10):
mixed = X_test.copy()
mixed[twins] = mixed[twins].to_numpy()[rng.permutation(len(mixed))]
falls.append(before - roc_auc_score(y_test, chance(mixed)))
print(round(np.mean(falls), 3))0.032
Run on Python 3.13.3, scikit-learn 1.9.1, shap 0.54.1, pandas 3.1.1, NumPy 2.5.5. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Gradient boosting
You keep adding boosted trees. The miss on the penguins they learned from keeps falling. What does the miss on new penguins do?
2 of 3
Shuffled on the calls kept aside, the phone column makes the bank's score fall the most: the model depends on it most. Should the bank now call everyone on a cell phone, to get more yeses?
3 of 3
On another company's rows kept aside, permutation_importance prints each column's fall in the area under the ROC curve: cancel_reason 0.21, tenure 0.02, plan 0.01. What do you check before the model goes live?
The ideas in this lesson
- Permutation importance
- Shuffle one column on rows kept aside: how far the score falls is how much the model depends on that column.
- What importance can't say
- A column the model depends on may only stand in for something else, and columns that say the same thing share the credit.
- SHAP values
- For one row, each fact's push from the average answer to this one, averaged over every order; the pushes add up.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Explaining a model
Here's a game. The bank knows twelve things about each customer. Its model picks who to call. Which one does it depend on most? Their age? Their job? Or the kind of phone the bank calls them on?
Keep your guess
Hold on to your guess. The model is boosted trees: forty-five small trees, added one after another. That's too many to read one by one.
Shuffle one column
So you test a model from the outside, like hiding one clue from a detective. Take the thousand calls kept aside, which the model never learned from.
Mix up the values of one column among those calls: the phone.
Every other column stays as it is. Now score the model again. Its score, the area under the ROC curve, falls from zero point seven three to zero point six eight.
How far it falls tells you how much the model depends on that column.
One shuffle can be luck, so you shuffle ten times and take the average. This is called permutation importance.
The bars
Do it for every column. Now, check your guess... The phone falls the most. Then comes credit in default, meaning money a customer never paid back, and the days since an earlier call. Age and job fall by only about a third as much as the phone. And a housing loan: almost nothing.
A leak stands out
What's this good for?
Add one more column: the call's length, which an earlier lesson showed is a leak. The score jumps to zero point eight nine. Which bar is wrong?
The call's length falls by a quarter. No other column falls by even a fiftieth. So the call's length falls sixteen times as far.
One bar far past the rest is a warning sign. Ask one question about that column: will the model have this when it makes real predictions?
Run this check before any model goes live.
Not a cause
Shuffle a column, and its fall says how much the model depends on it. Here, the phone leads.
So does calling a cell phone make people say yes?
The model can't tell you. Calls to a cell phone said yes fifteen times in a hundred. Calls to a landline, five. But the bank moved to cell phones over time. In 2008, half its calls went to cell phones. In 2009, nine in ten did. And later, far more people said yes. So the phone also stands in for when the bank called. A detective's clue is a reason. A column may not be. Importance says what the model uses, not what makes people say yes.
Columns that say the same thing
An earlier campaign is an earlier round of calls about an offer. Look at that campaign's outcome. It falls by almost nothing. Is it useless?
But sixty-five in a hundred customers whose earlier campaign worked said yes. Two other columns say pretty much the same thing: the days since an earlier call, and the calls before this campaign.
Shuffle one, and the others still tell the model. Shuffle all three together, and the score falls by zero point zero three.
A small bar can mean shared, not useless.
One fact, two pushes
Shuffling tells you about the model as a whole. But why did it pick this one customer? They're seventy-eight, retired, and they were called three days after an earlier campaign that worked. The model gives them seventy-five in a hundred: its second highest chance out of the thousand. The average customer gets twelve.
Start from the average customer, at twelve. Now give the model just one fact about this customer: the days since their earlier call. Their chance goes from twelve to forty-four.
Add their age: fifty-seven. So age adds thirteen. Now start again, and give it their age first: from twelve to thirty-eight. How much did age add this time?
Twenty-six. The same fact, two pushes. It depends on what came before it.
SHAP values
So which push is the right one? Try every order the twelve facts could come in. Take each fact's push in each order. Then average them.
Those averages are called SHAP values.
For this customer, the days since their earlier call push the chance up by twenty-eight, to forty in a hundred. Their age takes it to sixty-two. The earlier campaign's outcome, to sixty-nine. The other nine facts, to seventy-five. The pushes add up to the model's chance. A push can go down, too: for a call to a landline, the phone pulls the chance down. And a push is the model's reason, not the customer's.
In code
In real code, scikit-learn's permutation importance, with the area as its score, prints each column's fall. The phone comes first.
Then shap. You make an explainer for the model's chance, with five hundred training calls as the average customer. Run it on the thousand calls, and every call gets its pushes.
One more line draws one customer's pushes, step by step, as a waterfall. Shuffling is the check before any model goes live. And SHAP is the start of an answer to a customer who asks: why me?
Three ideas
So: shuffle a column, and its fall says how much the model depends on it. That's what the model uses, not what causes the answer. And SHAP gives one customer's pushes, and they add up.
The lab
That's the end of this unit. In the lab, you use these two lessons to forecast next week's bikes. Then you find out what the forecast depends on most.
Shuffle a column
So shuffle a column to see what a model depends on. Now try it on this lesson's page, and take the quiz. Find a customer whose age pulls their chance down.
You use this lesson in Lab 7: Next week's bikes, and what the forecast leans on, which comes next.
Facts last checked on .
