ML fundamentals19 / 22

Lesson 19 · In practice

A/B testing

The problem

The pizza shop has bought a new oven. The seller says it bakes faster, so more pizzas should arrive on time. With the old oven, about 80% of deliveries are on time.

To check, the shop runs both ovens side by side for 20 evenings. Each order goes to one oven or the other, by the toss of a coin. After 20 evenings each oven has baked 1,000 orders:

OvenOrdersOn timeOn-time rate
Old (A)1,00080080%
New (B)1,00082082%

The new oven is 2 percentage points ahead. (A percentage point is the gap between two percentages: 82% − 80% = 2 points.)

Predict first

Old oven: 80% on time. New oven: 82%. 1,000 orders each. Is that convincing evidence that the new oven is better?

This lesson builds the tools to answer "is this real?" with numbers. They are the standard tools of every online experiment, and the same tools test whether a new model beats an old one.

Splitting at random

The shop could have compared last month (old oven) with this month (new oven). But this month might have had better weather, or fewer new drivers. Any gap could come from those, not the oven.

Tossing a coin for every order fixes this. Rain, traffic and new drivers then land on both ovens about equally. The only thing that differs, on average, is the oven.

Send each customer at random to the old version (A) or a new version (B). Then compare a number between the two groups. This experiment is an A/B test. The old version is often called the control, and the new one the treatment. The number you compare, here the on-time rate, is the metric.

The random split is what lets you say the oven caused the change. Without it, you only know the two went together.

DigressionWhy randomise? When the evenings choose the ovenLet staff pick the oven, and the new one looks better for the wrong reason. · 2 min

Suppose the shop lets staff choose. On quiet evenings, they try the new oven. On busy evenings, they stick with the old one they know.

Quiet evenings have fewer orders, less traffic and fewer late pizzas anyway. So the new oven's evenings would look better even if the oven made no difference at all. Business levels drive both which oven is used and how many pizzas are late.

A third thing that affects both the choice and the result is called a confounder. A coin toss can't be influenced by how busy the evening is, so it breaks the link. The Causal inference course is about what to do when you can't randomise, and have to work from data like this.

How big is luck?

To see what luck alone does, pretend both ovens are the same: each gets every order on time with chance 0.8. Then run the whole 20-evening test again, and again, and record the gap each time. A test where both groups get the same version is called an A/A test.

−8−6−4−2024681001020304050new − old on-time rate (points)runstrue 0observed 2

300 runs. 74 (24.7%) were at least as far from 0 as ±2 points.

Each run is a fresh oven test with 1,000 orders per oven. The z-test called 18 of 300 runs significant (p-value below 0.05).

The oven test repeated many times, with 1,000 orders per oven. Each run's gap (new − old) goes in the histogram. Bars as far from 0 as the real gap, 2 points, are shaded. Switch to a world where the new oven is 2 points better.

Things to notice:

  • With no real difference, the gaps form a bell around 0. Most runs land within about 3.5 points either way.
  • A gap of 2 points or more is common. About a quarter of runs are at least 2 points from 0, in one direction or the other.
  • When the new oven is 2 points better, the bell moves to 2. But it's the same width. Many of those runs show a gap under 1 point, and some even show the old oven ahead.

So the real result, 2 points, sits comfortably inside what luck produces. The rest of this lesson turns that picture into numbers you can compute without running thousands of simulations.

The standard error

How wide is that bell? Start with one oven. Each order is a yes/no outcome: on time with chance pp. That's a Bernoulli variable, with variance p(1−p)p(1 - p).

The on-time rate is the sample mean of nn such outcomes. As the Maths toolkit showed, the spread of a sample mean shrinks like 1/n1/\sqrt{n}:

spread of the rate=p(1−p)n.\text{spread of the rate} = \sqrt{\frac{p(1-p)}{n}}.

The spread of an estimate from one sample to the next, measured as its standard deviation, is its standard error. It says how far the estimate typically lands from the truth.

Worked example

