LLGA · Course notes

Statistics in Action

APM_52066_EP · Year 1 · Period 2

Contents

Introduction and overview

Module Statistics in Action
Code APM_52066_EP
Team and workload Official instructor: Zacharie Naulet (École Polytechnique & INRAE, MaIAGE team) · 36 h of in-person classes (18 h lectures + 18 h small-class sessions; maximum enrollment: 90) · 4.5 ECTS (value on the MScT tracks; 5 ECTS in the engineering cycle) · the statistician’s craft on real data: planning a trial, randomizing, computing power, hunting biases, correcting multiple tests, bootstrapping and communicating honest results — from the agricultural trial to the A/B test.
Official course description (SynapseS 2026-2027) Official title: “Statistique en Action” (in-depth program, applied mathematics) · period: X-3A-P2, from 04/01/2027 to 19/03/2027 · language of the course: English · official assessment: a group project, an individual written test without documents on that project, and a final exam (sheet read on 24 October 2026) · site linked on the description: znaulet.pages-forge.inrae.fr/map566 · APM_52066_EP course description
Status in the program Notes kept for reference Not in the LLGA 2026–2027 list: the MScT-LLGA-GD1A track page (read on 22 October 2026) does not include this course unit in LLGA 1 – S2; it is still taught at the École in other tracks (the “P2 – Applied Mathematics” track of the engineering cycle), and these notes are kept for reference.

Audience: a product / data engineer who ships A/B tests and wants an honest pipeline.

Empirical first: a “significant” p-value after peeking; underpowered design → business false negative — then we name experimental design, randomization, bootstrap, multiplicity.

The statistician’s craft on real data: a differentiator in an AI master’s.

What you will be able to do

Official objectives and syllabus (2026-2027 catalog)

According to the APM_52066_EP — “Statistique en Action” description: the official objective is to show students how statistics are used in practice to answer a precise question, by introducing a series of important model-based approaches. Students learn to select and use the appropriate strategic methodologies, on concrete examples of real datasets from different fields — medicine, genomics, ecology, among others.

All analyses are carried out in R; knowledge of R programming is not required (only basic scripting).

The sheet also lists a detailed programme by topic, without a calendar: statistical tests (comparing two populations, power analysis, multiple testing), regression models (linear and nonlinear, diagnostics, model comparison), mixed-effects models (linear and nonlinear), mixture models and model-based clustering (Gaussian mixtures, stochastic block models, EM algorithm) and classification. The course unit appears in the 2026-2027 catalog via the “P2 – Applied Mathematics” track of the engineering cycle, without appearing in the SynapseS composition of the LLGA track S2.

Official item (SynapseS) Course section
Statistics used in practice to answer a precise question ch. 1 — The life cycle of a statistical study, and ch. 4 — Observational versus experimental
A series of important model-based approaches ch. 5 — Causal inference, ch. 6 — Regression in practice, ch. 8 — The bootstrap
Real data from medicine, genomics, ecology… ch. 3 — Case study: agricultural trials and blocks (partial coverage: application fields and the historical line of experimental designs)
All analyses carried out in R not explicitly covered: these materials remain software-independent
Programme: statistical tests (two populations, power analysis, multiple testing) ch. 0 — two-sample tests; ch. 2 — power (Theorem 2.4); ch. 7 — multiple testing
Programme: regression models (linear and nonlinear, diagnostics, model comparison) ch. 6 — Regression in practice (linear models, diagnostics, transformations); nonlinear regression and formal model comparison are not covered, beyond the transformations of Example 6.3
Programme: mixed-effects models (linear and nonlinear) not covered: these notes treat blocks as fixed effects (ch. 3); the split-plot error strata of the field-trial group project are the closest entry point
Programme: mixture models and model-based clustering (Gaussian mixtures, stochastic block models, EM) not covered here: taught in Machine Learning 7.2 (Gaussian mixtures and EM) and Graph ML ch. 9 (stochastic block models)
Programme: classification not covered here: taught in Machine Learning ch. 3

Complement to the official syllabus — the themes structuring these materials (experimental designs and power computation, multiple testing, sequential A/B testing, honest communication of uncertainties) extend the official description; they correspond to the historical topics of the MAP566 course associated with this course unit.

Where this course fits in the program

A 36 h course unit of period 2 (X-3A-P2) in other tracks of the École, kept here for reference: it is not in the 2026–2027 LLGA lists, so no LLGA module requires it, but it remains the methodological “reality check” of these notes. It is taught by Zacharie Naulet (École Polytechnique & INRAE, MaIAGE team).

Official prerequisites: not communicated (the “Prerequisites” tab of the SynapseS description is empty); the description only specifies that no knowledge of R is required, basic scripting being sufficient.

Course outline

Session plan

36 h in class = 12 sessions of 3 h. The volume is the one of the SynapseS 2026–2027 sheet (36 h in person: 18 h of lectures and 18 h of small-class sessions); the sheet publishes no session-by-session programme, so the split below is our proposal for covering these notes in that time. Level 1 = foundations (reviews, definitions, first worked examples), 2 = core methods, 3 = advanced material (sequential inference, recent research); the level never goes down from one session to the next.

Session Hours Level Content Practice
1 3 h 1 ch. 0 Review: the survival kit; ch. 1 The life cycle of a statistical study lab: coverage of a normal confidence interval by simulation
2 3 h 1 ch. 2 Randomization, the exact randomization test, block designs (Definitions 2.1–2.3) Ex. 1
3 3 h 2 ch. 2 Power and sample size (Theorem 2.4, Example 2.5) Ex. 2
4 3 h 2 ch. 3 Case study: a complete block trial and its analysis of variance Ex. 10 (start the project, Ex. 11)
5 3 h 2 ch. 4 Observational studies: confounding, Simpson’s paradox, selection and survivorship Ex. 3
6 3 h 2 ch. 5 Causal inference: potential outcomes, difference-in-differences Ex. 6
7 3 h 2 ch. 6 Regression in practice: leverage, Cook’s distance, diagnostic plots, transformations Ex. 4
8 3 h 2 ch. 7 Multiple testing: FWER, FDR, Bonferroni, Benjamini-Hochberg Ex. 7
9 3 h 2 ch. 8 The bootstrap: plug-in principle, consistency, intervals for a median, failure cases lab: the three intervals of Example 8.3
10 3 h 2 ch. 9 Communicating: p-values, intervals, honest figures Ex. 5
11 3 h 3 ch. 10 A/B testing: OEC, the cost of peeking, always-valid p-values Ex. 8
12 3 h 3 ch. 10 Bayesian A/B test, targeted effects, interference Ex. 9; project presentations (Ex. 11)

Self-study, outside the 36 h (about 2 h in total): ch. 11 Course research notes (Naulet, MaIAGE) — exchangeability, species sampling, bootstrap for graphs (≈ 2 h).

How to study this module

Independent note In a master’s program oriented toward LLMs and graphs, this module brings the discipline that makes everything else credible: A/B tests and rigorous evaluation are the daily life of the product teams deploying models, and the culture of uncertainty continues in M2 in Privacy and Uncertainty Quantification. It is also a sought-after profile in research — at the interface with applied sciences, as at INRAE — and in industrial data science wherever decisions have consequences.

0. Review: the statistician’s survival kit

This chapter gathers the few results of the statistics refresher that the module uses every week, and fixes the vocabulary — model, estimator, bias, variance — in which every later question is asked.

L3 background used (cf. Refresher Statistics module)

  • Convergence and limit theorems (ch. 4): law of large numbers, CLT \sqrt{n}(\bar X_n - \mu) \Rightarrow \mathcal{N}(0, \sigma^2), delta method and bootstrap — the engine of almost every approximation in this module;
  • Parametric estimation (ch. 5): bias, variance, quadratic error, maximum likelihood estimators and their asymptotic properties;
  • Confidence intervals and tests (ch. 6): level, power, p-value, type I and II errors, two-sample Student test, chi-square test;
  • Linear regression (ch. 7): ordinary least squares, Gauss-Markov, tests on the coefficients, R^2 — chapter 6 of this module revisits this foundation “on misbehaving data”;
  • Monte Carlo simulation: generating laws, checking a method by simulation — the permanent working tool of the applied statistician (and of all the labs in this course).

Definition 0.1 — Statistical model and data A statistical model for data x_1, \dots, x_n is a family (P_\theta)_{\theta \in \Theta} of candidate laws. In practice, the question is not “is the model true?” (it never is) but rather: what question are we asking the data, and which quantity \psi(\theta) — mean effect, difference of rates, quantile, coefficient — answers that question?

The whole module is organized around this triptych: question → collection plan → estimation + uncertainty.

The formula \bar x \pm 1.96\, s/\sqrt{n} from Refresher Statistics is legitimate only if the collection plan is: this module deals with what happens before and around the formula.

