Statistics and experimentation: intervals, tests, power, A/B tests and fair model comparison

  • Advanced
  • 1 h 40 min
  • Lesson 2 of 3 in Evaluation, statistics and data
  • Last verified

Open slides(26 slides)

Before you start

You will be able to

  • Explain an estimator, its bias and variance, and a confidence interval, and compute an analytic and a bootstrap interval while knowing when each one is unreliable.
  • Choose and run a z, chi-square or permutation test, and say what a p-value, a type I error, a type II error and power mean, including the standard misreadings.
  • Size an experiment from a baseline, a minimum effect, alpha and power, and control false positives from many comparisons (Bonferroni, Benjamini-Hochberg) and from peeking.
  • Design and sanity-check an A/B test of an ML system (unit of randomisation, sample ratio mismatch, novelty, interference, offline-online gaps) and say when a correlation can support a causal claim.
  • Compare two models with a paired test or interval instead of two separate scores, say why cross-validation scores are not independent, and apply Bayes' rule to a base-rate or posterior question.

Concept

The previous lesson made a single score honest. This lesson asks the next question: how much should you trust a number, and how do you decide that one thing is better than another? A score computed from a finite sample is an estimate with noise around it. Statistics is the discipline of saying how big that noise is. Experimentation is the discipline of arranging a comparison so the noise can be measured and the cause is not confused with something else.

QuestionTool in this lesson
How wrong could this number be?Standard error, confidence interval, bootstrap
Is the difference real or noise?z, chi-square and permutation tests, p-values
How much data do I need?Power and sample size
I looked at 20 metrics and one is significantBonferroni, Benjamini-Hochberg
Can I trust this A/B test?Unit of randomisation, SRM check, novelty, peeking
Is model B really better than model A?Paired tests, the corrected resampled t
Given a positive result, what is the chance it is real?Bayes’ rule and base rates
Did the change cause the outcome?Randomisation versus observational correlation

Why It Matters

Almost every shipped ML change is judged by an experiment, and the most common failure is not a bad model but a bad decision: shipping on noise, missing a real gain because the test was too small, or trusting a test whose assignment was broken. Interviewers for ML and applied-science roles ask about p-values, power, A/B pitfalls and base rates because they cannot be answered by recall alone (common industry pattern). The lesson is also a repair kit for earlier ones: the small-data error bars from the last lesson are confidence intervals, and a leaky split is one more way an estimate lies.

Mental Model

Treat every number you compute as one draw from a distribution you cannot see. Run the world again with a fresh sample and you would get a slightly different number. Four questions follow from that picture, and the whole lesson is their answers:

  1. How spread out is that distribution? (standard error, interval)
  2. Is the draw consistent with “nothing changed”? (a test and its p-value)
  3. Was the experiment large enough to see an effect of the size I care about? (power)
  4. Did I give myself so many chances to find something that a lucky draw was almost guaranteed? (multiple comparisons, peeking)

Beyond the noise sits a different problem that no sample size fixes: whether the comparison is fair, meaning that the two groups differ only in the thing being tested. Randomisation is the tool for that.

Sampling and estimators

An estimator is a rule that turns a sample into a guess about something in the population, such as the sample mean as a guess for the population mean. Its value changes from sample to sample, so the estimator has its own distribution, called the sampling distribution. Two properties describe it:

  • Bias is how far the average of the estimator is from the truth.
  • Variance is how much it moves from sample to sample.

The spread of the sample mean is the standard error:

SE(xˉ)=σn\mathrm{SE}(\bar{x}) = \frac{\sigma}{\sqrt{n}}

SymbolMeaning
σ\sigmaStandard deviation of one observation
nnNumber of independent observations
xˉ\bar{x}Sample mean

Quadrupling the data only halves the noise. That square root is why small effects are expensive to detect, which the power section makes concrete.

The central limit theorem says that averages of many independent draws look roughly Gaussian, whatever the shape of one draw, so the 68-95-99.7 rules work for means (common practice). “Many” depends on how skewed the data are. The script draws from an exponential distribution, which has mean 1 and standard deviation 1. The standard deviation of the sample mean matches σ/n\sigma/\sqrt{n} already at n=5n=5 (0.453 against 0.447). The shape does not match: with n=5n=5, only 0.1% of sample means fell below 1−1.96 σ/n1-1.96\,\sigma/\sqrt{n} and 4.4% fell above 1+1.96 σ/n1+1.96\,\sigma/\sqrt{n}, where a Gaussian would give 2.5% on each side. At n=200n=200 the two tails are 1.9% and 2.9%, closer but still not equal.

Bias and variance of an estimator

A biased estimator is not automatically worse. The script shows both sides.

  • An estimator that is biased by construction. For n=5n=5 draws from a distribution with true variance 1, dividing the sum of squares by nn averages 0.798, while dividing by n−1n-1 averages 0.997. The divisor n−1n-1 makes the variance estimator unbiased. The square root of it, the sample standard deviation, is still biased low (0.939 on average), because a square root bends an unbiased quantity.
  • A biased estimator that wins. To estimate a mean of 0.5 from n=10n=10 draws with standard deviation 1, the sample mean has mean squared error 0.1003 in the script (theory 0.1). Multiplying it by 0.8 adds a bias of −0.1-0.1 but cuts the variance, for 0.0743 (theory 0.0740).

MSE=bias2+variance\mathrm{MSE} = \mathrm{bias}^2 + \mathrm{variance}

This is the bias-variance trade-off from the first lesson, seen from an estimator instead of a model: accepting a little bias to cut variance is what regularisation does. The multiplier 0.8 helps only because the true mean (0.5) is small relative to the noise.

Confidence intervals

A point estimate has no error bar. A confidence interval adds one. A 95% interval is produced by a procedure that, over repeated experiments, would contain the true value in about 95% of them. It is a statement about the procedure. For a fixed interval that you already computed, the true value is either inside or not, so “there is a 95% probability the parameter is in this interval” is the common misreading.

The usual analytic interval for a mean is built from the standard error:

xˉ±z sn\bar{x} \pm z\,\frac{s}{\sqrt{n}}

SymbolMeaning
ssSample standard deviation (divisor n−1n-1)
zz1.96 for 95% under the normal approximation; for small samples a t quantile, which is larger, is used instead

It assumes the mean is roughly Gaussian, which the previous section showed is a question of sample size and skew.

Analytic and bootstrap

The bootstrap replaces the formula with a simulation. Treat the sample as a stand-in for the population, draw nn items from it with replacement, compute the statistic, repeat thousands of times, and read the interval off the sorted results. The percentile version takes the 2.5th and 97.5th percentiles. It works for statistics with no tidy formula, such as a median or an AUC, and it needs no distributional assumption beyond “the sample resembles the population”. The homework function bootstrap_ci takes the random generator as an argument so the result is reproducible.

Diagram: Use a formula when one exists and the sample is large and not very skewed, use the bootstrap when no formula exists, and be suspicious of...

yes

no formula
(median, AUC, ratio)

small n or heavy tail

Want an interval for a statistic

Is there a formula,
and is n large and
the data not heavily skewed?

Analytic interval:
estimate +/- z x SE

Bootstrap:
resample with replacement

Either may under-cover:
widen, get more data,
or report the limitation

Percentile interval from
sorted resampled statistics

Diagram summary: Use a formula when one exists and the sample is large and not very skewed, use the bootstrap when no formula exists, and be suspicious of both when the sample is small or heavy-tailed.

The bootstrap is not a repair for small samples. The script measures how often each interval covered the true mean over 400 repeats of each case:

DataNormal-approximation coveragePercentile bootstrap coverage
Normal, n=10n=100.9200.910
Lognormal, n=15n=150.8000.805
Lognormal, n=60n=600.8650.858

Both fall short of the promised 0.95, for different reasons. For normal data with n=10n=10, the analytic interval uses 1.96 where a t quantile belongs. The coverage of xˉ±1.96 s/n\bar{x}\pm1.96\,s/\sqrt{n} is P(∣t9∣<1.96)=0.918P(|t_9|<1.96)=0.918 (computed in the script), which matches the measured 0.920. The percentile bootstrap (0.910) behaves like a normal interval whose spread divides by nn instead of n−1n-1 (the variance of a resample is the divide-by-nn one), which makes it narrower by a factor 0.9\sqrt{0.9}: the coverage becomes P(∣t9∣<1.960.9)=0.904P(|t_9|<1.96\sqrt{0.9})=0.904, again close to the measurement (derived here). For skewed lognormal data the mean’s sampling distribution is right-skewed, and the sample standard deviation tends to be small exactly when the sample mean is small, because a sample without a large value has both. So the intervals are narrowest when they sit too low, and almost all the misses are below the true mean: 96% of the normal-approximation misses and 96% of the bootstrap misses at n=15n=15, and 94% and 89% at n=60n=60. These are results of this script’s lognormal(0,1) case and 400 repeats each, so they carry some noise of their own; the pattern, not the third digit, is the lesson. The SciPy documentation offers three bootstrap variants and defaults to the bias-corrected and accelerated one (BCa), and it warns that BCa endpoints can be undefined when the resampled statistics are degenerate, for example when all values are identical (SciPy, bootstrap). This lesson uses the plain percentile interval because it is the one you can write in ten lines.

