Lesson 11 of 117 min
A/B tests and p-values
A p-value says how often luck alone would give a result as big as yours if nothing were going on: rare means there is something to see, and common means you can't tell yet.
After this lesson you can decide whether a difference is real or noise.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Report the gap and its bar
Run the cells in order. The American Statistical Association asks readers to look beyond the p-value. On the same 200 questions, B won 18 and A won 10. Report the four-point gap and the range from a paired bootstrap alongside the p-value.
import numpy as np
from scipy import stats
d = np.repeat([0, -1, 1, 0], [150, 10, 18, 22])
bar = stats.bootstrap((d,), np.mean, method="percentile",
rng=np.random.default_rng(0)).confidence_interval
print(f"Gap {100 * d.mean():+.1f} points")
print(f"95% bar: {100 * bar.low:+.1f} to {100 * bar.high:+.1f} points")Gap +4.0 points 95% bar: -1.0 to +9.5 points
Pick one side or both
A two-sided test counts gaps at least this large in either direction. alternative="greater" counts results where B wins at least this often. Choose your direction before seeing the scores. These calls approximate the probabilities by shuffling which model gets credit on each question.
a, b = (d == -1), (d == 1)
for side in ("two-sided", "greater"):
result = stats.permutation_test(
(a, b), lambda a, b: b.mean() - a.mean(),
permutation_type="samples", alternative=side,
rng=np.random.default_rng(0))
print(f"{side}: p = {result.pvalue:.3f}")two-sided: p = 0.194 greater: p = 0.097
Count the 28 tosses exactly
Only the 28 disagreements can change the gap when you swap labels. Under equal win chances and independent questions, B's wins among those disagreements follow a fair binomial. binomtest finds the exact p-value of this paired test, the exact form of McNemar's test.
different = np.count_nonzero(d)
b_wins = np.count_nonzero(d > 0)
exact = stats.binomtest(b_wins, different, p=0.5)
print(f"B won {b_wins} of {different}, p = {exact.pvalue:.4f}")B won 18 of 28, p = 0.1849
Set the cutoff before the test
A cutoff of 0.05 is a convention. If you set it in advance, a valid test limits false positives under its null to about one in twenty or less. A tighter cutoff can make sense when a false positive would cost more. Report the p-value and your chosen cutoff.
p_value = stats.binomtest(20, different, p=0.5).pvalue
for cutoff in (0.05, 0.01):
passes = p_value < cutoff
print(f"p = {p_value:.3f} crosses cutoff {cutoff:.2f}: {passes}")p = 0.036 crosses cutoff 0.05: True p = 0.036 crosses cutoff 0.01: False
Plan how often to look
Repeated looks give luck more chances. Below, each trial has 20 chances to stop under a true null and uses a valid fixed-look p-value at each day. One simple planned rule divides 0.05 across the 20 looks. Sequential tests can also be built for continuous monitoring.
rng = np.random.default_rng(0)
wins = rng.binomial(10, 0.5, size=(10_000, 20)).cumsum(axis=1)
count = np.arange(1, 21) * 10
p = np.minimum(1, 2 * stats.binom.cdf(np.minimum(wins, count - wins), count, 0.5))
print(f"Last day only: {(p[:, -1] < 0.05).mean():.1%}")
print(f"Any day at 0.05: {(p.min(axis=1) < 0.05).mean():.1%}")
print(f"Any day at 0.05 / 20: {(p.min(axis=1) < 0.05 / 20).mean():.1%}")Last day only: 4.1% Any day at 0.05: 19.6% Any day at 0.05 / 20: 1.4%
Run on Python 3.13.3, NumPy 2.5.5 and SciPy 1.18.1. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Confidence intervals and the bootstrap
You build a model whose true score you know. You give it 200 tests, and put a 95% error bar on each score with the bootstrap. About how many of the 200 bars miss the true score?
2 of 3
In an A/B test of two prompts, prompt B gets more thumbs-up. The p-value is 0.03. What does 0.03 mean?
3 of 3
Two models answered the same questions. You shuffle 10,000 times. In 620 of the shuffles, the gap is at least as big as the real one, either way. What is the p-value?
The ideas in this lesson
- Null hypothesis
- The idea that nothing is going on, like two models being equally good: the world a test compares your result with.
- p-value
- If nothing were going on, how often luck alone would give a result at least as big as yours. Under 0.05 is called significant.
- A/B test
- Show each user version A or B at random, then ask how often luck would make a gap this big. Decide the size first, look once.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Better, or lucky?
Here's a bet. Two AI models take the same test. One scores a bit higher. Is it really better, or just lucky? People check with one number, the p-value. And most people read it wrong. So what does it really tell you?
Your guess
Here are two models on the same two hundred questions. Model B got a hundred and sixty-eight right: eighty-four percent. Model A got a hundred and sixty: eighty percent. So B leads by four points, and a test of that gap gives a p-value of zero point one nine. What does that mean?
One: there's a nineteen percent chance that B isn't really better.
Two: there's a nineteen percent chance the gap is just luck.
Three: if the two were equally good, luck alone would give a gap this big nineteen times in a hundred. Which one is right?
Where they differ
So where does B's lead come from?
Look at each question. When both models got it right, or both got it wrong, it's a tie. A tie can't show which one is better. They tie on a hundred and seventy-two questions. That leaves twenty-eight where they differ.
B is right on eighteen of them, and A on ten.
Nothing going on
Now suppose the two models are equally good.
That idea, that nothing is going on, is called the null hypothesis.
If the null hypothesis is true, each model is just as likely to win any question where they differ.
So each of the twenty-eight is like a coin toss: heads or tails, each half the time.
Nobody tosses a real coin. The computer does it for us.
One shuffle
If two models were equally good, each question where they differ would be like a coin toss. So toss twenty-eight coins. Heads, B wins the question. Tails, A wins it.
This time B wins fifteen, and A wins thirteen. That's two questions out of two hundred: a gap of one point.
One set of tosses like this is called a shuffle. How often will luck alone give a gap of four points or more, either way?
The p-value
Shuffle ten thousand times. The gaps pile up around zero, as they should when nothing is going on.
Now mark the real gap, four points, on both sides: A ahead by four would be just as far from "equal".
Luck reached it about nineteen times in a hundred.
That share is called the p-value. Here, it's zero point one nine.
Reading it
So which reading was right?
The third one. If the two were equally good, luck would make a gap this big about one time in five. That's common, so there's no reason to call B better. When the p-value is under zero point zero five, one time in twenty, people call a result significant.
Two wrong readings
And readings one and two?
Both wrong.
The nineteen percent was counted in a world where the two models are equal. So it can't be the chance that they are equal.
The American Statistical Association warned about exactly these two readings.
Not significant
So are the two models equally good?
We can't say that either.
Draw the same questions again, at random, many times, and the gap gets its own error bar. It runs from minus one, where A is one point ahead, to plus nine and a half, where B is far ahead. So B might be much better. Not significant just means this test can't tell yet.
An A/B test
Companies test their products the same way. Say a chatbot gets a new reply. Each user is shown the old one, version A, or the new one, version B, at random.
Then you compare the share of users who give a thumbs up. To get the p-value, shuffle which user saw which, many times. That's an A/B test. Here's one after twenty days, with two thousand users each. A hundred and ninety-six thumbs up, against two hundred and eleven. The p-value is zero point four six: not significant. And that's right, because here version B is an exact copy of version A.
Peeking
But what if the team looked every day? On day four, the p-value fell to about zero point zero two. Significant! A team that peeks stops right there, calls B better, and switches to it. Each look is one more chance for luck to fall under the line. So how often does that happen? Run a thousand tests where B is a copy of A. Checked every day, about two hundred of them call B better at some point. Checked once, at the end, about forty. So decide how many users you need first, and look once, at the end.
In code
Now in real code.
Here are the two models' results, ones and zeros, question by question.
SciPy's permutation test takes the results, and a small function that works out the gap.
"Samples" tells it to swap each question's two results at random, about ten thousand times. What will it print?
Zero point one nine: our p-value.
And one more SciPy line works out the twenty-eight coin tosses exactly, with no shuffling: zero point one eight five. The shuffles came close. Leave out "samples", and it deals the users out again at random: the shuffle of an A/B test.
How often would luck do it?
So suppose nothing's going on: that's the null hypothesis. The p-value is how often luck alone would give a result this big. If that's rare, there may be something real. If it's common, you can't tell yet. And in an A/B test, decide how many users you need first, and look once.
The lab
That's the end of this unit. In its lab, you use these two lessons to run an A/B test of two prompts, and to read it right.
How often would luck do it?
A p-value says how often luck would make this gap. Now try it on this lesson's page, and take the quiz. Find out how many questions B must win to be significant.
You use this lesson in Lab 4: An A/B test of two prompts, which comes next.
Facts last checked on .
