Slides · Evaluation, statistics and data

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

Statistics and experimentation

Intervals, tests, power, A/B tests of ML systems and fair model comparison.

Concept

Why this is worth 100 minutes

  • Every shipped ML change is judged by a number with noise around it. The costly mistakes are decisions: shipping on noise, missing a real gain, or trusting a broken test.
  • Interviewers ask about p-values, power, A/B pitfalls and base rates because they cannot be answered by recall (common industry pattern).
  • Mental model: each number is one draw from a distribution you cannot see.

Five things you will be able to do:

  1. Compute and interpret an interval, analytic or bootstrap.
  2. Run a test and read a p-value without the usual misreadings.
  3. Size a test and control many comparisons and peeking.
  4. Check an A/B test of an ML system before trusting it.
  5. Compare two models fairly and work a base-rate problem.

Math

Standard error and bias

SE(xˉ)=σn,MSE=bias2+variance\mathrm{SE}(\bar{x})=\frac{\sigma}{\sqrt{n}}, \qquad \mathrm{MSE}=\mathrm{bias}^2+\mathrm{variance}
  • Exponential data, n = 5: sd of the mean 0.453 against 0.447, but the tails are 0.1% and 4.4%, not 2.5% each.
  • Divide squared deviations by n and the variance averages 0.798 at n = 5; by n - 1 it averages 0.997.
  • A biased estimator can win: 0.8 times the mean had error 0.0743 against 0.1003.

Compare

What an interval says

ReadingVerdict
The procedure covers the truth in about 95% of repeated studiesCorrect
The parameter has a 95% chance of lying in this one intervalThe usual misreading
95% of single observations lie in itWrong: it is for the mean
  • Analytic: estimate plus or minus z times SE. Needs a roughly Gaussian mean.
  • Bootstrap: resample with replacement, recompute, read percentiles. No formula needed.

Worked example

Intervals under-cover on small, skewed data

DataNormal approximationPercentile bootstrap
Normal, n = 100.9200.910
Lognormal, n = 150.8000.805
Lognormal, n = 600.8650.858
  • The promise was 0.95. The bootstrap does not repair a small or heavy-tailed sample.
  • Normal, n = 10: 1.96 instead of a t quantile gives 0.918 in theory; the bootstrap divides by n, which is narrower, and gives 0.904 in theory.
  • Lognormal: the spread is small when the mean is small, so 96% of the misses at n = 15 fell below the true mean.

Source1 scipy.stats.bootstrap

Check yourself

Check: an interval for AUC

You need an interval for the AUC of a model on 400 test rows. There is no simple formula. What do you do?

Answer

Bootstrap the rows: draw 400 rows with replacement, recompute the AUC, repeat a few thousand times, and take the 2.5th and 97.5th percentiles. Keep each row’s label and score together. Expect a wide interval if positives are few.

Compare

Which test

DataTest
Two conversion ratesTwo-proportion z-test, pooled SE
Two meanst-test; Welch if variances differ
Counts against a designChi-square goodness of fit
Small, skewed or any statisticPermutation test
  • 1,000/10,000 against 1,090/10,000: z = 2.080, p = 0.0375. The same rates at a fifth of the traffic: p = 0.3522.
  • Randomised permutation p-value: (extreme + 1) / (B + 1).

Sources2 scipy.stats.ttest_ind3 scipy.stats.chisquare4 scipy.stats.permutation_test

Concept

What a p-value is

  • If there were no effect, how often would data this extreme occur?
  • It is not the probability that the null is true, not the effect size, and not a reason to ship.
  • Under a true null it is uniform: 2,000 A/A tests gave 4.1% below 0.05 and 49.5% below 0.5.
  • If 10% of ideas work, power is 0.8 and alpha 0.05, only 0.640 of significant results are real.
  • Errors: type I is alpha, type II is beta, power is 1 - beta.

Source5 American Statistical Association releases statement on statistical significance and p-values (press release, 7 March 2016)

Check yourself

Check: significant but tiny

A test of millions of users reports p = 0.001 for a lift of 0.01 percentage points. Ship?

Answer

Statistically significant does not mean practically significant. Read the interval for the lift, compare it with the cost of shipping and maintaining the change, and decide on effect size. With enough data any non-zero effect is significant.

Math

Sample size

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}
Baseline 0.10 againstUsers per arm
0.1203,839
0.11014,749
0.10557,760
  • Rule of 16: 14,400 for 0.10 against 0.11.
  • statsmodels NormalIndPower does a closely related two-sample z-test power calculation.
  • 0.30 against 0.35 needs 1,374 (power 0.800, simulated 0.817). At 500 the power is 0.394.

Source6 statsmodels.stats.power.NormalIndPower

Check yourself

Check: why 15 times more?

Going from a 2-point lift (3,839 per arm) to a 0.5-point lift (57,760) costs about 15 times the data for a lift only 4 times smaller. Why?

Answer

The lift is squared in the denominator, so a 4-fold smaller lift needs about 16 times the users. The small gap from 16 comes from the variance term, which changes a little with the rates.

