SchoolWhool
Quizzes and saved progress, freeSign in freeSign in

Stats 6.1Written lessonLesson 1 of 4 in Module 6

Hypothesis Testing and the p-Value

Test a claim against chance, and read a p-value correctly.

Video in production.

Read the lesson: Hypothesis Testing and the p-Value

The last module ended with a question: can our data show that something actually changed? This lesson answers it with one experiment. A store tries out a new checkout page that is designed to reduce item returns. Can one experiment show that the new page changed the return rate?

Every outcome in this lesson is simulated. The customers, orders and returns are synthetic, so you can work through the whole test without any claim that a real store changed its checkout. Nothing here describes the returns of a real retailer.

01State the test before the outcomes

A test is only as honest as the rules you fix before the data arrive. So start with the design, and write the rules down while every outcome is still unknown.

The unit and the arms

6,000 synthetic customers are randomly assigned to two arms of 3,000 each. An arm is one group in a randomized experiment.

  • The control arm keeps the current checkout.
  • The treatment arm gets the new checkout.

Each customer places one eligible order, and for each customer you record one outcome: returned or not returned. The unit of analysis is the customer.

The test statistic

Before seeing a single outcome, choose a test statistic, the quantity you will calculate from the observed outcomes. Here it is the treatment return rate minus the control return rate:

T = returned_treatment / 3000 − returned_control / 3000

The significance level and the direction

Next, fix a significance level, called alpha, at 5%: α = 0.05. This is the predeclared cutoff for rejecting the null, and it is the number the result will be compared with.

Finally, make the test two-sided. A rise in returns counts as evidence of a change in the same way a fall does. A two-sided test counts sufficiently extreme results in both directions.

The null hypothesis

Now you need a claim to test against: the null hypothesis, the claim used to calculate a reference distribution.

The null here says the new checkout does not change any customer's outcome at all. A customer who would return an order with the current page would also return it with the new one, and a customer who would keep the order keeps it with either page.

When a null makes a claim about every individual customer like this, it is called a sharp null: the treatment changes no individual outcome.

That is a stronger claim than saying the two arms have the same average return rate. The extra strength is what makes an exact calculation possible. If the sharp null is true, any difference between the arms comes only from which customers the random assignment happened to put in each one. The weaker claim of equal average rates would need additional modelling assumptions.

Should you switch direction after seeing the data?

Predict first

Suppose the treatment arm ends up with more returns than control. Should you switch to a one-sided test once you have seen that direction? Decide before reading on.

I have a guess. Show meHide the answer

No. If you pick the direction after seeing the data, a large difference in either direction could still end up counting as evidence, because you would choose whichever tail the data fell into. But the test would only count the probability of one of those directions.

That roughly doubles how often you would reject a null that is actually true: 0.05 in the chosen tail, with either tail available to choose, gives about 0.10 instead of the 0.05 you declared. So the test counts differences this large in either direction, exactly as declared before the outcomes arrived.

02Derive the observed difference

Count the returns

Now the outcomes come in. Count the returns in each arm before calculating anything else:

armreturnscustomers
control (current checkout)1963,000
treatment (new checkout)2153,000

Turn the counts into rates

Divide each count by 3,000:

  • Control: 196 / 3000 = 6.533…%, about 6.53%
  • Treatment: 215 / 3000 = 7.166…%, about 7.17%

Subtract

What is treatment minus control? In counts, 215 − 196 = 19 returns. As a rate:

19 / 3000 = +0.006333… = +0.633 percentage points

The unit is percentage points because this is a difference between two percentages, not a percentage change.

This observed difference, with its direction and its size, is the effect size: the observed magnitude and direction of a comparison. Note that it is what this sample showed, not the true effect the simulation assumed.

Is it unusual?

The treatment arm actually returned slightly more, which is the opposite of what the new page was designed to do. But random assignment alone decides which arm each returning customer lands in.

So here is the real question: is a difference of 19 returns large enough that random assignment alone would rarely produce it? Make a guess before you read the next part.

03Build the exact null distribution

Hold the outcomes fixed

To answer that, use the sharp null. Altogether there are 196 + 215 = 411 returns.

Under the sharp null, those 411 customers return their orders whichever arm they are in, so each return stays attached to its customer. What can change is the assignment.

So you move the arm labels around, keeping 3,000 customers in each arm, just as the original design did. An allowed assignment is one the original randomization design could have produced. Each new assignment puts a different number of the returning customers into treatment, so each one gives a different rate difference.

Enumerate exactly