Standard error of the gap, 1,000 orders each

  1. Old oven: p=0.8p = 0.8, so p(1−p)=0.8×0.2=0.16p(1 - p) = 0.8 \times 0.2 = 0.16. Its standard error is 0.16/1000=0.0126\sqrt{0.16 / 1000} = 0.0126: about 1.26 points.

In symbols, for two groups of nAn_A and nBn_B orders:

SE(p^B−p^A)=p^A(1−p^A)nA+p^B(1−p^B)nB.\text{SE}(\hat p_B - \hat p_A) = \sqrt{\frac{\hat p_A(1-\hat p_A)}{n_A} + \frac{\hat p_B(1-\hat p_B)}{n_B}}.

Here p^A\hat p_A and p^B\hat p_B (read "p-hat") are the rates you measured, 0.80 and 0.82. The hat means "estimated from data".

Why a bell? Each rate is an average of many independent outcomes. The central limit theorem says such an average is close to a normal distribution. So is the gap between two of them. With 1,000 orders each, the normal fits well, as the histogram shows.

Hypothesis tests and p-values

Now ask the question carefully. Suppose the ovens were the same. How surprising would a 2-point gap be?

That's a hypothesis test. The "no difference" assumption is called the null hypothesis. You don't believe it. You use it to measure how much luck could explain.

If the ovens were the same, both would share one on-time rate. The best guess of it pools both ovens: (800+820)/2000=0.81(800 + 820) / 2000 = 0.81. With that rate, the standard error of the gap is

0.81×0.19×(11000+11000)=0.01754,\sqrt{0.81 \times 0.19 \times \left(\tfrac{1}{1000} + \tfrac{1}{1000}\right)} = 0.01754,

about 1.75 points again. Now measure the gap in standard errors. This is the z-score:

z=p^B−p^ASE=0.020.01754=1.14.z = \frac{\hat p_B - \hat p_A}{\text{SE}} = \frac{0.02}{0.01754} = 1.14.

The gap is 1.14 standard errors from 0. How often does luck do that or more? Under a standard normal, the area beyond 1.14 on the right is 0.127. The area beyond −1.14 on the left is the same. Together they are 0.254.

That's the p-value. If there were no real difference, it's the chance of a gap at least as big as the one you saw, in either direction. For the oven, it's 0.25.

−6−4−20246difference new − old, if the ovens are the same (points)observed

Standard error 1.75 points. The gap is 1.14 standard errors from 0. p-value (shaded area) = 0.254: not below 0.05.

If the ovens were the same, the gap would follow this bell, centred on 0, with spread equal to the standard error. The p-value is the shaded area beyond the observed gap, on both sides. Slide the gap; switch to 4,000 orders per oven.

Things to notice:

  • At 2 points and 1,000 orders each, a quarter of the area is shaded. It's the same share as the shaded bars in the histogram above. The formula and the simulation agree.
  • The shaded area shrinks fast as the gap grows. At 3.5 points it's about 0.05; at 5 points it's under 0.005.
  • With 4,000 orders each, the bell is half as wide. The same 2-point gap is now 2.3 standard errors out, and its p-value drops to about 0.02.

Why count both tails? Before the test, the shop would have cared about a worse new oven too. A test that counts both directions is called two-sided. It's the usual choice.

Deciding

A small p-value means: if there were no difference, data like these would be rare. So you start to doubt "no difference". The usual rule is to call a result significant when p<0.05p < 0.05. The cut-off, 0.05, is the significance level, written α\alpha.

The oven's p-value, 0.25, is far above 0.05. So the test is not significant. That doesn't mean the ovens are the same. It means 1,000 orders each can't tell a 2-point gain from luck.

Why 0.05? It's a convention, not a law. It means that when there is no real difference, you'll wrongly call a difference 5% of the time. A wrong "significant" is a false positive, or false alarm. Medicine and physics often ask for much smaller p-values.

Predict first

The oven test's p-value is 0.25. What does that mean?

Confidence intervals