On one small dataset with an outlier (12 values, one of them 20), the script gives a mean of 6.0 with a 95% bootstrap interval of (4.083, 8.750), and a median interval of (4.000, 5.500). The mean interval is wide and lopsided because of the single large value.

Hypothesis tests

A hypothesis test asks whether the data are surprising if nothing is going on. You state a null hypothesis H0H_0 (no difference), choose a test statistic that measures the difference, and ask how often a statistic at least this extreme would occur if H0H_0 were true. That probability is the p-value.

Which test follows from the data type:

DataTestNotes
Two conversion ratesTwo-proportion z-testLarge counts; pooled standard error
Two meanst-testSciPy defaults to equal variances; equal_var=False gives Welch’s test (SciPy, ttest_ind)
Counts against expected proportionsChi-square goodness of fitRule of thumb: every observed and expected count at least 5 (SciPy, chisquare)
Any statistic, small or odd dataPermutation testShuffle the group labels

The two-proportion statistic uses the pooled rate p^=(x1+x2)/(n1+n2)\hat{p}=(x_1+x_2)/(n_1+n_2), because under H0H_0 both groups share one rate:

z=p^2−p^1p^ (1−p^)(1n1+1n2)z = \frac{\hat{p}_2-\hat{p}_1}{\sqrt{\hat{p}\,(1-\hat{p})\left(\frac{1}{n_1}+\frac{1}{n_2}\right)}}

On a conversion test with 1,000 of 10,000 users converting in control and 1,090 of 10,000 in the variant, the script gives a lift of 0.0090, z=2.080z=2.080 and p=0.0375p=0.0375, with a 95% interval for the lift of (0.0005, 0.0175). The same rates on a fifth of the traffic (200 of 2,000 against 218 of 2,000) give z=0.930z=0.930 and p=0.3522p=0.3522. The effect did not change; the evidence did. A p-value mixes the size of the effect with the amount of data, which is why you report the interval for the effect next to it.

The permutation test needs almost no theory. If the group labels did not matter, any reshuffling of the pooled values is as likely as the one you saw. Shuffle many times, compute the difference each time, and count how often it is at least as extreme as the observed one. For a randomised test SciPy adds one to the count and to the total, so the p-value is never exactly zero (SciPy, permutation_test):

p=extreme+1B+1p = \frac{\text{extreme} + 1}{B + 1}

When the number of resamples is at least the number of distinct permutations, the same documentation switches to an exact test that visits every one. For two skewed samples of 6 and 7 values, the script finds a difference in means of 7.048, an exact two-sided pp of 0.0280 over 1,716 splits, and a randomised pp of 0.0293 from 9,999 shuffles, with a one-sided exact pp of 0.0198. The randomised value is an approximation of the exact one, and it moves a little with the seed. A note on conventions: this lesson and the homework call a permuted difference extreme when ∣t∣≥∣tobs∣|t|\ge|t_{\text{obs}}| for the two-sided case, while scipy.stats.permutation_test doubles the smaller one-sided p-value. On this data SciPy’s rule gives 2×0.0198=0.03962\times0.0198=0.0396 against 0.0280 here. The two agree when the null distribution is symmetric (derived here) and differ on skewed data like this, so say which rule you used.

P-values and what they are not

The p-value answers one question: if there were truly no effect, how often would data this extreme occur? The American Statistical Association’s 2016 statement lists six principles. Among them: p-values can show how incompatible the data are with a model, they do not measure the probability that the hypothesis is true, they do not measure the size or importance of an effect, and a conclusion should not rest on whether a p-value crosses a threshold alone (ASA, 2016 release).

MisreadingWhy it is wrong
”p=0.03p=0.03 means a 97% chance the effect is real”The p-value is computed assuming H0H_0; it is not the probability of H0H_0
”p>0.05p>0.05 means there is no effect”The test may have been too small to see it; the result is inconclusive
“A tiny p-value means a big effect”With enough data a trivial effect is significant
“Significant means worth shipping”Statistical and practical significance are different questions

Under a true H0H_0 the p-value is spread evenly between 0 and 1, so “p below 0.05” happens 5% of the time by design. The script checks this with 2,000 A/A tests (both arms identical, 500 users each, 10% conversion): 4.1% had p<0.05p<0.05 and 49.5% had p<0.5p<0.5.

To see why “97% real” is wrong, apply Bayes’ rule (derived here). Suppose 10% of the ideas you test truly work, your tests have power 0.80, and alpha is 0.05. Of 1,000 ideas, 100 work and 80 of those test significant; of the 900 that do not work, 45 test significant by chance. So 80 of 125 significant results are real, which is 0.640. A significant result is far from certain when real wins are rare.

Gelman and Loken add a subtler point. A multiple-comparisons problem can arise even without any deliberate fishing, whenever the details of the analysis (what to exclude, which measure, which interaction) are chosen after seeing the data. The count of comparisons that matters includes the ones you would have made had the data looked different (Gelman and Loken 2013). Fixing the metric, the exclusions and the analysis before the data arrive is the defence.

Errors, power and sample size

A test can be wrong in two ways.

H0H_0 true (no effect)H0H_0 false (real effect)
Reject H0H_0Type I error (false positive), probability α\alphaCorrect: this probability is the power, 1−β1-\beta
Keep H0H_0CorrectType II error (false negative), probability β\beta

You pick α\alpha (commonly 0.05) and power (commonly 0.80) before the experiment (common practice). Power depends on the sample size, the size of the true effect and the noise, so for a given test you choose the minimum detectable effect that would matter to the business and solve for nn. For two proportions, with a two-sided test:

n=(z1−α/2+zpower)2(p1(1−p1)+p2(1−p2))(p1−p2)2n = \frac{\left(z_{1-\alpha/2}+z_{\text{power}}\right)^2\left(p_1(1-p_1)+p_2(1-p_2)\right)}{(p_1-p_2)^2}

SymbolMeaning
nnUsers needed in each arm, rounded up
z1−α/2z_{1-\alpha/2}1.96 for α=0.05\alpha=0.05
zpowerz_{\text{power}}0.84 for power 0.80 (the table’s counts use exact quantiles, so 1.96 and 0.84 are rounded)
p1,p2p_1,p_2Baseline rate and the rate you want to detect

The effect sits in the denominator squared, so halving the lift quadruples the cost. For a baseline of 0.10 the script gives these per-arm sizes:

Target rateLiftUsers per arm
0.1202 points3,839
0.1101 point14,749
0.1050.5 point57,760

A well-known shortcut is n≈16σ2/δ2n \approx 16\sigma^2/\delta^2 per arm (common practice), where σ2\sigma^2 is the variance of one observation and δ\delta the lift to detect. The 16 is about 2(1.96+0.84)2=15.72(1.96+0.84)^2 = 15.7 (derived here). For baseline 0.10 and a 0.01 lift it gives 14,400 against the exact 14,749: close, and fine for a first estimate. The statsmodels class NormalIndPower does a closely related power calculation for a two-sample z-test, which it documents as using a pooled variance (statsmodels, NormalIndPower); it takes an effect-size argument, so check how the statsmodels reference defines it before comparing its output with the formula above.

The script checks the formula by simulation. A baseline of 0.30 against 0.35 needs 1,374 per arm, where the formula’s power is 0.800. Over 600 simulated tests the share of significant results was 0.817. With only 500 per arm the formula gives a power of 0.394 and the simulation 0.403: a test that is too small misses a real effect more often than it finds it. A non-significant result from such a test says “inconclusive”, not “no effect”. Report the interval; if it still includes both zero and an effect worth shipping, the test could not tell you.

Many comparisons

Every test you run is another chance for a false positive. With 20 independent true nulls, the chance of at least one p<0.05p<0.05 is 1−0.9520=0.6421-0.95^{20}=0.642. Dashboards with dozens of metrics and segments produce “winners” this way. Two ideas of error rate matter:

  • The family-wise error rate (FWER) is the chance of any false positive. Bonferroni controls it by testing each hypothesis at α/m\alpha/m for mm tests. It is simple and strict, and it loses power as mm grows.
  • The false discovery rate (FDR) is the expected share of rejected hypotheses that are false. Benjamini-Hochberg (BH) controls it, and it is less strict because it accepts a few false discoveries among many. Benjamini and Hochberg’s abstract notes that the two rates coincide when all hypotheses are true and that the false discovery rate is smaller otherwise, so controlling it can give a gain in power, and they prove that a simple sequential Bonferroni-type procedure controls it for independent test statistics (Benjamini and Hochberg 1995).