Proposition 0.2 — The bias-variance identity and what it implies For every square-integrable estimator \hat\theta of \theta:

Key result — bias-variance decomposition \mathbb{E}\big[(\hat\theta - \theta)^2\big] = \underbrace{\big(\mathbb{E}\hat\theta - \theta\big)^2}_{\text{bias}^2} + \underbrace{\mathrm{Var}(\hat\theta)}_{\text{variance}}.

Proof. Set \mu = \mathbb{E}\hat\theta and expand \mathbb{E}[(\hat\theta-\mu) + (\mu - \theta)]^2 = \mathbb{E}(\hat\theta-\mu)^2 + 2(\mu-\theta)\underbrace{\mathbb{E}(\hat\theta - \mu)}_{=0} + (\mu-\theta)^2 . The cross term is zero because \mu is the expectation of \hat\theta. ∎

In practice, the bias mostly comes from the plan (selection, confounding) and the variance from the sample size: increasing n never corrects a selection bias — this is the central message of chapters 2 and 4.

Position in the master’s program This module is the “craft” complement of Refresher Statistics: less new theory, more decisions. It also prepares the M2 module “Privacy and Uncertainty Quantification”, which pushes the uncertainty question as far as the calibration of predictive models; the statistics–ML bridge is provided by the Machine Learning module (ch. 1 and 8), and the processing of textual data by the NLP module.

1. The life cycle of a statistical study

Concrete scene: an A/B test stopped too early “proves” a lift that does not exist. This chapter shows how to structure the question before touching the data, so that such errors are ruled out by the plan rather than detected afterwards.

What breaks Peeking without correction; forgotten multiple testing; confusing correlation and causation without design.

A real statistical study does not begin with a dataset: it begins with a question. The diagram below structures the whole module; each chapter tackles a link where studies typically fail.

Step Key question Where it breaks Chapter
1. Question Which effect, on which population, which unit? Vague question, undefined indicator ch. 1
2. Plan Can we randomize? Block? How many units? Underpowered, no randomization ch. 2
3. Collection Who enters the sample? Who leaves it? Selection bias, survival bias, missing data ch. 4
4. Analysis Which estimator? Which diagnostics? Mis-specified model, multiple tests ch. 6–7
5. Uncertainty Intervals, bootstrap, robustness Underestimated uncertainty ch. 8
6. Communication What to report, in what form? Over-interpreted p-value, misleading chart ch. 9

Definition 1.1 — Population, sample, statistical unit, indicator The population is the set of units the question concerns; the sample is the observed subset; the statistical unit is the grain at which we measure (a patient, a field, a user, a query); the indicator (or outcome, OEC for “Overall Evaluation Criterion” in online experimentation) is the quantity measured.

A study is externally valid if the sample allows an answer for the target population; internally valid if the comparisons made within the sample are reliable. One can be internally valid and externally wrong (a trial on healthy volunteers).

Reproducibility: HARKing and the garden of forking paths Two documented pathologies: HARKing (Kerr, 1998 — hypotheses formulated after seeing the results, presented as a priori) and the “garden of forking paths” (Gelman & Loken, 2013): without any fraud, the mere freedom to choose the specification after the fact (control variables, coding, exclusion of points, subgroups) multiplies the tests actually performed far beyond those reported.

Practical answers: pre-registration of the analysis plan, reproducible scripts, reports of every look taken at the data — exactly the disciplines of ch. 10 for A/B testing.

2. Experimental designs: randomization, blocks, power

Before any data are collected, two decisions fix what a study can prove: how the treatments are assigned to the units, and how many units are needed. This chapter answers both — randomization and blocks for the first, a power computation for the second.

Definition 2.1 — Randomized experiment (Fisher, 1935) n experimental units receive K treatments; the assignment is drawn at random among the possible allocations (with possible balance constraints). Randomization plays three roles:

(i) on average, it balances all factors, measured or not;

(ii) it grounds an exact test of the null effect (prop. 2.2);

(iii) it legitimizes the causal inference of ch. 5.

Historical note: the “lady tasting tea” experiment (Fisher, 1935) — 8 cups, 4 “milk first”, 4 “tea first”, randomized order.

Proposition 2.2 — Exact randomization test, computed by hand Six plots with yields 3, 4, 5, 6, 7, 8 (q/ha; teaching data) receive A or B, three each. Observed: A = {6, 7, 8}, B = {3, 4, 5}, difference of means \hat d = 7 - 4 = 3.

Under the null hypothesis “no effect”, \hat d takes each of the \binom{6}{3} = 20 values \bar x_A - \bar x_B with probability 1/20. The largest possible value of |\hat d| is 3, reached only for the splits {6,7,8} and {3,4,5} (the split {5,7,8} against {3,4,6} gives \hat d = 6.67 - 4.33 = 2.33 < 3). Therefore p \;=\; \mathbb{P}\big(|\hat d| \geq 3 \,\big|\, H_0\big) \;=\; \frac{2}{20} \;=\; 0.10 \quad\text{(exact, without any distributional assumption).}

Proof. The only thing used: under H_0, the treatment does not influence the yield, so the six yields are fixed numbers whatever the assignment, and only the assignment is random; the assignment being uniform over the 20 balanced allocations, the p-value is the proportion of allocations at least as extreme.

Enumerating the 20 splits (or a symmetry argument on A/B) gives exactly 2 splits with |\bar x_A - \bar x_B| = 3 and all others \leq 2.33. ∎

Definition 2.3 — Randomized complete block design (RCBD) When the units are heterogeneous but can be grouped into homogeneous blocks (neighboring plots, production days, hospitals), one draws independently within each block a permutation of the K treatments. Analysis model: y_{ij} = \mu + \tau_i + \beta_j + \varepsilon_{ij}, \qquad \varepsilon_{ij} \ \text{i.i.d.}, with \tau_i the effect of treatment i, \beta_j the effect of block j.

Blocks turn the variability between units into an explicit factor: ch. 3 shows, on numerical data, a variance gain by a factor of 30 and more.

Theorem 2.4 — Sample size for a target power (two-sample Gaussian test) To test H_0 : \mu_A = \mu_B against \mu_B - \mu_A = \delta at level \alpha (two-sided) with common variance \sigma^2, n measurements per group and the normal approximation, the power is \pi(\delta) \;=\; \Phi\!\Big( \frac{\delta}{\sigma}\sqrt{\tfrac{n}{2}} - z_{1-\alpha/2} \Big), and power 1 - \beta is reached for

Key result — sample size per group n \;=\; \frac{2\,(z_{1-\alpha/2} + z_{1-\beta})^2}{(\delta/\sigma)^2} \quad \text{measurements per group.}

Proof. The test rejects when |\hat d| > z_{1-\alpha/2}\,\sigma\sqrt{2/n} with \hat d = \bar y_B - \bar y_A \sim \mathcal{N}(\delta, 2\sigma^2/n).

Under the alternative, \mathbb{P}(\hat d < -s) \approx 0 (with s = z_{1-\alpha/2}\sigma\sqrt{2/n} and \delta > 0), so \pi = \mathbb{P}(\hat d > s) = \Phi\big(\tfrac{\delta - s}{\sigma\sqrt{2/n}}\big) = \Phi\big(\tfrac{\delta}{\sigma}\sqrt{\tfrac n2} - z_{1-\alpha/2}\big).

Writing \pi = 1 - \beta amounts to \tfrac{\delta}{\sigma}\sqrt{\tfrac n2} - z_{1-\alpha/2} = z_{1-\beta}, hence the formula by isolating n. ∎

Example 2.5 — Power computed, and a sizing table We want to detect \delta = 0.3\,\sigma (a small but economically relevant effect) with \alpha = 5\,\% and 80 % power: z_{0.975} = 1.960, z_{0.8} = 0.842, n = \frac{2\,(1.960 + 0.842)^2}{0.3^2} = \frac{2 \times 7.85}{0.09} = 174.4 \;\Rightarrow\; \boxed{175 \text{ units per group}}.

Complete table (values rounded up):

\delta/\sigma Power 80 % Power 90 % Reading
0.2 393 526 very small effect: costly
0.3 175 234 our case
0.5 63 85 medium effect
0.8 25 33 large effect: a pilot suffices

Professional moral: precision grows only like the square root of n, so halving the detectable effect costs four times the sample, and nobody “finds” an effect of 0.2σ with 30 observations.

In practice one replaces \sigma^2 with an estimate from a pilot or the literature, and \delta with the smallest useful effect (the minimum clinically or economically relevant difference), never with the effect one hopes for.

Power a priori, never a posteriori Power is a design tool. The “observed power” computed after the fact with \hat\delta is a monotone transformation of the p-value: it brings no new information and muddles the report (Hoenig & Heisey, 2001). What should be reported: the confidence interval of the effect (ch. 9).

3. Case study: agricultural trials and blocks