A p-value answers a yes/no question. Often you'd rather know: how big could the real gain be?

Take the measured gap and go about two standard errors either way. For 95%, the multiplier is 1.96, because 95% of a normal's area lies within 1.96 standard deviations of its centre:

gap±1.96×SE=2±1.96×1.75=2±3.4 points.\text{gap} \pm 1.96 \times \text{SE} = 2 \pm 1.96 \times 1.75 = 2 \pm 3.4 \text{ points}.

So the range is −1.4 to 5.4 points. This is a 95% confidence interval for the gap.

Read it as: the data fit anything from the new oven being 1.4 points worse to 5.4 points better. That range includes 0, so "no difference" is still possible. It also includes 5 points, which would be a big win. The test hasn't found out much yet.

What does "95%" mean? The true gap is a fixed number; it doesn't move. The interval is what moves: each new run of the experiment gives a different one. The method is built so that 95% of those intervals contain the true gap.

−6−4−20246810new − old on-time rate (points)true 2

Each interval is about ±3.4 points. 20 of 20 contain the true 2 points; 4 leave out 0.

Twenty runs of the oven test when the new oven truly is 2 points better. Each line is one run's 95% interval; the dot is its measured gap. Intervals that miss the true value are marked. Try more orders, or 20 new runs.

Things to notice:

  • Every run's interval is in a different place. The dashed line, the truth, stays put.
  • Most intervals cross the dashed line. Over many batches, about 19 in 20 do. The occasional miss is the 5%.
  • At 1,000 orders each, most intervals also include 0. So most runs would not be significant, even though the new oven is better.
  • 4 times the orders halves the width. At 4,000 each, the interval is about ±1.7 points. At 16,000, about ±0.86. The width shrinks like 1/n1/\sqrt{n}.

The interval and the test agree. An interval that leaves out 0 goes with a p-value below 0.05, almost always. They can disagree right at the edge, because the test uses the pooled standard error. The interval also tells you how big the gap could be.

Power: how many orders do you need?

The new oven might be 2 points better and still fail the test, as the intervals showed. The chance that an experiment comes out significant when a real effect of a given size is there is its statistical power.

Look back at the histogram's second tab. The bell is centred on 2, and a run is significant only when its gap is more than 3.4 points from 0. Most of the bell is short of that. With 1,000 orders each, the power to detect a 2-point gain is only about 21%.

05k10k15k0%20%40%60%80%100%orders per ovenpower6,03621%

With 1,000 orders per oven, a real 2-point improvement comes out significant 21% of the time.

Power: the chance of a significant result when the new oven is 2 points better, against orders per oven. The dashed lines mark 80% power.

The usual target is 80% power. You work out the number of orders before the experiment starts. The formula asks for two numbers from the normal distribution: 1.96 (for the 5% significance level, two-sided) and 0.84 (for 80% power).

Worked example

Orders per oven to detect 80% → 82% with 80% power

  1. Add the two normal numbers and square: (1.960+0.842)2=2.8022≈7.85(1.960 + 0.842)^2 = 2.802^2 \approx 7.85.

n=(z1−α/2+zpower)2 (pA(1−pA)+pB(1−pB))(pB−pA)2n = \frac{(z_{1-\alpha/2} + z_{\text{power}})^2 \, \big(p_A(1-p_A) + p_B(1-p_B)\big)}{(p_B - p_A)^2}

Read it back. The top grows with how sure you want to be (α\alpha and power) and how noisy each order is. The bottom is the gap you're looking for, squared. The square is the expensive part.

Predict first

The shop now wants to detect a 1-point gain (80% → 81%) instead of 2 points. Roughly how many orders per oven does it need?

Don't stop when it looks good

Here's the shop's real test, checked after every evening. The manager looks at the running totals and works out the p-value each time.

The real oven test

24681012141618200.00.20.40.60.81.0eveningp-value so far0.05

Below 0.05 (■) first on evening 1. A manager who stops there declares a winner. After all 20 evenings: 0.25.