BH sorts the mm p-values and compares the one at rank kk with a rising threshold. Its adjusted p-value is the smallest of m p(j)/jm\,p_{(j)}/j over all ranks j≥kj\ge k, capped at 1:

p~(k)=min⁡j≥k min⁡ ⁣(1, m p(j)j)\tilde{p}_{(k)} = \min_{j\ge k}\ \min\!\left(1,\ \frac{m\,p_{(j)}}{j}\right)

You reject every hypothesis whose adjusted value is at most qq. The running minimum pulls adjusted values down, so a larger p-value that passes its rank threshold carries the smaller ones with it (BH is a step-up rule). SciPy’s documentation says BH controls FDR at a level at most q m0/mq\,m_0/m (with m0m_0 true nulls) for independent tests or tests with positive regression dependence, and offers the more conservative Benjamini-Yekutieli variant for arbitrary dependence (SciPy, false_discovery_control). statsmodels lists these and more under multipletests (statsmodels, multipletests).

A worked case from the script: p-values 0.001, 0.012, 0.018, 0.030, 0.45. Bonferroni’s cut-off is 0.05/5=0.0100.05/5=0.010, so it rejects 1. The BH adjusted values are 0.005, 0.03, 0.03, 0.0375 and 0.45, so BH rejects 4 at q=0.05q=0.05.

The script also simulates 500 rounds of 100 tests, of which 80 are true nulls and 20 are real effects (the test statistic shifted by 3 standard deviations):

RuleFalse discoveries per 100 testsTrue discoveries per 100 testsShare of discoveries that are false
No correction (p<0.05p<0.05)3.8317.150.177
Bonferroni0.056.520.007
Benjamini-Hochberg0.5512.300.038

Which to use depends on the cost of a false positive. For a single launch decision, control the family-wise error. For screening many candidate features or metrics, where a few false leads are acceptable, control the false discovery rate (common practice). The best fix is to name one primary metric before the test and treat the rest as secondary or guardrails.

Experiments on ML systems

A randomised experiment compares two versions of a system on live traffic. It is the only method in this lesson that can support a causal claim without further assumptions, because random assignment makes the groups alike in everything except the change. The book Trustworthy Online Controlled Experiments is a standard reference, with chapters on Twyman’s law and on sample ratio mismatch (Kohavi, Tang and Xu 2020).

Diagram: Decide the metric, the unit and the size before launch, run to the planned end, check that the arms are the sizes the design promised...

mismatch

ok

Pick one primary metric,
guardrails, minimum effect

Choose the unit of
randomisation

Compute sample size
and duration

Run: no early stopping
unless the method allows it

SRM check:
do arm sizes match the design?

Stop and debug:
do not read the result

Interval and test on the
primary metric, then guardrails

Decide on effect size,
cost and risk

Diagram summary: Decide the metric, the unit and the size before launch, run to the planned end, check that the arms are the sizes the design promised before reading any result, and only then analyse.

Randomisation and the unit

The unit of randomisation is the thing that gets assigned to an arm: a user, a session, a page view, a device, a region. It should match the unit of analysis, or the analysis must account for clustering, and it should be the unit across which effects do not leak (common practice). If you assign by user but analyse page views as if they were independent, the page views of one user are correlated, so the standard error is too small.

The script runs 500 A/A tests with 200 users per arm and 20 page views each, where each user has their own click probability drawn from a Beta(1, 9) distribution. Users are assigned at random, but the z-test treats the 8,000 page views per arm as independent. Result: 21.4% of A/A tests came out “significant” at 5%. The design-effect formula (derived here) predicts the inflation. With within-user correlation ρ=0.0909\rho=0.0909 and m=20m=20 views per user, the variance is inflated by

DEFF=1+(m−1)ρ=2.73,\mathrm{DEFF} = 1 + (m-1)\rho = 2.73,

so the test behaves as if the threshold were 1.96/2.731.96/\sqrt{2.73}, which predicts a false-positive rate of 0.235. The simulation (0.214, with 500 repeats) is close. The fix is to analyse at the level you randomised: one number per user, or a method that accounts for clustering.

Interference is the other side of the unit. If treated users affect control users, as in a marketplace, a social network or a shared recommender that learns from all traffic, user-level randomisation compares contaminated groups. Randomising whole clusters (regions, communities) or alternating the whole system over time (switchbacks) are the usual remedies (common practice). Both reduce the number of independent units, so they cost power.

Sample ratio mismatch

If you designed a 50/50 split, the arm sizes should match it up to chance. A sample ratio mismatch (SRM) is an arm-size ratio that chance does not explain, and it means the assignment or the logging is broken: a bot filter that treats the arms differently, a crash in one arm, a redirect that loses users. Check it with a chi-square goodness-of-fit test on the arm counts:

χ2=∑i(Oi−Ei)2Ei,Ei=N ri∑jrj\chi^2 = \sum_{i}\frac{(O_i-E_i)^2}{E_i}, \qquad E_i = N\,\frac{r_i}{\sum_j r_j}

SymbolMeaning
OiO_iObserved users in arm ii
EiE_iExpected users in arm ii under the design
rir_iDesign ratio of arm ii

The p-value comes from a chi-square distribution with k−1k-1 degrees of freedom for kk arms. The script gives:

ObservedDesignχ2\chi^2p-value
10,400 and 9,60050/5032.001.54×10−81.54\times10^{-8}
50,500 and 49,50050/5010.000.00157
520 and 48050/501.600.206
5,200 and 4,80050/5016.006.33×10−56.33\times10^{-5}
3,400, 3,300, 3,3001:1:12.000.368

The same 52/48 split is harmless at 1,000 users and a red flag at 10,000: the question is never “is the ratio exactly 50/50” but “is the deviation larger than chance allows”. Many teams alarm only at a strict threshold such as 0.001, so the check does not cry wolf across many experiments (common practice). When it fires, do not read the treatment effect: whatever broke the assignment may also have biased the metric.

Novelty, peeking and early stopping

Novelty and primacy effects mean early behaviour differs from steady state: users click a new layout because it is new, or resist it because it is unfamiliar. Run for whole weekly cycles, look at the effect over time, and treat a decaying lift with suspicion (common practice).

Peeking is checking the p-value repeatedly and stopping when it first falls below 0.05. Each look is another chance for a false positive. The script runs 1,000 A/A tests with up to 10 looks. A single test at the end had a false-positive rate of 0.058, and stopping at the first significant look had 0.219. The remedies are a fixed horizon, or a sequential method designed for continuous monitoring, such as alpha-spending boundaries or always-valid tests (common practice; the lesson does not derive them).

Offline and online metrics disagree

A frequent surprise: the offline metric improved and the A/B test shows nothing. The usual causes, from most to least mundane (common practice):

  • The test was too small to see the lift: check power first.
  • The offline metric is not what users respond to (a metric mismatch), for example AUC on all items while users only see the top five.
  • The offline data are stale or selected: the logged data came from the old model’s choices, so the new model is judged on items it would not have shown.
  • Distribution shift between the offline sample and live traffic.
  • A bug in feature computation between training and serving.
  • Novelty hiding or inflating the effect.

The practical habit is to treat the offline metric as a filter for what deserves an online test, and to keep guardrail metrics (latency, errors, revenue, complaints) in every test.

Simpson’s paradox

An aggregate trend can reverse inside every segment when the groups have different mixes. In a constructed example, arm A succeeds on 90 of 100 easy cases (0.900) and 300 of 900 hard cases (0.333), for 0.390 overall. Arm B succeeds on 800 of 900 easy cases (0.889) and 30 of 100 hard cases (0.300), for 0.830 overall. A is better inside both segments and worse overall, because A was given mostly hard cases. With random assignment the mixes match in expectation, so the paradox signals broken assignment, pooling periods that had different allocation ratios (for example a ramp-up), or an observational comparison. Stratify, or check the randomisation.

Comparing models fairly

Two scores on the same test set are not two independent measurements. Both models see the same items, and most items are easy for both. A paired test uses that structure: only the items where the models disagree carry information. McNemar’s test counts the items where only A is right (bb) and where only B is right (cc), and tests whether they are equally common:

χ2=(max⁡(∣b−c∣−1, 0))2b+c\chi^2 = \frac{\left(\max(|b-c|-1,\,0)\right)^2}{b+c}