Agricultural experimentation is the cradle of experimental design: Fisher at Rothamsted in the 1920s invented randomization, blocks and analysis of variance precisely because plots are heterogeneous — the same problem as your users or your patients.

It is also the daily ground of INRAE, the instructor’s institution: multi-year multi-location variety trials, complete blocks and alpha-lattices (Patterson & Williams, 1976) to screen hundreds of varieties.

Example 3.1 — RCBD computed end to end (teaching data) 4 varieties (A–D) × 5 blocks, yields (t/ha) constructed as y_{ij} = 50 + \tau_i + \beta_j + e_{ij} with variety effects (+3, +1, -2, -2), block effects (+8, +2, 0, -4, -6) and residuals summing to zero row-wise and column-wise:

Variety Block 1 Block 2 Block 3 Block 4 Block 5 Mean
A 62 54 54 48 47 53.0
B 58 54 50 48 45 51.0
C 57 50 48 44 41 48.0
D 55 50 48 44 43 48.0
Mean 58 52 50 46 44 50

The residuals are \pm 1 in twelve cells and 0 elsewhere, so the variety means estimate 50 + \tau_i and the block means 50 + \beta_j exactly.

Analysis of variance — each mean square is a sum of squares divided by its degrees of freedom, and F = \text{MS}_v / \text{MS}_e compares the spread between varieties with the residual noise; under the null hypothesis of no varietal effect, it follows a Fisher law with (3, 12) degrees of freedom:

Source df Sum of squares Mean square F
Varieties 3 SS_v = 5 Σ(τ̂ᵢ)² = 90 30.0 30.0
Blocks 4 SS_b = 4 Σ(β̂ⱼ)² = 480 120.0 120.0
Residuals 12 SS_e = Σ e² = 12 1.0 —

Observed F_{3,12} = 30 against a threshold of F_{0.95;\,3,12} = 3.49 — highly significant varietal differences.

Pairwise comparisons: standard deviation of a difference of means \sqrt{2 \times 1.0/5} = 0.63, LSD at the 5 % level: 2.179 \times 0.63 = 1.38. Hence A (53.0) > B (51.0) > C = D (48.0): every pair is separated (A against B: 2.0 > 1.38) except C and D.

The gain from blocking: without blocks, the block variability would join the residual: (480 + 12)/16 = 30.75 \quad \text{instead of } 1.0 . The same trial under a completely randomized design would have an F on the order of 1: the trial would have seen nothing.

This is literally Fisher’s lesson: planning well beats modeling well after the fact.

Natural continuation Multi-environment trials: genotype × environment interactions, AMMI/GGE models (the PCA of the Machine Learning module ch. 7 applied to interactions); resolvable incomplete blocks (alpha-lattices) when K > block size; spatial analysis (fertility trend by rows/columns). The INRAE thread: dozens of trials, thousands of plots, one imperative — randomize, block, estimate the uncertainty, communicate honestly (ch. 9).

4. Observational versus experimental: biases

Randomizing is often impossible (one does not assign smoking or a degree at random), and the data then come from observation. This chapter shows what goes wrong when the groups compared were not formed by chance, and how to recognize it.

Definition 4.1 — Observational study, confounding factor A study is observational when the assignment of “treatments” (exposure, product, degree) is not controlled by the experimenter. A confounding factor Z is a variable that influences both the exposure and the response; it creates a “natural” difference of means between groups even without any effect.

Canonical example: ice cream sales and drownings (confounded by weather). Adjustment (standardization, regression, matching) only corrects measured confounders; randomization also neutralizes the unmeasured ones — that is the whole difference between ch. 2 and the present chapter.

Theorem 4.2 — Simpson’s paradox, real data: kidney stones (Charig et al., 1986) Historical comparison of two kidney stone treatments (B: minimally invasive surgery; A: open surgery), % success:

Stratum Treatment A Treatment B
Small stones 81/87 = 93 % 234/270 = 87 %
Large stones 192/263 = 73 % 55/80 = 69 %
Overall 273/350 = 78 % 289/350 = 83 %

A is better in every stratum and worse in aggregate: B was preferentially given to small stones (easy cases). This is a pure confounding effect by severity, mechanically reversible by standardization.

Proof. Let p_{ks} be the success rate of treatment k in stratum s and w_s^{(k)} the proportion of patients of stratum s in group k.

The overall rate of group k is \sum_s w_s^{(k)}\, p_{ks}: it mixes effectiveness (p) and case mix (w).

B can win in aggregate with p_{Bs} \leq p_{As} for every s as soon as w^{(B)} loads the easy strata: here w^{(B)}_{\text{small}} = 270/350 = 0.77 versus 87/350 = 0.25 for A.

Standardizing on a common profile w (e.g. w^{(A)}) restores A’s advantage in each stratum, hence on average. ∎

Definition 4.3 — Selection bias and survivorship bias Selection bias: the sample is not representative of the target population (volunteers, trade shows, survey respondents). Survivorship bias: the special case where the filter is survival / still being in activity; the departed carry their bad results away with them.

Example 4.4 — Two worked examples (a) Wald’s airplanes (1943). Returning from missions, bullet holes concentrate on the wings and fuselage, almost none on the engines. Reinforcing the hit zones would be the survivor’s error: planes hit in the engine do not come back. The armor goes where the survivors are untouched. (The episode, popularized by W. Allen, is reconstructed and discussed by Mangel & Samuels, 2002.)

(b) Mutual funds (teaching figures calibrated on Elton, Gruber & Blake, 1996). Of 200 funds existing in 2015, 100 closed before 2025. Advertising cites the average return of the 100 survivors: 8 %/year. The 100 vanished ones made −5 %/year before closing. The return actually experienced by a 2015 investor: \frac{100 \times 8 + 100 \times (-5)}{200} = 1.5\,\%/\text{year} \quad \text{versus} \quad 8\,\% \text{ displayed.}

Over 10 years the gap compounds: 1.08^{10} \approx 2.16 against 1.015^{10} \approx 1.16 — the advertised figure doubles the wealth, the real one adds 16 %. Even a bias of only 1 %/year would cost about 10 % of final wealth, enough to rank every product on the market differently.

Where do you meet these biases in ML? Everywhere: models trained on current customers (churners do not notify their departure); evaluations of a recruitment system on hires (non-hires have no observed performance — this is the crux of ch. 5); academic benchmarks filtered by the publications that use them (failures are not submitted). Reflex: always ask how the sample was constituted and who dropped out of it.

5. Causal inference: potential outcomes and DiD

“Does the treatment cause the improvement?” needs a precise meaning before it can be answered. This chapter gives one — the comparison of two potential outcomes of the same unit — and shows how randomization, or failing that a difference-in-differences, estimates it.

Definition 5.1 — Potential outcomes, ATE (Neyman 1923; Rubin 1974) For each unit i and treatment w \in \{0, 1\}, we posit two potential outcomes Y_i(0) and Y_i(1); the individual effect is \tau_i = Y_i(1) - Y_i(0) and the average effect \mathrm{ATE} = \mathbb{E}[\tau_i].

We only ever observe one value Y_i = W_i Y_i(1) + (1 - W_i) Y_i(0): the fundamental causal problem is a missing data problem (cf. Refresher Statistics, ch. 10).

Two a priori assumptions: consistency (the observed value equals the potential outcome of the received treatment) and no interference (the treatment of unit j does not affect i) — together SUTVA.

Theorem 5.2 — Randomization debiases the difference of means If W \perp (Y(0), Y(1)) (unbiased randomization), then \hat\tau = \bar Y_1 - \bar Y_0 is unbiased for the ATE, and \mathrm{Var}(\hat\tau) \approx \frac{s_1^2}{n_1} + \frac{s_0^2}{n_0}.

Proof. By independence, \mathbb{E}[\bar Y_1 \mid W] = \mathbb{E}[Y(1) \mid W = 1] = \mathbb{E}[Y(1)], and likewise for \bar Y_0, hence \mathbb{E}\hat\tau = \mathbb{E}[Y(1)] - \mathbb{E}[Y(0)] = \mathrm{ATE}. The two means are over disjoint, hence independent, groups, which gives the sum of the empirical variances. ∎

In an observational setting, W is self-selected: \mathbb{E}[Y(1)\mid W{=}1] - \mathbb{E}[Y(0)\mid W{=}0] mixes the causal effect with selection. The whole modern machinery (adjustment, matching, instrumental variables, DiD) aims at reconstructing a randomized comparison.

Definition 5.3 — Difference-in-differences, the sketch Two groups (treated, control), two dates (before, after), without randomization:

Key result — difference-in-differences \widehat{\mathrm{DiD}} \;=\; \big(\bar Y_{\text{after, treated}} - \bar Y_{\text{before, treated}}\big) - \big(\bar Y_{\text{after, control}} - \bar Y_{\text{before, control}}\big).

