Sub topic 13
Using attribution to inspect single errors
This chapter covers attribution as a tool for forming hypotheses about individual misclassified examples. It assumes you have read the earlier chapters on collecting errors into a table and building an error taxonomy. It also assumes you can train a scikit-learn text classifier and read predicted probabilities.
What attribution gives you
An attribution method assigns each input piece, usually a token, a score for how much it contributed to one output. For a classifier, the output is typically the probability or logit of one class. You look at the scores for a single example and ask which words pushed the model toward its wrong answer.
Attribution answers a narrow question: what did the model rely on for this input? It does not tell you what the model should have relied on, and it does not tell you how often the pattern occurs. That is why this topic sits late in the plan. Your taxonomy and slices tell you where to look. Attribution helps you explain a few representative cases inside a category.
Where it fits in the workflow
Use attribution after you have a category of errors, not before. Pick two or three examples from a category, such as confident mistakes with negation. Inspect them, write down a hypothesis, then test the hypothesis on the whole category.
Common attribution methods
The methods differ in cost, in what they assume about the model, and in how they fail.
| Method | How it works | Needs model internals | Typical cost | Main weakness |
|---|---|---|---|---|
| Occlusion (leave-one-out) | Remove or mask one token, measure the change in the output | No | One forward pass per token | Ignores interactions between tokens |
| LIME | Fit a small linear model on many perturbed copies of the input | No | Hundreds of forward passes | Results vary between runs |
| SHAP | Estimate Shapley values over token subsets | No (model-agnostic variants) | Many forward passes | Slow on long texts, depends on the masking choice |
| Gradient times input, Integrated Gradients | Use gradients of the output with respect to input embeddings | Yes (gradients) | A few backward passes | Noisy, depends on the baseline choice |
| Attention weights | Read the attention matrices | Yes | Free | Not a reliable explanation of the output |
For a first pass, occlusion is the easiest to write and to reason about, and it works with any model that returns probabilities. Libraries such as Captum (PyTorch models) and SHAP implement the other methods.
A worked example with occlusion
The script below trains a small bag-of-words classifier and scores each token of a misclassified review. The score is the drop in the predicted class's probability when that token is removed. A large positive score means the token supported the prediction.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
texts = [
"great phone", "love it", "good battery", "great screen", "good value",
"bad battery", "bad screen", "bad phone", "very bad", "bad value",
]
labels = ["pos"] * 5 + ["neg"] * 5
model = make_pipeline(TfidfVectorizer(), LogisticRegression(max_iter=1000))
model.fit(texts, labels)
def occlusion(model, text):
"""Return (predicted class, its probability, [(token, drop), ...])."""
tokens = text.split()
pred = model.predict([text])[0]
idx = list(model.classes_).index(pred)
base = model.predict_proba([text])[0][idx]
scores = []
for i, tok in enumerate(tokens):
reduced = " ".join(tokens[:i] + tokens[i + 1:])
p = model.predict_proba([reduced])[0][idx]
scores.append((tok, base - p))
return pred, base, scores
text = "not bad at all" # gold label: pos
pred, base, scores = occlusion(model, text)
print(f"text={text!r} predicted={pred} p={base:.2f}")
for tok, drop in scores:
print(f"{tok:>8} {drop:+.3f}")Only "bad" appears in the training vocabulary, so "bad" carries the whole prediction. The words "not", "at" and "all" score zero because the model has never seen them. The attribution shows why the model fails: it treats "bad" as negative evidence and has no mechanism for the negation in front of it.
That is a hypothesis, not a finding. It says the model misreads negated negative words. To test it, you would collect every example in your error table that contains a negation word and compare accuracy against the rest. That is the slice analysis from an earlier chapter, now guided by what attribution suggested.
Reading attribution output carefully
Four habits keep you from over-reading the scores.
- Attribute the right output. Always compute scores for a specific class. For an error, there are two useful views: the predicted (wrong) class, which shows what pushed the model there, and the gold class, which shows what failed to push it the other way.
- Compare with correct examples. If the same token gets a similar score in examples the model classifies correctly, it is not the cause of the error. Run the same method on a few correct examples that share the suspect feature.
- Look for artifacts. Attribution often reveals shortcuts: punctuation, product names, or a formatting marker that correlates with a label in the training data. Such shortcuts show up as high scores on tokens that carry no meaning for the task.
- Expect disagreement between methods. Two methods can give different rankings for the same example. If a conclusion depends on one method's ranking, it is weak.
Failure modes
Occlusion creates unnatural inputs
Deleting a word from "not bad at all" produces "not at all", which the model never saw in training. For a bag-of-words model this is harmless, but for a transformer the shortened text can be out of distribution, and the probability change reflects that oddity as much as the token's role. Masking with the model's mask token or a neutral placeholder sometimes helps, but each choice changes the scores.
Token interactions are hidden
Occlusion removes one token at a time. If two tokens jointly cause the error, such as "not" and "bad", removing either one alone may produce a misleading drop. Occluding pairs or short phrases handles this at the cost of more forward passes. A cheap fix is to occlude whole phrases that your taxonomy has already identified.
Subword tokens split words
With transformer tokenizers, one word can become several pieces. Scores on pieces are hard to read, so sum them back to the word level before you interpret them.
Saturated predictions
When the model is very confident, removing a single token may barely change the probability, so every score is near zero. Use the logit instead of the probability, which does not saturate, or occlude groups of tokens.
Attention is not attribution
Attention weights are easy to extract and look like an explanation, but studies have shown that they often do not match the importance of tokens for the output. Do not use them as evidence in an error analysis unless you confirm them with a perturbation test.
A quick check that scores are faithful
Before relying on an attribution method for your model, run a deletion check on a sample of examples. Remove the top-scoring token and see whether the prediction actually changes more often than it does when you remove a random token. If the top token is no more influential than a random one, the method is not telling you anything useful for this model.
import random
def top_token_flips(model, texts, seed=0):
rng = random.Random(seed)
top_flips = random_flips = 0
for text in texts:
tokens = text.split()
if len(tokens) < 2:
continue
pred, _, scores = occlusion(model, text)
top = max(range(len(tokens)), key=lambda i: scores[i][1])
rand = rng.randrange(len(tokens))
for i, counter in ((top, "top"), (rand, "rand")):
reduced = " ".join(tokens[:i] + tokens[i + 1:])
changed = model.predict([reduced])[0] != pred
if counter == "top":
top_flips += changed
else:
random_flips += changed
return top_flips, random_flips
sample = ["great phone", "bad battery", "good value", "very bad", "love it"]
print(top_token_flips(model, sample))The function returns two counts. The first is how many predictions flipped when the top-scoring token was removed. The second is the same count for a random token. With only a few examples the counts are noisy, so use a few hundred in practice. The same caution about uncertainty from the slice analysis chapter applies here.
When to skip attribution
Attribution takes effort per example and gives you information about one input. Skip it when the taxonomy already explains the errors, such as label noise or an obvious distribution shift. Use it when errors look unexplained, when you suspect shortcuts, or when you need to explain a failure to someone who will ask why the model did that.
Summary
- Attribution scores show which input pieces a model used for one output. They generate hypotheses about errors.
- Start from a taxonomy category, sample a few errors, read the scores, and then test the hypothesis on the whole category.
- Occlusion is simple and model-agnostic. Its weaknesses are off-distribution inputs, hidden token interactions, and saturation.
- Compare errors with correct examples, and check faithfulness with a deletion test before trusting a method.
- Do not treat attention weights as an explanation.
Exercise
Occlusion on a misclassified review shows that the word "Acme" (a brand name) has the largest score for the predicted class "neg". What should you do next before deciding the model has a brand bias?
Show answer
Treat it as a hypothesis and test it. Run the same attribution on a few correctly classified examples that contain "Acme" to see whether the score is similar. Then measure accuracy and the share of "neg" predictions on all examples that contain "Acme" versus those that do not, with a count and an uncertainty interval for the slice. You can also run an invariance test that swaps "Acme" for other brand names in the same template. Only if the prediction shifts across these checks is a brand bias supported.
Exercise
Why can occlusion give near-zero scores for every token when a transformer classifier is 99.9% confident, and what is one way to handle it?
Show answer
The probability is saturated, so removing one token barely changes it even when the token matters. Attribute the logit (the pre-softmax score) instead of the probability, or occlude groups of tokens at once so the change becomes visible.