Robustness testing and rigorous model evaluation
Treat model evaluation as test engineering using corruption and natural-shift benchmarks, behavioral templates, metamorphic testing without an oracle, and automatic subgroup discovery. Report disaggregated metrics, intervals, seeds, and model cards.
After this lesson you can
- Calculate mCE and effective robustness and distinguish them from in-distribution accuracy.
- Design minimum functionality, invariance, and directional tests for a text model.
- Define valid metamorphic relations and generate randomized property tests.
- Automatically discover error-prone subgroups and measure worst-group accuracy with intervals.
- Write a model card with disaggregated metrics and deployment assumptions.
Before you start
- 30Dataset shift detection pipelineUncertainty evaluation under dataset shift
- 13Spurious correlations and shortcut learningGroup distributionally robust optimizationAccuracy on the line
- 05Bootstrap percentile and basic intervalsFamilywise error rate control: Bonferroni, Šidák and Holm
- 00pytest fixtures, parametrization and markersProperty-based testing
- 31Experimental unit in MLStatistical comparison report
One accuracy number is not a test plan
A model may pass its usual test yet systematically fail when lighting changes, a negation appears, or a small group is encountered. The same mean accuracy can hide failures incompatible with intended use. Recht and colleagues constructed new sets following the CIFAR-10 and ImageNet process and observed drops for the evaluated models. This motivates measuring change, not attributing every drop to overfitting or assuming every new set follows the same process.
A defensible test suite fixes population, experimental unit, label, and cost before selecting metrics. Start with individual examples the model should not fail, transform cases where the correct relationship is known, and find subgroups on a split separate from confirmation. After a distribution shift alert, this suite helps determine whether relevant behavior deteriorates.
Corruptions, severities, and a reference
Corruption robustness measures performance under predefined transformations such as noise, blur, or contrast changes. ImageNet-C evaluates fifteen main types at five severities and normalizes against AlexNet; Hendrycks and Dietterich distinguish these corruptions from adversarial attacks. An extreme transformation may change the recognizable label: the protocol must justify label preservation or treat that condition as a limitation.
For corruption and severity , write for the error rate and for the reference error rate. With fifteen corruptions and five severities,
mCE is sometimes expressed as a percentage by multiplying by 100: lower is better; the reference equals one when each denominator is positive. To measure error increase relative to clean images, the relative variant replaces numerator and denominator with and . A zero denominator makes the ratio undefined; a negative one can make interpretation as relative improvement misleading. A mean of ratios and a ratio of means are not interchangeable. Break results down by corruption: an average may hide serious regressions.
For example, suppose two corruptions have reference error sums 1.0 and 0.1, and candidate sums 0.5 and 0.2. Ratios are 0.5 and 2: their macro mean is 1.25, although the ratio of total sums is . The first weights both corruptions equally; the second gives more weight to the one with larger reference error. One is not an alternative calculation of the other. A large ratio may come from a small denominator, so also report original errors and sample sizes.
For relative mCE, subtract clean error at each severity before summing: with five levels subtract it five times. If a corruption improves clean performance, that difference can be negative; do not force the ratio to zero or interpret it as a probability. Changing the reference changes the number even when candidate predictions stay fixed. Cross-study comparison requires the same images, severities, reference, and aggregation convention.
In this run, logistic regression and the MLP had clean errors of 0.0289 and 0.0156 respectively. MLP mCE relative to logistic regression was 1.679 and relative mCE 2.485, with positive denominators for all fifteen corruptions. Clean difference does not determine robustness under every corruption, and ratios may amplify differences when denominators are small. The MLP hit its 250-iteration limit: we do not generalize this comparison to a model family or claim complete convergence.
We refit the MLP with seeds 31, 37, and 47, keeping split and corruptions paired. mCE values were 1.679, 1.828, and 1.842: mean 1.783 and sample deviation 0.090. Relative mCE values were 2.485, 2.762, and 2.710: mean 2.652 and deviation 0.147. Three seeds describe variability of these fits and do not alone provide a reliable interval for future performance; the figure shows the first.
To compare two models on the same images, retain paired predictions. Estimate error difference by averaging, per image, the candidate failure indicator minus the reference indicator; this uses the fact that both face the same case. Image resampling must keep both results and all severities from each image together. Resampling each cell separately breaks that dependence and can exaggerate the evidence. If training variation also matters, seeds require another repetition layer: an image interval for one seed does not measure that uncertainty source.
Effective robustness compares observed OOD performance with that expected for a model at that ID accuracy according to a curve fitted on a reference family; it is a residual from that curve and depends on benchmark, fit, and family. Do not confuse absolute OOD gain with effective robustness: a more accurate ID model can improve OOD while following the trend. Taori and colleagues evaluate natural shifts and show synthetic robustness does not always transfer. WILDS includes real shifts across hospitals, cameras, and regions; ImageNet-R and ImageNet-A also test specific alternatives, not a universal guarantee.
To construct this comparison, fit the ID/OOD relationship using a collection of reference models and leave out the candidate where possible. Fit scale matters: near accuracy one, transforming probabilities can prevent a raw-scale line from being interpreted outside . Then report the residual alongside both accuracies and curve uncertainty. Changing reference family or OOD domain may change the residual sign; it is not an intrinsic number for a model in isolation.
Behavioral tests and metamorphic relations
Behavioral testing breaks a capability into cases and expectations. CheckList distinguishes minimum functionality (MFT: a known answer, such as classifying an unambiguous sentence), invariance (INV: a transformation should not change the relevant prediction), and directional expectation (DIR: a transformation should move a score in one direction). Ribeiro and colleagues formalize this matrix and show it can uncover failures hidden by aggregate accuracy.
Random word changes are insufficient. Replacing one name with another may be a reasonable sentiment invariance if the remaining context does not change its meaning; replacing “excellent” with “horrible” changes the label and is not an invariance. Adding “not” requires analyzing the scope of negation. Templates generate examples quickly, but coverage and labels require review; failure rate depends on templates and does not automatically estimate production rate.
A template produces a family of correlated cases. If six names share the same sentence, counting six failures as six independent observations exaggerates evidence about language in general. Cluster by template and document dependence. A minimum test can check “this movie is excellent” with a positive label; an invariance test changes only the character name; a directional test compares positive confidence for “it is boring” versus “it is never boring.” These expectations require context not to reverse the meaning, and a continuous score can change even if the class does not.
Before aggregation, decide what constitutes failure: a different class, a confidence drop beyond tolerance, or violation of an inequality. These decisions answer different questions. A directional expectation does not require assigning a positive label to the negated sentence: “it is not boring” can be neutral while still requiring a higher positive score than “it is boring.” Also check generated variants for grammar and preservation of relevant context. A template failure is an oracle problem, not valid evidence against the model; retain rejected cases and the reason.
In the documented run, DistilBERT achieved 0.911 accuracy on 872 SST-2 validation sentences. The original model card identifies that set as model development evaluation, not a new independent test. On the figure’s templates it failed none of the 18 directional negation comparisons or 40 name-invariance comparisons. These are very small and related tests, not evidence of no negation failures in general. In particular, we do not attribute a one-half failure rate to the model without observing it.
Metamorphic testing uses input-output relationships when an oracle for each case is unavailable. If a credit model returns approval probability, a business hypothesis might require increasing income while holding debt and conditions fixed not to reduce it. This hypothesis does not automatically follow from data: it must be valid for the policy and population. Changing an irrelevant variable should preserve output only if it is truly irrelevant and does not encode an omitted legitimate condition. Property-based generation explores many cases; shrinking a counterexample reveals the boundary that failed.
Groups hidden by the average
Slice discovery searches for regions with systematic errors. Stratify by metadata, cluster error embeddings, or fit a tree to predict failure indicators. A geometric group need not be interpretable or stable: inspect examples and metadata. Domino studies discovery of coherent low-performing groups in multimodal representations.
Searching for the worst among many groups favors extreme values by chance. Selecting on one sample and confirming on another avoids using the same noise twice; simultaneously reporting multiple confirmatory groups requires controlling comparisons or providing simultaneous intervals. A binomial Wilson interval assumes appropriately independent observations and a group fixed before the confirmation sample. One seed, one split, or a group with few examples does not establish robustness.
Selection design matters as much as the estimator. If a group is defined after seeing all test labels, its ordinary interval describes a rule chosen by the same noise. If the rule is frozen during discovery and evaluated once on independent confirmation, the interval can describe that rule’s accuracy in the confirmation population under its assumptions. Determining which group is truly worst among all possibilities additionally requires controlling the search, not just constructing an interval for the selected group. If examples come from multiple hospitals or patients, resampling must respect that dependence unit.
Lab: credit and counterexamples
We construct synthetic data, not a real policy. The label depends on income, debt, and latent noise; holding noise fixed, increasing income cannot turn true approval into rejection. Postal code is generated without affecting the label. A tree using all four columns can learn spurious relationships from a finite sample. Discovery and confirmation are independent of training.
import numpy as np
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
rng=np.random.default_rng(67)
def generate(n):
income=rng.uniform(15,100,n);debt=rng.uniform(0,80,n);age=rng.uniform(20,75,n);postal=rng.integers(0,3,n)
x=np.column_stack([income,debt,age,postal])
y=(income-.85*debt+rng.normal(0,8,n)>28).astype(int)
return x,y
train,yt=generate(900);disc,yd=generate(600);test,ytest=generate(600)
model=DecisionTreeClassifier(max_depth=5,min_samples_leaf=12,random_state=7).fit(train,yt)
print('exactitud train, descubrimiento, test',*[round(accuracy_score(y,model.predict(x)),3) for x,y in [(train,yt),(disc,yd),(test,ytest)]])The transformation changes neither debt, age, nor latent noise. The tree predicts a probability, so a decrease already violates the score relationship even if both discrete predictions agree. Bisection maintains one endpoint without failure and one with failure; it shrinks an example but does not guarantee the globally smallest counterexample if the relationship changes sign again.
base=disc.copy();raised=base.copy();raised[:,0]=np.minimum(100,base[:,0]+15)
p=lambda x:model.predict_proba(x)[:,1]
viol=np.flatnonzero(p(raised)<p(base)-1e-12)
print('violaciones de monotonía',len(viol),'/',len(base))
if len(viol):
i=viol[0];lo=0.;hi=raised[i,0]-base[i,0]
for _ in range(25):
mid=(lo+hi)/2;point=base[i].copy();point[0]+=mid
if p(point[None,:])[0]<p(base[i:i+1])[0]-1e-12:hi=mid
else:lo=mid
point=base[i].copy();point[0]+=hi
print('ingreso, deuda, incremento, puntuaciones',round(base[i,0],3),round(base[i,1],3),round(hi,4),round(p(base[i:i+1])[0],3),round(p(point[None,:])[0],3))
alter=base.copy();alter[:,3]=(alter[:,3]+1)%3
print('cambios por código postal',int(np.sum(abs(p(base)-p(alter))>1e-12)),'/',len(base))Train the error tree only on discovery, select the highest-error leaf, and freeze its rule before viewing test. Bootstrap resamples within that leaf to estimate uncertainty about the fixed group’s error rate. It does not itself correct selection-and-evaluation bias on the same sample.
errors=(model.predict(disc)!=yd).astype(int)
tree=DecisionTreeClassifier(max_depth=3,min_samples_leaf=30,random_state=5).fit(disc,errors)
leaves=tree.apply(disc);selected=max(np.unique(leaves),key=lambda leaf:errors[leaves==leaf].mean())
print('hoja descubrimiento',selected,'n',sum(leaves==selected),'error',errors[leaves==selected].mean())
test_leaf=tree.apply(test)==selected;testerr=(model.predict(test)!=ytest).astype(int)
subset=testerr[test_leaf]
boot=np.array([rng.choice(subset,size=len(subset),replace=True).mean() for _ in range(1000)])
print('confirmación n',len(subset),'error',subset.mean(),'intervalo',np.quantile(boot,[.025,.975]))Local lab: corruptions and text
corruptions_lab.py trains our own logistic regression and MLP on digits, holds out one quarter, and evaluates fifteen corruptions at five severities with imagecorruptions 1.1.2. The script retains the same sample for both models and reports clean error, error per cell, and mCE relative to logistic regression. For three repetitions, set environment variable CORR_MODEL_SEED to 31, 37, or 47 and CORR_OUTPUT to different files. Using digit images resized to 32 pixels is our own experiment; it is not ImageNet-C or its published figures. Some severe changes can make labels unreadable, so the table measures the transformation protocol and does not prove all errors are unjustified.
sentiment_lab.py downloads classifier distilbert-base-uncased-finetuned-sst-2-english and SST-2 validation with pinned revisions, verifies the data file SHA-256, and generates the figure’s scores. Change templates or add capabilities, verify their expectations, and rerun: precomputed numbers cover only the stated cases. The model’s minimal card records English binary sentiment, SST-2 training published by its authors, model revision, and evaluation on SST-2 validation and artificial templates; it does not support high-impact decisions or other languages or domains without further evaluation.
Documenting to discuss the decision
The model card identifies version, provenance, architecture, purpose, and out-of-scope uses. Add splits, transformations, hyperparameter selection, number of seeds, independent units, global and group metrics with intervals and sizes. Document possible contamination, unmeasured conditions, false-rejection cost, and update mechanism. Mitchell and colleagues propose model cards accompanying the model with evaluations relevant to its application.
A small difference relative to between-seed variability does not establish improvement. An interval over examples from one seed does not capture training variation; report both uncertainty sources and do not treat correlated images from one patient as independent units. Documentation supports a decision; it does not replace validation under real deployment.
Exercises
More than one answer may be correct.
worst_group_accuracy(y_true, y_pred, groups, B=500, seed=0). Return (worst, stats), where worst is the lowest observed accuracy and stats maps each group label to a tuple (exactitud, límite inferior, límite superior) (accuracy, lower bound, upper bound) from a 95% percentile bootstrap resampling within that group. Groups are nonempty.import numpy as np
def worst_group_accuracy(y_true, y_pred, groups, B=500, seed=0):
pass