Central assumption: parallel trends — without treatment, the treated/control gap would have stayed constant; the control serves as a “trajectory counterfactual”.

This is the most used causal identification in applied economics since Card & Krueger (1994).

Example 5.4 — Minimum wage New Jersey / Pennsylvania (Card & Krueger, 1994) Rise of the NJ minimum wage (April 1992); neighboring Pennsylvania serves as the control. Average full-time employment (FTE) per restaurant:

Before After Change
New Jersey (treated) 20.44 21.03 +0.59
Pennsylvania (control) 23.33 21.17 −2.16

\widehat{\mathrm{DiD}} = 0.59 - (-2.16) = +2.75 \ \text{FTE} \quad (\approx +13\,\% \text{ vs before}).

The regional economy was depressing both states; the naive “NJ before/after” comparison (+0.59) would underestimate the effect, and the “NJ/PA after” comparison (21.03 − 21.17 = −0.14 FTE) would outright flip its sign: only the double difference neutralizes the common shock.

Crucial methodological point (Bertrand, Duflo & Mullainathan, 2004): naive DiD standard errors are massively too small because of serial correlation — one must cluster by unit or aggregate.

Further Causal graphs and the back-door criterion (Pearl), instrumental variables, regression discontinuity: beyond the sketch of this module — see Imbens & Rubin (2015). Estimating effect heterogeneity with causal forests (Wager & Athey, 2018) is also beyond it: it turns the prediction forests of Machine Learning ch. 6 into “honest” trees that estimate the effect of each covariate profile, with confidence intervals. When units are linked in a network, the treatment of one spills over onto its neighbours — the interference of ch. 10, where graphs (Graph ML) describe the dependence structure.

6. Regression in practice: diagnostics and transformations

A fitted regression always produces coefficients and p-values, even when its assumptions are badly violated. This chapter gives the checks that tell whether those numbers can be trusted, and the repairs to apply when they cannot.

Reminders (cf. Refresher Statistics module, ch. 7)

  • OLS estimator \hat\beta = (X^\top X)^{-1} X^\top y, residuals e = y - \hat y, hat matrix H = X(X^\top X)^{-1}X^\top, \hat y = Hy;
  • Gauss-Markov: BLUE under i.i.d. zero-mean errors; Student tests if moreover Gaussian;
  • The Machine Learning module (ch. 2) covers ridge/lasso regularization — here we stay in inferential mode: the coefficients are the object of interest.

Proposition 6.1 — Leverage and Cook’s distance The leverage of observation i is h_{ii}, the diagonal of H; \sum_i h_{ii} = p (number of parameters), 0 \leq h_{ii} \leq 1.

Cook’s distance D_i = \frac{e_i^2}{p\,s^2}\cdot \frac{h_{ii}}{(1 - h_{ii})^2} measures the influence of i on the whole set of coefficients.

Leverage point: h_{ii} > 2p/n; influential point: D_i > 4/n.

Proof. For the trace: H is an orthogonal projector (onto im X), and the trace of a projector equals its rank = \mathrm{rank}(X) = p. Removing row i and re-estimating gives \hat\beta - \hat\beta_{(-i)} = \frac{(X^\top X)^{-1}x_i e_i}{1 - h_{ii}} ; Cook’s distance standardizes this variation by the dispersion p s^2 of the estimators.

Hence the formula: the residual alone (an outlier can be well predicted!) or the leverage alone (an extreme point can be perfectly aligned) do not suffice; it is their product that tips the line. ∎

Definition 6.2 — The four diagnostic plots

  1. Residuals vs fitted values: curvature ⇒ non-linearity (add quadratic terms, splines); funnel ⇒ heteroscedasticity.
  2. Q-Q of residuals: heavy tails ⇒ fragile intervals/Student tests at small n.
  3. Scale-location (\sqrt{|e|} vs \hat y): checks the constancy of s^2.
  4. Residuals vs leverage (Cook): hunts influential points.

Professional reflex: these four plots before any interpretation, systematically.

Example 6.3 — Transformations: the log as a universal tool Prices of 30 goods (y, euros) against surface area (x, m²). Typical symptoms: funnel-shaped residuals, the line pulled by a few very high-leverage luxury goods.

Remedy: regress \log y on \log x: \log y_i = \beta_0 + \beta_1 \log x_i + \varepsilon_i \iff y_i = e^{\beta_0}\, x_i^{\beta_1}\, e^{\varepsilon_i}.

\beta_1 becomes an elasticity: +1\,\% of surface ⇒ +\beta_1\,\% of price. If \hat\beta_1 = 1.08, the interpretation “1 % more surface, about 1.08 % higher price” — a price slightly more than proportional to the surface — replaces the fragile linear interpretation “each square meter adds €3,120”, wrong for a studio as for a mansion. (A fixed percentage per square meter would be the semi-elasticity of a regression of \log y on x.)

The log transformation: (i) symmetrizes distributions and stabilizes variance when the effect is multiplicative; (ii) crushes extreme leverages; (iii) makes errors relative, which is often the right physical/economic model.

General family: Box-Cox y^{(\lambda)} = (y^\lambda - 1)/\lambda, with \lambda chosen by profile likelihood; special cases \lambda = 1 (identity), \lambda = 0 (log), \lambda = 1/2 (square root, Poisson).

Heteroscedasticity: robust errors, no panic Heteroscedasticity does not bias \hat\beta (Gauss-Markov only needs homoscedasticity for efficiency, not consistency); it distorts the standard errors. Modern solution: the sandwich estimator of White (1980), called HC0, \widehat{\mathrm{Var}}(\hat\beta) = (X^\top X)^{-1} X^\top \mathrm{diag}(e_i^2) X (X^\top X)^{-1}, available everywhere (statsmodels, sandwich in R). Its variant HC1, the default of Stata and the one used in exercise 4, multiplies it by n/(n-p) to correct its small-sample downward bias. With grouped or panel data, cluster by unit (cf. ch. 5, Bertrand et al. 2004).

7. Multiple testing: Bonferroni and Benjamini-Hochberg

The modern statistician tests thousands of hypotheses at once (genomics, multi-metric A/B testing, subgroup analyses). Testing m true null hypotheses each at \alpha = 5\,\% produces on average \alpha m false positives — with m = 1000: 50 “discoveries” in pure noise. One must choose what to control.

Definition 7.1 — FWER and FDR Among R rejected hypotheses of which V are false (false positives): \mathrm{FWER} = \mathbb{P}(V \geq 1) \qquad \text{(at least one error)} \mathrm{FDR} = \mathbb{E}\!\left[ \frac{V}{R \vee 1} \right] \qquad \text{(expected proportion of errors).}

Controlling the FWER is required when a single false discovery is costly (pivotal clinical trial); controlling the FDR is enough for exploration (differential expression, product optimization) — we accept some noise among the discoveries.

Theorem 7.2 — Bonferroni controls the FWER Rejecting the p_i \leq \alpha/m gives \mathrm{FWER} \leq \alpha.

Proof. Union bound (Boole): if an error is made, at least one p-value under a true null has crossed its threshold, so \mathrm{FWER} \leq \mathbb{P}\Big( \bigcup_{i \in I_0} \{p_i \leq \alpha/m\} \Big) \leq \sum_{i \in I_0} \frac{\alpha}{m} \leq \frac{m_0\,\alpha}{m} \leq \alpha, where m_0 \leq m is the number of true nulls. No independence is required. ∎

Price to pay: as m grows, the threshold \alpha/m becomes untenable (m = 10^4 ⇒ 5 \times 10^{-6}) and power collapses; the Šidák variant (1 - (1-\alpha)^{1/m}, exact under independence) does not change the order of magnitude.

Theorem 7.3 — Benjamini-Hochberg controls the FDR (Benjamini & Hochberg, 1995) Let p_{(1)} \leq \dots \leq p_{(m)} be the sorted p-values and

Key result — Benjamini-Hochberg threshold k^* = \max\Big\{ k : p_{(k)} \leq \frac{k}{m}\,q \Big\}.

Rejecting the k^* smallest p-values (none if the set is empty) controls \mathrm{FDR} \leq \frac{m_0}{m} q \leq q when the p-values under true nulls are independent of each other and of the rest (extension: PRDS positive dependence, Benjamini & Yekutieli 2001; otherwise, replace q by q / \sum_{k=1}^m 1/k).

Proof. Case where all nulls are true (m_0 = m). Then V = R whenever R \geq 1, so V/(R \vee 1) = \mathbf{1}\{R \geq 1\} and \mathrm{FDR} = \mathbb{P}(R \geq 1).

The event R \geq 1 means that p_{(k)} \leq kq/m for some k — not necessarily k = 1: it is the rejection event of Simes’ global test (Simes, 1986), whose probability under i.i.d. uniform p-values is exactly q (induction on m).