Compare

Many comparisons

RuleControlsPer 100 tests: false / true discoveries
None, p < 0.05Nothing3.83 / 17.15
BonferroniAny false positive0.05 / 6.52
Benjamini-HochbergShare of false discoveries0.55 / 12.30
  • 20 true nulls: chance of at least one p < 0.05 is 0.642.
  • p = 0.001, 0.012, 0.018, 0.030, 0.45: Bonferroni rejects 1, BH rejects 4.
  • Forking paths: choosing the analysis after seeing the data is also a multiple comparison (Gelman and Loken).

Sources7 scipy.stats.false_discovery_control8 statsmodels.stats.multitest.multipletests9 Controlling the False Discovery Rate: A Practical and Powerful Approach to Multiple Testing10 The garden of forking paths: Why multiple comparisons can be a problem, even when there is no fishing expedition or p-hacking and the research hypothesis was posited ahead of time

Check yourself

Check: forty metrics

A report tests 40 metrics, none has a real effect. How many significant results at 0.05 do you expect, and what do you tell the team?

Answer

About 2 (40 x 0.05). Two significant metrics among forty are what chance alone produces. Treat them as hypotheses for a follow-up test, or correct for 40 comparisons.

Diagram

An A/B test, in order

Diagram: Fix the metric, unit and size before launch, run to the planned end, check the arm sizes before reading the result, and analyse at the unit...

mismatch

ok

One primary metric,
guardrails, minimum effect

Unit of randomisation

Sample size and duration

Run to the planned end

SRM check

Debug, do not read the result

Analyse at the randomised unit

Decide on effect size and risk

Diagram summary: Fix the metric, unit and size before launch, run to the planned end, check the arm sizes before reading the result, and analyse at the unit you randomised.

Worked example

Unit and sample ratio

  • Randomised by user, analysed by page view (20 views each): 21.4% of A/A tests significant at 5%. Design effect 1 + (m - 1) rho = 2.73, predicted 0.235.
Observed against 50/50Chi-squarep
10,400 and 9,60032.001.54e-08
50,500 and 49,50010.000.00157
520 and 4801.600.206
  • Peeking: 0.058 at the planned end, 0.219 when stopping at the first significant of 10 looks.

Source11 Trustworthy Online Controlled Experiments: A Practical Guide to A/B Testing

Check yourself

Check: three arms

A 1:1:1 test shows 3,400, 3,300 and 3,300 users. Is there a sample ratio mismatch?

Answer

No. The chi-square statistic is 2.00 with 2 degrees of freedom, p = 0.368, which is well within chance. Degrees of freedom are the number of arms minus one.

Concept

Offline win, online nothing

Check in this order (common practice):

  1. Power: could the test see the lift?
  2. Metric mismatch: is the offline metric what users respond to?
  3. Selected data: did the old model choose what was logged?
  4. Distribution shift and training-serving bugs.
  5. Novelty: does the effect decay over weeks?

Correlation: with a hidden Z behind X and Y, corr(X, Y) was 0.502 with no effect; with X randomised it was -0.008.

Math

Comparing models

χ2=(max⁡(∣b−c∣−1,0))2b+c,t=dˉ(1k+ntestntrain)s2\chi^2=\frac{\left(\max(|b-c|-1,0)\right)^2}{b+c}, \qquad t=\frac{\bar d}{\sqrt{\left(\frac1k+\frac{n_{\text{test}}}{n_{\text{train}}}\right)s^2}}
  • Accuracies 0.770 and 0.798, disagreements 29 and 57: McNemar p = 0.0036, unpaired test p = 0.128.
  • Bootstrap interval for the gain: (0.0100, 0.0450).
  • Ten 90/10 splits: naive t 8.95, corrected t 6.16.
  • Dietterich: random-split t-test has a high type I error; McNemar is low.

Sources12 Approximate Statistical Tests for Comparing Supervised Classification Learning Algorithms13 Introduction to correctR (corrected resampled t-test of Nadeau and Bengio)14 Statistical Comparisons of Classifiers over Multiple Data Sets

Check yourself

Check: McNemar inputs

Two models are both right on 800 of 1,000 test items and both wrong on 90. What goes into McNemar’s test?

Answer

Only the 110 items where they disagree: how many only A got right and how many only B got right. Items both get right or both get wrong carry no information about which is better.

Worked example

Bayes and base rates

  • Natural frequencies, 10,000 people at 1% prevalence, 90% sensitivity, 10% false-positive rate: 90 true and 990 false positives, so P(sick | positive) = 0.0833.
  • At 99% and 5% it is 0.1667. At 10% prevalence with the first test it is 0.5000.
  • A/B posterior (flat prior): A 100/1000, B 120/1000 gives P(B > A) = 0.925, while the z-test gives p = 0.1529. Different quantities.
  • Gaussian prior is L2 and Laplace prior is L1 (common practice).

Check yourself

Check: a rarer disease

Keep the 90% sensitivity and 10% false-positive rate, but prevalence falls to 0.1%. Does P(sick | positive) rise or fall, and why?

