A/B testing and back-to-back testing
Why This Matters
A new model version is ready. Is it better than the one in production? You often cannot say what the right answer is for each input (the oracle problem), but you can compare the two. A/B testing asks which one performs better, statistically. Back-to-back testing asks where do they differ, input by input. Both work without expected results, and they answer different questions.
What you will learn
- How A/B testing works for ML systems, including self-learning ones, and which statistics it uses
- How back-to-back testing works, what a pseudo-oracle is, and why independence matters
- The difference between the two, applied to the practice model’s v1 and v2
Syllabus: AI-6.1.9, AI-6.1.10.
A/B testing
A/B testing compares the responses of two variants, A and B, to the same kind of input, to decide which is better. It is statistical: it needs many runs or users, and a test to decide whether the difference is real.
- Classic example: two promotional offers sent to two halves of a mailing list; the one with more responses wins.
- ML example: two routing models for public transport, each used for one week; compare the average commute time.
- For model updates: the current model is the partial oracle. The new variant must perform at least as well on the agreed acceptance criteria (accuracy, recall, a business metric).
- For self-learning systems: after each change the system makes to itself, run automated tests and keep the change only if the system improved; otherwise revert.
- Statistics: t-test, z-test, chi-squared test, Mann-Whitney U test, depending on the metric.
A/B testing compares performance; it does not generate test cases.
Back-to-back testing
Back-to-back testing runs the system and an alternative version of it on the same inputs and compares the outputs. The alternative is a pseudo-oracle: it does not know the right answer, but where the two disagree, at least one is wrong. Only inputs are needed, no expected results.
- Pseudo-oracle options: a version built by another team, with another framework, another algorithm or other settings, or even conventional software that solves the same problem. It only needs to match the functional behaviour; it may be slow.
- Independence: ideally the pseudo-oracle shares no components with the system under test. Shared components (the same open-source library, the same training data) can make both wrong in the same way, and then they agree on the wrong answer.
- Inputs: a regression test suite, or inputs generated from the training data.
- Uses: migration (development to production, an old framework to a new one), comparison across environments, and finding subtle defects in edge cases.
A/B versus back-to-back: A/B compares two variants with performance metrics and statistics to choose the better one. Back-to-back finds defects by comparing outputs one by one.
Hands-on: v1 versus v2
The practice model has two versions. Version 2 was built to remove gender and name from the decision. Compare them on the 40 test applicants. You continue in the practice project; create module-7/test_ab_and_back_to_back.py:
"""Lesson "A/B testing and back-to-back testing": compare model v2 with v1."""
import numpy as np
import pytest
from scipy import stats
APPLICANT_FIELDS = ["name", "gender", "age", "income", "creditScore", "employmentYears", "zipCode"]
@pytest.fixture(scope="module")
def results(api):
rows = api.get(f"{api.base}/test-set", timeout=10).json()["data"]
applicants = [{f: r[f] for f in APPLICANT_FIELDS} for r in rows]
def run(model):
response = api.post(f"{api.base}/predict/batch", timeout=10,
json={"applicants": applicants, "model": model, "seed": 1})
response.raise_for_status()
return np.array([p["approved"] for p in response.json()["predictions"]])
return rows, run("v1"), run("v2"), np.array([r["repaid"] for r in rows])
def test_back_to_back_differences(results):
"""Back-to-back: same inputs, compare outputs. No expected results needed; every difference is investigated."""
rows, v1, v2, _ = results
different = [rows[i] for i in np.flatnonzero(v1 != v2)]
for r in different:
print(f"\n id {r['id']:2}: v1 {'approve' if v1[r['id'] - 1] else 'reject '} v2 {'approve' if v2[r['id'] - 1] else 'reject '}"
f" {r['gender']:6} zip {r['zipCode']} employed {r['employmentYears']:2} yrs", end="")
assert [r["id"] for r in different] == [2, 3, 24, 29, 36]
def metrics(approved, repaid):
tp, fp = (approved & repaid).sum(), (approved & ~repaid).sum()
fn, tn = (~approved & repaid).sum(), (~approved & ~repaid).sum()
return {"accuracy": (tp + tn) / len(repaid), "precision": tp / (tp + fp), "recall": tp / (tp + fn)}
def test_a_b_comparison_on_the_acceptance_criteria(results):
"""A/B: compare both variants on the agreed metrics. v2 must be at least as good as v1."""
_, v1, v2, repaid = results
m1, m2 = metrics(v1, repaid), metrics(v2, repaid)
print("\n " + " ".join(f"{k} v1 {m1[k]:.3f} v2 {m2[k]:.3f}" for k in m1))
with pytest.raises(AssertionError): # v2 is worse on every metric: it may not replace v1 as is
assert all(m2[k] >= m1[k] for k in m1)
def test_is_the_difference_significant(results):
"""McNemar's test on the cases where exactly one model is right."""
_, v1, v2, repaid = results
only_v1, only_v2 = ((v1 == repaid) & (v2 != repaid)).sum(), ((v2 == repaid) & (v1 != repaid)).sum()
p_value = stats.binomtest(int(min(only_v1, only_v2)), int(only_v1 + only_v2), 0.5).pvalue
print(f"\n only v1 right: {only_v1}, only v2 right: {only_v2}, p = {p_value:.3f}")
assert p_value > 0.05 # on 40 cases the difference is not significant
The significance test is McNemar’s test: when two models are evaluated on the same cases, only the cases where they disagree about correctness carry information. If v2 were no better or worse than v1, those cases would split 50/50 between “only v1 right” and “only v2 right”. binomtest checks how unlikely the observed split is.
Run it
pytest module-7/test_ab_and_back_to_back.py -v -s
id 2: v1 reject v2 approve Female zip 10002 employed 3 yrs
id 3: v1 approve v2 reject Male zip 10001 employed 7 yrs
id 24: v1 reject v2 approve Female zip 90210 employed 5 yrs
id 29: v1 approve v2 reject Male zip 10001 employed 13 yrs
id 36: v1 reject v2 approve Female zip 30301 employed 12 yrs
PASSED
accuracy v1 0.775 v2 0.700 precision v1 0.812 v2 0.706 recall v1 0.684 v2 0.632
PASSED
only v1 right: 4, only v2 right: 1, p = 0.375
PASSED
Read the result
Back-to-back found five differences, and every one is explained by a change between the versions:
- Ids 2, 24 and 36 are women. v1 penalised their gender and rejected them; v2 approves them. For id 2 (who repaid) v2 is right. Ids 24 and 36 did not repay (incomes of $44,000 and $40,000): v1 rejected them, but for the wrong reason, their gender. v2 removed the bias and with it a “lucky” correct answer.
- Ids 3 and 29 live in zip 10001 and have 7 and 13 years of employment. v2 penalises that zip code more heavily and ignores employment history (the regression documented in the practice API). Both repaid; v2 rejects them wrongly.
A/B on the acceptance criteria: v2 is worse on accuracy, precision and recall. By the rule “the new variant must be at least as good”, v2 may not replace v1 as it is.
But is the difference real? Of the five disagreements, v1 was right in 4, v2 in 1. With so few cases, a 4-1 split happens by chance 37.5% of the time (p = 0.375). On this test set the two versions are not significantly different in accuracy. A proper A/B test needs far more cases, or live traffic over time.
What the tester reports: v2 fixes the gender bias, introduces a stronger zip-code penalty and ignores employment history; it is not demonstrably better or worse in accuracy on 40 cases; it should not be released until the zip code and employment regressions are fixed and the A/B comparison is repeated on a larger set.
Exercise
- For back-to-back testing of a new fraud model, a team proposes as the pseudo-oracle “the same model, retrained by the same team with the same pipeline on next month’s data”. What is the weakness of this pseudo-oracle?
- An online shop shows recommendation model A to 50% of visitors and model B to the other 50% for two weeks, and measures the click-through rate. Is this A/B or back-to-back testing? Which statistical test fits?
Show suggested answer
- It is not independent: same team, same pipeline, same features and same framework. A defect in the pipeline or a shared misconception would be in both versions, and they would agree on the wrong answer. A better pseudo-oracle: a model built by another team with another algorithm, or the existing rule-based fraud checks.
- A/B testing: two variants compared on a performance metric with statistics, not output by output. Click-through rate is a proportion, so a z-test for two proportions or a chi-squared test fits.
Exam-style questions
1. What is the main difference between A/B testing and back-to-back testing?
- A. A/B testing compares two variants statistically on performance metrics; back-to-back testing compares outputs on the same inputs to detect defects
- B. A/B testing needs expected results; back-to-back testing does not
- C. Back-to-back testing is only for conventional software
- D. There is no difference
Show answer
2. Why should a pseudo-oracle ideally share no components with the system under test?
- A. To make the tests run faster
- B. Shared components could cause both to fail in the same way, hiding the defect
- C. Because pseudo-oracles must be conventional software
- D. Shared components are not allowed by the syllabus
Show answer
3. A self-learning system changes its own behaviour. How is A/B testing used for such a system?
- A. It is not possible
- B. After each change, automated tests compare the new behaviour with the old; the change is kept only if the system improves, otherwise it is reverted
- C. Only the first version is tested
- D. Users decide manually which version to keep
Show answer
Your project so far
ai-testing-practice/
├── ...
└── module-7/
├── test_functional_performance.py
├── test_adversarial.py
├── test_metamorphic.py
├── test_drift.py
├── test_fitting.py
└── test_ab_and_back_to_back.py new in this lesson
The finished version is in the example repository: module-7/test_ab_and_back_to_back.py.