For m = 2 the computation fits in one line: R \geq 1 iff \max(p_1, p_2) \leq q or \min(p_1, p_2) \leq q/2, so \mathrm{FDR} = \mathbb{P}(\max \leq q) + \mathbb{P}(\min \leq q/2,\ \max > q) = q^2 + 2\cdot\frac{q}{2}(1-q) = q. The bound of the theorem is therefore attained when all nulls are true.

General case (sketch). Decompose \mathrm{FDR} = \sum_{i \in I_0} \mathbb{E}\big[ \tfrac{1}{R} \mathbf{1}\{p_i \leq p_{(k^*)}\}\big] over the rejection rank. The two ingredients of the complete proof (Benjamini & Hochberg, Thm 1):

(i) for each null i, the event “i rejected at rank r” requires p_i \leq qr/m and at least r - 1 of the other p-values \leq qr/m;

(ii) by independence of p_i from the rest, the product of probabilities yields a factor qr/m, which, killed by the 1/r of the weighting, leaves the bound \frac{q}{m} — then the telescoping summation over ranks (Abel’s transformation) bounds the total by \frac{m_0}{m} q.

The subtlety (and beauty) of the result: the data-dependent threshold q k^*/m “self-adjusts” to the number of apparent discoveries. ∎

Example 7.4 — BH computed, against Bonferroni m = 10 p-values: 0.001 · 0.004 · 0.009 · 0.019 · 0.021 · 0.031 · 0.043 · 0.71 · 0.88 · 0.92. With q = 0.05:

k p_{(k)} threshold qk/m BH decision
1 0.001 0.005 reject
2 0.004 0.010 reject
3 0.009 0.015 reject
4 0.019 0.020 reject
5 0.021 0.025 reject (k* = 5)
6 0.031 0.030 stop

BH rejects k^* = 5 hypotheses (all p ≤ 0.021); Bonferroni at \alpha = 0.05 rejects only p \leq 0.005: 2 hypotheses.

If the first 5 nulls are false, Bonferroni leaves 3 discoveries on the table; BH in exchange claims \leq 5\,\% false positives in proportion.

In the lab, we will verify by simulation (exercise 7) that the empirical FDR of BH settles at q\, m_0/m.

Adaptive and genomic version If many nulls are false, m_0/m makes BH conservative. Adaptive procedures estimate \pi_0 = m_0/m (Storey, 2002 — the large p-values are almost all true nulls) and gain power. This is the default setting of differential analyses in genomics (qvalue, IHW). Internal link: estimating \pi_0 and the “missing mass” is exactly a species sampling problem — a research axis of the instructor (ch. 11).

8. The bootstrap in practice

For a median, a ratio or a trimmed mean there is no simple formula for the standard error. The bootstrap obtains the uncertainty of almost any statistic by simulation from the data themselves; this chapter explains why it works and when it does not.

Reminder (cf. Refresher Statistics module, ch. 4)

The nonparametric bootstrap resamples B times, with replacement, n observations, recomputes the statistic on each resample, and reads the variability off the bootstrap distribution. Here we push through to intervals, edge cases and code.

Definition 8.1 — The plug-in principle (Efron, 1979) The empirical law \hat P_n = \frac{1}{n}\sum_i \delta_{x_i} is the natural nonparametric estimator of the unknown law P. The bootstrap simulates the inference problem by replacing P with \hat P_n: if T_n = t(x_1, \dots, x_n\,; P) is the statistic of interest, its bootstrap version T_n^* = t(x_1^*, \dots, x_n^* ; \hat P_n) is computed by Monte Carlo.

Ideal: the law of T_n^* - t(\hat P_n) approximates that of T_n - t(P).

Theorem 8.2 — Consistency for the mean (and beyond, sketch) If x_i are i.i.d., \mathbb{E}X^2 < \infty, the law of \sqrt n(\bar x^* - \bar x) conditional on the data converges to the same limit \mathcal{N}(0, \sigma^2) as \sqrt n(\bar x_n - \mu).

Proof. Conditional on the data, the x_i^* are i.i.d. with law \hat P_n, expectation \bar x and variance \hat\sigma_n^2 = \frac{1}{n}\sum (x_i - \bar x)^2.

The CLT applied to this sequence (for almost every draw of the data) gives \sqrt n(\bar x^* - \bar x) \Rightarrow \mathcal{N}(0, \hat\sigma_n^2), and \hat\sigma_n^2 \to \sigma^2 almost surely (LLN) — the conditional Slutsky lemma concludes.

The same scheme holds for regular functionals of P (differentiable functionals — functional delta method); this is the subject of the empirical Donsker theorem and van der Vaart’s theory (ch. 23). ∎

Example 8.3 — Three intervals for the median Eight response times (ms): 118, 132, 127, 141, 122, 135, 128, 240 (one heavy point). Observed median: (128+132)/2 = 130. A “hand-made” normal CI: delicate (no simple \sqrt n formula for the median).

Bootstrap with B = 5000 (the code below): draw 5000 resamples, each yields a median m_b^*; take the 2.5 % and 97.5 % percentiles; typical output: percentile CI ≈ [122; 141].

The basic interval (reverse percentile) reverses: [2\hat m - q_{97.5}^*,\ 2\hat m - q_{2.5}^*], which corrects a version bias; BCa additionally readjusts for bias and skewness via jackknife.

Reading rule: if percentile and basic differ strongly, the bootstrap distribution is very asymmetric — a signal in itself.

import numpy as np
rng = np.random.default_rng(0)

x = np.array([118, 132, 127, 141, 122, 135, 128, 240])
n, B = len(x), 5000
med_star = np.median(rng.choice(x, size=(B, n), replace=True), axis=1)
mhat = np.median(x)

# 1. percentile: quantiles of the bootstrap law
lo, hi = np.quantile(med_star, [0.025, 0.975])
# 2. basic (reverse percentile): symmetrization around the estimate
lo_b, hi_b = 2*mhat - hi, 2*mhat - lo
print(f"median = {mhat}, percentile CI [{lo:.0f}, {hi:.0f}], basic CI [{lo_b:.0f}, {hi_b:.0f}]")
# 3. bootstrap bias: E*[m*] - mhat
print(f"estimated bootstrap bias: {med_star.mean() - mhat:+.2f} ms")

When the bootstrap fails

  • Dependent data: the i.i.d. bootstrap breaks the structure — use the block bootstrap (weather, financial series, web streams);
  • extremes and deep quantiles: the empirical law does not have a rich enough tail;
  • small n (< 10): the empirical law is too coarse a scale (at most n^n distinct resamples, and often far fewer distinct values of the statistic);
  • non-regular statistics (boundaries, number of components): the bootstrap can be inconsistent.

Research bridge: Naulet, Roy, Sharma & Veitch use weighted bootstraps for the graphex tail index — the estimator of the “hidden mass” of large networks (ch. 11).

9. Communicating: intervals, p-values, honest visualizations

A correct analysis is useless if the report misleads its reader. This chapter fixes what a p-value does and does not say, why an interval tells more than a test, and how to draw figures that do not distort the result.

Milestone 9.1 — The ASA’s six principles on the p-value (Wasserstein & Lazar, 2016)

  1. a p-value measures the incompatibility of the data with a specified statistical model;
  2. it is not the probability that the null hypothesis is true, nor that the result is due to chance;
  3. scientific conclusions and decisions should not pass only through a threshold (p < 0.05);
  4. full transparency: correct p-values only with the procedure and analysis reported in full;
  5. a p-value, or statistical significance, measures neither the size of an effect nor its importance;
  6. an isolated p-value proves nothing by itself — facts, context and replication make the proof.

Collective follow-up: Amrhein, Greenland & McShane (2019), “Scientists rise up against statistical significance” — more than 800 signatories: stop classifying results as “significant” / “not significant”.

Example 9.2 — Same data, two stories Trial with n = 40 per arm, \hat d = 7.0 points, s = 15, so a standard error 15\sqrt{2/40} = 3.35, z = 2.09 and p = 0.037 (two-sided).

Test story: “significant effect (p = 0.04)” — suggests clear evidence.

Estimation story: 95 % CI of d: 7.0 \pm 1.96 \times 3.35 = 7.0 \pm 6.6 = [0.4; 13.6]: the data are compatible with an almost null effect (0.4 point) as well as with one twice the estimate. The second story is the right one: same numbers, honest information.

Corollary: “p = 0.20” does not mean “proven that the effect is null” — the CI might be [−1; +8]: absence of evidence is not evidence of absence.

Definition 9.3 — Honest visualizations: the rules of the craft

  • Axes: never silently truncated on bar charts (a 2 % difference becomes a mountain); bars for counts start at zero, lines may be truncated if stated.
  • Error bars: always say what they carry — SD (dispersion of the data), SE (precision of the mean) or a 95 % CI (inference); by default, show the CI.
  • Raw data: overlay individual points (jitter, violin) on the summaries — 8 observations do not deserve a boxplot.
  • Dual axis: almost always a lie.
  • Effect size + uncertainty + n in every figure/caption; never show a percentage without a count.

