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
Select text in the lesson first to keep it with your note. With the keyboard, move focus here and press the button: the note goes with the section you are reading.
In this module
On this page
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.
| Question | Tool 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 significant | Bonferroni, 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:
- How spread out is that distribution? (standard error, interval)
- Is the draw consistent with “nothing changed”? (a test and its p-value)
- Was the experiment large enough to see an effect of the size I care about? (power)
- 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:
| Symbol | Meaning |
|---|---|
| Standard deviation of one observation | |
| Number of independent observations | |
| 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 already at (0.453 against 0.447). The shape does not match: with , only 0.1% of sample means fell below and 4.4% fell above , where a Gaussian would give 2.5% on each side. At 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 draws from a distribution with true variance 1, dividing the sum of squares by averages 0.798, while dividing by averages 0.997. The divisor 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 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 but cuts the variance, for 0.0743 (theory 0.0740).
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:
| Symbol | Meaning |
|---|---|
| Sample standard deviation (divisor ) | |
| 1.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 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.
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:
| Data | Normal-approximation coverage | Percentile bootstrap coverage |
|---|---|---|
| Normal, | 0.920 | 0.910 |
| Lognormal, | 0.800 | 0.805 |
| Lognormal, | 0.865 | 0.858 |
Both fall short of the promised 0.95, for different reasons. For normal data with , the analytic interval uses 1.96 where a t quantile belongs. The coverage of is (computed in the script), which matches the measured 0.920. The percentile bootstrap (0.910) behaves like a normal interval whose spread divides by instead of (the variance of a resample is the divide-by- one), which makes it narrower by a factor : the coverage becomes , 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 , and 94% and 89% at . 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 (no difference), choose a test statistic that measures the difference, and ask how often a statistic at least this extreme would occur if were true. That probability is the p-value.
Which test follows from the data type:
| Data | Test | Notes |
|---|---|---|
| Two conversion rates | Two-proportion z-test | Large counts; pooled standard error |
| Two means | t-test | SciPy defaults to equal variances; equal_var=False gives Welch’s test (SciPy, ttest_ind) |
| Counts against expected proportions | Chi-square goodness of fit | Rule of thumb: every observed and expected count at least 5 (SciPy, chisquare) |
| Any statistic, small or odd data | Permutation test | Shuffle the group labels |
The two-proportion statistic uses the pooled rate , because under both groups share one rate:
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, and , 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 and . 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):
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 of 0.0280 over 1,716 splits, and a randomised of 0.0293 from 9,999 shuffles, with a one-sided exact 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 for the two-sided case, while scipy.stats.permutation_test doubles the smaller one-sided p-value. On this data SciPy’s rule gives 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).
| Misreading | Why it is wrong |
|---|---|
| ” means a 97% chance the effect is real” | The p-value is computed assuming ; it is not the probability of |
| ” 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 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 and 49.5% had .
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.
| true (no effect) | false (real effect) | |
|---|---|---|
| Reject | Type I error (false positive), probability | Correct: this probability is the power, |
| Keep | Correct | Type II error (false negative), probability |
You pick (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 . For two proportions, with a two-sided test:
| Symbol | Meaning |
|---|---|
| Users needed in each arm, rounded up | |
| 1.96 for | |
| 0.84 for power 0.80 (the table’s counts use exact quantiles, so 1.96 and 0.84 are rounded) | |
| Baseline 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 rate | Lift | Users per arm |
|---|---|---|
| 0.120 | 2 points | 3,839 |
| 0.110 | 1 point | 14,749 |
| 0.105 | 0.5 point | 57,760 |
A well-known shortcut is per arm (common practice), where is the variance of one observation and the lift to detect. The 16 is about (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 is . 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 for tests. It is simple and strict, and it loses power as 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 p-values and compares the one at rank with a rising threshold. Its adjusted p-value is the smallest of over all ranks , capped at 1:
You reject every hypothesis whose adjusted value is at most . 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 (with 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 , 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 .
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):
| Rule | False discoveries per 100 tests | True discoveries per 100 tests | Share of discoveries that are false |
|---|---|---|---|
| No correction () | 3.83 | 17.15 | 0.177 |
| Bonferroni | 0.05 | 6.52 | 0.007 |
| Benjamini-Hochberg | 0.55 | 12.30 | 0.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).
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 and views per user, the variance is inflated by
so the test behaves as if the threshold were , 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:
| Symbol | Meaning |
|---|---|
| Observed users in arm | |
| Expected users in arm under the design | |
| Design ratio of arm |
The p-value comes from a chi-square distribution with degrees of freedom for arms. The script gives:
| Observed | Design | p-value | |
|---|---|---|---|
| 10,400 and 9,600 | 50/50 | 32.00 | |
| 50,500 and 49,500 | 50/50 | 10.00 | 0.00157 |
| 520 and 480 | 50/50 | 1.60 | 0.206 |
| 5,200 and 4,800 | 50/50 | 16.00 | |
| 3,400, 3,300, 3,300 | 1:1:1 | 2.00 | 0.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 () and where only B is right (), and tests whether they are equally common:
with one degree of freedom, where the 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 and , while an unpaired two-proportion test on the same accuracies gives and . 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
where is the mean score difference over resamples, the sample variance of those differences, and the set sizes. That page also notes that no unbiased estimator exists for this variance, so for -fold cross-validation it uses an approximation with (correctR vignette). The script applies the correction to ten constructed score gaps from 90/10 splits: the naive is 8.95 and the corrected 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:
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 . 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 successes in trials has a Beta(, ) 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 . 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, 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 drive both and , with no effect of on : the observed correlation between and is 0.502 (theory 0.5). If is assigned at random instead, the correlation is -0.008. Randomisation breaks the link from to , 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.
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 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 . 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: 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 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
scipy.stats.permutation_test (opens in a new tab)
The reference for permutation tests, with the exact and randomised cases used in the homework.
Further reading
Trustworthy Online Controlled Experiments: A Practical Guide to A/B Testing (opens in a new tab)Essential
The practical guide to running trustworthy A/B tests, including the sample ratio check and what to do when an experiment looks too good.
Research papers
The classic study of which tests to trust when comparing two learning algorithms, and why random-split t-tests mislead.
The paper that introduced false discovery rate control, short and readable.
Shows how a single analysis can still hide many comparisons when choices depend on the data.
Statistical Comparisons of Classifiers over Multiple Data Sets (opens in a new tab)
Which tests to use when comparing classifiers over many datasets.
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.
Keyboard: arrow keys move between options. Space or Enter selects the focused option.