The p-value of the running totals after each evening. Squares are below 0.05. Start with the real oven test, then simulate A/A tests, where the ovens are the same.

After the first evening, the new oven was 18 points ahead, with a p-value of 0.03. It stayed below 0.05 for four evenings. A manager who stopped the moment the result was "significant" would have bought new ovens for every branch. By evening 20, the gap had settled to 2 points, with a p-value of 0.25.

Things to notice in the A/A tests:

  • The p-value wanders. With no real difference, it drifts up and down from evening to evening.
  • Each single check is wrong only 5% of the time. But a wandering path gets 20 chances to dip below 0.05.
  • About a quarter of A/A tests dip below 0.05 on some evening. Only about 5% are below it at the end.

Checking the results as they come in, and stopping as soon as they look significant, is called peeking. It turns a 5% false-alarm rate into something like 25%.

The fix is to decide the number of orders in advance, from the power calculation, and judge the test once at the end. You can still look at the data along the way, to catch bugs and disasters. But don't stop early for a "win". There are also sequential tests, designed to be checked often; they pay for it with wider margins.

DigressionMany metrics, many testsTest 20 things at the 5% level, and one will probably look like a win. · 2 min

The shop measures more than on-time rate. It also tracks complaints, tips, repeat orders, average delivery time, and so on. Say it checks 20 metrics, and the new oven changes none of them.

Each test has a 5% chance of a false alarm. The chance that all 20 stay quiet is 0.9520=0.360.95^{20} = 0.36. So there's a 64% chance that at least one metric "improves significantly", by luck.

This is the multiple comparisons problem. It's the same trap as peeking: many chances to see a fluke. Two common defences:

  • Pick one main metric before the test, and treat the rest as clues to follow up, not as results.
  • Ask for a smaller p-value when you test many things. The simplest rule, the Bonferroni correction, divides 0.05 by the number of tests: 0.05/20=0.00250.05 / 20 = 0.0025 each.

In Python

The oven data comes from the shared pizza datasets:

The oven test
oven = load("oven-test")
old = np.array(oven["old"])  # 1 = on time, one entry per order
new = np.array(oven["new"])
n_a, n_b = len(old), len(new)
s_a, s_b = int(old.sum()), int(new.sum())
print(f"old oven: {s_a} of {n_a} on time ({s_a / n_a:.1%})")  # 800 of 1000 (80.0%)
print(f"new oven: {s_b} of {n_b} on time ({s_b / n_b:.1%})")  # 820 of 1000 (82.0%)

The z-test needs the normal distribution's area to the left of a point (its CDF). Python's standard library has math.erf, which gives it in one line:

The z-test by hand
def normal_cdf(z: float) -> float:
    """P(Z <= z) for a standard normal Z."""
    return 0.5 * (1 + math.erf(z / math.sqrt(2)))


def z_test(s_a: int, n_a: int, s_b: int, n_b: int) -> tuple[float, float, float]:
    """Two-sided z-test for 'rate B differs from rate A'. Returns (difference, z, p-value)."""
    p_a, p_b = s_a / n_a, s_b / n_b
    pooled = (s_a + s_b) / (n_a + n_b)  # the one rate both ovens share if there's no difference
    se = math.sqrt(pooled * (1 - pooled) * (1 / n_a + 1 / n_b))
    z = (p_b - p_a) / se
    p_value = 2 * (1 - normal_cdf(abs(z)))  # both tails: a gap this big either way
    return p_b - p_a, z, p_value


diff, z, p_value = z_test(s_a, n_a, s_b, n_b)
print(f"difference {diff:+.3f}, z = {z:.2f}, p-value = {p_value:.3f}")  # +0.020, z = 1.14, p = 0.254
difference +0.020, z = 1.14, p-value = 0.254

The interval needs the other direction: the point with 97.5% of the area to its left, which is 1.96. statistics.NormalDist().inv_cdf gives it:

