Sub topic 12
Behavioral tests with input perturbations
This chapter assumes you can train and evaluate a text classifier, read a confusion matrix, and write basic Python with pandas. Earlier chapters built an error taxonomy from the mistakes your test set happened to contain. Behavioral testing asks a different question: what should the model do on inputs you design, whether or not they appear in the data?
Why test behavior directly
A test set is a sample. It cannot tell you whether the model handles negation, typos, or a change of person's name, because those cases may be rare or missing. A held-out score of 91% can sit on top of a model that flips its answer when "Alice" becomes "Olga".
Behavioral testing treats the model as a black box. You write a rule about how it should behave, generate many inputs that exercise the rule, and count violations. The result is a failure rate for a named capability, which is easier to act on than a vague sense that the model is brittle.
This approach follows the CheckList framework (Ribeiro et al., 2020), which names three kinds of test.
| Test type | What you check | Example |
|---|---|---|
| Minimum functionality test (MFT) | The model gets simple, clear cases right | "I love this phone." is positive |
| Invariance test (INV) | An irrelevant change leaves the prediction unchanged | Swapping a name, adding a typo |
| Directional expectation test (DIR) | A change moves the output in a known direction | Appending a negative sentence must not raise the positive score |
Invariance tests
An invariance test asserts that a perturbation which should not matter does not change the label. Typical perturbations:
- Swapping person names, places, or numbers.
- Adding typos or changing capitalization.
- Adding punctuation, extra whitespace, or a neutral suffix.
- Replacing a word with a close synonym.
The example below fills one template with different names. Any name that changes the prediction is a failure. The predict function is a toy stand-in. Replace it with a call to your own model.
def predict(text):
# Stand-in for a real model: a toy rule-based sentiment classifier.
return "neg" if "terrible" in text.lower() else "pos"
names = ["Alice", "Mohammed", "Wei", "Olga"]
template = "{} said the service was terrible."
preds = {name: predict(template.format(name)) for name in names}
failures = [name for name, p in preds.items() if p != "neg"]
# An invariance test: swapping the name must not change the prediction.
print(f"failure rate: {len(failures) / len(names):.0%}", failures)The toy model passes, so the rate is 0%. A real model trained on skewed data may not. When it fails, the output names which inputs failed, so you can read them. That makes this more useful than a single "bias score".
Typos and other noise
Typos are a realistic perturbation because users make them. This function swaps two adjacent letters inside one word. It uses a seeded random generator so the test is reproducible.
import random
def add_typo(text, rng):
words = text.split()
candidates = [i for i, w in enumerate(words) if len(w) > 3]
if not candidates:
return text
i = rng.choice(candidates)
w = words[i]
j = rng.randrange(1, len(w) - 2) # swap two inner letters
words[i] = w[:j] + w[j + 1] + w[j] + w[j + 2:]
return " ".join(words)
def predict(text):
return "neg" if "terrible" in text.lower() else "pos"
rng = random.Random(0)
sentences = [
"the service was terrible",
"terrible battery and a cracked screen",
"great phone and fast delivery",
]
for s in sentences:
noisy = add_typo(s, rng)
status = "ok" if predict(s) == predict(noisy) else "FAIL"
print(f"{status}: {s!r} -> {noisy!r}")Run this on your real model many times with different seeds and report the fraction of examples whose label changed. A single random typo can miss the sensitive word, so one pass understates the problem.
Directional expectation tests
Some changes should move the output in a known direction without fixing an exact label. If you append a clearly negative sentence to a review, the positive score should not go up. You do not need gold labels for this, only a rule.
def score(text):
# Toy positive-class probability. Replace with model.predict_proba.
words = text.lower().replace(".", "").split()
pos = {"great", "good", "love"}
neg = {"terrible", "bad", "awful"}
s = 0.5
for w in words:
if w in pos:
s += 0.2
if w in neg:
s -= 0.2
return min(max(s, 0.0), 1.0)
bases = ["I love this phone.", "Good screen.", "The camera is fine."]
suffix = " The battery is terrible."
violations = [b for b in bases if score(b + suffix) > score(b)]
print(f"violations: {len(violations)} of {len(bases)}", violations)Directional tests need a model that outputs a score, or at least a label order. For classification you can also check that the predicted label did not move toward the opposite class.
Minimum functionality tests
An MFT uses simple, unambiguous inputs that any competent model should handle. They resemble unit tests. Examples for sentiment analysis:
- Plain positive and negative statements: "I love it", "I hate it".
- Simple negation: "I don't love it".
- Intensifiers: "very good" against "good".
MFTs are most useful for capabilities that the aggregate score hides. A model can score well on a test set full of long reviews and still fail on "not good". Generate many variants from a template by filling slots with words from a list, and report the failure rate for each capability separately.
Reading and reporting results
A failure rate alone is not enough. For each test:
- Record the capability, the test type, the number of generated inputs, and the failure count.
- Read at least ten failing examples. Check whether the perturbation was valid and whether the failures share a pattern.
- Add a column for the test to your error table so failures connect to your taxonomy.
Small test sets give noisy rates. If you generate 20 inputs and 3 fail, the true rate is poorly known. Use the bootstrap approach from the earlier chapter on slice uncertainty, or generate more inputs. Templates make this cheap.
Common mistakes
- Treating the failure rate as a model-wide score. It describes one capability under one set of templates. Different templates give different rates.
- Unrealistic inputs. Template output such as "Alice said the service was terrible." is fine, but absurd combinations may never occur in production. Weight your priorities by how plausible the inputs are.
- Testing on training data. If your perturbed inputs overlap with training examples, the model may pass by memorization.
- Ignoring label-changing perturbations. See the warning above.
- Fixing the tests by training on them. If you add the test inputs to the training set, you can no longer use them to measure the model. Keep a separate generator or hold-out templates for evaluation.
Connecting to prioritization
Each behavioral test yields a number you can compare with other error categories. A capability that fails 40% of the time but never appears in your data matters less than one that fails 8% of the time and covers a quarter of your traffic. The next chapters use failure rate together with frequency and fixability to rank what to work on.
Exercise
You write an invariance test that replaces "good" with "excellent" in 200 positive reviews and finds the label changes in 12 of them. List two steps you should take before reporting a 6% failure rate for synonym robustness.
Show answer
First, read the 12 failing examples and check whether the perturbation was label-preserving. In some reviews "excellent" may change the sentiment strength or sit in a phrase such as "not good enough", where the replacement alters the meaning. Remove invalid cases and recompute. Second, estimate the uncertainty, for example with a bootstrap interval over the 200 results, because 12 failures is a small count and the true rate could be well above or below 6%. Also check that none of the 200 reviews appear in the training data.
Exercise
What is the difference between an invariance test and a directional expectation test, and which one needs a model that outputs a score?
Show answer
An invariance test requires the prediction to stay the same after an irrelevant change, such as swapping a name. A directional expectation test requires the output to move in a known direction after a change, such as a lower positive score after adding a negative sentence. The directional test needs a score or an ordered output, so you can compare the direction of change. An invariance test can use labels alone.