Synthesis reference: Cumming (2014), “The new statistics”.

Example 9.4 — Arithmetic of the reproducibility crisis (Ioannidis, 2005) A field tests 1000 hypotheses, 100 of which are true. Power 80 %, \alpha = 5\,\%: true positives = 80, false positives = 0.05 \times 900 = 45. Among the published discoveries (125), the proportion of real discoveries is \frac{80}{80 + 45} = 64\,\%.

Lower the power to 20 % (underpowered studies, cf. ch. 2): true positives 20, false 45 ⇒ 31 %.

Add the biases of ch. 1 (analytical flexibility, selective publication): the PPV can plummet toward 0 — hence systematic replication, pre-registration, and the “announced n and analysis plan” standards of the industrial A/B testing world.

10. A/B testing: sequential and targeted effects

Online platforms run thousands of randomized experiments a year, watched in real time by teams eager to conclude. This chapter brings together the design, multiple-testing and causal tools of the module to answer the questions specific to that setting: when may one stop, and for whom does the variant work?

Definition 10.1 — A/B test and OEC An online randomized experiment: every unit (user, query, session — the randomization unit must be the analysis unit) receives variant A (control) or B (treatment). The OEC (Overall Evaluation Criterion) is the single decision metric, defined before the experiment; secondary metrics (guardrails: latency, error rate, churn) are tested with multiple-testing correction (ch. 7). Discipline: no OEC, no test.

Theorem 10.2 — The cost of “peeking” (looking before the end) A fixed-horizon test of level \alpha, examined K times with stopping as soon as a p-value drops below \alpha, has a false positive rate \mathbb{P}(\exists k \leq K : p_k \leq \alpha) \;\geq\; \alpha \quad \text{and} \quad \leq\; 1 - (1 - \alpha)^K \ \text{(two-sided Gaussian tests).}

For K = 5 looks and \alpha = 5\,\%, this upper value is already 1 - 0.95^5 = 22.6\,\%. The exact rate of five equally spaced looks at a Gaussian test is 14 % (Armitage, McPherson & Rowe, 1969), almost three times the nominal level, and it keeps growing with the number of looks: about 27 % for 28 daily looks. On A/B tests monitored continuously, Johari, Koomen, Pekelis and Walsh (KDD 2017) report type-I errors several times the nominal level.

Proof. The lower bound is clear (the first look is a level-\alpha test). The upper value: if the K looks were independent tests, each of level \alpha under H_0, the probability of no false alarm would be (1-\alpha)^K, hence a rate of exactly 1 - (1-\alpha)^K.

Without any assumption, the union bound over the K events \{p_k \leq \alpha\} gives K\alpha.

In practice successive p-values are strongly positively correlated (each look reuses the earlier data). For two-sided Gaussian tests, Šidák’s inequality (1967) — the probability that all the |Z_k| stay below their thresholds is at least the product of the marginal probabilities — then gives a rate at most 1 - (1-\alpha)^K, with equality for independent looks. The true rate is smaller, but still far above \alpha. Hence the simulation of exercise 8. ∎

Definition 10.3 — Always-valid p-values and mSPRT (Johari et al., 2017) A sequential p-value p_t is always valid if \mathbb{P}(\exists t : p_t \leq \alpha) \leq \alpha for every stopping time — one may then look as often as desired.

Construction: the mixture sequential probability ratio test (mSPRT, Robbins 1970) averages the likelihood ratio of an effect \theta against \theta = 0 over a mixing density h, and turns it into a p-value: \Lambda_t = \int \prod_{s \leq t} \frac{f_\theta(x_s)}{f_0(x_s)}\, h(\theta)\, d\theta, \qquad p_t = \min\Big(1,\ \min_{s \leq t} \frac{1}{\Lambda_s}\Big).

Why it is valid: under H_0, \Lambda_t is a nonnegative martingale of mean 1, and Ville’s inequality gives \mathbb{P}_0\big(\exists t : \Lambda_t \geq 1/\alpha\big) \leq \alpha .

\Lambda_t is a Bayes factor whose prior on the effect is h. For Gaussian data and a Gaussian h, the rejection boundary on the mean difference shrinks like \sqrt{\log t / t}, slightly slower than the fixed-horizon z_{1-\alpha/2}/\sqrt t: the price of looking at will.

Not the same thing: watching the posterior of d = p_B - p_A under a flat Beta(1,1) prior, and stopping as soon as its 95 % credible interval excludes 0, uses a fixed-horizon boundary in disguise (width about z/\sqrt t). Its frequentist type-I error inflates under continuous monitoring exactly like peeking. The code below is therefore a decision rule at a planned horizon (expected loss), not an always-valid test; the bandits of Reinforcement Learning ch. 4 are the other answer, which exploits during the experiment.

import numpy as np
rng = np.random.default_rng(52)

# ---- Bayesian A/B test: Beta posteriors, decision by expected loss ----
conv = np.array([1274, 1378])          # conversions
n    = np.array([12000, 12000])        # visits
a, b = 1.0, 1.0                        # Beta(1, 1) prior
post = [rng.beta(conv[i] + a, n[i] - conv[i] + b, size=200_000) for i in range(2)]

d = post[1] - post[0]                  # absolute uplift drawn a posteriori
loss_if_B = np.where(d < 0, -d, 0.0)   # loss if we deploy B and A was better

print(f"P(B > A)            : {(d > 0).mean():.3f}")
print(f"gain median         : {np.median(d):.5f}")
print(f"95 % CI of the gain : {np.quantile(d, [0.025, 0.975])}")
print(f"E[loss | deploy B] : {loss_if_B.mean():.2e}")
# Typical outputs: P(B>A) = 0.984; median uplift = 0.0087;
# CI = [0.0007, 0.0166]; E[loss] = 2.3e-05.
# Decision: the cost of a wrong choice of B (2 conversions out of 10^5) is negligible
# compared with the expected gain (+0.87 point) -- we deploy B.

Definition 10.4 — Targeted (heterogeneous) effects and the associated errors The average effect hides heterogeneity: B wins on mobile, loses on desktop. Two symmetric pitfalls:

(i) subgroup spinning: 20 segments ⇒ expect a “significant gain” in one of them by pure noise (ch. 7, Bonferroni/BH mandatory);

(ii) ignored real interaction effects: the aggregated OEC can cancel out opposite effects (Simpson, ch. 4).

A sound framework: specify segments a priori, test the segment × treatment interaction, correct for multiple testing.

On the variance side: CUPED (Deng et al., 2013) reuses the metric measured before the experiment as a covariate — a typical “free” variance reduction of 30–50 %, statistically equivalent to the blocks of ch. 2.

Interference and validity Two-sided market (Uber: more drivers ⇒ wait time drops for everyone, including the control), CDN caches, social network effects: SUTVA (ch. 5) violated. Answers: randomize by clusters (cities, IP clusters — power loss via the design effect 1 + (m-1)\rho), or isolate (switchback). See Kohavi, Tang & Xu (2020) for the complete catalog of production pitfalls; the Reinforcement Learning module (bandits, ch. 4) addresses the “exploit during the experiment” alternative.

11. Course research notes (Naulet, MaIAGE)

Zacharie Naulet is a junior professor (INRAE, MaIAGE team — Mathematics and Computer Science applied to Food and the Environment) and teaches at École Polytechnique; his PhD (Université Paris-Saclay) was on nonparametric Bayesian methods for signal and image processing. His themes — nonparametric Bayesian statistics, exchangeability, hidden state space models, applications to biological data and networks — directly feed several chapters of this module: the bootstrap (ch. 8), multiple testing and the estimation of \pi_0 (ch. 7), and, beyond this module, random-graph models.

Example 11.1 — Exchangeability and de Finetti: the backbone De Finetti’s theorem (1931) states that an infinite sequence of exchangeable variables is conditionally i.i.d. with respect to a random law: this is the foundation of Bayesian inference. The quantitative question — how fast does exchangeability approach i.i.d.? — was solved by Dolera & Favaro (“De Finetti’s theorem: rate of convergence in Kolmogorov distance”, Bernoulli 2020; arXiv:1802.02244) — work by colleagues in the field, cited here as a standard, and not by the instructor. Z. Naulet’s work extends the de Finetti program on two fronts:

Example 11.2 — From the bootstrap to networks, and the bridge to privacy

Other recent work: change-point detection in preferential attachment graphs (with I. Kaddouri and E. Gassiat), robust community detection (SubSearch, with L. Bianco and C. Keribin).

Common thread This work shares a signature: guarantees (minimaxity, concentration rates, exact risk) for usable procedures on real data — exactly the ambition of this module at the M1 level, and its M2 extension (privacy, uncertainty, calibration).

