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.
What runs in CodeSplash
- Support vector machine Verified in Python and R
- Neural network (MLP) Verified in Python and R
- Random forest Verified in Python and R
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
Five questions
ReadThey all treat the model as a black box that takes rows and returns predictions.
| Question | Method | Check 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? |
KernelSHAP
ReadShapley values for any model, estimated from predictions on subsets of features. Absent features take values from background rows.
View data
| feature | SHAP value (log-odds) | value |
|---|---|---|
| glucose | 1.222 | 168 |
| BMI | 0.5650 | 38.2 |
| age | 0.3460 | 51 |
| pedigree | −0.2740 | 0.21 |
| pregnancies | 0.1140 | 3 |
| blood pressure | −0.0630 | 74 |
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.
A straight line, nearby
ExploreLIME 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?
Data
Model
k for neighbors, depth for trees, γ × 2 for the kernel, hidden units for the network.
Commit your prediction above to see the result
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.
Trust LIME how far?
PredictPredict first
LIME gives a row a neat explanation, but Top-feature stability is low. What does that mean?
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.
A tree that imitates
ReadA surrogate tree is a small tree fitted to the model's predictions, not to the target.
View data
| node | parent | split | rows | P(diabetic) |
|---|---|---|---|---|
| 0 | −1 | glucose ≤ 127 | 400 | 0.3520 |
| 1 | 0 | age ≤ 29 | 250 | 0.1870 |
| 2 | 1 | 130 | 0.0810 | |
| 3 | 1 | BMI ≤ 26.4 | 120 | 0.3130 |
| 4 | 3 | 30 | 0.0890 | |
| 5 | 3 | 90 | 0.3830 | |
| 6 | 0 | BMI ≤ 30 | 150 | 0.6230 |
| 7 | 6 | 45 | 0.3580 | |
| 8 | 6 | 105 | 0.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.
Who works with whom?
ExploreFriedman'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.
View data
| feature | with | H |
|---|---|---|
| glucose | glucose | 0.3110 |
| BMI | BMI | 0.2390 |
| age | age | 0.1810 |
| pedigree | pedigree | 0.0720 |
| glucose | BMI | 0.2690 |
| glucose | age | 0.1220 |
| glucose | pedigree | 0.0510 |
| BMI | age | 0.0890 |
| BMI | pedigree | 0.0280 |
| age | pedigree | 0.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.
What would change it?
ReflectA 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?
Check your understanding
CheckpointCheck 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.
Try them
In the appIn 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.
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)))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)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