with one degree of freedom, where the −1-1 is a continuity correction (standard form). The script builds two models of accuracy 0.770 and 0.798 on 1,000 constructed items whose difficulty is shared. A is right alone on 29 items and B on 57. McNemar gives χ2=8.48\chi^2=8.48 and p=0.0036p=0.0036, while an unpaired two-proportion test on the same accuracies gives z=1.52z=1.52 and p=0.1281p=0.1281. The unpaired test ignores the pairing, which costs power. A bootstrap interval for the per-item accuracy gain (B minus A) is (0.0100, 0.0450). Report that interval, not just the verdict.

Dietterich’s study of five tests found that a test on the difference of two proportions and a paired t-test over several random train/test splits have a high probability of type I error and should not be used, that a paired t-test over 10-fold cross-validation has somewhat elevated error, and that McNemar’s test has low type I error. His 5x2 cross-validation test also had acceptable error (Dietterich 1998). McNemar uses one training set, so it ignores how much the result depends on which training data were drawn, and it can over-reject when that variation is large (derived here); the paper recommends it only when the algorithm can be run once.

Why does a t-test on cross-validation scores fail? The training sets of different folds overlap heavily, so the fold scores are positively correlated, and the plain variance estimate is too small. Nadeau and Bengio’s correction adds a term that depends on the ratio of test size to training size. In the correctR documentation the statistic is

t=dˉ(1k+ntestntrain)s2t = \frac{\bar{d}}{\sqrt{\left(\frac{1}{k}+\frac{n_{\text{test}}}{n_{\text{train}}}\right)s^2}}

where dˉ\bar{d} is the mean score difference over kk resamples, s2s^2 the sample variance of those differences, and ntrain,ntestn_{\text{train}},n_{\text{test}} the set sizes. That page also notes that no unbiased estimator exists for this variance, so for kk-fold cross-validation it uses an approximation with ρ=1/k\rho=1/k (correctR vignette). The script applies the correction to ten constructed score gaps from 90/10 splits: the naive tt is 8.95 and the corrected tt is 6.16, 31% smaller (a ratio of 0.688). The corrected value is still large here; the point is that the naive one overstates the evidence by a fixed factor.

To compare several models over several datasets, Demsar recommends the Wilcoxon signed-ranks test for two classifiers and the Friedman test with post-hoc tests for more (Demsar 2006). In every case the earlier lesson’s rule still holds: the test set used for the comparison must not have been used to choose the models.

A Bayesian view

Bayesian inference answers a different question: given the data, how plausible are different values of the parameter? It starts from a prior, updates it with the data through Bayes’ rule, and ends with a posterior:

P(θ∣D)=P(D∣θ) P(θ)P(D)P(\theta\mid D)=\frac{P(D\mid \theta)\,P(\theta)}{P(D)}

Base rates first. The simplest use is the diagnostic-test problem, and it is the most common interview version of Bayes. In natural frequencies, with 1% prevalence, 90% sensitivity and a 10% false-positive rate, out of 10,000 people 100 are sick and 90 of them test positive; of the 9,900 healthy people 990 test positive. So P(sick∣+)=90/1,080=0.0833P(\text{sick}\mid +)=90/1{,}080=0.0833. With 99% sensitivity and a 5% false-positive rate it is 0.1667. At 10% prevalence with the first test it is 0.5000. The lesson is the same one as precision under class imbalance: when the condition is rare, even a good test produces mostly false alarms. The earlier lesson’s precision collapse and this calculation are one fact.

MLE and MAP. Maximum likelihood chooses the parameters that make the data most probable. For a classifier, the negative log-likelihood of the labels is the cross-entropy loss, so minimising cross-entropy is maximum likelihood (the linear-models lesson). Maximum a posteriori (MAP) adds a prior. A Gaussian prior on the weights gives an L2 penalty and a Laplace prior gives L1 (common practice). Regularisation can be read as a prior.

A posterior for an A/B test. With a flat Beta(1,1) prior, a conversion rate with xx successes in nn trials has a Beta(1+x1+x, 1+n−x1+n-x) posterior. For A with 100 of 1,000 and B with 120 of 1,000, the script gives posterior means 0.1008 and 0.1208, a probability that B beats A of 0.925, and a 95% credible interval for the lift of (-0.0072, 0.0472). The z-test on the same data gives p=0.1529p=0.1529. These are not the same quantity: 0.925 is a probability about the parameters given a prior, and 0.1529 is a probability of data given no effect. With a flat prior, 1−0.925=0.0751-0.925=0.075 is close to the one-sided z-test p-value of 0.0765 (the script prints both), but the two are conceptually different and the closeness is not a general identity. Neither is “the chance the variant is better” in a sense that survives a bad prior or a broken experiment. A Bayesian analysis also does not remove the need to plan the stopping rule or to run a fair comparison; it changes what is reported.

Correlation and causation

Two things move together for three reasons: one causes the other, a third thing causes both (a confounder), or chance. Observational data cannot separate the first two without assumptions. The script makes a hidden variable ZZ drive both XX and YY, with no effect of XX on YY: the observed correlation between XX and YY is 0.502 (theory 0.5). If XX is assigned at random instead, the correlation is -0.008. Randomisation breaks the link from ZZ to XX, which is why it is the gold standard.

When you cannot randomise, the usual designs are matching, difference-in-differences, regression discontinuity and instrumental variables, each with assumptions you must state and defend (common practice; none is derived here). For ML the practical consequence is this: a model that predicts an outcome well does not tell you what happens if you intervene on one of its features. A feature that predicts churn may be a symptom of churn, and changing it may do nothing.

Code

This standard-library script produced every number in the lesson that is computed here. The first part is the helper functions from homework/solution.py (without docstrings); the rest is the experiments. It has fixed seeds and runs in about 1 second (Python 3.14.6, run with python3 -I). Another Python version may draw different random numbers, which moves the simulated figures slightly but not their pattern: the sampling, coverage, A/A, peeking, power, multiple-comparison, user-unit, model-comparison and posterior simulations, and the randomised permutation p-value. The closed-form numbers (sample sizes, SRM statistics, Bayes calculations, BH values, the exact permutation p-values) do not depend on the version. The exact two-sided p-value follows this lesson’s convention, and the line below it prints SciPy’s doubled one-sided value for comparison.

Python

import math
from itertools import combinations
from statistics import NormalDist

EPS = 1e-12


def _mean(xs):
    return sum(xs) / len(xs)


def bootstrap_ci(data, stat, n_resamples, alpha, rng):
    n = len(data)
    if n == 0 or n_resamples < 1 or not 0 < alpha < 1:
        raise ValueError("need data, n_resamples >= 1 and 0 < alpha < 1")
    stats = []
    for _ in range(n_resamples):
        stats.append(stat([data[rng.randrange(n)] for _ in range(n)]))
    stats.sort()
    lo = int(math.floor(round(alpha / 2 * n_resamples, 9)))
    hi = int(math.ceil(round((1 - alpha / 2) * n_resamples, 9))) - 1
    return stats[lo], stats[hi]


def _check_alt(alternative):
    if alternative not in ("two-sided", "greater", "less"):
        raise ValueError("alternative must be 'two-sided', 'greater' or 'less'")


def _is_extreme(t, observed, alternative):
    if alternative == "greater":
        return t >= observed - EPS
    if alternative == "less":
        return t <= observed + EPS
    return abs(t) >= abs(observed) - EPS


def permutation_test(a, b, n_resamples, rng, alternative="two-sided"):
    _check_alt(alternative)
    if not a or not b or n_resamples < 1:
        raise ValueError("need two non-empty samples and n_resamples >= 1")
    na = len(a)
    observed = _mean(a) - _mean(b)
    pooled = list(a) + list(b)
    extreme = 0
    for _ in range(n_resamples):
        rng.shuffle(pooled)
        t = _mean(pooled[:na]) - _mean(pooled[na:])
        if _is_extreme(t, observed, alternative):
            extreme += 1
    return observed, (extreme + 1) / (n_resamples + 1)


def exact_permutation_test(a, b, alternative="two-sided"):
    _check_alt(alternative)
    if not a or not b:
        raise ValueError("need two non-empty samples")
    n, na = len(a) + len(b), len(a)
    if math.comb(n, na) > 200000:
        raise ValueError("too many permutations for an exact test")
    pooled = list(a) + list(b)
    total_sum = sum(pooled)
    observed = _mean(a) - _mean(b)
    extreme = total = 0
    for idx in combinations(range(n), na):
        sa = sum(pooled[i] for i in idx)
        t = sa / na - (total_sum - sa) / (n - na)
        total += 1
        if _is_extreme(t, observed, alternative):
            extreme += 1
    return observed, extreme / total