There are far too many possible assignments to list one by one. But each assignment matters only through one number: how many of the 411 returning customers land in the treatment arm. Call that count k.

The hypergeometric distribution gives the exact probability of each value of k. It describes the count of marked outcomes in a fixed-size draw from a fixed total, and it applies here because 3,000 customers are drawn from 6,000, and 411 of the 6,000 return their orders. In SciPy that is hypergeom(6000, 411, 3000).pmf(k).

So you calculate the probability of every possible treatment count, from 0 to 411, and turn each count into its rate difference. If treatment has k returns, control has 411 − k, so:

T = (2k − 411) / 3000

The distribution is centered on 205.5 treatment returns, half of 411, which is where the difference is zero.

This distribution of the test statistic across every allowed assignment, under the sharp null, is called the randomization distribution. Because it comes from listing every possible count with its exact probability, it is exact, conditional on the 411 returns and the 3,000/3,000 design.

Count both tails

The treatment arm has 215 returns, which is 215 − 205.5 = 9.5 above the center.

What is the equally extreme result in the other direction? It is 196 treatment returns, because 411 − 215 = 196. Then control would have 411 − 196 = 215, and the difference would be −19 returns, or −19/3000.

So the two-sided test adds up the probabilities of every treatment count that is:

  • at least 215, or
  • at most 196.

This is a sum of exact assignment probabilities, not a count of sampled shuffles.

The p-value

When you add them up, the total probability is 0.3576.

That total is the p-value: the probability of a test statistic at least this extreme, if the sharp null is true and assignment works the way the design says.

In other words, about 36% of the possible assignments give a difference at least as large as ours, even when the new page changes nothing at all. Keep the conditions attached to that number: it is conditional on 411 returns and a 3,000/3,000 assignment.

The decision

Compare the p-value with the alpha you declared. Since 0.3576 is larger than 0.05, you do not reject the sharp null.

This test has not shown a change in returns, even though the treatment arm's observed rate is higher.

The whole procedure fits in five steps: declare, count, construct the null, compare the tails, decide.

04What the decision can miss

Two common mistakes

The first common mistake is to read the p-value as the probability that the null is true. But the p-value was calculated by assuming the null is true, so it cannot also tell you how likely the null is.

  • Wrong: p = P(H₀ true | data)
  • Right: p = P(statistic this extreme | H₀, design)

The second mistake is to treat a result you did not reject as evidence that the two checkouts have the same return rate. Nonrejection only means the data did not cross this test's predeclared rejection rule. A test can fail to cross that rule even when the effect is real.

The truth the simulation assumed

You can check that here, because you know what the simulation actually assumed. It gave control an 8% chance of a return and treatment a 7% chance:

  • P(return | control) = 0.08
  • P(return | treatment) = 0.07

That is a true decrease of 1 percentage point. The new page really did reduce returns in this simulation, but this run showed an increase of 0.633 percentage points instead. Neither rate is an estimate for a real retailer; both are assumptions of the simulation.

When a test fails to reject a null that is actually false, that is a false negative: the test fails to reject despite a real effect.

Repeat under no effect

How often does this rule make each kind of mistake? To find out, simulate 2,000 fresh experiments where both arms have an 8% return chance, so the null is true in every one of them.

For speed, each one is tested with the two-proportion z test instead of the exact calculation. It divides the difference in return rates by its pooled standard error:

z = (rate_T − rate_C) / pooled SE

It rejects the null when |z| > 1.96 (exactly 1.959963984540054). That is the same normal cutoff used for intervals in Stats 5.3. This repeated-experiment z rule is a separate calculation from the exact randomization test above.

Across the 2,000 experiments, it rejects the null 99 times. 99 / 2000 = 4.95%, which is close to the 5% alpha declared at the start.

Each of those rejections is a false positive: a false alarm, raised when the null is true.

Repeat under a real effect

Next, simulate 2,000 more experiments, this time with 8% in control and 7% in treatment, so the effect is real. The same z test, with the same two-sided cutoff, now rejects the null 619 times:

resultexperiments
rejected, treatment lower than control618
rejected, treatment higher (wrong direction)1
not rejected1,381
total2,000

The fraction of experiments that reject when there is a real effect is called power: the chance a declared test rejects under a specified real effect. Here, 619 / 2000 gives a power of 30.95%. A rejection is the event counted, even when one result has the wrong sign, so it would be imprecise to call all 619 correct-direction detections.