The 95% interval
def confidence_interval(s_a: int, n_a: int, s_b: int, n_b: int, level: float = 0.95) -> tuple[float, float]:
    """Interval for p_B - p_A: the difference plus or minus z* standard errors."""
    p_a, p_b = s_a / n_a, s_b / n_b
    se = math.sqrt(p_a * (1 - p_a) / n_a + p_b * (1 - p_b) / n_b)
    z_star = NormalDist().inv_cdf(1 - (1 - level) / 2)  # 1.96 for 95%
    return p_b - p_a - z_star * se, p_b - p_a + z_star * se


lo, hi = confidence_interval(s_a, n_a, s_b, n_b)
print(f"95% interval for the difference: {lo:+.3f} to {hi:+.3f}")  # -0.014 to +0.054
95% interval for the difference: -0.014 to +0.054

Power and sample size follow the formulas above:

Power and sample size
def sample_size_per_arm(p_a: float, p_b: float, power: float = 0.8, alpha: float = 0.05) -> int:
    """Orders per arm for the two-sided test at level alpha to catch a true change with this power."""
    z = NormalDist().inv_cdf(1 - alpha / 2) + NormalDist().inv_cdf(power)  # 1.96 + 0.84
    return math.ceil(z**2 * (p_a * (1 - p_a) + p_b * (1 - p_b)) / (p_b - p_a) ** 2)


def power(p_a: float, p_b: float, n: int, alpha: float = 0.05) -> float:
    """Chance the test comes out significant when the true rates are p_a and p_b."""
    se = math.sqrt((p_a * (1 - p_a) + p_b * (1 - p_b)) / n)
    z_crit = NormalDist().inv_cdf(1 - alpha / 2)
    shift = abs(p_b - p_a) / se
    return normal_cdf(shift - z_crit) + normal_cdf(-shift - z_crit)


print(f"power at 1,000 per arm: {power(0.80, 0.82, 1000):.0%}")  # 21%
print(f"orders per arm for 80% power: {sample_size_per_arm(0.80, 0.82):,}")  # 6,036
power at 1,000 per arm: 21%
orders per arm for 80% power: 6,036

The simulation draws each run's on-time count straight from the binomial distribution (the number of successes in nn independent yes/no tries). NumPy draws 10,000 runs at once:

Simulating many experiments
rng = np.random.default_rng(0)


def simulate(p_a: float, p_b: float, n: int, runs: int) -> tuple[np.ndarray, np.ndarray]:
    """Run the experiment `runs` times. Returns each run's difference and p-value."""
    s_a = rng.binomial(n, p_a, size=runs)  # on-time orders with oven A, one count per run
    s_b = rng.binomial(n, p_b, size=runs)
    pooled = (s_a + s_b) / (2 * n)
    se = np.sqrt(pooled * (1 - pooled) * 2 / n)
    z = (s_b - s_a) / n / se
    p_values = 2 * (1 - 0.5 * (1 + np.vectorize(math.erf)(np.abs(z) / math.sqrt(2))))
    return (s_b - s_a) / n, p_values


aa_diff, aa_p = simulate(0.80, 0.80, n=1000, runs=10_000)  # A/A: no real difference
print(f"A/A runs with a gap of 2 points or more: {np.mean(np.abs(aa_diff) >= 0.02):.1%}")  # about 27%
print(f"A/A runs called significant: {np.mean(aa_p < 0.05):.1%}")  # about 5%

ab_diff, ab_p = simulate(0.80, 0.82, n=1000, runs=10_000)  # the new oven really is 2 points better
print(f"A/B runs called significant (power): {np.mean(ab_p < 0.05):.1%}")  # about 21%
A/A runs with a gap of 2 points or more: 27.0%
A/A runs called significant: 4.8%
A/B runs called significant (power): 20.5%

The 27% is a little above the p-value of 25%, because on-time counts are whole numbers. A gap of exactly 2 points has a real chance of happening, and the bell curve smooths that over. The other two match the 5% significance level and the 21% power.

Peeking, with running totals from cumsum:

