Robustness Testing
A test set measures performance on data that looks like the training data. Production is less polite: sensors drift and add noise, a field arrives empty, a form changes its units, a user types in capitals, an image is darker. Robustness testing asks how the model behaves when the input is perturbed in ways that should not matter, or that matter in a known direction, before users find out. It borrows from software testing: each test states an expectation, and a model that breaks it fails the test, whatever its accuracy.
Kinds of tests
| Test | Question | Example |
|---|---|---|
| Perturbation (noise) | how fast does the score degrade as inputs get noisier? | Gaussian noise on sensor features, blur and JPEG compression on images, typos in text |
| Missing or broken feature | what if one input is unavailable? | a feature replaced by its training median |
| Invariance | does changing something irrelevant change the prediction? | an application number, a person's name, the image's file name |
| Directional (monotonicity) | does changing something relevant move the prediction the right way? | higher income should not lower a credit score |
| Worst-case slices | which subgroup is served worst? | the slices of Error Analysis, kept as fixed tests |
| Stress / edge cases | extreme or rare but valid inputs | zero, very large values, empty text, a one-pixel image |
The behavioural testing idea (minimum functionality, invariance and directional tests) was popularised for NLP models by the CheckList paper (Ribeiro et al., 2020); it applies to any model.
Perturbation: noise on the inputs
Add Gaussian noise with a standard deviation of times each feature's training standard deviation to the test inputs, and watch accuracy. Breast-cancer data, two models, five noise draws per level:
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
X, y = load_breast_cancer(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)
sd = X_tr.std(axis=0)
models = {"logistic": make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)),
"random forest": RandomForestClassifier(n_estimators=200, random_state=0)}
rng = np.random.default_rng(0)
print("noise eps " + " ".join(f"{e:5.2f}" for e in [0, 0.1, 0.25, 0.5, 1.0]))
for name, m in models.items():
m.fit(X_tr, y_tr)
accs = []
for eps in [0, 0.1, 0.25, 0.5, 1.0]:
runs = [m.score(X_te + eps * sd * rng.normal(size=X_te.shape), y_te) for _ in range(5)]
accs.append(np.mean(runs))
print(f"{name:14s} " + " ".join(f"{a:5.3f}" for a in accs))noise eps 0.00 0.10 0.25 0.50 1.00
logistic 0.959 0.963 0.956 0.942 0.901
random forest 0.953 0.952 0.932 0.910 0.868
Both models start at about 0.96 on the 171 test tumours. Small noise () changes nothing that matters (the 0.004 rise for logistic regression is noise in the noise). At the logistic model keeps 0.942 and the forest falls to 0.910; at , noise as large as the natural spread of each feature, it is 0.901 against 0.868. The two models were tied on clean data and are not tied on dirty data. Whether is realistic is a question for whoever knows the measuring process; the test makes the trade-off visible.
Missing features
If one input fails upstream and arrives as a default value, how much is lost? Replace each feature in turn by its training median and record the drop in accuracy, here for the logistic model:
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
data = load_breast_cancer()
X_tr, X_te, y_tr, y_te = train_test_split(data.data, data.target, test_size=0.3, stratify=data.target, random_state=0)
m = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)).fit(X_tr, y_tr)
base = m.score(X_te, y_te)
drops = []
for j in range(X_te.shape[1]):
X_broken = X_te.copy()
X_broken[:, j] = np.median(X_tr[:, j])
drops.append(base - m.score(X_broken, y_te))
print(f"intact accuracy {base:.3f}")
for j in np.argsort(drops)[::-1][:5]:
print(f" {data.feature_names[j]:22s} replaced by median: accuracy {base - drops[j]:.3f}")
print(f"features whose loss costs nothing: {sum(d <= 0 for d in drops)} of {len(drops)}")intact accuracy 0.959
worst concavity replaced by median: accuracy 0.947
mean concave points replaced by median: accuracy 0.947
radius error replaced by median: accuracy 0.947
smoothness error replaced by median: accuracy 0.953
worst concave points replaced by median: accuracy 0.953
features whose loss costs nothing: 24 of 30
No single missing feature costs more than 0.012 (two tumours of 171), and losing any of 24 of the 30 features costs nothing at all. That is because the breast-cancer features are strongly correlated (radius, perimeter and area measure nearly the same thing), so the information is spread out. A model that relies on one feature this way would show a large drop here, and that feature's pipeline deserves monitoring. Test pairs and groups of features too when they come from the same source and fail together.
Invariance and monotonicity
A credit model uses income (thousands) and debt ratio. The table also has an application number, a meaningless identifier that slipped into the features. Two behavioural tests on the test rows:
- Invariance: draw a new application number for every row. No prediction should change.
- Directional: raise every applicant's income by 5. No approval probability should fall.
Gradient-boosted trees can learn non-monotone wiggles from noise and can split on the identifier. The fix is to drop the identifier and impose the known direction with monotonic_cst (+1: increasing, -1: decreasing):
import numpy as np
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import train_test_split
rng = np.random.default_rng(0)
n = 3000
income = rng.normal(50, 15, n)
debt = rng.uniform(0, 1, n)
app_no = rng.integers(0, 100000, n).astype(float)
z = 0.06 * (income - 50) - 3 * (debt - 0.5)
approved = (rng.random(n) < 1 / (1 + np.exp(-z))).astype(int)
X = np.column_stack([income, debt, app_no])
X_tr, X_te, y_tr, y_te = train_test_split(X, approved, test_size=0.5, random_state=0)
def behaviour_tests(model, cols):
p = model.predict_proba(X_te[:, cols])[:, 1]
X_id = X_te.copy(); X_id[:, 2] = rng.integers(0, 100000, len(X_te)) # new identifiers
X_inc = X_te.copy(); X_inc[:, 0] += 5 # +5k income
flips = np.mean((model.predict_proba(X_id[:, cols])[:, 1] >= 0.5) != (p >= 0.5))
worse = np.mean(model.predict_proba(X_inc[:, cols])[:, 1] < p - 1e-9)
return model.score(X_te[:, cols], y_te), flips, worse
free = HistGradientBoostingClassifier(max_iter=300, learning_rate=0.1, random_state=0).fit(X_tr, y_tr)
fixed = HistGradientBoostingClassifier(max_iter=300, learning_rate=0.1, monotonic_cst=[1, -1],
random_state=0).fit(X_tr[:, :2], y_tr)
for name, model, cols in [("unconstrained, with app_no", free, [0, 1, 2]), ("monotone, no app_no", fixed, [0, 1])]:
acc, flips, worse = behaviour_tests(model, cols)
print(f"{name:27s} accuracy {acc:.3f} decisions flipped by new app_no {flips:.1%} "
f"probability fell after +5k income {worse:.1%}")unconstrained, with app_no accuracy 0.653 decisions flipped by new app_no 20.1% probability fell after +5k income 39.9%
monotone, no app_no accuracy 0.703 decisions flipped by new app_no 0.0% probability fell after +5k income 0.0%
The unconstrained model fails both tests badly: a new application number flips 20.1 % of the decisions, and raising income lowers the approval probability for 39.9 % of applicants. Its accuracy, 0.653, is also lower, since it has spent its capacity fitting noise in the identifier. The model without the identifier and with monotone constraints passes both tests by construction (0.0 % and 0.0 %) and is more accurate, 0.703. The accuracy gain is a bonus of this example; the reason to use the constraints is the guarantee.
Building a robustness suite
- Write the expectations down with the people who know the domain: what must not matter, what must move which way, which subgroups must be served at least as well as average.
- Turn each into a test with a threshold: "accuracy under noise at least 0.90", "no decision flips under identifier changes", "monotone in income".
- Run the suite on every new model, like unit tests in continuous integration, and keep failing examples as regression tests.
- Fix with data or constraints, not with special cases: augmentation for the perturbations you expect (image augmentation), dropping or constraining features, collecting data for weak slices.
Robustness to natural variation is different from robustness to an adversary who searches for the smallest perturbation that flips a decision; adversarial robustness for neural networks is a field of its own, touched on in the deep learning course.
Practice
- A model's accuracy drops from 0.95 to 0.60 under noise of . What does this suggest?
Answer
It relies on fine detail in the inputs that is smaller than realistic measurement noise, typical of an overfitted model or one that uses a near-duplicate of the target. Look at which features it depends on, regularise it, or train with noise augmentation if that noise level is realistic.
- Why is an invariance test more informative than checking that the identifier's feature importance is small?
Answer
Importance is an average; a model can use a feature rarely but decisively. The invariance test measures what matters directly: how many decisions change when the irrelevant input changes.
- In the example the constraints also raised accuracy. On another data set they lower test accuracy slightly. Keep them?
Answer
Usually yes, when the direction is known to be true (and often required by regulation or fairness rules): the small accuracy loss buys predictable behaviour on inputs the test set does not cover. If the drop is large, check whether the assumed direction is actually right.
Test yourself
Which is an invariance test?
- Raising income and checking the score does not fall
- Changing an applicant's name and checking the decision does not change
- Adding noise and measuring the accuracy drop
- Computing accuracy per region
What does monotonic_cst=[1, -1] in HistGradientBoostingClassifier impose?
- The first feature is dropped
- Predictions increase with the first feature and decrease with the second
- Both features are scaled
- Only one tree is used
Why add noise in units of each feature's training standard deviation?
- So the noise is the same in absolute units
- So every feature is perturbed by a comparable relative amount whatever its scale
- Because it is faster
- To keep features positive