def two_proportion_ztest(x1, n1, x2, n2):
    if n1 <= 0 or n2 <= 0 or not 0 <= x1 <= n1 or not 0 <= x2 <= n2:
        raise ValueError("need 0 <= x <= n and n > 0 in both groups")
    pooled = (x1 + x2) / (n1 + n2)
    if pooled in (0.0, 1.0):
        raise ValueError("pooled proportion is 0 or 1: no variation")
    se = math.sqrt(pooled * (1 - pooled) * (1 / n1 + 1 / n2))
    diff = x2 / n2 - x1 / n1
    z = diff / se
    return diff, z, math.erfc(abs(z) / math.sqrt(2))


def sample_size_per_arm(p1, p2, alpha=0.05, power=0.8):
    if not (0 < p1 < 1 and 0 < p2 < 1 and 0 < alpha < 1 and 0 < power < 1) or p1 == p2:
        raise ValueError("need different proportions in (0, 1) and alpha, power in (0, 1)")
    nd = NormalDist()
    z_sum = nd.inv_cdf(1 - alpha / 2) + nd.inv_cdf(power)
    return math.ceil(z_sum ** 2 * (p1 * (1 - p1) + p2 * (1 - p2)) / (p1 - p2) ** 2)


def power_two_proportions(p1, p2, n, alpha=0.05):
    if n < 1 or not (0 < p1 < 1 and 0 < p2 < 1 and 0 < alpha < 1):
        raise ValueError("need n >= 1, proportions in (0, 1) and alpha in (0, 1)")
    nd = NormalDist()
    se = math.sqrt((p1 * (1 - p1) + p2 * (1 - p2)) / n)
    d = abs(p1 - p2) / se
    zc = nd.inv_cdf(1 - alpha / 2)
    return nd.cdf(d - zc) + nd.cdf(-d - zc)


def bonferroni_reject(pvals, alpha=0.05):
    m = len(pvals)
    return [p <= alpha / m + EPS for p in pvals]


def bh_adjust(pvals):
    m = len(pvals)
    order = sorted(range(m), key=lambda i: (pvals[i], i))
    adjusted = [0.0] * m
    running = 1.0
    for rank in range(m, 0, -1):
        i = order[rank - 1]
        running = min(running, pvals[i] * m / rank)
        adjusted[i] = running
    return adjusted


def bh_reject(pvals, q=0.05):
    return [a <= q + EPS for a in bh_adjust(pvals)]


def _gamma_upper_regularized(a, x):
    if x <= 0:
        return 1.0
    if x < a + 1:
        term = total = 1.0 / a
        n = a
        for _ in range(1000):
            n += 1
            term *= x / n
            total += term
            if abs(term) < abs(total) * 1e-15:
                break
        return 1.0 - total * math.exp(-x + a * math.log(x) - math.lgamma(a))
    tiny = 1e-300
    b = x + 1 - a
    c = 1 / tiny
    d = 1 / b
    h = d
    for i in range(1, 1000):
        an = -i * (i - a)
        b += 2
        d = an * d + b
        d = tiny if abs(d) < tiny else d
        c = b + an / c
        c = tiny if abs(c) < tiny else c
        d = 1 / d
        delta = d * c
        h *= delta
        if abs(delta - 1) < 1e-15:
            break
    return math.exp(-x + a * math.log(x) - math.lgamma(a)) * h


def chi2_sf(x, df):
    if not isinstance(df, int) or df < 1:
        raise ValueError("df must be a positive integer")
    return min(1.0, max(0.0, _gamma_upper_regularized(df / 2, x / 2)))


def srm_check(observed, expected_ratios):
    k = len(observed)
    if k < 2 or len(expected_ratios) != k or any(o < 0 for o in observed):
        raise ValueError("need k >= 2 arms, matching ratios and non-negative counts")
    if any(r <= 0 for r in expected_ratios) or sum(observed) <= 0:
        raise ValueError("ratios must be positive and the total must be positive")
    total = sum(observed)
    rsum = sum(expected_ratios)
    stat = 0.0
    for o, r in zip(observed, expected_ratios):
        e = total * r / rsum
        stat += (o - e) ** 2 / e
    return stat, chi2_sf(stat, k - 1)


def mcnemar_test(b, c):
    if b < 0 or c < 0:
        raise ValueError("counts cannot be negative")
    if b + c == 0:
        return 0.0, 1.0
    stat = max(abs(b - c) - 1, 0) ** 2 / (b + c)
    return stat, chi2_sf(stat, 1)


def corrected_resampled_t(diffs, n_train, n_test):
    k = len(diffs)
    if k < 2 or n_train <= 0 or n_test <= 0:
        raise ValueError("need at least 2 differences and positive set sizes")
    mu = _mean(diffs)
    s2 = sum((d - mu) ** 2 for d in diffs) / (k - 1)
    if s2 == 0:
        raise ValueError("zero variance")
    return mu / math.sqrt((1 / k + n_test / n_train) * s2)


# ---------------------------------------------------------------- experiments
import random
import time
from statistics import NormalDist

T0 = time.time()
ND = NormalDist()


def mean(xs):
    return sum(xs) / len(xs)


def var_unbiased(xs):
    m = mean(xs)
    return sum((x - m) ** 2 for x in xs) / (len(xs) - 1)


def binomial(rng, n, p):
    return sum(1 for _ in range(n) if rng.random() < p)


def normal_pvalue(z):
    return math.erfc(abs(z) / math.sqrt(2))


print("== 1. Sampling, estimators, bias and variance")
rng = random.Random(1)
print("1a. mean of n draws from Exponential(1) (mean 1, sd 1), 4000 repeats")
for n in (5, 30, 200):
    means = [mean([rng.expovariate(1.0) for _ in range(n)]) for _ in range(4000)]
    mu = mean(means)
    sd = math.sqrt(var_unbiased(means))
    lo = sum(1 for m in means if m < 1 - 1.96 / math.sqrt(n)) / len(means)
    hi = sum(1 for m in means if m > 1 + 1.96 / math.sqrt(n)) / len(means)
    print("   n=%3d: mean of means %.3f, sd of the mean %.3f (sigma/sqrt(n) = %.3f), below-tail %.3f, above-tail %.3f"
          % (n, mu, sd, 1 / math.sqrt(n), lo, hi))

rng = random.Random(2)
v_n, v_n1, sd_n1 = [], [], []
for _ in range(20000):
    xs = [rng.gauss(0, 1) for _ in range(5)]
    m = mean(xs)
    ss = sum((x - m) ** 2 for x in xs)
    v_n.append(ss / 5)
    v_n1.append(ss / 4)
    sd_n1.append(math.sqrt(ss / 4))
print("1b. n=5, true variance 1, 20000 repeats: average of divide-by-n %.3f, divide-by-(n-1) %.3f, average of the square root of the latter %.3f"
      % (mean(v_n), mean(v_n1), mean(sd_n1)))

rng = random.Random(3)
true_mu, n, c = 0.5, 10, 0.8
err_plain, err_shrunk = [], []
for _ in range(40000):
    xbar = mean([rng.gauss(true_mu, 1) for _ in range(n)])
    err_plain.append((xbar - true_mu) ** 2)
    err_shrunk.append((c * xbar - true_mu) ** 2)
print("1c. estimating a mean of 0.5 from n=10 draws with sd 1: MSE of the sample mean %.4f (theory %.4f), MSE of 0.8 x the mean %.4f (theory %.4f = variance %.4f + bias^2 %.4f)"
      % (mean(err_plain), 1 / n, mean(err_shrunk), c * c / n + ((c - 1) * true_mu) ** 2, c * c / n, ((c - 1) * true_mu) ** 2))

def t_coverage(c, df, steps=20000):
    def pdf(x):
        return math.exp(math.lgamma((df + 1) / 2) - math.lgamma(df / 2)) / math.sqrt(df * math.pi) * (1 + x * x / df) ** (-(df + 1) / 2)
    h = c / steps
    total = pdf(0) + pdf(c) + sum(pdf(i * h) * (4 if i % 2 else 2) for i in range(1, steps))
    return 2 * total * h / 3


print("\n== 2. Confidence intervals: analytic and bootstrap")
print("   theory for normal data, n=10: an interval mean +/- 1.96 s/sqrt(n) covers with probability P(|t9| < 1.96) = %.3f; with the divide-by-n spread (as the bootstrap sees it) P(|t9| < 1.96 sqrt(0.9)) = %.3f"
      % (t_coverage(1.96, 9), t_coverage(1.96 * math.sqrt(0.9), 9)))
