Why statistical testing is needed
Why This Matters
Run a test once, it passes, you move on. With an AI-based system, the same test may fail on the next run, and pass again on the one after. A single result, pass or fail, says almost nothing. Testers need a different question: not “did it pass?” but “how often does it pass, and how sure are we?”
What you will learn
- The four reasons the syllabus gives for testing AI-based systems statistically
- How to run one test many times and turn the results into a rate with a confidence interval
- What “pass” means for a system that varies
Syllabus: AI-4.1.2.
Four reasons
- Non-determinism. The same input can give different outputs (lesson 25). One misclassified cat says little about overall correctness, and one correctly classified cat says just as little. The test suite has to be large enough for statistically significant results.
- Distributional performance. Training data rarely matches operational data exactly. Performance is a property of the model on a distribution of inputs, so test samples must be drawn from the operational distribution: the kind of inputs it will really get, in the proportions it will get them.
- Uncertainty and bias. Models can be confidently wrong, and wrong more often for some groups than others. Statistics such as confidence intervals, hypothesis tests and error analysis quantify how sure you can be and where the errors are concentrated.
- Regulation and safety. In regulated domains such as healthcare and transport, you need high-confidence evidence that the system is reliable across many scenarios. “It worked in our tests” is not evidence; “at least 99% with 95% confidence over 3,000 representative cases” is.
Hands-on: one applicant, fifty answers
The practice loan model adds noise to every prediction. Ask about this applicant ten times:
{"name": "Sam Taylor", "gender": "Male", "age": 40, "income": 45000,
"creditScore": 680, "employmentYears": 10, "zipCode": "60601"}
With POST /api/ml/predict?model=v1&seed=1 up to seed=10 (try it in the ML API in Swagger):
| seed | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
|---|---|---|---|---|---|---|---|---|---|---|
| score | 57.9 | 57.5 | 56.8 | 59.0 | 63.7 | 60.3 | 59.6 | 55.8 | 61.8 | 64.8 |
| approved | no | no | no | no | yes | yes | no | no | yes | yes |
Same applicant, same model. A test that checks “Sam is rejected” passes with seed 1 and fails with seed 5. Neither result is the truth: the truth is a rate.
Turn it into a test. You continue in the practice project; create module-5/test_statistical.py:
"""Lesson "Why statistical testing is needed": test a model whose answer varies from run to run."""
import math
import pytest
BORDERLINE = {
"name": "Sam Taylor", "gender": "Male", "age": 40, "income": 45000,
"creditScore": 680, "employmentYears": 10, "zipCode": "60601",
}
CLEAR = {**BORDERLINE, "income": 90000, "creditScore": 760}
RUNS = 50
def run(api, applicant, model="v1", runs=RUNS):
"""Ask for the same applicant `runs` times in one batch. With a seed the batch is reproducible."""
response = api.post(
f"{api.base}/predict/batch",
json={"applicants": [applicant] * runs, "model": model, "seed": 1},
timeout=10,
)
response.raise_for_status()
return response.json()["predictions"]
def wilson_interval(successes, n, z=1.96):
"""95% confidence interval for a proportion (Wilson score interval)."""
p = successes / n
centre = (p + z * z / (2 * n)) / (1 + z * z / n)
margin = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / (1 + z * z / n)
return centre - margin, centre + margin
The batch endpoint scores the same applicant 50 times in one request; with a seed, the 50 answers are the same on every run of your test, so the test itself is not flaky. The Wilson interval is a standard way to put a 95% confidence interval around a proportion; it behaves better than the textbook formula for small samples and rates near 0 or 1.
def test_the_same_applicant_gets_different_answers(api):
predictions = run(api, BORDERLINE)
approved = sum(p["approved"] for p in predictions)
scores = [p["score"] for p in predictions]
print(f"\n approved {approved} of {RUNS}; score {min(scores)} to {max(scores)}")
assert 0 < approved < RUNS
def test_borderline_applicant_is_a_coin_toss(api):
approved = sum(p["approved"] for p in run(api, BORDERLINE))
low, high = wilson_interval(approved, RUNS)
print(f"\n approval rate {approved / RUNS:.2f}, 95% interval {low:.2f} to {high:.2f}")
assert low < 0.5 < high
def test_clear_applicant_is_always_approved(api):
assert all(p["approved"] for p in run(api, CLEAR))
@pytest.mark.parametrize("model, max_spread", [("v1", 10), ("v2", 4)])
def test_spread_of_the_score(api, model, max_spread):
scores = [p["score"] for p in run(api, BORDERLINE, model)]
print(f"\n {model}: score {min(scores)} to {max(scores)}")
assert max(scores) - min(scores) <= max_spread
Run it
pytest module-5/test_statistical.py -v -s
module-5/test_statistical.py::test_the_same_applicant_gets_different_answers
approved 31 of 50; score 55.2 to 64.9
PASSED
module-5/test_statistical.py::test_borderline_applicant_is_a_coin_toss
approval rate 0.62, 95% interval 0.48 to 0.74
PASSED
module-5/test_statistical.py::test_clear_applicant_is_always_approved PASSED
module-5/test_statistical.py::test_spread_of_the_score[v1-10]
v1: score 55.2 to 64.9
PASSED
module-5/test_statistical.py::test_spread_of_the_score[v2-4]
v2: score 53 to 57
PASSED
============================== 5 passed
What “pass” means now
- Sam is approved 62% of the time, and with 50 runs we can only say the true rate is somewhere between 48% and 74%. The interval contains 50%: for this applicant, version 1 of the model is effectively a coin toss. Whether that is acceptable is a business question, and now it can be asked with numbers. Most banks would not accept that the same customer gets a different decision depending on when they apply.
- A clear applicant is approved 50 of 50 times. Far from the threshold, the noise does not matter. Non-determinism hurts near decision boundaries, so that is where statistical testing is most needed.
- Version 2 varies less (53 to 57, versus 55.2 to 64.9 for v1), and rejects Sam every time. Consistent is not the same as right, but it can be tested and explained.
A pass criterion for a varying system is a statement about a rate with a confidence: “for applicants at least 10 points away from the threshold, the decision is the same in at least 99% of runs”. Lesson 44 shows how to calculate how many runs or test cases such a statement needs.
Exercise
- Change
RUNSto 10 and runtest_borderline_applicant_is_a_coin_toss. How wide is the interval now, and what does that tell you about testing with few runs? - The model is consistent for clear applicants and varies near the threshold. Write an acceptance criterion for consistency that a bank could agree on, and say how you would test it.
Show suggested answer
With 10 runs, 4 are approved, and the interval is 0.17 to 0.69: more than half of the whole range. The rate is now 0.40 instead of 0.62, and you can say almost nothing about the true rate. The width of the interval shrinks with the square root of the number of runs: four times as many runs halves it. Few runs give a result that looks precise but is not.
For example: “Over 100 repeated predictions per applicant, at least 99% give the same decision, for every applicant in the consistency test set of 200 applicants spread over the score range.” Test it by running each applicant 100 times through
/predict/batchand counting the share of the majority decision. Expect the failures near the threshold; the bank then decides whether to reduce the noise (as v2 does) or to send borderline cases to a person.
Exam-style questions
1. Which is a reason given in the syllabus for using a statistical approach to testing AI-based systems?
- A. AI-based systems do not have any test inputs
- B. Non-determinism means one test result does not reflect overall correctness, so the test suite must be large enough for statistically significant results
- C. Statistical testing is faster than conventional testing
- D. AI-based systems are always tested by statisticians
Show answer
2. Why should test samples for an ML model be drawn from the operational distribution?
- A. Because training data rarely matches operational data, and performance depends on the distribution of inputs
- B. Because operational data is always labelled
- C. Because test data must be identical to training data
- D. Because the operational distribution is easier to collect
Show answer
3. Which techniques help quantify uncertainty and bias in a model’s results?
- A. Code reviews and static analysis
- B. Confidence intervals, hypothesis tests and error analysis
- C. Statement and branch coverage
- D. Equivalence partitioning only
Show answer
Your project so far
ai-testing-practice/
├── ...
└── module-5/
├── red-team-cases.csv
└── test_statistical.py new in this lesson
The finished version is in the example repository: module-5/test_statistical.py.