Exercises

  1. ★ Randomization by hand. Data 3, 4, 5, 6, 7, 8, split 3+3. Enumerate the 20 allocations, compute all values of \hat d, recover p = 0.10 and the exact distribution (stem-and-leaf display). Which split gives exactly \hat d = 2.33?

  2. ★ Power. (a) Redo the computation of 2.5 for \delta/\sigma = 0.4 and 85 % power.

    (b) A two-sided test has \alpha = 5\,\% and n = 50 per group: plot \pi(\delta) for \delta/\sigma \in [0; 1] and read off the smallest detectable effect size with 80 % power.

    (c) For proportions (p_A = 0.10, expected effect +1 point), adapt the formula by replacing 2\sigma^2 with p_A(1-p_A) + p_B(1-p_B) and compute n.

  3. ★ Simpson. Verify all the cells of table 4.2 (e.g. 289/350 = 82.6 %), then recompute the overall rates by standardizing on A’s profile and on B’s; comment on the sensitivity to the profile choice.

  4. ★ Regression. On the cars dataset (or an equivalent): fit d \sim s, plot the 4 diagnostics, apply Box-Cox, refit; identify the point with the largest Cook’s distance, redo without it; compare the classical and HC1 standard errors (statsmodels).

  5. ★ Communication. You have \hat d = 7.0, 95 % CI = [0.4; 13.6], p = 0.037, n = 80 (Example 9.2). Write in 5 lines: (a) a misleading “press” summary; (b) an honest summary; (c) list the three graphical manipulations that would reverse the reader’s impression, and their fixes.

  6. ★★ DiD. With table 5.4: compute the naive before/after comparison, the cross-sectional after comparison, and the DiD; check that the DiD equals the interaction coefficient of the model y = \beta_0 + \beta_1 \text{NJ} + \beta_2 \text{After} + \beta_3 (\text{NJ} \times \text{After}) + e . Simulate 500 restaurants with common AR(1) shocks and show that naive standard errors are 3–5× too small without clustering (Bertrand et al. 2004).

  7. ★★ BH in practice. (a) Apply Bonferroni, Holm and BH to the p-values of example 7.4 for q = \alpha = 0.10 and q = 0.01. (b) Simulation: generate m = 1000 p-values (m_0 = 900 uniform, 100 false nulls with p ~ Beta(1, 8)), repeat 500 times, estimate the empirical FWER and FDR of each procedure and verify the calibration \mathrm{FDR} \approx q\, m_0/m.

  8. ★★ Peeking. Simulate 1000 A/B tests under H_0 (two Bernoulli p = 0.10, n = 10^5 per arm): (a) a single look at midpoint — false positive rate; (b) daily looks for 28 days with stopping if p < 0.05: compare the rate with the independence (Šidák) value 1-0.95^{28} \approx 76\,\% (the union bound, 28 × 5 % = 140 %, says nothing here) and with the inflation reported by Johari et al.; (c) implement a Gaussian mSPRT and verify its “always” validity.

  9. ★★ Bayesian A/B. Take up the code of ch. 10: (a) analyze the sensitivity to the Beta(1,1) vs Beta(10,10) prior; (b) turn the decision rule into “expected loss < cost of a rollout”; (c) add the per-segment analysis (mobile/desktop) with BH correction of the interaction tests; (d) relate to the frequentist Wald CI — when do they diverge?

  10. ★★ RCBD. Add to the data of Example 3.1 a moderate block × variety (interaction) effect, redo the ANOVA, test the interaction; build the same trial under a completely randomized design (same values, assignment blind to the blocks) and show the loss of F. Write the simultaneous (Tukey) confidence interval for the 6 comparisons.

  11. ★★★ Project. INRAE or open data from a blocked trial (or kaggle: agricultural crop yield): from plan to conclusions — map the potential biases, justify the plan, ANOVA + diagnostics, bootstrap of the contrasts, multiple-comparison correction, final one-page report with honest visualizations and limits. Grading: 40 % plan, 40 % correct analysis, 20 % communication.

Projects and assessment

Official assessment (SynapseS 2026–2027 sheet of APM_52066_EP, read on 24 October 2026): “a group project, an individual written test without documents on that project, and a final exam”, with no weights displayed. The 2024–2025 and 2025–2026 sheets announced “1 or 2 group projects + 1 lab-session report + a final exam” instead.

The unit is not in the LLGA lists (notes kept for reference), so everything below is a proposal in that format, sized for a 36 h course: group subjects of about 25 h per member for the group project, solo subjects of about 20 h for students who work alone, a two-hour final exam, and a rubric for the project reports. The individual written test can question each member on the group’s analysis plan and on one derivation it uses, for instance theorem 2.4 for the sizing.

The projects exercise two master objectives: O1 (ML foundations, here the statistics under every ML evaluation: power, intervals, multiplicity, causal identification) and O7 (hands-on practice, from the analysis plan to an honest report). The LLM leaderboard adds O3 (large language models); the bias audit adds O8 (trustworthy and responsible AI) and prepares the end-of-year project Y1.3.

Solo projects

  1. [Solo · ≈ 20 h] Peeking simulator and a sequential A/B toolkit. How far does the type-I error inflate under daily looks, and what do an always-valid test, a Bayesian stopping rule and variance reduction cost or save?
    • Implement: a simulator of K looks (theorem 10.2, exercise 8); a Gaussian mSPRT with always-valid p-values (definition 10.3); the expected-loss rule of the ch. 10 code, applied at every look; CUPED with a pre-period covariate (definition 10.4).
    • Prove: under the null hypothesis the mixture ratio is a nonnegative martingale of mean 1, hence always valid by Ville’s inequality; CUPED multiplies the variance by 1-\rho^2, where \rho is the correlation between the metric and its pre-period value.
    • Data: simulated Bernoulli streams; then Kevin Hillstrom’s MineThatData e-mail experiment (2008: 64,000 customers randomized between two e-mail campaigns and no e-mail, with past-year spend as pre-period covariate), replayed in a random arrival order.
    • Deliverables: code, 4–6 page report, 10-minute talk. Chapters: ch. 2, 7, 8, 10.
    • Success criterion: over 1,000 null experiments, the 28-look rate is close to 27 % and the mSPRT stays at or below 5 %, both with Monte Carlo intervals; the report gives the power and the median sample size at stopping against the fixed horizon, and the CUPED gain on the Hillstrom data with a bootstrap interval, next to 1-\rho^2.
  2. [Solo · ≈ 20 h] Paper study: how much should we trust difference-in-differences? Reproduce the central experiment of Bertrand, Duflo and Mullainathan (2004), then apply its lesson to Card and Krueger (1994).
    • Implement: the DiD as the interaction regression of exercise 6, with naive, HC1 and clustered standard errors; an event-study check of parallel trends on the simulated panels (the Card and Krueger survey has a single pre-period); the placebo-law simulation — 50 “states” × 20 years with AR(1) shocks of coefficient 0.8, a fake law passed in half of the states at a random year, 1,000 replications.
    • Prove: in the 2 × 2 design, the OLS interaction coefficient equals the double difference of cell means (definition 5.3).
    • Data: the Card and Krueger survey of 410 fast-food restaurants in New Jersey and Pennsylvania (public on David Card’s data page); the simulated panels.
    • Deliverables: code, 4–6 page report, 10-minute talk. Chapters: ch. 4, 5, 6, 8.
    • Success criterion: the DiD of about +2.75 FTE is recovered with an interval clustered by restaurant (with two states, clustering by state is impossible, a limit the report discusses); in the placebo simulation, naive standard errors reject a true null far more often than 5 % (about 38 % in a check run made for these notes) while clustering by state brings the rate within [3 %, 8 %].