rng = random.Random(4)
reps = 400
cases = [("normal data, n=10", 10, lambda: rng.gauss(0, 1), 0.0),
         ("lognormal(0,1) data, n=15", 15, lambda: math.exp(rng.gauss(0, 1)), math.exp(0.5)),
         ("lognormal(0,1) data, n=60", 60, lambda: math.exp(rng.gauss(0, 1)), math.exp(0.5))]
for label, n, draw, truth in cases:
    hit_z = hit_b = low_z = low_b = 0
    width_z = width_b = 0.0
    for _ in range(reps):
        xs = [draw() for _ in range(n)]
        m, s = mean(xs), math.sqrt(var_unbiased(xs))
        lo, hi = m - 1.96 * s / math.sqrt(n), m + 1.96 * s / math.sqrt(n)
        hit_z += lo <= truth <= hi
        low_z += hi < truth
        width_z += hi - lo
        blo, bhi = bootstrap_ci(xs, mean, 200, 0.05, rng)
        hit_b += blo <= truth <= bhi
        low_b += bhi < truth
        width_b += bhi - blo
    print("   %-26s coverage: normal-approximation %.3f (width %.2f), percentile bootstrap %.3f (width %.2f)"
          % (label, hit_z / reps, width_z / reps, hit_b / reps, width_b / reps))
    print("   %-26s share of misses that lie entirely below the true mean: normal-approximation %.2f, bootstrap %.2f"
          % ("", low_z / max(reps - hit_z, 1), low_b / max(reps - hit_b, 1)))
