Skip to content

Any model: KernelSHAP, LIME, surrogate trees, H and counterfactuals

Explanations that only need a model's predictions. Each answers a different question, each has its own quality check, and none of them turns a model into a cause.

Advanced ~13 min10 steps

What runs in CodeSplash

You will be able to

  • Match KernelSHAP, LIME, surrogate trees, H and counterfactuals to the question each answers
  • Read each explainer's own check, such as fidelity or stability
  • Find interactions, and limit a counterfactual to what's changeable

Read first

01

Five questions

Read

They all treat the model as a black box that takes rows and returns predictions.

QuestionMethodCheck its answer with
Why this prediction?KernelSHAPKernelSHAPShapley values for any model, estimated from its predictions on subsets of features; base value + all values = the prediction.Base value + values = prediction
What does the model do near this row?LIMELIMEA simple line fitted to a model's predictions on perturbed copies of one row: a local explanation of that prediction.Local R² and Top-feature stability
What's the overall logic, in rules?Surrogate treeGlobal surrogate treeA small decision tree fitted to a model's own predictions, so you can read an approximation of what it does.Fidelity R²
Which features work together?Friedman's HFriedman's HHow much of two features' joint effect their separate effects do not explain: 0 means they add up, 1 means pure interaction.Does the pair show on ICE?
What would have to change?CounterfactualsCounterfactual explanationThe smallest feature changes that would move this row's prediction across its target.Is the change possible?
02

KernelSHAP

Read

Shapley values for any model, estimated from predictions on subsets of features. Absent features take values from background rows.

SHAP force plotWhich features pushed this one prediction up, and which pulled it down?
View data
featureSHAP value (log-odds)value
glucose1.222168
BMI0.565038.2
age0.346051
pedigree−0.27400.21
pregnancies0.11403
blood pressure−0.063074

Features push from the base value to the prediction. It's slow, as each row needs many predictions, and KernelSHAP rows and KernelSHAP background rows set the budget. With correlated features, background rows can create unrealistic combinations, so credit can move between the correlated pair.

03

A straight line, nearby

Explore

LIME fits a straight line around one row, using perturbed copies of it. Pick Random forest on Two moons, and look along the boundary. A line is a fine description close by. How far along before it's wrong?

DExplorable · Decision boundary zoo

What shapes of boundary can each kind of model draw?

Which model will score highest on new data from this shape?

How sure?

Data

Model

5

k for neighbors, depth for trees, γ × 2 for the kernel, hidden units for the network.

0.20
150
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

That's the limit of any local explanation. It's good near the row, and it says little about anywhere else.

04

Trust LIME how far?

Predict

Predict first

LIME gives a row a neat explanation, but Top-feature stability is low. What does that mean?

Report it: LIME can't be unstableDoubt it: a second fit chose different featuresIt's fine, as long as Local R² is high
Reveal

Doubt it. Stability is the share of the top features that a second fit on new perturbations also picks. If it's low, the story depends on the random draw. Look at Local R² too: a low value means even a line near this row doesn't fit.

05

A tree that imitates

Read

A surrogate tree is a small tree fitted to the model's predictions, not to the target.

Surrogate decision treeCan a small, readable tree imitate what this complicated model does?
View data
nodeparentsplitrowsP(diabetic)
0−1glucose ≤ 1274000.3520
10age ≤ 292500.1870
211300.0810
31BMI ≤ 26.41200.3130
43300.0890
53900.3830
60BMI ≤ 301500.6230
76450.3580
861050.7270

Fidelity R² is how well it reproduces the model's scores on these rows. Trust its rules only as far as its fidelity goes. A surrogate explains the model, not the data, and Surrogate depth trades readability for fidelity.

06

Who works with whom?

Explore

Friedman's H compares a pair's joint partial dependence with the sum of their separate ones. Zero means they don't interact in this model, and larger means a bigger share of their joint effect comes from working together.

Friedman's H interactionsWhich features does the model combine, rather than use one at a time?
View data
featurewithH
glucoseglucose0.3110
BMIBMI0.2390
ageage0.1810
pedigreepedigree0.0720
glucoseBMI0.2690
glucoseage0.1220
glucosepedigree0.0510
BMIage0.0890
BMIpedigree0.0280
agepedigree0.0200

Find the strongest pair. It's costly, with time growing as H rows squared, and noisy for weak effects. So limit H features, and confirm the top pair with ICE lines.

07

What would change it?

Reflect

A counterfactual is the smallest set of feature changes that moves this row's prediction across its target. "Your loan would be approved with income 10% higher."

Two cautions. It describes this model, and following it in real life may not produce the promised outcome. And some features can't change. Never change in the explanation settings holds fixed what a person can't change, such as age or a past event. Without that, you might tell a person to be younger. For your model, which features belong on that list?

08

Check your understanding

Checkpoint

Check yourself

A surrogate tree has a fidelity R² of 0.45. What should you do with its rules?

Show the answer

Answer: b

Fidelity measures imitation of the model. Even a perfect imitation says nothing about the world.

Check yourself

A forest's H for age and income is near zero. What does this show?

Show the answer

Answer: a

H measures how the model combines them, not how important either is, and not how they're distributed.

Check yourself

A counterfactual tells a patient to lower their age by ten years. What went wrong?

Show the answer

Answer: b

Search for changes people can actually make. Even then, the result says what moves the model, not what would help the patient.

Check yourself

You need an explanation for one prediction from a neural network, and its parts must add up to the prediction. Which fits?

Show the answer

Answer: a

A surrogate and permutation describe the whole model. LIME's line doesn't promise that its effects add up to the prediction.

09

Try them

In the app

In a run's Explanations tab, tick methods under The whole model and One prediction. Explanation settings next to Explain sets the rows and depths, and the Never change list. Each method carries its own check. Slow methods say so on hover. Explanations are cached for each run and setting.

Python
import numpy as np
import pandas as pd
from sklearn.metrics import r2_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeRegressor, export_text

df = pd.read_csv("pima.csv")
X, y = df.drop(columns="diabetic"), df["diabetic"]
model = make_pipeline(StandardScaler(), SVC(probability=True, random_state=1)).fit(X, y)
scores = model.predict_proba(X)[:, 1]
surrogate = DecisionTreeRegressor(max_depth=3, random_state=1).fit(X, scores)
print("fidelity R2", round(r2_score(scores, surrogate.predict(X)), 3))
print(export_text(surrogate, feature_names=list(X.columns)))
R
library(e1071)
library(rpart)
df <- rbind(MASS::Pima.tr, MASS::Pima.te)
model <- svm(type ~ ., df, probability = TRUE)
scores <- attr(predict(model, df, probability = TRUE), "probabilities")[, "Yes"]
d <- df[, setdiff(names(df), "type")]; d$score <- scores
tree <- rpart(score ~ ., d, control = rpart.control(maxdepth = 3, cp = 0))
c(fidelity_r2 = 1 - sum((scores - predict(tree))^2) / sum((scores - mean(scores))^2))
print(tree)
10

Recap

Recap
  • Each explainer answers its own question, and each has its own check.
  • Fidelity and stability say how far to trust the story. Without them, it's only a story.
  • Lock what can't change, and remember that all of these describe the model.

Concepts in this lesson