Group projects

  1. [Group of 3 · ≈ 25 h each] An honest LLM leaderboard. Which published rankings of four to six small open LLMs survive per-item uncertainty and the correction for many pairwise comparisons? A paper study of E. Miller, “Adding Error Bars to Evals: A Statistical Approach to Language Model Evaluations” (2024), carried out with the tools of this course.
    • Data: per-item outcomes on ARC-Challenge (Clark et al., 2018; 1,172 test questions), GSM8K (Cobbe et al., 2021; 1,319 test problems) and BoolQ (Clark et al., 2019; 3,270 dev questions), from EleutherAI’s lm-evaluation-harness run with --log_samples on models of at most 2B parameters (free GPU tier).
    • Implement: the smallest detectable paired gain of each benchmark, before scoring (theorem 2.4 for paired differences); paired bootstrap intervals for every score difference (ch. 8); McNemar tests, then Holm against Benjamini–Hochberg over all model pairs and benchmarks (ch. 7); a report whose figures follow definition 9.3.
    • Split of work: A runs the models with fixed prompts and seeds and logs per-item outputs; B owns the sizing, the bootstrap and the variance over 3 prompt templates; C owns the multiple-testing plan, written before scoring, and the report.
    • Deliverables: repository, analysis plan, 6-page report, 15-minute talk. Chapters: ch. 2, 7, 8, 9. Links: Large Language Models 9.6 and Machine Learning 4.9.
    • Success criterion: every difference comes with its paired 95 % interval and n; the report states which adjacent ranks stay separated after each correction, and how many orderings published in the model cards do not survive.
  2. [Group of 3 · ≈ 25 h each] A blocked field trial from plan to report. How much did blocking buy in real trials, and which treatment differences survive honest multiple comparisons? It extends exercise 11 to two classic, public trials.
    • Data: Yates’ Rothamsted oats experiment (1935: 6 blocks, 3 varieties, 4 nitrogen doses, 72 plots; MASS::oats in R, or statsmodels.datasets.get_rdataset("oats", "MASS")), and the alpha-lattice oat trial agridat::john.alpha (24 genotypes, 3 replicates of 6 incomplete blocks; John & Williams, 1995).
    • Implement: the analysis of variance with blocks (ch. 3), with the split-plot error strata for the oats; the four diagnostic plots and a Box-Cox check (ch. 6); bootstrap intervals for the contrasts (ch. 8); Tukey against Benjamini–Hochberg for the pairwise comparisons (ch. 7); the efficiency of blocking against a completely randomized design.
    • Split of work: A reconstructs the design and sizes the next trial (ch. 2: plots needed to detect a 5 % yield gain); B runs the models and the diagnostics; C owns the bootstrap, the multiple comparisons and the one-page summary.
    • Deliverables: code, 6-page report ending with the one-page summary of exercise 11, 15-minute talk. Chapters: ch. 2, 3, 6, 7, 8, 9.
    • Success criterion: the classic split-plot analysis of the oats is reproduced (nitrogen F ≈ 37.7 on 3 and 45 degrees of freedom, as in Venables & Ripley’s Modern Applied Statistics with S); the efficiency of blocking comes with a bootstrap interval; every claimed difference states its correction and its interval.
  3. [Group of 3 · ≈ 25 h each] Bias audit of a recommendation dataset. Which selection and survivorship biases shape logged ratings, and could a recommender change look good for the wrong reasons? The audit prepares the evaluation of the end-of-year project Y1.3 (cold-start news recommendation).
    • Data: MovieLens-1M (Harper & Konstan, 2015: 1,000,209 ratings by 6,040 users with age, gender and occupation); MIND-small (Wu et al., 2020) for the Y1.3 setting.
    • Implement: a map of the biases (ch. 4) — ratings exist only for chosen items, heavy raters dominate, users who leave stop rating; a search for Simpson reversals between segments; a simulated randomized change on the logged users with a planted segment-dependent effect, analysed by segment × treatment interaction tests with Benjamini–Hochberg (ch. 7, definition 10.4); a written discussion of interference (SUTVA, ch. 5).
    • Split of work: A owns the bias map and the Simpson search; B the simulator and the interaction tests; C the interference discussion, the figures and the report.
    • Deliverables: repository, 6-page report, 15-minute talk. Chapters: ch. 4, 5, 7, 9, 10.
    • Success criterion: over 200 simulated experiments, the planted segments are found with an average false discovery proportion at most q; every bias of the map comes with a number (share of ratings, gap, reversal) and its consequence for an offline evaluation.

Written exam (proposal)

Two hours, one handwritten A4 sheet allowed, a non-programmable calculator; four independent questions. Use z_{0.975}=1.96 and z_{0.80}=0.842.

  1. Question (5 points). A product team checked its A/B test every morning and stopped on day 9, when the p-value first fell below 0.05; it reports “a significant +2 % on conversion (p = 0.04)”. (a) Why is the error rate of this procedure not 5 %? Bound it for 9 looks. (b) Give two valid ways to run the next test. (c) A colleague proposes to stop instead when the 95 % credible interval of a flat-prior Bayesian analysis excludes 0. Does this fix the problem?

    Expected: (a) The procedure rejects if any of the 9 looks crosses the threshold (theorem 10.2): the rate is at least 5 % and, for two-sided Gaussian tests, at most 1-0.95^9 \approx 37\,\%. Positive correlation between looks makes it smaller — about 19 % for equally spaced looks — but far above 5 %.

    (b) A fixed horizon sized in advance (theorem 2.4) with a single look; or an always-valid p-value such as the mSPRT (definition 10.3); group-sequential boundaries also qualify. (c) No: with a flat prior the credible interval is close to the Wald interval, a fixed-horizon boundary, so the same inflation occurs. Validity needs a mixture likelihood ratio (a Bayes factor) as stopping boundary, which shrinks like \sqrt{\log t / t}.

  2. Question (6 points). Two LLMs are scored on the same benchmark items; a pilot shows that they disagree on 20 % of the items. (a) How many items give 80 % power to detect an accuracy gain of 3 points at the 5 % level (two-sided), with a paired analysis? (b) ARC-Challenge has 1,172 test questions: which gain can it detect with the same power? (c) Five models are compared pairwise on it; the ten p-values are 0.001, 0.008, 0.012, 0.030, 0.041, 0.09, 0.20, 0.33, 0.52, 0.81. Which pairs do Bonferroni, Holm and Benjamini–Hochberg declare different at level 0.05?

    Expected: (a) The per-item difference takes the values −1, 0 or 1, with variance 0.20 - 0.03^2 = 0.1991. Theorem 2.4, written for one sample of paired differences, gives n = \frac{(1.96 + 0.842)^2 \times 0.1991}{0.03^2} \approx 1737 \text{ items.}

    (b) Solving for the gain, \delta \approx 2.802\sqrt{0.2/1172} \approx 0.037: about 3.7 points, so smaller gains are invisible on this benchmark. (c) Bonferroni (threshold 0.005) and Holm (0.005, then 0.05/9 ≈ 0.0056, which 0.008 fails) reject one pair. BH compares p_{(k)} with 0.005\,k: 0.001, 0.008 and 0.012 pass, 0.030 > 0.020 and every later one fails, so k^* = 3 pairs (theorem 7.3).

  3. Question (5 points). Under the null hypothesis the observations are i.i.d. with density f_0; the mSPRT of definition 10.3 mixes the alternatives f_\theta with a prior density h. (a) Show that its mixture ratio \Lambda_t is a nonnegative martingale of mean 1 under the null. (b) Ville’s inequality states that such a martingale exceeds a level c > 0 at some time with probability at most 1/c. Deduce that the p-value of definition 10.3 is always valid.

    Expected: (a) For a fixed \theta, the product L_t(\theta) of the ratios f_\theta(x_s)/f_0(x_s) over s \leq t satisfies \mathbb{E}_0\big[L_{t+1}(\theta) \mid x_{1:t}\big] = L_t(\theta) \int f_\theta(x)\,dx = L_t(\theta); integrating against h keeps the martingale property (Tonelli: everything is nonnegative), and \Lambda_0 = 1.

    (b) For any stopping time T, the event p_T \leq \alpha means that \Lambda_s \geq 1/\alpha for some s \leq T, so \mathbb{P}_0(p_T \leq \alpha) \leq \mathbb{P}_0\big(\sup_t \Lambda_t \geq 1/\alpha\big) \leq \alpha .

  4. Question (4 points). A company runs 200 A/B tests a year, and 10 % of the ideas tested truly work. (a) With 80 % power at the 5 % level and a single look, how many “wins” are expected, and which fraction of them is real? (b) Daily peeking raises the false-positive rate to 27 % and the power to 90 %: same questions. What should the company report next to each win?

    Expected: (a) 20 real ideas give 16 true wins and 180 null ideas give 9 false wins: 25 wins, of which 64 % are real (the arithmetic of example 9.4). (b) 18 true and 0.27 \times 180 \approx 49 false wins: only about 27 % of 67 wins are real, so peeking turns most “wins” into noise. Next to each win: the effect with its interval and n, the planned horizon and the number of looks (definitions 9.3 and 10.1).

Total: 5 + 6 + 5 + 4 = 20 points.

Grading rubric (proposal)

Criterion Weight What earns the marks
Plan written before the data 20 % Question, unit, outcome, sample size or detectable effect and analysis plan fixed in advance; every deviation reported
Correctness of the analysis and code 30 % The estimator and test match the design; derivations are complete; the code is checked on simulated data with a known answer
Uncertainty and multiplicity 20 % Intervals at the right unit (paired, clustered, blocked); bootstrap where no formula exists; a correction that matches the goal (FWER or FDR)
Communication 20 % Effect, interval and n in every figure; no truncated axes; limits and negative results stated (ch. 9)
Reproducibility and teamwork 10 % One command reruns everything from a fixed seed; data provenance and licence given; for groups, a visible split of the work

References