data = [3, 5, 4, 9, 4, 6, 3, 5, 4, 5, 20, 4]
lo, hi = bootstrap_ci(data, mean, 2000, 0.05, random.Random(5))
print("   one dataset: mean %.3f, 95%% bootstrap interval (%.3f, %.3f)" % (mean(data), lo, hi))
lo, hi = bootstrap_ci(data, lambda xs: sorted(xs)[len(xs) // 2 - 1] / 2 + sorted(xs)[len(xs) // 2] / 2, 2000, 0.05, random.Random(5))
print("   same data, median: 95%% bootstrap interval (%.3f, %.3f)" % (lo, hi))

print("\n== 3. Hypothesis tests on a conversion test")
d, z, p = two_proportion_ztest(1000, 10000, 1090, 10000)
se = math.sqrt(0.1 * 0.9 / 10000 + (1090 / 10000) * (1 - 1090 / 10000) / 10000)
print("   1000/10000 against 1090/10000: lift %.4f, z %.3f, p %.4f, 95%% interval for the lift (%.4f, %.4f)"
      % (d, z, p, d - 1.96 * se, d + 1.96 * se))
d, z, p = two_proportion_ztest(200, 2000, 218, 2000)
print("   same rates on a fifth of the traffic (200/2000 against 218/2000): lift %.4f, z %.3f, p %.4f" % (d, z, p))
d, z, p = two_proportion_ztest(10000, 100000, 10090, 100000)
print("   same lift of 0.0009 with 100000 per arm: z %.3f, p %.5f" % (z, p))
a = [12, 15, 9, 20, 31, 11]
b = [8, 10, 7, 11, 9, 14, 6]
obs, p_exact = exact_permutation_test(a, b)
obs2, p_rand = permutation_test(a, b, 9999, random.Random(6))
print("   permutation test, 6 against 7 skewed values: difference in means %.3f, exact p %.4f (1716 splits), randomised p %.4f (9999 shuffles)"
      % (obs, p_exact, p_rand))
p_greater = exact_permutation_test(a, b, "greater")[1]
print("   one-sided exact p (greater) %.4f; twice the smaller one-sided p, the convention of scipy.stats.permutation_test, is %.4f against the %.4f above" % (p_greater, 2 * p_greater, p_exact))

print("\n== 4. What a p-value is, and is not")
rng = random.Random(7)
ps = []
for _ in range(2000):
    x1, x2 = binomial(rng, 500, 0.1), binomial(rng, 500, 0.1)
    ps.append(two_proportion_ztest(x1, 500, x2, 500)[2])
print("   2000 A/A tests (no true effect), 500 users per arm: share with p < 0.05 is %.3f, share with p < 0.5 is %.3f"
      % (sum(1 for q in ps if q < 0.05) / len(ps), sum(1 for q in ps if q < 0.5) / len(ps)))
rng = random.Random(8)
sims, looks, per_look = 1000, 10, 100
fixed = peeked = 0
for _ in range(sims):
    c1 = c2 = 0
    stopped = False
    for k in range(1, looks + 1):
        c1 += binomial(rng, per_look, 0.1)
        c2 += binomial(rng, per_look, 0.1)
        q = two_proportion_ztest(c1, k * per_look, c2, k * per_look)[2] if c1 + c2 > 0 else 1.0
        if q < 0.05:
            stopped = True
        if k == looks and q < 0.05:
            fixed += 1
    peeked += stopped
print("   1000 A/A tests with up to 10 looks (1000 users per arm at the end): fixed-horizon false positives %.3f, stop-at-first-significant %.3f"
      % (fixed / sims, peeked / sims))
prior_real, power_, alpha_ = 0.10, 0.80, 0.05
ppv = power_ * prior_real / (power_ * prior_real + alpha_ * (1 - prior_real))
print("   if 10%% of tested ideas truly work, power is 0.80 and alpha 0.05, the chance that a significant result is real is %.3f" % ppv)

print("\n== 5. Power and sample size")
for p2 in (0.12, 0.11, 0.105):
    print("   baseline 0.10 against %.3f: %6d users per arm" % (p2, sample_size_per_arm(0.10, p2)))
print("   cost ratio, 0.5-point lift against 2-point lift: %.2f times the users" % (sample_size_per_arm(0.10, 0.105) / sample_size_per_arm(0.10, 0.12)))
print("   rule of 16 for baseline 0.10 and a 0.01 lift: %.0f per arm; exact formula: %d" % (16 * 0.09 / 0.01 ** 2, sample_size_per_arm(0.10, 0.11)))
n_need = sample_size_per_arm(0.30, 0.35)
print("   baseline 0.30 against 0.35 needs %d per arm; formula power at that n %.3f; at 500 per arm %.3f" % (n_need, power_two_proportions(0.30, 0.35, n_need), power_two_proportions(0.30, 0.35, 500)))
rng = random.Random(9)
for n in (n_need, 500):
    wins = 0
    trials = 600
    for _ in range(trials):
        q = two_proportion_ztest(binomial(rng, n, 0.30), n, binomial(rng, n, 0.35), n)[2]
        wins += q < 0.05
    print("   simulated power with %d per arm over %d trials: %.3f" % (n, trials, wins / trials))

print("\n== 6. Many comparisons")
print("   chance of at least one p < 0.05 among 20 independent true nulls: %.3f" % (1 - 0.95 ** 20))
pv = [0.001, 0.012, 0.018, 0.030, 0.45]
print("   p-values %s: Bonferroni cut-off %.3f rejects %d; BH adjusted %s rejects %d at q 0.05"
      % (pv, 0.05 / 5, sum(bonferroni_reject(pv)), [round(x, 4) for x in bh_adjust(pv)], sum(bh_reject(pv))))
rng = random.Random(10)
tot = {"uncorrected": [0, 0, 0], "bonferroni": [0, 0, 0], "bh": [0, 0, 0]}
reps = 500
for _ in range(reps):
    pvals = [rng.random() for _ in range(80)] + [normal_pvalue(rng.gauss(3, 1)) for _ in range(20)]
    for name, rej in (("uncorrected", [x < 0.05 for x in pvals]), ("bonferroni", bonferroni_reject(pvals)), ("bh", bh_reject(pvals))):
        false_d = sum(rej[:80])
        true_d = sum(rej[80:])
        tot[name][0] += false_d
        tot[name][1] += true_d
        tot[name][2] += (false_d / (false_d + true_d)) if false_d + true_d else 0.0
for name, (f, t, fdp) in tot.items():
    print("   %-12s per 100 tests (80 null, 20 real, z shift 3): false discoveries %.2f, true discoveries %.2f, false discovery proportion %.3f"
          % (name, f / reps, t / reps, fdp / reps))

print("\n== 7. Experiments on ML systems")
rng = random.Random(11)
sims, users, views = 500, 200, 20
a_, b_ = 1, 9
rho = (a_ * b_ / ((a_ + b_) ** 2 * (a_ + b_ + 1))) / (0.1 * 0.9)
deff = 1 + (views - 1) * rho
bad = 0
for _ in range(sims):
    counts = []
    for _arm in range(2):
        clicks = 0
        for _u in range(users):
            pu = rng.betavariate(a_, b_)
            clicks += binomial(rng, views, pu)
        counts.append(clicks)
    bad += two_proportion_ztest(counts[0], users * views, counts[1], users * views)[2] < 0.05
print("   A/A tests, 200 users per arm, 20 page views each, randomised by USER but analysed by page view: false positives %.3f" % (bad / sims))
print("   within-user correlation rho %.4f, design effect 1 + (m - 1) rho = %.2f, predicted false-positive rate %.3f"
      % (rho, deff, 2 * (1 - ND.cdf(1.96 / math.sqrt(deff)))))
for obs_ in ([10400, 9600], [50500, 49500], [520, 480], [5200, 4800]):
    stat, p = srm_check(obs_, [1, 1])
    print("   SRM check, observed %s against a 50/50 design: chi-square %.2f, p %.3g" % (obs_, stat, p))
print("   three arms 3400/3300/3300 against 1:1:1 -> chi-square %.2f, p %.3f" % srm_check([3400, 3300, 3300], [1, 1, 1]))
a_easy, a_hard, b_easy, b_hard = (90, 100), (300, 900), (800, 900), (30, 100)
print("   Simpson: arm A easy %.3f hard %.3f overall %.3f; arm B easy %.3f hard %.3f overall %.3f"
      % (a_easy[0] / a_easy[1], a_hard[0] / a_hard[1], (a_easy[0] + a_hard[0]) / (a_easy[1] + a_hard[1]),
         b_easy[0] / b_easy[1], b_hard[0] / b_hard[1], (b_easy[0] + b_hard[0]) / (b_easy[1] + b_hard[1])))

print("\n== 8. Comparing two models fairly")
rng = random.Random(12)
n_items = 1000
a_right, b_right = [], []
for _ in range(n_items):
    difficulty = rng.gauss(0, 1)
    a_right.append(difficulty + rng.gauss(0, 0.3) < 0.84)
    b_right.append(difficulty + rng.gauss(0, 0.3) < 0.99)
acc_a, acc_b = mean(a_right), mean(b_right)
only_a = sum(1 for x, y in zip(a_right, b_right) if x and not y)
only_b = sum(1 for x, y in zip(a_right, b_right) if y and not x)
stat, p_mc = mcnemar_test(only_a, only_b)
_, z_u, p_u = two_proportion_ztest(sum(a_right), n_items, sum(b_right), n_items)
print("   accuracy A %.3f, B %.3f; A-only right %d, B-only right %d" % (acc_a, acc_b, only_a, only_b))
print("   McNemar (paired): chi-square %.2f, p %.4f; unpaired two-proportion z-test on the same accuracies: z %.2f, p %.4f" % (stat, p_mc, z_u, p_u))
diffs_items = [(1 if y else 0) - (1 if x else 0) for x, y in zip(a_right, b_right)]
lo, hi = bootstrap_ci(diffs_items, mean, 2000, 0.05, random.Random(13))
print("   bootstrap 95%% interval for the accuracy gain B minus A over the items: (%.4f, %.4f)" % (lo, hi))
diffs = [0.012, 0.020, 0.008, 0.015, 0.011, 0.018, 0.006, 0.014, 0.017, 0.009]
k = len(diffs)
naive = mean(diffs) / math.sqrt(var_unbiased(diffs) / k)
corr = corrected_resampled_t(diffs, 900, 100)
print("   ten 90/10 splits, score gaps (constructed): naive t %.2f, corrected t %.2f (ratio %.3f)" % (naive, corr, corr / naive))

print("\n== 9. A Bayesian view")
print("   1%% prevalence, sensitivity 90%%, false-positive rate 10%%: P(disease | +) = %.4f" % (0.01 * 0.9 / (0.01 * 0.9 + 0.99 * 0.1)))
print("   1%% prevalence, sensitivity 99%%, false-positive rate 5%%: P(disease | +) = %.4f" % (0.01 * 0.99 / (0.01 * 0.99 + 0.99 * 0.05)))
print("   10%% prevalence, sensitivity 90%%, false-positive rate 10%%: P(disease | +) = %.4f" % (0.10 * 0.9 / (0.10 * 0.9 + 0.90 * 0.1)))
print("   0.1%% prevalence, sensitivity 90%%, false-positive rate 10%%: P(disease | +) = %.4f" % (0.001 * 0.9 / (0.001 * 0.9 + 0.999 * 0.1)))
rng = random.Random(14)
draws = 20000
pa = [rng.betavariate(1 + 100, 1 + 900) for _ in range(draws)]
pb = [rng.betavariate(1 + 120, 1 + 880) for _ in range(draws)]
lift = sorted(y - x for x, y in zip(pa, pb))
print("   Beta(1,1) prior, A 100/1000, B 120/1000: posterior mean A %.4f, B %.4f, P(B > A) = %.3f, 95%% credible interval for the lift (%.4f, %.4f)"
      % (101 / 1002, 121 / 1002, sum(1 for x, y in zip(pa, pb) if y > x) / draws, lift[int(0.025 * draws)], lift[int(0.975 * draws) - 1]))
d, z, p = two_proportion_ztest(100, 1000, 120, 1000)
print("   same data with the z-test: lift %.3f, z %.3f, two-sided p %.4f, one-sided p %.4f (posterior P(A >= B) = %.3f)" % (d, z, p, p / 2, 1 - sum(1 for x, y in zip(pa, pb) if y > x) / draws))

print("\n== 10. Correlation and causation")
rng = random.Random(15)
N = 20000
zs = [rng.gauss(0, 1) for _ in range(N)]
xs = [z_ + rng.gauss(0, 1) for z_ in zs]
ys = [z_ + rng.gauss(0, 1) for z_ in zs]
xr = [rng.gauss(0, 1.4142135623730951) for _ in range(N)]


def corr(u, v):
    mu, mv = mean(u), mean(v)
    cov = sum((a_ - mu) * (b_ - mv) for a_, b_ in zip(u, v))
    return cov / math.sqrt(sum((a_ - mu) ** 2 for a_ in u) * sum((b_ - mv) ** 2 for b_ in v))


print("   a hidden Z drives both X and Y; X has no effect on Y. Observed corr(X, Y) = %.3f (theory 0.5)" % corr(xs, ys))
print("   assign X at random instead: corr(X, Y) = %.3f" % corr(xr, ys))

print("\ntotal %.1f s" % (time.time() - T0))

What to look for: section 1 (standard error and the two kinds of bias), section 2 (interval coverage), section 3 (the tests on the conversion data), section 4 (uniform p-values, peeking), section 5 (sample size and power), section 6 (multiple comparisons), section 7 (unit of randomisation, SRM, Simpson), section 8 (paired comparison), section 9 (Bayes), section 10 (confounding). In SciPy and statsmodels the equivalents are scipy.stats.bootstrap, permutation_test, chisquare, false_discovery_control, statsmodels.stats.proportion.proportions_ztest, statsmodels.stats.power.NormalIndPower and statsmodels.stats.multitest.multipletests.

Real-World Application

A sound recipe for testing a model change: write the hypothesis and one primary metric with guardrails, choose the unit of randomisation and the minimum effect worth shipping, compute the sample size and the duration in whole weeks, run to the planned end, check the sample ratio first, analyse at the level you randomised, report the interval for the effect with the p-value, and decide on effect size and cost. When the offline gain does not appear online, check power, then the metric, then the data path, in that order. When a dashboard shows a surprising winner among many metrics, correct for the number of metrics or treat it as a hypothesis for the next test.

Interview Perspective

Expect “what does a p-value of 0.03 mean”, “how would you size this experiment”, “your 50/50 test shows 52/48 with millions of users”, “why is peeking a problem”, “your offline metric improved but the A/B test shows no lift”, “a test is 99% accurate and you test positive”, and “how do you know one model is better than another”. A strong answer states the definition in one sentence, names the assumption that matters, gives a number or a check, and says what it would do next. A weak answer recites a rule (“p less than 0.05 is significant”) without saying what the experiment could have gotten wrong.

Provenance: Common industry pattern. These are standard statistics and experimentation topics for ML and applied-science roles, not a verified list for any named company.

Practice Questions

  • Basic (Common industry pattern): What does a 95% confidence interval mean, and what does it not mean?
  • Basic (Common industry pattern): What does a p-value of 0.03 mean? Give two things it does not mean.
  • Intermediate (Common industry pattern): Your 50/50 A/B test shows a 52/48 split over millions of users. What do you do?
  • Intermediate (Common industry pattern): Why does checking an A/B test every day and stopping at the first significant result inflate false positives, and how would you monitor safely?
  • Intermediate (Generated practice): Baseline conversion is 5% and you want to detect a lift of 0.5 percentage points. Set up the sample-size calculation and say what happens to the size if the lift halves.
  • Advanced (Common industry pattern): Your offline metric improved but the A/B test showed no lift. List the causes in the order you would check them.
  • Advanced (Generated practice): You test 40 metrics and 3 are significant at 0.05. What can you conclude, and what would you do?
  • Product-Company (Generated practice): Compare two classifiers offline on one test set with 0.8 and 0.82 accuracy. Design the comparison so that the claim “B is better” is defensible.

Activity

Run the script, then change two things. In section 4, raise the number of looks from 10 to 20 and note how the stop-at-first-significant rate moves. In section 7, cut the page views per user from 20 to 5 and check that the page-level false-positive rate falls. Then write the sentence you would send a product manager about an A/B test with p=0.07p=0.07 and an interval for the lift of (-0.2, 1.4) percentage points.

Homework

Implement the experiment toolkit: a percentile bootstrap interval that takes its random generator as an argument, exact and randomised permutation tests, a two-proportion z-test, sample size and power, Bonferroni and Benjamini-Hochberg, a chi-square tail with an SRM check, McNemar’s test and the corrected resampled t statistic. The code is in homework/; run the tests until they pass.

Quick Revision

  • A statistic is one draw from a sampling distribution. Standard error is σ/n\sigma/\sqrt{n}. A 95% interval is a property of the procedure. The bootstrap needs no formula but does not rescue small, skewed samples.
  • A p-value is the chance of data this extreme if there were no effect. It is not the chance the null is true, not the effect size, and a non-significant result from a small test is inconclusive.
  • Size the test before running it: nn grows with the inverse square of the lift. About 14,749 per arm for 10% to 11%. Halving the lift quadruples the size.
  • Many looks, many metrics: Bonferroni controls any false positive, Benjamini-Hochberg controls the share of false discoveries. Peeking at 10 looks took the false-positive rate from about 0.06 to 0.22.
  • A/B testing: randomise at the level you analyse, check the sample ratio first, run whole weeks, keep guardrails, and treat offline gains as hypotheses.
  • Compare models with a paired test or interval, correct the cross-validation t-test, and remember that base rates decide what a positive result means.

Check yourself

  • Walk-through: Without notes, explain how you would size and run an A/B test for a new ranking model, from the metric to the decision, naming the check you do before you look at the result.
  • Variation: A test shows p=0.04p=0.04 for the primary metric, an SRM p-value of 0.0002, and two of nine secondary metrics significant. Say what you believe and what you do next.
  • Common misconception: “p = 0.03 means a 97% chance the effect is real”, “a non-significant result means no effect”, and “a 95% interval has a 95% chance of containing the truth”.

Resources & Further Reading

Checked sources to go deeper. The essential ones come first in each group.

Official documentation

Further reading

Research papers

More for this module: Evaluation, statistics and data resources

Practice

Test what you just read. Quizzes and cards are grouped by module: Evaluation, statistics and data.

Check yourself23 questions on what this lesson set out to teach

Checking answers needs JavaScript. You can still read every question and option below.

0 of 23 answered

Keyboard: arrow keys move between options. Space or Enter selects the focused option.

ObjectiveExplain an estimator, its bias and variance, and a confidence interval, and compute an analytic and a bootstrap interval while knowing when each one is unreliable.

  1. Question 1 of 23You draw 4,000 samples of size 5 from a right-skewed distribution with mean 1 and standard deviation 1. The standard deviation of the sample means is 0.453, close to the theoretical 0.447. Yet only 0.1% of the means fall below 1 - 1.96 x 0.447, while 4.4% fall above 1 + 1.96 x 0.447. What does this show?

    Choose one answer.

  2. Question 2 of 23A report says: "the 95% interval for the mean session length is (4.1, 8.8) minutes." Which reading is correct?

    Choose one answer.

  3. Question 3 of 23For samples of size 5 from a distribution with true variance 1, the average of the sum of squared deviations divided by n is 0.798, and divided by n - 1 it is 0.997. What follows?

    Choose one answer.

  4. Question 4 of 23Estimating a mean of 0.5 from 10 draws with standard deviation 1, the sample mean has mean squared error about 0.100. Multiplying it by 0.8 gives about 0.074. How is that possible when the second estimator is biased?

    Choose one answer.

  5. Question 5 of 23Which statements about bootstrap and analytic confidence intervals are true? Select all that apply.

    Choose all that apply.

ObjectiveChoose and run a z, chi-square or permutation test, and say what a p-value, a type I error, a type II error and power mean, including the standard misreadings.

  1. Question 6 of 23A colleague says a result with p = 0.03 means there is a 97% chance that the effect is real. What is the best correction?

    Choose one answer.

  2. Question 7 of 23The same conversion rates (10.0% against 10.9%) give p = 0.0375 with 10,000 users per arm and p = 0.3522 with 2,000 per arm. What is the right interpretation?

    Choose one answer.

  3. Question 8 of 23You have 9 and 11 revenue values per user from two small groups, with one huge outlier in each, and you cannot justify a normal model. Which test is the most defensible, and why?

    Choose one answer.

  4. Question 9 of 23A randomised permutation test with 9,999 shuffles finds no shuffled difference as large as the observed one. Why is its reported p-value 1 / 10,000 and not 0?

    Choose one answer.

  5. Question 10 of 23Which statements about errors and power are true? Select all that apply.

    Choose all that apply.

ObjectiveSize an experiment from a baseline, a minimum effect, alpha and power, and control false positives from many comparisons (Bonferroni, Benjamini-Hochberg) and from peeking.

  1. Question 11 of 23A baseline conversion rate is 10%. Detecting a lift to 11% needs 14,749 users per arm at alpha 0.05 and power 0.8. About how many are needed to detect a lift to 10.5%?

    Choose one answer.

  2. Question 12 of 23A test of 0.30 against 0.35 with 500 users per arm is not significant (p = 0.20). The formula says its power for this effect was 0.394. What should the team say?

    Choose one answer.

  3. Question 13 of 23You get five p-values: 0.001, 0.012, 0.018, 0.030 and 0.45. Which result is correct at an overall level of 0.05?

    Choose one answer.

  4. Question 14 of 23A dashboard has 20 independent metrics and no real effects anywhere. Roughly what is the chance that at least one has p < 0.05?

    Choose one answer.

  5. Question 15 of 23In 1,000 simulated A/A tests (no true effect), a single test at the planned end gave a false-positive rate of 0.058. Stopping at the first of 10 looks with p < 0.05 gave 0.219. What explains the second number?

    Choose one answer.

ObjectiveDesign and sanity-check an A/B test of an ML system (unit of randomisation, sample ratio mismatch, novelty, interference, offline-online gaps) and say when a correlation can support a causal claim.

  1. Question 16 of 23Your 50/50 experiment has 50,500 users in control and 49,500 in treatment. The SRM chi-square is 10.0 (p = 0.0016). The treatment shows a significant gain. What should you do?

    Choose one answer.

  2. Question 17 of 23A team randomises 200 users per arm, each with 20 page views, but runs a page-view-level z-test as if all 8,000 views per arm were independent. In an A/A simulation, 21.4% of tests were significant at 5%. What is the cause and the fix?

    Choose one answer.

  3. Question 18 of 23Your new model improved the offline metric but an A/B test shows no lift. Which are plausible causes to check? Select all that apply.

    Choose all that apply.

  4. Question 19 of 23A hidden variable Z drives both X and Y, and X has no effect on Y. The observed correlation between X and Y is 0.502. When X is assigned at random instead, the correlation is -0.008. What does this show?

    Choose one answer.

ObjectiveCompare two models with a paired test or interval instead of two separate scores, say why cross-validation scores are not independent, and apply Bayes' rule to a base-rate or posterior question.

  1. Question 20 of 23Two models have accuracies 0.770 and 0.798 on the same 1,000 items. An unpaired two-proportion test gives p = 0.128, while McNemar's test on the disagreements (29 items only A right, 57 only B right) gives p = 0.0036. Why do they differ?

    Choose one answer.

  2. Question 21 of 23Ten random 90/10 train-test splits give ten paired score differences. A plain t-test gives t = 8.95. The Nadeau-Bengio corrected statistic is 6.16. What problem does the correction address?

    Choose one answer.

  3. Question 22 of 23A disease has 1% prevalence. A test has 90% sensitivity and a 10% false-positive rate. Someone tests positive. About what is the chance they are sick?

    Choose one answer.

  4. Question 23 of 23With a flat prior, variant A has 100 conversions in 1,000 and variant B has 120 in 1,000. The posterior probability that B beats A is 0.925, and the z-test p-value is 0.153. How do the two numbers relate?

    Choose one answer.