AI & Machine Learning Master Course — 177. Robustness and out-of-distribution behavior
Smartyfy AI & Machine Learning Master Course
Course ID: smartyfy-ai-ml-master-200
Lesson 177: Robustness and out-of-distribution behavior
Prerequisites: Lesson 176. Learning outcome: Define realistic stress tests, abstention, and escalation procedures.
Robustness is a question about conditions
A model may work on the evaluation population and fail when lighting, devices, language, user behavior, or measurement procedures change. Out-of-distribution behavior refers to a mismatch with the distribution relevant to the model's development and evaluation. It is not a single universal category that one detector can recognize perfectly.
Begin with the intended operating envelope. State supported input types, measurement units, ranges, groups, and acquisition conditions. Identify plausible changes and their consequences. A shifted temperature sensor and a newly introduced product can demand different tests even when both change a histogram. Some changes affect inputs while the target mechanism remains stable; others change the relationship between inputs and outcomes.
Design a stress-test matrix
Choose transformations from domain knowledge, then specify their severity, expected label behavior, and affected users. Measurement noise may preserve an inspection label within a defensible tolerance, whereas removing the object from an image usually does not. Evaluate baseline and stressed inputs using aligned examples when appropriate, and retain failure cases rather than reporting only the average.
Keep development stress tests separate from final evidence. Repeatedly adjusting thresholds to pass the final stress suite makes that suite part of development. Create a new independent evaluation when substantial tuning occurs. A synthetic stress generator samples assumptions you wrote; success against it is not evidence that every real shift is covered.
Distinguish input validity from familiarity. An input can satisfy a schema while lying far from training support. Conversely, a familiar-looking input can have a changed label mechanism. Detection based only on features cannot observe a hidden change in outcomes immediately.
Selective prediction adds a second decision
A selective system first decides whether to accept a prediction and then returns the prediction for accepted cases. Coverage is accepted cases divided by all eligible cases. Selective risk is the error rate among accepted cases. Always report both: rejecting almost everything can produce an attractive accepted-case score with little practical usefulness.
A rejection policy needs a destination. It might request another measurement, send a case to review, or use a safe fallback. Account for delay, cost, accessibility, and review capacity. Rejecting difficult cases can move rather than eliminate harm, especially if some populations are rejected much more often.
A large softmax or sigmoid output is not proof that an input belongs to the operating envelope. Confidence is computed by the model, including on unfamiliar inputs. Calibration evidence from one population does not automatically transfer to shifted populations. Estimate acceptance thresholds on appropriate development data and test their realized behavior independently.
CPU lab: confidence and distance can disagree
The four reference points determine a mean of [0,0] and population standard deviation [1,1]. This is an invented reference fixture, not representative training data. A supplied sigmoid score depends on the first coordinate. The acceptance rule requires maximum standardized coordinate magnitude at most two and predicted-class probability at least 0.7. These thresholds are preset for teaching, not statistically calibrated.
Run the complete script as example177.py. The point [4,4] receives probability about 0.999665 but is rejected by the envelope check. The point [0,0] is inside the envelope but rejected for ambiguity. Two cases are accepted, giving coverage 0.5 and accepted error zero on two fictional labels. All-case error is 0.5. Four cases cannot establish a useful production error bound.
The reference mean and scale are computed before stress inputs are considered. Re-estimating them on the stress batch would change the detector and could hide the shift. This small rule ignores feature correlations and cannot detect arbitrary semantic shifts.
import numpy as np
reference = np.array([[-1., -1.], [-1., 1.], [1., -1.], [1., 1.]])
mean, scale = reference.mean(axis=0), reference.std(axis=0)
x = np.array([[0.5, 0.5], [0., 0.], [4., 4.], [-0.5, -0.5]])
y = np.array([1, 0, 0, 0]) # fictional stress-test labels
prob = 1 / (1 + np.exp(-2 * x[:, 0])) # supplied score, not fitted
pred = (prob >= 0.5).astype(int)
radius = np.max(abs((x - mean) / scale), axis=1)
accept = (radius <= 2.0) & (np.maximum(prob, 1-prob) >= 0.7)
assert accept.tolist() == [True, False, False, True]
print('probabilities', prob.round(6).tolist())
print('coverage', round(float(accept.mean()), 6))
print('accepted error', round(float((pred[accept] != y[accept]).mean()), 6))
print('all-case error', round(float((pred != y).mean()), 6))
A compact reporting contract
For every stress condition, record sample count, severity, overall error, coverage, accepted-case error, rejection reasons, and resulting action. Include uncertainty and important slices when sample size permits. Undefined accepted risk when no cases are accepted should be recorded as undefined, not zero.
Escalation criteria should be actionable. For example, suspend automated inspection recommendations if unsupported devices exceed a predeclared fraction or if mature outcome errors exceed a reviewed threshold. An alert needs an owner, a response time, and a fallback that has actually been rehearsed.
Finally, review whether the fallback itself changes the data you later observe. If only reviewed cases obtain reliable labels, the observed error stream is selected. Monitoring and subsequent retraining must account for this observation process rather than assuming labels arrive uniformly for every prediction.
Four practice questions with worked answers
Practice 1
Calculate coverage and accepted error for the fixture.
Answer: Two of four cases pass both acceptance checks, so coverage is 2/4 = 0.5. Both accepted predictions match their fictional labels, giving accepted error 0/2 = 0. The denominator is two, not four.
Practice 2
Why reject [4,4] despite a probability near one?
Answer: Its maximum standardized coordinate magnitude is four, exceeding the declared envelope threshold two. The model can extrapolate a confident score without evidence that its prediction is reliable there.
Practice 3
What should accepted risk be if a threshold rejects every case?
Answer: It is undefined because the accepted denominator is zero. Report zero coverage and no accepted-risk estimate. Reporting zero error would suggest evidence of correctness that does not exist.
Practice 4
A new camera produces larger feature values. Should the detector automatically refit its reference scale on that batch?
Answer: No. That would change the reference before assessing the shift. Investigate units and acquisition conditions, evaluate the revised domain, and version any justified recalibration using appropriate development evidence.
Five multiple-choice questions
Question 1
Which pair is essential for selective prediction?
- A. Coverage and error among accepted cases
- B. Rejected count and training loss without accepted outcomes
- C. Training accuracy and the number of model layers
Correct: A. Coverage measures retained workload; accepted-case error measures performance on that retained subset.
Question 2
What does high predicted-class probability establish on a novel input?
- A. The prediction has a calibrated real-world error rate under every shift
- B. The input is necessarily from the training distribution
- C. The model strongly favors a class under its scoring rule
Correct: C. A model score is not a distribution-membership guarantee or a universal calibration statement.
Question 3
Which is the strongest basis for choosing a stress transformation?
- A. One with a justified domain interpretation and explicit label assumptions
- B. Any transformation that lowers accuracy, regardless of plausibility
- C. Any small numeric change, because size alone preserves labels
Correct: A. Stress tests need realistic constraints and a defensible target interpretation.
Question 4
Why preserve the original reference statistics during evaluation?
- A. Refitting can alter confidence calibration but cannot change the envelope detector
- B. Refitting on stress inputs changes the detector being evaluated
- C. Reference statistics must never change across any future version
Correct: B. Freeze the evaluated procedure; later justified recalibration is a separately versioned development step.
Question 5
What can feature-only monitoring miss?
- A. Any change in input units
- B. A change in outcomes conditional on otherwise similar features
- C. Every observation beyond a known numerical range
Correct: B. A conditional outcome shift can occur without an obvious change in the input distribution.
Common pitfalls
Avoid declaring all rejected cases safe, using confidence as a universal OOD detector, refitting reference statistics on evaluation inputs, or reporting selective error without coverage and sample size.
Summary
Robustness requires realistic stress conditions, stable evaluation boundaries, and a useful response when inputs are unsupported. Selective prediction must be judged as a complete decision process, including rejection costs and limitations.