Checking after every evening
def peeking_false_alarms(looks: int, per_look: int = 50, runs: int = 2_000) -> float:
    """A/A tests checked after every evening: the share that look significant at least once."""
    s_a = rng.binomial(per_look, 0.8, size=(runs, looks)).cumsum(axis=1)  # running totals
    s_b = rng.binomial(per_look, 0.8, size=(runs, looks)).cumsum(axis=1)
    n = per_look * np.arange(1, looks + 1)  # orders per arm after each evening
    pooled = (s_a + s_b) / (2 * n)
    se = np.sqrt(pooled * (1 - pooled) * 2 / n)
    z = np.abs(s_b - s_a) / n / se
    ever = (z > NormalDist().inv_cdf(0.975)).any(axis=1)
    return float(ever.mean())


for looks in [1, 5, 20]:
    print(f"checking {looks:2d} times: {peeking_false_alarms(looks):.0%} false alarms")  # 5%, about 14%, about 24%
checking  1 times: 5% false alarms
checking  5 times: 14% false alarms
checking 20 times: 24% false alarms

In practice you'd use a library. statsmodels has proportions_ztest, confint_proportions_2indep and power calculators. We wrote the formulas out to see what each one does, and to avoid adding a library for one lesson.

Putting it together

What should the pizza shop do with its oven test?

  1. Randomise. Toss a coin for each order, so nothing but the oven differs on average.
  2. Decide the size first. For 80% power to detect a 2-point gain, it needs 6,036 orders per oven. That's about 121 evenings.
  3. Run it to the end. Look along the way only for bugs. Don't stop on a good evening.
  4. Report the interval, not only the p-value. After 1,000 orders each: a gap of 2 points, 95% interval −1.4 to 5.4, p = 0.25. That's "we don't know yet", not "the oven doesn't work".

The same steps judge a new model. A model with a better validation score still has to prove itself on real customers. The lesson on evaluation you can trust comes back to this.

Common misconceptions

"The p-value is the chance that there's no real difference." It's the chance of a gap this big if there were no difference. The oven's p = 0.25 does not mean a 25% chance that the ovens are the same.

"Not significant means no effect." It means the test couldn't tell. The oven's interval runs from −1.4 to 5.4 points: a 5-point gain is still possible. With 21% power, missing a real 2-point gain is the likely outcome.

"There's a 95% chance the true gap is in this interval." The 95% belongs to the method. Over many experiments, 95% of intervals contain the truth. Any one interval either does or doesn't.

"You can stop as soon as the result is significant." Stopping at the first significant evening raised false alarms from 5% to about 25%. The real oven test looked significant for its first four evenings.

"Significant means important." With enough orders, a 0.1-point gain becomes significant. Whether it's worth a new oven is a business question. Look at the size of the gap and its interval.

"Twice the data, half the uncertainty." The standard error shrinks like 1/n1/\sqrt{n}. Halving the interval takes 4 times the orders.

Recap

  • An A/B test sends each customer at random to the old or the new version, so the version is the only systematic difference.
  • The standard error is the typical size of an estimate's luck. For the gap between two rates it's pA(1−pA)/nA+pB(1−pB)/nB\sqrt{p_A(1-p_A)/n_A + p_B(1-p_B)/n_B}: 1.75 points for the oven test.
  • A hypothesis test assumes no difference and asks how surprising the data are. The p-value is the chance of a gap at least this big if there were no difference: 0.25 for the oven.
  • A 95% confidence interval is the gap ± 1.96 standard errors. Over many experiments, 95% of such intervals contain the true gap. Its width shrinks like 1/n1/\sqrt{n}.
  • Power is the chance of detecting a real effect. Decide the sample size from it before you start: 6,036 orders per oven for a 2-point gain with 80% power.
  • Peeking and testing many metrics both give luck extra chances, and inflate false alarms.
  • Python names in this lesson: math.erf, statistics.NormalDist().inv_cdf, NumPy's default_rng, rng.binomial and cumsum; statsmodels has the ready-made versions.