Answer

It falls, to about 0.9% (0.0089): of 10,000 people, 9 sick people and 999 healthy people test positive. The rarer the condition, the larger the share of positives that are false alarms.

Code

Homework: the experiment toolkit

Python

def bootstrap_ci(data, stat, n_resamples, alpha, rng):
    """Percentile interval; rng.randrange(n) draws the indices."""

def sample_size_per_arm(p1, p2, alpha=0.05, power=0.8):
    """Users per arm, rounded up."""

def srm_check(observed, expected_ratios):
    """Chi-square statistic and p-value for the arm counts."""
  • Also: exact and randomised permutation tests, z-test, power, Bonferroni, Benjamini-Hochberg, McNemar and the corrected t.

Summary

Recap

  • Every number is one draw: report an interval. The bootstrap needs no formula but cannot rescue a small, skewed sample.
  • A p-value is about data given no effect. Size the test first: halving the lift quadruples n.
  • Many looks and many metrics need Bonferroni, Benjamini-Hochberg or a fixed horizon.
  • Randomise at the analysed unit, check the sample ratio before reading the effect, treat offline wins as hypotheses.
  • Compare models with paired tests, correct the cross-validation t, and let base rates set what a positive means.

References

References & Sources (1 of 3)

  1. scipy.stats.bootstrap (opens in a new tab)

    SciPy2026Documentation

    Used for Percentile, basic and BCa bootstrap methods, BCa as the default, and the warning about degenerate resamples.

  2. scipy.stats.ttest_ind (opens in a new tab)

    SciPy2026Documentation

    Used for The equal-variance default and Welch's test with equal_var=False.

  3. scipy.stats.chisquare (opens in a new tab)

    SciPy2026Documentation

    Used for Chi-square goodness of fit, the expected-count rule of thumb, and degrees of freedom.

  4. scipy.stats.permutation_test (opens in a new tab)

    SciPy2026Documentation

    Used for Permutation test types, exact versus randomised tests, and the (extreme + 1) / (B + 1) p-value for randomised tests.

  5. American Statistical Association releases statement on statistical significance and p-values (press release, 7 March 2016) (opens in a new tab)

    American Statistical Association2016Documentation

    Used for The six principles of the American Statistical Association statement on p-values, as listed in its press release.

References

References & Sources (2 of 3)

  1. statsmodels.stats.power.NormalIndPower (opens in a new tab)

    statsmodels2026Documentation

    Used for A power calculation for a two-sample z-test with a pooled variance.

  2. scipy.stats.false_discovery_control (opens in a new tab)

    SciPy2026Documentation

    Used for Benjamini-Hochberg and Benjamini-Yekutieli, the FDR definition, the independence or positive-dependence condition, Bonferroni for family-wise error, and the worked adjusted values.

  3. statsmodels.stats.multitest.multipletests (opens in a new tab)

    statsmodels2026Documentation

    Used for The list of multiple-testing corrections (Bonferroni, Holm, Benjamini-Hochberg and others).

  4. Controlling the False Discovery Rate: A Practical and Powerful Approach to Multiple Testing (opens in a new tab)

    Yoav Benjamini, Yosef Hochberg1995Journal of the Royal Statistical Society: Series B 57(1)Paper

    Used for The definition of the false discovery rate and its power advantage over family-wise error control (abstract page).

  5. The garden of forking paths: Why multiple comparisons can be a problem, even when there is no fishing expedition or p-hacking and the research hypothesis was posited ahead of time (opens in a new tab)

    Andrew Gelman, Eric Loken2013Unpublished manuscript, Columbia UniversityPaper

    Used for Multiple comparisons arising from data-contingent analysis choices without deliberate fishing (abstract and introduction).

References

References & Sources (3 of 3)

  1. Trustworthy Online Controlled Experiments: A Practical Guide to A/B Testing (opens in a new tab)

    Ron Kohavi, Diane Tang, Ya Xu2020Book

    Used for A standard reference on online controlled experiments, with chapters on Twyman's law and on sample ratio mismatch (publisher description and chapter listing only).

  2. Approximate Statistical Tests for Comparing Supervised Classification Learning Algorithms (opens in a new tab)

    Thomas G. Dietterich1998Neural Computation 10(7)Paper

    Used for Type I error of five tests for comparing classifiers, McNemar's test, the limits of a single training set, and the 5x2 cross-validation test (abstract and McNemar section read).

  3. Introduction to correctR (corrected resampled t-test of Nadeau and Bengio) (opens in a new tab)

    CRAN correctR2026Documentation

    Used for The Nadeau-Bengio corrected resampled t statistic, why the plain test is too liberal, and the rho = 1/k approximation for k-fold.

  4. Statistical Comparisons of Classifiers over Multiple Data Sets (opens in a new tab)

    Janez Demsar2006Journal of Machine Learning Research 7Paper

    Used for Wilcoxon signed-ranks for two classifiers and Friedman with post-hoc tests for several, over many datasets (abstract page).