That leaves 1,381 experiments that missed the effect, about 69% of them. With 3,000 customers per arm, missing a 1-percentage-point decrease is the most likely outcome. The first run's miss is what this design produces most of the time. A valid procedure can miss a small effect in one run.

Two kinds of number

This lesson produced two kinds of number, and they answer different questions.

calculationquestion it answers
one observed run: exact conditional p-value, 0.3576How unusual is this one experiment's difference, if the new page changes nothing?
2,000 repeated runs per scenario: z-rule rejection fractions, 4.95% and 30.95%With 3,000 customers per arm, how often does the z test raise a false alarm, and how often does it detect a 1-percentage-point decrease?

Do not merge them. The repeated-run percentages are not the p-value of the first experiment.

05Reproduce and report

The core code

In code, seed the assignment and the outcomes separately, and count the returns before you calculate any rate. The outcome seed is SEED = 20260926 and the assignment seed is SEED + 6. Seeds make the run reproducible; they do not make the inference valid.

The exact tail function takes the treatment count, the total number of returns and the arm size:

from scipy.stats import hypergeom
import numpy as np


def two_sided_randomization_p(k_treatment: int, successes: int, n_each: int) -> float:
    """Exact sharp-null p for equal-size randomized arms, conditioned on successes."""
    distribution = hypergeom(2 * n_each, successes, n_each)
    low = max(0, successes - n_each)
    high = min(successes, n_each)
    possible = np.arange(low, high + 1)
    observed = abs(2 * k_treatment - successes)
    return float(distribution.pmf(possible[abs(2 * possible - successes) >= observed]).sum())

The line abs(2 * possible - successes) >= observed is the two-sided tail: it keeps every count at least as far from the center as the observed one, in either direction.

The simulated experiment assigns the arms, draws the outcomes, counts the returns and calls the tail function with 215, 411 and 3,000:

SEED = 20260926

rng = np.random.default_rng(SEED)
n = 3000
p_control, p_treatment = 0.08, 0.07
assigned_treatment = np.random.default_rng(SEED + 6).permutation(2 * n) < n
control = rng.binomial(1, p_control, n)
treatment = rng.binomial(1, p_treatment, n)
k0, k1 = int(control.sum()), int(treatment.sum())
p = two_sided_randomization_p(k1, k0 + k1, n)

For the repeated experiments, draw binomial counts for both arms and apply the same z cutoff to every pair:

repeats = 2000
null_counts = rng.binomial(n, p_control, size=(repeats, 2))
effect_counts = np.column_stack(
    [rng.binomial(n, p_control, repeats), rng.binomial(n, p_treatment, repeats)]
)


def rejected(counts: np.ndarray) -> np.ndarray:
    rates = counts / n
    pooled = counts.sum(axis=1) / (2 * n)
    se = np.sqrt(pooled * (1 - pooled) * 2 / n)
    z = np.divide(rates[:, 1] - rates[:, 0], se, out=np.zeros(repeats), where=se > 0)
    return np.abs(z) > 1.959963984540054


effect_rejected = rejected(effect_counts)
effect_direction_correct = effect_counts[:, 1] < effect_counts[:, 0]

The module's analysis reports these values:

observed_returns: control 196, treatment 215
total_returns: 411
observed_treatment_minus_control: 0.006333...
exact_null_center_treatment_returns: 205.5
mirror_treatment_returns: 196
exact_two_sided_randomization_p: 0.357616702...
alpha: 0.05
null_false_alarms: 99 (0.0495)
effect_run_rejections: 619 (0.3095)
effect_run_rejections_in_assumed_direction: 618
effect_run_rejections_opposite_direction: 1
effect_run_nonrejections: 1381

State the scope

When you report a test like this, name four things: the unit, the observed difference, the two-sided p-value, and the null that p-value assumes. For this checkout:

  • Unit: one simulated customer, 3,000 per arm.
  • Observed difference: treatment minus control, +0.633 percentage points.
  • p-value: 0.3576, exact, under the sharp null of no change for any customer.
  • Decision: do not reject at α = 0.05.

Then state the limits. Not rejecting does not show that the effect is zero, so make no equivalence claim. And invented outcomes say nothing about a real retailer.

Try it yourself

In the notebook, choose a different sample size before running anything, then rerun both simulations with the same two-sided cutoff. Report how the detection rate changes, and explain in two sentences why a large p-value still cannot prove there is no effect.

The next lesson asks which labels you are allowed to move when the data come in pairs or in two independent groups. There, the pairs are two forecasts made for the same taxi trip.

Next steps: Hypothesis Testing and the p-Value