Module contents
Lesson 18 of 27Core 105 min

Multiple comparisons: FWER, FDR and the garden of forking paths

Control familywise error and false discoveries, and recognize hidden multiplicity in analysis choices.

After this lesson you can

  • Define FWER and FDR and prove Bonferroni, Holm and Benjamini–Hochberg guarantees.
  • Interpret adjusted p-values, q-values and local FDR under independence and dependence.
  • Recognize optional stopping, selection and forking paths, and design appropriate remedies.

Before you start

Motivation: twenty variants and a “discovery”

A team tests twenty model variants (or twenty experimental metrics, or twenty candidate genes) one by one at the usual level, α=0.05\alpha = 0.05. Suppose none works: all null hypotheses are true. Each individual test is impeccable: its probability of mistaken rejection is exactly 0.050.05. Yet the team will find “something” almost every time. The following cell measures this by repeating the experiment of twenty no-effect tests twenty thousand times.

[ ]Twenty tests with all null hypotheses trueBrowser
import numpy as np
from scipy import stats

rng = np.random.default_rng(18)
R, m, n = 20000, 20, 50                       # estudios, contrastes por estudio, observaciones por contraste
t = rng.standard_t(n - 1, (R, m))             # sin efecto, el estadístico t de una muestra normal es una t(n-1)
p = 2 * stats.t.sf(np.abs(t), n - 1)          # R x m valores p
signif = p < 0.05

print(f"falsos positivos esperados por estudio : {signif.sum(1).mean():.3f}   (m·alfa = {m * 0.05:.1f})")
print(f"P(al menos un p < 0.05)                : {np.mean(signif.any(1)):.4f}   (1 - 0.95^20 = {1 - 0.95**m:.4f})")
print(f"mediana del valor p mínimo             : {np.median(p.min(1)):.4f}   (teoría: 1 - 0.5^(1/20) = {1 - 0.5**(1 / m):.4f})")
print(f"P(p mínimo < 0.05/20)                  : {np.mean(p.min(1) < 0.05 / m):.4f}")

Nearly two out of three studies with no effect have at least one “significant result,” and the smallest of twenty p-values is typically 0.0340.034. If the team picks the best variant and presents it as an individual test (p=0.03p = 0.03, “significant”), the procedure followed has level 0.640.64, not 0.050.05. The last line anticipates the simplest remedy: requiring p<0.05/20p < 0.05/20 returns the error rate to 5 %5\,\%.

This lesson studies how that inflation is measured, controlled and avoided. It has three acts:

  1. Counting errors in a family. Two rates, FWER (probability of any false positive) and FDR (expected fraction of false discoveries), and procedures controlling them: Bonferroni, Šidák, Holm, Tukey and Benjamini–Hochberg, with complete proofs.
  2. Reading thousands of p-values. Dependence, estimation of the null proportion, qq-values and local FDR.
  3. Invisible multiplicity. When comparisons happen in the analyst’s head rather than code: p-hacking, optional stopping, selecting the best variant, and remedies.

We use without further explanation p-values, hypothesis tests, type I and II errors, and the power function, and from probability the union bound and order statistics.

The problem: many tests at once

An individual test controls one error: rejecting a true null with probability at most α\alpha. When mm tests are performed, the important question is rarely “is each one reliable?” but “can I trust the set of conclusions I have declared?” To formulate it we must specify the set and count errors.

With one hypothesis, P(V≥1)=α\Pr(V \ge 1) = \alpha and there is nothing more to say. With mm hypotheses, the first result is already unsettling.

The formula follows because “no rejection” is the intersection of mm independent events of probability 1−α1 - \alpha; the bound is Boole’s inequality: P(⋃i{pi≤α})≤∑iP(pi≤α)=mα\Pr(\bigcup_i \{p_i \le \alpha\}) \le \sum_i \Pr(p_i \le \alpha) = m\alpha. With α=0.05\alpha = 0.05: m=5m = 5 gives 22.6 %22.6\,\%; m=20m = 20, 64.2 %64.2\,\%; m=100m = 100, 99.4 %99.4\,\%. And the expected number of false positives is mαm\alpha regardless of dependence: with twenty true nulls, one on average.

The following figure lets you explore the curve and, above all, what dependence does to it. With correlated statistics, tests do not draw independent noise: if the common factor pushes all upward, either none reject or many reject together, and the probability of any rejection is less than under independence.

InteractiveProbability of at least one false positive
Probability of at least one false positive when all null hypotheses are true
α = 0.0564.2 %
  • uncorrected (your ρ\rho)
  • Bonferroni (your ρ\rho)
  • uncorrected, independent
  • bound mαm\alpha
How many independent tests are equivalent to your mm correlated tests
m_ef = 20.0
  • mefm_{\mathrm{ef}} with your ρ\rho
  • independent (mef=mm_{\mathrm{ef}} = m)
0.05
0.00
20
Uncorrected, independent: 1−(1−α)m1-(1-\alpha)^m64.15 %
Uncorrected, with your ρ\rho64.15 %
Union bound min⁡(1,mα)\min(1, m\alpha)100.00 %
Bonferroni (α/m\alpha/m per test)4.88 %
Šidák (1−(1−α)1/m1-(1-\alpha)^{1/m} per test)5.00 %
Equivalent independent tests mefm_{\mathrm{ef}}20.0
With 20 independent tests and α=0.05\alpha = 0.05, the probability of at least one false positive is 64.2 %. Bonferroni reduces it to 4.88 %, just below α\alpha.
All nulls are true and the mm two-sided zz statistics have common correlation ρ\rho (calculated exactly by conditioning on the common factor). Blue is uncorrected FWER; aqua is Bonferroni (level α/m\alpha/m per test); dashed gray is the independence formula 1−(1−α)m1-(1-\alpha)^m; dotted yellow is the bound mαm\alpha. Right: number of independent tests with the same FWER. Try ρ=0\rho = 0 and m=20m = 20 (64%), increase mm to a thousand, then increase ρ\rho to 0.90.9: with a thousand highly correlated tests FWER falls to a third and mefm_{\mathrm{ef}} to about eight. Notice that Bonferroni with ρ=0\rho = 0 uses almost its entire α\alpha budget, while with high ρ\rho it wastes almost all of it.

Two readings of the figure that we will revisit:

  • Under independence, Bonferroni is almost exact. Its actual FWER is 1−(1−α/m)m≈α(1−(m−1)α2m )1 - (1 - \alpha/m)^m \approx \alpha(1 - \tfrac{(m-1)\alpha}{2m}\,), just below α\alpha (4.88 %4.88\,\% for α=0.05\alpha = 0.05 and any m≥20m \ge 20).
  • Under positive dependence it is conservative and overcorrects. Tests “count” less than mm independent tests. An effective size mefm_{\mathrm{ef}} (the mm of an independent family with the same FWER) measures this, although it depends on level and dependence structure and has no general formula.

What counts as a family?

The definition says “hypotheses read together,” and it is subtler than it looks. This is a design decision, not a property of the dataset:

  • A small, well-defined family (for example three drug efficacy endpoints, any one sufficient for approval) calls for FWER control over those three.
  • A huge exploratory family (twenty thousand genes) makes FWER control impractical, and another rate is often preferable.
  • It is unacceptable to choose the family after seeing results or count only the tests “reported.” The family includes everything examined with intent to draw a conclusion, even if it never reaches the paper. This most frequent error returns in the last part.

FWER control: Bonferroni, Šidák and Holm

The oldest and most conservative family error rate is the probability of making at least one mistake.

Strong control is what matters: we do not know which hypotheses are true, and a procedure controlling only the extreme case where none is false does not protect in every real case. (Rejecting the global null ⋂iHi\bigcap_i H_i with an “is there anything anywhere?” test and then reporting the hypothesis with minimum pip_i as a specific discovery uses weak control as if it were strong.)

Bonferroni

Proof

True-null p-values satisfy P(pi≤u)≤u\Pr(p_i \le u) \le u. A false positive rejects some i∈I0i \in I_0, so by the union bound

P(V≥1)=P(⋃i∈I0{pi≤αm})≤∑i∈I0P(pi≤αm)≤m0αm≤α.\Pr(V \ge 1) = \Pr\Big(\bigcup_{i \in I_0} \{p_i \le \tfrac{\alpha}{m}\}\Big) \le \sum_{i \in I_0} \Pr\big(p_i \le \tfrac{\alpha}{m}\big) \le m_0 \frac{\alpha}{m} \le \alpha.

No independence or distribution of pip_i with i∉I0i \notin I_0 was used.

∎

Two important points. First, the result is so general that it has a price: Bonferroni uses none of the problem’s structure, and its power cost grows with mm. To detect an effect of μ\mu standard errors with 80% power for m=20 000m = 20\,000 requires μ=z1−α/(2m)+z0.8=4.71+0.84=5.55\mu = z_{1 - \alpha/(2m)} + z_{0.8} = 4.71 + 0.84 = 5.55, versus 2.802.80 for one test: an effect almost twice as large. Second, the actual bound is m0α/mm_0 \alpha / m, not α\alpha: if a large fraction of nulls is false, effective FWER is well below α\alpha and that margin is wasted (some can be recovered by estimating m0m_0, as we will see).

The Bonferroni adjustment to adjusted p-values is p~i=min⁡(1,m pi)\tilde p_i = \min(1, m\,p_i): rejection at level α\alpha is equivalent to p~i≤α\tilde p_i \le \alpha. Adjusted p-values are useful because α\alpha may be chosen afterward: “the smallest family level at which HiH_i is rejected.”

Šidák

With independent tests, P(ninguˊn rechazo)=(1−α′)m\Pr(\text{ningún rechazo}) = (1 - \alpha')^m when each uses level α′\alpha', and setting that probability to 1−α1 - \alpha gives the Šidák threshold, α′=1−(1−α)1/m\alpha' = 1 - (1 - \alpha)^{1/m}, slightly less strict than α/m\alpha/m (for α=0.05\alpha = 0.05 and m=20m = 20: 0.0025610.002561 versus 0.00250.0025). It controls FWER exactly under independent p-values, and also under “favorable” dependence such as normal statistics with two-sided tests (Šidák’s inequality, 1967), but there is no general guarantee. In practice the gain over Bonferroni is 2%: Šidák is used for elegance and Bonferroni for robustness.

Holm: sequential Bonferroni

Bonferroni has an obvious waste: once a hypothesis is rejected, there are at most m−1m - 1 possible true nulls, not mm, so threshold α/m\alpha/m can be relaxed. Holm (1979) uses this observation step by step.

Thresholds are α/m,α/(m−1),…,α/1\alpha/m, \alpha/(m-1), \dots, \alpha/1: they increase as we proceed. The first step is exactly Bonferroni; subsequent ones are more permissive. Most importantly, Holm is uniformly more powerful than Bonferroni (it rejects everything Bonferroni rejects and more) with the same control, at no cost.

Proof

Let I0I_0 be the set of true nulls, with m0=∣I0∣≥1m_0 = \abs{I_0} \ge 1 (if m0=0m_0 = 0 no false positives are possible). Let i∗i^\ast be the position, in the global ordering of the mm p-values, of the smallest pip_i with i∈I0i \in I_0. Only false hypotheses can precede it, of which there are m−m0m - m_0, so i∗≤m−m0+1i^\ast \le m - m_0 + 1, i.e.

m+1−i∗≥m0.m + 1 - i^\ast \ge m_0.

If Holm rejects any true null, it rejects in particular the one with smallest true-null p-value, and to reach it must pass step i∗i^\ast:

p(i∗)≤αm+1−i∗≤αm0.p_{(i^\ast)} \le \frac{\alpha}{m + 1 - i^\ast} \le \frac{\alpha}{m_0}.

Since p(i∗)=min⁡i∈I0pip_{(i^\ast)} = \min_{i \in I_0} p_i, we have proved the event inclusion

{V≥1}⊆{min⁡i∈I0pi≤αm0},\{V \ge 1\} \subseteq \Big\{\min_{i \in I_0} p_i \le \tfrac{\alpha}{m_0}\Big\},

whose probability by the union bound is at most ∑i∈I0P(pi≤α/m0)≤m0⋅α/m0=α\sum_{i \in I_0} \Pr(p_i \le \alpha/m_0) \le m_0 \cdot \alpha/m_0 = \alpha. This holds for every I0I_0 and any dependence.

∎

The proof teaches more than the result: control does not depend on which nulls are true, only how many, and “reduction to m0m_0” is why Holm can relax its threshold at each rejection without losing the guarantee. The Hochberg procedure (1988) is its step-up version: find the largest kk with p(k)≤α/(m+1−k)p_{(k)} \le \alpha/(m + 1 - k) and reject all preceding hypotheses; it is more powerful, but unlike Holm its control requires independence (or positive dependence, of MTP2_2 type).

The closure principle

Holm is not an isolated trick: it is the simplest instance of a general recipe (Marcus, Peritz and Gabriel, 1976). For each nonempty index subset II, let HI=⋂i∈IHiH_I = \bigcap_{i \in I} H_i be the hypothesis “all HiH_i, i∈Ii \in I, are true,” and let φI\varphi_I be a level-α\alpha test of HIH_I.

Proof

Let I0I_0 be the set of true nulls; then HI0H_{I_0} is true and P(φI0=1)≤α\Pr(\varphi_{I_0} = 1) \le \alpha. If some HiH_i with i∈I0i \in I_0 is rejected, then by definition HIH_I was rejected for every I∋iI \ni i, in particular for I=I0I = I_0. Thus P(V≥1)≤P(φI0=1)≤α\Pr(V \ge 1) \le \Pr(\varphi_{I_0} = 1) \le \alpha.

∎

Holm is closure with local Bonferroni tests, φI=1[min⁡i∈Ipi≤α/∣I∣]\varphi_I = \ind[\min_{i \in I} p_i \le \alpha/\abs{I}]. To see they coincide, fix H(k)H_{(k)}. Every I∋(k)I \ni (k) has at least one p(j)p_{(j)} with j≤kj \le k, and among sets II whose smallest rank is jj, the hardest to reject is the largest, {(j),…,(m)}\{(j), \dots, (m)\}, of size m+1−jm + 1 - j. Rejecting every I∋(k)I \ni (k) is thus equivalent to p(j)≤α/(m+1−j)p_{(j)} \le \alpha/(m + 1 - j) for every j≤kj \le k: Holm’s rule. Changing local tests (e.g. Simes or permutation tests) yields more powerful procedures with the same control; logical structure among hypotheses (e.g. pairwise comparisons where certain intersections are impossible) is exploited through II.

Tukey comparisons after ANOVA

The classic structured family has kk groups with one mean each and (k2)\binom{k}{2} pairwise comparisons. With nn observations per group, common variance and ν=k(n−1)\nu = k(n - 1) degrees of freedom, the standardized maximum mean difference max⁡i,j∣yˉi−yˉj∣n/s\max_{i,j} \abs{\bar y_i - \bar y_j}\sqrt{n}/s has the studentized range distribution qk,νq_{k,\nu} when all means coincide. Rejecting pair (i,j)(i, j) when

∣yˉi−yˉj∣>qk,ν;1−α sn\abs{\bar y_i - \bar y_j} > q_{k,\nu;1-\alpha}\,\frac{s}{\sqrt n}

is Tukey’s HSD test, and intervals yˉi−yˉj±qk,ν;1−α s/n\bar y_i - \bar y_j \pm q_{k,\nu;1-\alpha}\,s/\sqrt n cover all (k2)\binom{k}{2} true differences simultaneously with exact probability 1−α1 - \alpha in the balanced design. Since a false rejection requires some interval to miss, FWER is ≤α\le \alpha with strong control. For unequal group sizes Tukey–Kramer is conservative. The gain over Bonferroni is small but real because Tukey uses the exact joint distribution of differences, not the union bound. The cell compares constants and runs the test with statsmodels.

[ ]Tukey versus Bonferroni in 5 groupsBrowser
import numpy as np
from scipy.stats import studentized_range, t as tdist
from statsmodels.stats.multicomp import pairwise_tukeyhsd

# constantes críticas: 5 grupos de 10 observaciones (gl = 45) y las 10 comparaciones por pares
k, n = 5, 10
gl = k * (n - 1)
q = studentized_range.ppf(0.95, k, gl)
print(f"t sin corregir        : {tdist.ppf(0.975, gl):.3f}")
print(f"Tukey  q/sqrt(2)      : {q / np.sqrt(2):.3f}")
print(f"Bonferroni (10 pares) : {tdist.ppf(1 - 0.05 / (2 * 10), gl):.3f}")

# un experimento: cuatro grupos sin efecto y uno desplazado 1.5 desviaciones típicas
rng = np.random.default_rng(3)
y = rng.standard_normal((k, n)); y[4] += 1.5
res = pairwise_tukeyhsd(y.ravel(), np.repeat(list("ABCDE"), n), alpha=0.05)
print(res.summary())

Without correction the tt threshold is 2.012.01; Bonferroni raises it to 2.952.95; Tukey to 2.842.84. In the experiment, group E (shifted 1.51.5) separates from A, B and D, but not C, whose mean unluckily came out high: the price of FWER control and a reminder that “not significant” does not mean “equal.” (ANOVA and experimental design are covered in their lesson.)

False discovery rate: another way to be wrong

Twenty thousand genes, perhaps two thousand genuinely altered by a disease. We want a candidate list for laboratory validation. With FWER at 5 %5\,\%, Bonferroni requires p≤2.5×10−6p \le 2.5 \times 10^{-6}, i.e. z≥4.71z \ge 4.71. A gene with an effect of 3.53.5 standard errors, a strong signal, has 11 %11\,\% power to pass that threshold. But the goal was not never to err: it was a list that is mostly good. Accepting a handful of false candidates among many true ones is reasonable because every candidate will be validated anyway. Benjamini and Hochberg (1995) formalized this tolerance.

FDR is the average fraction of false discoveries among those declared, averaged over hypothetical repetitions of the experiment. Two properties place it relative to FWER.

Proof

Since V≤RV \le R, V/max⁡(R,1)≤1[V≥1]V/\max(R, 1) \le \ind[V \ge 1] (if V≥1V \ge 1 the ratio is at most 1, and if V=0V = 0 it is 0). Taking expectations, FDR≤P(V≥1)\mathrm{FDR} \le \Pr(V \ge 1). If m0=mm_0 = m, every rejection is false, V=RV = R, and V/max⁡(R,1)=1[V≥1]V/\max(R, 1) = \ind[V \ge 1], giving equality.

∎

Thus controlling FWER implies controlling FDR, and controlling only FDR is a weaker guarantee paid for with tolerance of false positives and rewarded with power. FDR adapts to problem scale: with m0=mm_0 = m it requires the same as FWER, but as signal increases it permits more rejections, because each true rejection “cushions” false ones. This makes it natural when screening thousands of hypotheses.

Take care with interpretation. FDR is not the probability that a particular discovery is false: it is a property of the procedure, an average over many possible lists. In a particular list FDP can lie well above or below FDR, and within a list some findings are far more reliable than others. The latter is local FDR, covered below.

Why most findings can be false

An elementary probability calculation explains the importance of π0\pi_0. Suppose a field tests hypotheses with fraction π0\pi_0 true nulls, at level α\alpha and power 1−β1 - \beta against alternatives. What proportion of significant results are true?

P(rechazo∩H0)=π0 α\Pr(\text{rechazo} \cap H_0) = \pi_0\,\alpha
A fraction π0\pi_0 of hypotheses are null and each is rejected with probability α\alpha.
1/4

With α=0.05\alpha = 0.05: if π0=0.9\pi_0 = 0.9 and power is 80%, positive predictive value is 0.640.64; with 50% power, 0.530.53; with 20%, 0.310.31. If the hypothesis is implausible, π0=0.99\pi_0 = 0.99, even at 80% power it is only 0.140.14: six of seven “discoveries” are false. This is Ioannidis’s (2005) argument for why many published results do not replicate: a field testing unlikely hypotheses with low-powered studies and threshold p<0.05p < 0.05 produces a literature full of false positives even when every individual test is correct. (Low power also inflates the effect size of detected results; see type S and M errors.)

FWER or FDR?

Neither rate is universally better; one answers the question being asked.

SituationRateWhy
Confirm a drug with several efficacy criteria; one failure approves a defective productFWER (strong control)Small family and irreversible decision; any false positive is costly.
Screen 20,000 genes to select those for validationFDRCandidate list followed by validation; the false fraction is what costs.
Explore 50 secondary A/B-test metrics to generate hypothesesFDRExploratory; false results will be discarded in the next experiment.
Choose the best of 30 configurations and claim it beats baselineFWER (or held-out data)The claim concerns “the best,” so probability of any false discovery must be bounded.

The practical question: “what does a list with a fraction qq false cost, and what does a single false result cost?” If one false positive ruins the conclusion, FWER; if a fraction is tolerable because a later step filters them, FDR.

Benjamini–Hochberg

The Benjamini–Hochberg procedure is surprisingly simple, and its proof is an example of how elegant an error-control result can be.

This is a step-up procedure: search backward for the last p-value below the line k q/mk\,q/m and reject everything before it, even if some earlier values lie above the line. That is the distinction from a step-down procedure such as Holm. In the plot of ordered p-values versus rank, BH draws a line from the origin with slope q/mq/m and rejects everything to the left of the last point below it.

InteractiveBenjamini–Hochberg in a graph
Ordered p-values of m=100m = 100 hypotheses (20 with a true effect)
BH rejects 19iα/mα/mHolm
  • true effect
  • null
  • BH false discovery
  • Bonferroni
  • Holm
  • BH
Average over 300 experiments like this one (vertical mark: level α\alpha)
FWER
FDR
Power
Bonferroni
7.3 %
0.9 %
39 %
Holm
7.3 %
0.8 %
40 %
BH
73 %
8.3 %
72 %
BY
12 %
1.2 %
46 %
FWER: fraction of experiments with any false positive. FDR: mean fraction of false discoveries among rejections (its scale reaches 20 %). Power: fraction of the 20 true effects detected. FWER family methods (≤α\le \alpha) pay in power for what BH spends on FDR (π0α\pi_0\alpha).
0.10
20 %
3.00
0.0
Number of hypotheses mm
P-value axis
Bonferroni: rejections (false)7 (0) · FDP 0.0 %
Holm: rejections (false)7 (0) · FDP 0.0 %
BH: rejections (false)19 (3) · FDP 15.8 %
BY: rejections (false)11 (0) · FDP 0.0 %
Mean BH FDR over 300 experiments | target π0α\pi_0\alpha8.3 % | 8.0 %
Standard deviation of BH FDP6.9 %
BH rejects 19 hypotheses (3 false) and Bonferroni rejects 7. BH gains 12 discoveries in exchange for accepting an expected false fraction of 8.0 %, rather than zero.
Ordered p-values for mm hypotheses, blue for real effects and gray for nulls. The magenta line is iα/mi\alpha/m (BH), orange is Bonferroni threshold α/m\alpha/m, and purple is Holm threshold α/(m+1−i)\alpha/(m + 1 - i). Filled points are BH rejections (red ones false). Right: the mean of 300 identical experiments: FWER, FDR and power for each method. Initially BH rejects 19 hypotheses (3 false) versus 7 for Bonferroni, and mean FDR is π0α\pi_0\alpha, not α\alpha. Increase α\alpha and μ\mu and watch methods separate; lower the fraction of real effects to zero (all rejections are false: FWER and FDR coincide); increase ρ\rho to 0.80.8 and observe FDP standard deviation: its mean remains, but each individual experiment is a lottery. Show Benjamini–Yekutieli and see the price of no dependence assumptions.
Proof

Let RR be the number of rejections and N(t)=#{j:pj≤t}N(t) = \#\{j : p_j \le t\}. Since p(k)≤kq/mp_{(k)} \le kq/m is equivalent to N(kq/m)≥kN(kq/m) \ge k, we have R=max⁡{k:N(kq/m)≥k}R = \max\{k : N(kq/m) \ge k\}, and HiH_i is rejected if and only if pi≤Rq/mp_i \le Rq/m. Thus

FDR=∑i∈I0E[1[pi≤Rq/m]max⁡(R,1)].\mathrm{FDR} = \sum_{i \in I_0} \E\left[\frac{\ind[p_i \le Rq/m]}{\max(R, 1)}\right].

Fix i∈I0i \in I_0 and let RiR_i be the number of BH rejections when pip_i is replaced by 0; with Ni(t)=N(t)+1[pi>t]N_i(t) = N(t) + \ind[p_i > t] we have Ri=max⁡{k:Ni(kq/m)≥k}R_i = \max\{k : N_i(kq/m) \ge k\}. Since Ni≥NN_i \ge N, Ri≥RR_i \ge R; and Ri≥1R_i \ge 1, because Ni(q/m)≥1N_i(q/m) \ge 1.

Lemma: {pi≤Rq/m}={pi≤Riq/m}\{p_i \le Rq/m\} = \{p_i \le R_i q/m\}, and on that event R=RiR = R_i. Indeed, if pi≤Riq/mp_i \le R_i q/m, then at t=Riq/mt = R_i q/m we have N(t)=Ni(t)≥RiN(t) = N_i(t) \ge R_i, so R≥RiR \ge R_i and, with R≤RiR \le R_i, R=RiR = R_i and HiH_i is rejected. Conversely, if HiH_i is rejected, pi≤Rq/m≤Riq/mp_i \le Rq/m \le R_i q/m.

By the lemma, and since Ri≥1R_i \ge 1,

E[1[pi≤Rq/m]max⁡(R,1)]=E[1[pi≤Riq/m]Ri].\E\left[\frac{\ind[p_i \le Rq/m]}{\max(R, 1)}\right] = \E\left[\frac{\ind[p_i \le R_i q/m]}{R_i}\right].

Now RiR_i is a function only of (pj)j≠i(p_j)_{j \ne i} and by independence is independent of pip_i. Conditioning on RiR_i (with Riq/m≤1R_i q/m \le 1), P(pi≤Riq/m∣Ri)≤Riq/m\Pr(p_i \le R_i q/m \given R_i) \le R_i q/m, with equality if pip_i is uniform. Thus the expectation is at most E[(Riq/m)/Ri]=q/m\E[(R_i q/m)/R_i] = q/m. Summing over i∈I0i \in I_0 gives FDR≤m0q/m\mathrm{FDR} \le m_0 q/m.

∎

The result has two useful readings. First, FDR is exactly π0q\pi_0 q, not qq: BH is conservative to the extent there is signal (π0<1\pi_0 < 1), and equals qq only when all nulls are true. (This is why the figure’s mean FDP is π0α\pi_0\alpha and why estimating π0\pi_0 can improve it.) Second, when all are true (π0=1\pi_0 = 1), BH is an exact level-qq test of the global null, the Simes test (1986): reject if any p(k)≤kq/mp_{(k)} \le kq/m.

Regarding Holm: BH thresholds kq/mkq/m are at least Holm thresholds q/(m+1−k)q/(m + 1 - k), because k(m+1−k)≥mk(m + 1 - k) \ge m for 1≤k≤m1 \le k \le m. Thus BH always rejects at least as much as Holm at the same level, and almost always more, although they control different things (FDR versus FWER). There is no magic: BH relaxes the guarantee. Its FDR π0q\pi_0 q is moderate, but its FWER can be enormous (with the figure’s initial values, almost three in four experiments contain a false positive). This tradeoff must be decided beforehand.

Dependence: Benjamini–Yekutieli and positive dependence

The proof used independence exactly once: RiR_i does not depend on pip_i. When p-values are related (genes in the same pathway, neighboring pixels, product metrics that move together), two paths are available.

A procedure valid always

Proof

Let q′=q/(mcm)q' = q/(m c_m) and RR be the number of rejections. Fix i∈I0i \in I_0 and partition [0,mq′][0, m q'] into intervals J1=[0,q′]J_1 = [0, q'] and Jk=((k−1)q′,kq′]J_k = ((k-1)q', k q'] for k=2,…,mk = 2, \dots, m. If HiH_i is rejected, pi≤Rq′p_i \le R q', so pip_i lies in interval JkiJ_{k_i} with ki≤Rk_i \le R, and 1/R≤1/ki1/R \le 1/k_i. Therefore

1[Hi se rechaza]max⁡(R,1)≤∑k=1m1k 1[pi∈Jk],\frac{\ind[H_i \text{ se rechaza}]}{\max(R, 1)} \le \sum_{k=1}^m \frac{1}{k}\,\ind\big[p_i \in J_k\big],

because on the right only term k=kik = k_i contributes, with value 1/ki≥1/R1/k_i \ge 1/R. With Fi(u)=P(pi≤u)≤uF_i(u) = \Pr(p_i \le u) \le u, the expectation on the right is rearranged by summation by parts (Abel):

∑k=1mFi(kq′)−Fi((k−1)q′)k=∑k=1m−1Fi(kq′)(1k−1k+1)+Fi(mq′)m≤∑k=1m−1kq′k(k+1)+q′=q′cm=qm,\sum_{k=1}^m \frac{F_i(kq') - F_i((k-1)q')}{k} = \sum_{k=1}^{m-1} F_i(kq')\Big(\frac1k - \frac1{k+1}\Big) + \frac{F_i(mq')}{m} \le \sum_{k=1}^{m-1} \frac{kq'}{k(k+1)} + q' = q' c_m = \frac{q}{m},

where in the first term take Fi(0):=0F_i(0) := 0 (interval J1J_1 includes 0) and the inequality uses positivity of coefficients 1/k−1/(k+1)1/k - 1/(k+1). Summing over i∈I0i \in I_0 gives FDR≤m0q/m\mathrm{FDR} \le m_0 q/m. Nothing about dependence was used: only each null’s marginal distribution. (Summation by parts matters: P(pi≤u)≤u\Pr(p_i \le u) \le u does not imply that each interval has probability ≤q′\le q', whereas the weighted sum is bounded.)

∎

The price is factor cm≈ln⁡m+0.577c_m \approx \ln m + 0.577: 5.25.2 for m=100m = 100, 7.57.5 for m=1000m = 1000 and 9.89.8 for m=104m = 10^4. It is a logarithmic but real penalty: in the figure BY rejects considerably less than BH. It protects against the worst case, which is almost never the real case.

Positive dependence (PRDS)

Benjamini and Yekutieli (2001) proved something more useful: BH still controls FDR by π0q\pi_0 q under a form of positive dependence, PRDS (positive regression dependence on a subset): informally, for each true null ii, the probability that an “increasing” set of other statistics lies in a “high” region rises with statistic ii. This holds for one-sided normal statistics with nonnegative correlations, tt statistics comparing against a common control, and other typical situations. For two-sided tests with arbitrary correlations there is no general guarantee, but experience (and the simulation below) suggests BH holds up well. Remember three nuances:

  • The mean remains, but variance does not. Under strong dependence, the FDP of a particular experiment is highly variable: with all nulls correlated, either none are rejected or many false ones are rejected together. The previous figure shows this at high ρ\rho: mean FDR ≤π0q\le \pi_0 q and much greater FDP standard deviation.
  • Adaptive procedures are more fragile. Those estimating π0\pi_0 and raising the level to compensate (next section) can lose control under strong dependence because the estimate of π0\pi_0 becomes highly variable. We will check this.
  • Dependence can be exploited instead of feared. Westfall–Young uses the joint permutation distribution: under the global null, permute labels, recalculate the maximum statistic (or minimum p-value), and reject what exceeds the 1−α1 - \alpha quantile of that maximum. This controls FWER (under the “subset pivotality” condition) while accounting for actual correlation among tests, ignored by Bonferroni and Holm. It is a permutation test applied to the maximum.

Reading thousands of p-values: null proportion, q-values and local FDR

When mm is large, the set of p-values itself is structured data worth studying: its histogram says how many nulls there are and which hypotheses are suspicious.

The mixture and estimating π₀

If each hypothesis is null with probability π0\pi_0 and alternative with 1−π01 - \pi_0, independently, p-values form a mixture with density

f(p)=π0⋅1+(1−π0) f1(p),p∈[0,1],f(p) = \pi_0 \cdot 1 + (1 - \pi_0)\,f_1(p), \qquad p \in [0, 1],

where nulls are uniform and f1f_1 is the alternative density, concentrated near 0 and decreasing. The consequence is visual: at the histogram’s right, where f1f_1 is almost zero, height is π0\pi_0. This allows π0\pi_0 to be estimated by counting large p-values.

Proof

Each pip_i is independently a uniform null with probability π0\pi_0 and an alternative with probability 1−π01 - \pi_0, so P(pi>λ)=π0(1−λ)+(1−π0)(1−F1(λ))\Pr(p_i > \lambda) = \pi_0(1 - \lambda) + (1 - \pi_0)(1 - F_1(\lambda)). Dividing its expectation, mP(pi>λ)m\Pr(p_i > \lambda), by m(1−λ)m(1 - \lambda) gives the formula, and the second term is nonnegative.

∎

Choosing λ\lambda balances bias and variance: small λ\lambda includes alternatives (upward bias), large λ\lambda counts few p-values (variance). Storey proposes fitting a smooth curve to π^0(λ)\hat\pi_0(\lambda) and extrapolating to λ→1\lambda \to 1, or choosing λ\lambda by resampling. Fixing λ=0.5\lambda = 0.5 is reasonable and simple; truncate the estimator at 1.

q-values

BH controls FDR at a prespecified level qq. Storey (2003) proposes the analogue of adjusted p-values, a per-hypothesis measure of significance on the FDR scale.

The estimator is thus the BH adjusted p-value multiplied by π^0\hat\pi_0. Rejecting hypotheses with q≤q0q \le q_0 is equivalent to applying BH at level q0/π^0q_0/\hat\pi_0 (adaptive BH): gain a factor 1/π^01/\hat\pi_0 in effective level, noticeable when signal is strong. “Min over t≥pt \ge p” makes the qq-value monotonic: a hypothesis with a larger p-value can never have a smaller qq-value.

Local FDR and Efron’s empirical Bayes view

The qq-value concerns the list; Efron (2010) wants to address each hypothesis. For a test statistic zz (or the p-value itself), local FDR is the posterior probability that a hypothesis with that value is null,

fdr(z)=P(H0∣Z=z)=π0 f0(z)f(z),\mathrm{fdr}(z) = \Pr(H_0 \given Z = z) = \frac{\pi_0\,f_0(z)}{f(z)},

where f0f_0 is the null density and f=π0f0+(1−π0)f1f = \pi_0 f_0 + (1 - \pi_0) f_1 the marginal, estimated directly from data, e.g. by smoothing the histogram. On the p-value scale, f0=1f_0 = 1 and fdr(p)=π0/f(p)\mathrm{fdr}(p) = \pi_0/f(p): the flat-section height divided by histogram height at pp. This is the reading “in each bar.” Its relationship to the list rate is simple and revealing.

Proof

By Bayes’s rule, P(H0∣P∈A)=∫Aπ0 ⁣dp/∫Af(p) ⁣dp\Pr(H_0 \given P \in A) = \int_A \pi_0 \dd p \big/ \int_A f(p) \dd p. And since π0=fdr(p) f(p)\pi_0 = \mathrm{fdr}(p)\,f(p), the numerator is ∫Afdr(p)f(p) ⁣dp\int_A \mathrm{fdr}(p) f(p) \dd p, and dividing by ∫Af\int_A f gives the expectation of fdr(P)\mathrm{fdr}(P) conditional on P∈AP \in A.

∎

The following figure shows this with a thousand p-values. Its second half is particularly revealing: the list value (magenta) is always below the local FDR of its last element (red). A list meeting “10% FDR” includes edge findings with a much higher probability of being false: the marginal finding is worse than the list average.

InteractiveHistogram of a thousand p-values
Histogram of m=1000m = 1000 p-values (200 alternatives)
π̂0·m/20 = 42.1bars estimating π0
  • alternatives
  • nulls
  • Storey estimate
  • true height π0m/20\pi_0 m/20
Probability of being null: for one bar (local FDR) and the list up to tt (tail FDR)
list: 29 %
  • local FDR fdr(p)\mathrm{fdr}(p)
  • tail FDR Fdr(t)\mathrm{Fdr}(t)
  • estimated by bar
0.80
50 %
0.50
p ≤ 0.05
Storey π^0(λ)\hat\pi_0(\lambda) | true π0\pi_00.842 | 0.80
Bar 0.00 to 0.05: observed | expected if all null130 | 42.1
Local FDR of the bar (estimated | theoretical)32 % | 29 %
List “p≤0.05p \le 0.05”: rejections130
List FDR (estimated | realized | theoretical)32 % | 27 % | 29 %
With only the first bar, the list and the bar coincide: 130 rejections and 29 % nulls among them. Move the threshold to the right: the list grows, but each bar added is worse than the last.
A thousand p-values, a mixture of uniform nulls (gray) and alternatives from a zz test with chosen power (blue). The yellow line is Storey's flat-section height (π^0⋅m/20\hat\pi_0 \cdot m/20, estimated using bars right of λ\lambda, shaded); the thin dotted line is the true value. Right: theoretical local FDR fdr(p)\mathrm{fdr}(p) (red), list tail FDR for p≤tp \le t (magenta), and bar-based local FDR estimate (circles). Click a bar or use the slider to choose threshold tt. With π0=0.8\pi_0 = 0.8 and 50% power, list p≤0.05p \le 0.05 has 29% false; choose the second bar: list p≤0.10p \le 0.10 has 39%, but its marginal bar 62%. Reduce power to 20% or raise π0\pi_0 to 0.950.95: what signal remains? Move λ\lambda from 0.10.1 to 0.90.9 and see when π^0\hat\pi_0 is biased and when noisy.

Two usage warnings:

  • The theoretical null may not be the real null. All the above assumes null p-values are uniform. With observational data, batch effects or correlations, the null statistic distribution can be wider or shifted, and the histogram no longer has a clean flat part. Efron proposes estimating the empirical null from the central part of the zz histogram; when the two differ substantially, conclusions change completely, diagnosing the experiment rather than the method.
  • Adaptive methods assume more. Estimating π0\pi_0 and local FDRs requires large mm (hundreds or thousands) and some independence: with few hypotheses or strong dependence, nonadaptive BH is safer.

Implementation from scratch and with libraries

The first cell implements all procedures using the same structure (ordered thresholds and a step-up or step-down pass) and measures FWER, FDR and power by simulation, independently and with correlation ρ=0.5\rho = 0.5. One hundred hypotheses, twenty with an effect of 3.53.5 standard errors, α=0.05\alpha = 0.05.

[ ]Bonferroni, Šidák, Holm, Hochberg, BH, BY and adaptive BH from scratchBrowser
import numpy as np
from scipy.stats import norm

def paso_arriba(P, umbrales):
    """Step-up por filas: rechaza los k menores, con k = max{k : p_(k) <= umbrales[k-1]}."""
    ordenados = np.sort(P, axis=1)
    cumple = ordenados <= umbrales
    return np.where(cumple.any(1), P.shape[1] - np.argmax(cumple[:, ::-1], axis=1), 0)

def paso_abajo(P, umbrales):
    """Step-down por filas: para en el primer p_(k) que supera su umbral."""
    ordenados = np.sort(P, axis=1)
    falla = ordenados > umbrales
    return np.where(falla.any(1), np.argmax(falla, axis=1), P.shape[1])

def procedimiento(P, metodo, alpha=0.05):
    """Devuelve la matriz booleana de rechazos (filas = réplicas) de cada método."""
    m = P.shape[1]
    k = np.arange(1, m + 1)
    cm = np.sum(1 / k)
    if metodo == "bonferroni":
        return P <= alpha / m
    if metodo == "sidak":
        return P <= 1 - (1 - alpha) ** (1 / m)
    if metodo == "holm":
        n_rech = paso_abajo(P, alpha / (m + 1 - k))
    elif metodo == "hochberg":
        n_rech = paso_arriba(P, alpha / (m + 1 - k))
    elif metodo == "bh":
        n_rech = paso_arriba(P, k * alpha / m)
    elif metodo == "by":
        n_rech = paso_arriba(P, k * alpha / (m * cm))
    elif metodo == "storey":                      # BH adaptativo a nivel alpha / pi0_hat (lambda = 0.5)
        pi0 = np.clip((P > 0.5).mean(1) / 0.5, 1 / m, 1.0)[:, None]
        n_rech = paso_arriba(P, k * alpha / (m * pi0))
    # el procedimiento rechaza los n_rech menores: se traduce a la matriz por rangos
    rangos = np.argsort(np.argsort(P, axis=1), axis=1)
    return rangos < n_rech[:, None]

def valores_p(rng, R, m, m1, mu, rho):
    """R réplicas de m tests z bilaterales, los m1 primeros con efecto mu; correlación rho (factor común)."""
    w = rng.standard_normal((R, 1))
    e = rng.standard_normal((R, m))
    z = np.sqrt(rho) * w + np.sqrt(1 - rho) * e
    z[:, :m1] += mu
    return 2 * norm.sf(np.abs(z))

rng = np.random.default_rng(18)
R, m, m1, mu, alpha = 2000, 100, 20, 3.5, 0.05
for rho in (0.0, 0.5):
    P = valores_p(rng, R, m, m1, mu, rho)
    print(f"\nm = {m}, m1 = {m1}, efecto = {mu} errores estándar, correlación {rho}")
    print(f"{'método':11s} {'FWER':>6s} {'FDR':>6s} {'potencia':>9s}")
    for met in ("bonferroni", "sidak", "holm", "hochberg", "bh", "by", "storey"):
        rech = procedimiento(P, met, alpha)
        V = rech[:, m1:].sum(1)                  # falsos positivos
        S = rech[:, :m1].sum(1)                  # verdaderos positivos
        fdp = V / np.maximum(V + S, 1)
        print(f"{met:11s} {np.mean(V >= 1):6.3f} {fdp.mean():6.3f} {S.mean() / m1:9.3f}")

# un cribado grande, una sola realización: 20 000 hipótesis, 2 000 con efecto de 3.5 errores estándar
m, m1 = 20000, 2000
P = valores_p(np.random.default_rng(0), 1, m, m1, 3.5, 0.0)
print(f"\nm = {m}, m1 = {m1}, efecto 3.5 errores estándar: rechazos, falsos y potencia")
for met in ("bonferroni", "bh"):
    rech = procedimiento(P, met, alpha)[0]
    V = rech[m1:].sum(); S = rech[:m1].sum()
    print(f"  {met:10s} {V + S:5d} rechazos, {V:2d} falsos, potencia {S / m1:.3f}")

Reading the table under independence:

  • FWER methods succeed, with values below 0.050.05: Bonferroni 0.0410.041, Šidák 0.0420.042, Holm and Hochberg 0.0470.047, the largest power gains (from 0.5070.507 to 0.5190.519). Holm costs nothing over Bonferroni.
  • BH has FDR 0.0410.041, close to π0α=0.8×0.05=0.04\pi_0\alpha = 0.8 \times 0.05 = 0.04, as the theorem’s equality says, with power 0.810.81 versus Holm’s 0.520.52. Its FWER is 0.510.51: it neither controls nor claims to control probability of any false positive.
  • BY pays for the worst case: FDR 0.0090.009 (far below level) and power 0.600.60, between Holm and BH.
  • Adaptive BH (Storey) brings FDR to 0.0520.052, near level, gaining a little more power (0.830.83).

And with ρ=0.5\rho = 0.5:

  • FWER methods and BY become even more conservative (Bonferroni FWER 0.0210.021): positive dependence makes their correction excessive, as in the first figure.
  • BH still controls: FDR 0.0380.038.
  • Adaptive BH no longer does: FDR 0.0860.086, clearly above its target of 0.050.05, because with a common factor the fraction of p-values above 0.50.5 varies enormously across experiments and the π0\pi_0 estimate sometimes fails. This measures the preceding section’s warning.

The last block, one realization with twenty thousand hypotheses and ten percent with an effect, illustrates why FDR exists: Bonferroni finds 223 of the 2000 with effects (11 %11\,\% power) and BH finds 1501, of which 70 are false (4.7 %4.7\,\% FDP and 72 %72\,\% power).

The second cell calculates adjusted p-values (rather than decisions at a fixed level), compares them with statsmodels.stats.multitest.multipletests and calculates Storey qq-values for a thousand hypotheses.

[ ]Adjusted p-values, q-values and comparison with statsmodelsBrowser
import numpy as np
from scipy.stats import norm
from statsmodels.stats.multitest import multipletests

def ajustados(p, metodo):
    """Valores p ajustados: el menor nivel al que el procedimiento rechaza cada hipótesis."""
    m = len(p)
    o = np.argsort(p)
    ps = p[o]
    k = np.arange(1, m + 1)
    if metodo == "bonferroni":
        a = ps * m
    elif metodo == "holm":
        a = np.maximum.accumulate((m + 1 - k) * ps)           # máximo acumulado de menor a mayor
    elif metodo == "hochberg":
        a = np.minimum.accumulate(((m + 1 - k) * ps)[::-1])[::-1]
    elif metodo in ("bh", "by"):
        a = ps * m / k
        if metodo == "by":
            a = a * np.sum(1 / k)
        a = np.minimum.accumulate(a[::-1])[::-1]              # mínimo acumulado de mayor a menor
    salida = np.empty(m)
    salida[o] = np.minimum(a, 1.0)
    return salida

def pi0_storey(p, lam=0.5):
    return min(1.0, np.mean(p > lam) / (1 - lam))

def valores_q(p, lam=0.5):
    return pi0_storey(p, lam) * ajustados(p, "bh")

rng = np.random.default_rng(5)
m, m1 = 1000, 100
z = rng.standard_normal(m)
z[:m1] += rng.choice([2.5, 3.0, 3.5, 4.0], m1)
p = 2 * norm.sf(np.abs(z))

nombres = {"bonferroni": "bonferroni", "holm": "holm", "hochberg": "simes-hochberg", "bh": "fdr_bh", "by": "fdr_by"}
print("diferencia máxima con statsmodels (valores p ajustados):")
for propio, sm in nombres.items():
    ref = multipletests(p, alpha=0.05, method=sm)[1]
    print(f"  {propio:11s} {np.max(np.abs(ajustados(p, propio) - ref)):.2e}")

print(f"\nmil hipótesis, 100 con efecto; pi0 verdadero = 0.9, pi0 de Storey = {pi0_storey(p):.3f}")
verdad = np.arange(m) < m1
print(f"{'método':11s} {'rechazos':>8s} {'falsos':>7s} {'FDP':>6s}   (todos a nivel 0.1)")
for nombre, aj in [(n, ajustados(p, n)) for n in ("bonferroni", "holm", "bh", "by")] + [("q-valor", valores_q(p))]:
    rech = aj <= 0.1
    V = int(np.sum(rech & ~verdad))
    print(f"{nombre:11s} {rech.sum():8d} {V:7d} {V / max(rech.sum(), 1):6.3f}")

The implementation agrees with statsmodels to rounding error (10−1610^{-16}). With a thousand hypotheses: Storey’s π^0\hat\pi_0 is 0.8920.892 (true π0\pi_0, 0.90.9); Bonferroni and Holm reject 21 hypotheses, none false; BH rejects 71, of which 9 are false (FDP 0.1270.127, above 0.10.1 in this realization: FDR is an average, not a guarantee per experiment); Storey’s qq-value rejects 73 (10 false). BY rejects 38 with none false. In statsmodels, multipletests(p, method=...) also accepts 'sidak', 'holm-sidak', 'fdr_tsbh' and 'fdr_tsbky' (two-stage adaptive versions); Storey’s qq-values are not in statsmodels (they are in R/Bioconductor’s qvalue package).

Application: screening hundreds of A/B-test metrics

A product experiment measures 300 metrics. Thirty have a small real effect (between 0.050.05 and 0.150.15 standard deviations), with 2000 users per arm. Compare discoveries uncorrected, with Bonferroni and with BH, and examine in an independent replication how many become significant again with the same sign.

[ ]300 metrics: uncorrected, Bonferroni and BH, and what replicatesBrowser
import numpy as np
from scipy.stats import norm

def bh_ajustados(p):
    m = len(p)
    o = np.argsort(p)
    a = np.minimum.accumulate((p[o] * m / np.arange(1, m + 1))[::-1])[::-1]
    out = np.empty(m)
    out[o] = np.minimum(a, 1)
    return out

rng = np.random.default_rng(2024)
M, M1, n = 300, 30, 2000                       # métricas, con efecto real, usuarios por brazo
d = np.zeros(M)
d[:M1] = rng.uniform(0.05, 0.15, M1)            # efectos reales de 0.05 a 0.15 desviaciones típicas
lam = d * np.sqrt(n / 2)                       # no centralidad de cada métrica

def experimento():
    z = lam + rng.standard_normal(M)
    return z, 2 * norm.sf(np.abs(z))

z1, p1 = experimento()                          # experimento original
z2, p2 = experimento()                          # réplica independiente
real = d > 0
print(f"{'criterio':22s} {'descubr.':>8s} {'falsos':>7s} {'replican':>9s}")
for nombre, rech in [("p < 0.05 sin corregir", p1 < 0.05),
                     ("Bonferroni (0.05)", p1 < 0.05 / M),
                     ("BH con q = 0.10", bh_ajustados(p1) <= 0.10)]:
    rep = rech & (p2 < 0.05) & (np.sign(z1) == np.sign(z2))
    print(f"{nombre:22s} {rech.sum():8d} {np.sum(rech & ~real):7d} {rep.sum():5d} de {rech.sum()}")
print(f"\nmétricas con efecto real: {M1}")

Without correction, 38 “improvements”: 15 false and only 19 reproduced in replication. Bonferroni leaves 8, none false, with 6 replicating. BH at 10 %10\,\% leaves 20 discoveries, 3 false, with 13 replicating. Two nuances prevent overreading. First, failure to replicate does not mean false: a real effect of 0.050.05 standard deviations with 2000 users has modest replication power, and some true discoveries fail by chance; replication estimates a real effect, it does not certify truth. Second, BH found over twice as many as Bonferroni at the price of 3 false positives: choosing between them is a decision about the cost of a false candidate, not “rigor.”

Invisible multiplicity: the garden of forking paths

Everything above assumes the number of comparisons is known. The greatest practical multiplicity problem is the one that goes uncounted.

Researcher degrees of freedom

Real data analysis is not one test but a chain of decisions. Exclude outliers and by what rule? Which outcome metric? Adjust for covariates and which? Analyze the full sample or a subgroup? Transform variables? Collect more data or stop? Each decision looks reasonable alone, and each opens a fork.

The last point is the subtlest and most important. There is one honestly performed analysis, without any “fishing.” But the researcher saw a plot, noticed an outlier and decided to exclude it; saw the effect seemed concentrated in women and focused on them. With different data they would have seen different plots and made different decisions. The actual procedure is “inspect data and choose the analysis that seems reasonable,” and its false-positive rate is not 0.050.05. Multiplicity is potential, not executed: there are no visible mm tests to correct.

The following figure simulates this using purely random data: treatment is randomly assigned and there is no effect anywhere. The analyst makes four decisions: which of four metrics (Y1,Y2,Y3Y_1, Y_2, Y_3 and their mean), which outlier exclusion rule (none, or ∣z∣>3\abs z > 3, 2.52.5 or 22), which subgroup (all, women, men, younger, older), and which covariates (none, one, the other, or both). There are 4×4×5×4=3204 \times 4 \times 5 \times 4 = 320 paths.

InteractiveThe garden of forking paths
Metric
Y₁Y₂Y₃mean(Y₁, Y₂, Y₃)
Outliers
exclude noneexclude |z| > 3exclude |z| > 2.5exclude |z| > 2
Subgroup
allwomen onlymen onlyyoungestoldest
Covariates
no covariates+ C₁+ C₂+ C₁ and C₂
Ordered p-values of the 54 paths explored (red points: p<0.05p < 0.05)
p = 0.05best: 0.014
  • p<0.05p < 0.05
  • p≥0.05p \ge 0.05
  • ordered uniform p-values (reference)
Actual false positive rate in 250 pure-noise studies (marker: 5%)
One path, fixed before seeing the data
calculating…
Your procedure: best of 54 paths
calculating…
Same, Bonferroni corrected (× 54)
calculating…
Best of all 320 paths
calculating…
The 54 paths are not 54 independent tests: they share data, so the actual rate (…) is below 1−0.95541 - 0.95^{54} = 94 %. Bonferroni, which assumes the worst case, stays below 5%: ….
3
3
3
2
Paths explored54 of 320
Best p-value in this study0.014
Paths with p<0.05p < 0.05 in this study8 of 54
Actual false positives of your procedurecalculating…
“Finding”: p = 0.014 for Y₂ · exclude none · men only · no covariates. But treatment was randomly assigned and has no effect anywhere: 8 of the 54 paths you examined are significant by chance.
Pure noise data: 60 people, randomized treatment, nothing to find. Each slider opens an analysis choice (top labels show options you are willing to inspect). Left: ordered p-values of paths explored in this study; right: the REAL false-positive rate of the procedure 'if any path gives p<0.05p < 0.05, there is a discovery,' measured using 250 new pure-noise studies (each rate has about 2 or 3 percentage points of Monte Carlo error with 250 studies). With everything at 1 (one path), it is 5%. Open only subgroups (5 paths): it rises to 16%. Open only metrics (4): 13%. Open everything: nearly two thirds. Note covariates, which barely change the hypothesis, add little, while metrics and subgroups, which change data used, add much. The third bar is Bonferroni with KK paths: it protects with a large margin because paths are not independent.

Four readings:

  • Rates rise rapidly and a few decisions do most of the damage. With five subgroups or four metrics, probability of “discovering” something is already 13–17%. Full flexibility gets close to two thirds. In one sentence: a few reasonable decisions suffice to find a result almost always.
  • Paths are not independent tests. How many paths “count” depends on how much they change the data used. Changing covariates or the outlier rule moves p-values little; changing metric or subgroup moves them much. Hence the actual rate is far below 1−0.95K1 - 0.95^{K}, and the effective number of tests, as in the first figure, is hard to know.
  • Bonferroni on the number of paths is a valid but extreme bound. For K=320K = 320, its actual rate is practically zero.
  • Bad faith is unnecessary. Simmons, Nelson and Simonsohn (2011) showed by simulation that combining four common flexibilities (choose between two dependent variables, add a covariate, enlarge the sample if nothing appears, and remove a condition) pushes the false-positive rate above 60 %60\,\%, with pure-noise data and decisions that each appear defensible alone.

Optional stopping

A very common special case is looking at data as they are collected and stopping when p<0.05p < 0.05. Each look is a test, and successive statistics are highly correlated (they share data). The law of the iterated logarithm implies that if we look indefinitely, the probability of eventually rejecting a true null is 1. The cell measures what happens with finitely many looks, and also shows the other major source of multiplicity in machine learning: choosing the best of KK variants with the same test set.

[ ]Optional stopping and best of K variants with a single test setBrowser
import numpy as np
from scipy.stats import norm

rng = np.random.default_rng(7)

# 1) Parada opcional: mirar los datos cada 10 observaciones y parar al primer p < 0.05
R, nmax, paso = 10000, 200, 10
x = rng.standard_normal((R, nmax))                         # datos bajo H0: N(0, 1)
n = np.arange(paso, nmax + 1, paso)
z = np.cumsum(x, axis=1)[:, paso - 1::paso] / np.sqrt(n)    # estadístico z tras cada bloque
print("miradas   tasa de falsos positivos (nivel nominal 0.05)")
for miradas in (1, 2, 5, 10, 20):
    sig = np.any(np.abs(z[:, :miradas]) > norm.ppf(0.975), axis=1)
    print(f"{miradas:6d}    {sig.mean():.3f}")

# 2) Elegir la mejor de K variantes con el mismo conjunto de test (todas con exactitud real 0.80)
acc, ntest, R2 = 0.80, 1000, 4000
print("\nK variantes   exactitud del ganador en test   en un test nuevo")
for K in (1, 5, 20, 100):
    a = rng.binomial(ntest, acc, (R2, K)) / ntest
    nuevo = rng.binomial(ntest, acc, R2) / ntest              # el ganador reevaluado en datos frescos
    print(f"{K:8d}      {a.max(1).mean():.4f}                          {nuevo.mean():.4f}")

With one look, 0.0490.049; two, 0.0820.082; five, 0.1400.140; twenty, nearly a quarter (0.2460.246). Sequential theory permits looking as often as desired with an appropriate procedure (varying thresholds, Wald sequential tests or e-values); that is the subject of the sequential experiments lesson.

The second part is the machine-learning equivalent: KK model variants, all with the same true accuracy of 0.800.80, a 1000-example test set, and the best accuracy on that test is published. Best of 5 scores 0.8150.815; best of 20, 0.8230.823; best of 100, 0.8310.831 (with accuracy standard error only 0.01260.0126 per variant). This overestimates by 1.51.5, 2.32.3 and 3.13.1 points, and on a new set the winner returns to 0.8000.800: the familiar winner’s curse, this time caused not by a significance filter but explicit selection. Overestimation is the maximum of KK approximately normal variables and grows slowly with KK according to order statistics: E[max⁡kZk]≤2ln⁡K\E[\max_k Z_k] \le \sqrt{2 \ln K}, with exact value 1.871.87 for K=20K = 20. Multiplying by standard error 0.01260.0126 gives 2.42.4 points, as observed. Choosing hyperparameters on the test set, or reusing a public benchmark for years, is hidden multiplicity with growing, uncounted KK. (The same problem, in different language, appears for the Sharpe ratio of a strategy selected among many in quantitative finance.)

HARKing and the replication crisis

A fourth source of multiplicity is changing the hypothesis after seeing results (HARKing, hypothesizing after the results are known): exploration presented as confirmatory testing. A single unadjusted test chosen because it succeeded is not confirmation. Across a discipline, combining unlikely prior hypotheses (the high π0\pi_0 above), underpowered studies, analytical flexibility and selection of publishable results produces the replication crisis: in the Open Science Collaboration’s reproducibility project (2015), only around a third of replications of 100 psychology studies obtained significant results (versus a large majority of originals), and average effect sizes were half as large. Each link in that chain is studied in this lesson.

Remedies

No statistical procedure repairs an analytical choice made while looking at data; designs can prevent or account for it.

  • Preregistration. Publish before seeing data the hypotheses, metrics, exclusion rules, model and sample size to be used. This turns a garden into a path. Work outside the plan remains valid but is presented as exploratory, with its multiplicity declared (and corrected if drawing a conclusion).
  • Held-out data. Split the sample: one part for free exploration (choosing model, subgroup, threshold), the other untouched for one confirmatory test of the chosen path. A model’s test set is exactly this, and ceases to be when examined more than once. It is the simplest, most robust solution; its cost is power.
  • Multiverse analysis. Instead of choosing one path, run all reasonable ones and show the distribution of effects and p-values (Steegen et al., 2016). A result depending on one combination of choices and disappearing under nearly all others is fragile. It is not a test, but it makes hidden multiplicity visible.
  • Correct for selection. If exploring, correct: either Bonferroni or BH over everything explored (when enumerable), or apply Westfall–Young to the full procedure: repeat the entire selection process (all paths) on data with permuted labels and compare the best observed p-value against the distribution of the best permuted p-value. This remains valid with highly dependent paths (it accounts for how many “count”). Valid inference after arbitrary selection has its own theory, in post-selection inference.
  • Report everything. Number of metrics measured, models tried and looks taken; null results; intervals and not just p-values. Without the denominator, a discovery is incomprehensible.

Common mistakes

Exercises

NumericTwenty independent tests without effects
Twenty independent tests are performed, each with α=0.05\alpha = 0.05, and all null hypotheses are true. What is the probability of at least one significant result?
NumericHow many hypotheses does BH reject?
Ten ordered p-values: 0.001, 0.008, 0.018, 0.027, 0.030, 0.033, 0.036, 0.039, 0.046, 0.740.001,\ 0.008,\ 0.018,\ 0.027,\ 0.030,\ 0.033,\ 0.036,\ 0.039,\ 0.046,\ 0.74. With Benjamini–Hochberg at level q=0.05q = 0.05, how many hypotheses are rejected?
NumericStorey's estimator of π₀
Of m=2000m = 2000 p-values, 700 exceed λ=0.5\lambda = 0.5. What is Storey's estimator π^0(0.5)\hat\pi_0(0.5)?
ProofHolm strongly controls FWER
Prove: Under any p-value dependence, Holm's procedure satisfies FWER≤α\mathrm{FWER} \le \alpha for every configuration of true nulls.
0
Let I0I_0 be the set of true nulls, with m0=∣I0∣≥1m_0 = \abs{I_0} \ge 1, and assume P(pi≤u)≤u\Pr(p_i \le u) \le u for i∈I0i \in I_0. Holm rejects H(1),…,H(k−1)H_{(1)}, \dots, H_{(k-1)}, where kk is the first index with p(k)>α/(m+1−k)p_{(k)} > \alpha/(m + 1 - k).

Step 1 of 4. What event must be bounded?

ProofBH controls FDR under independence
Prove: If true-null p-values are independent of each other and the others, and uniform on [0,1][0, 1], BH at level qq satisfies FDR=π0q\mathrm{FDR} = \pi_0 q.
0
Let RR be the number of BH rejections, which rejects HiH_i if and only if pi≤Rq/mp_i \le Rq/m. For i∈I0i \in I_0, let RiR_i be BH's rejection count when pip_i is replaced by 0.

Step 1 of 4. How is FDR reduced to a sum over true nulls?

CodeVectorized BH with adjusted p-values
Complete bh_ajustados(p): return Benjamini–Hochberg adjusted p-values p~(i)=min⁡j≥imin⁡{1,m p(j)/j}\tilde p_{(i)} = \min_{j \ge i}\min\{1, m\,p_{(j)}/j\} in the original order of p, at cost O(mlog⁡m)O(m \log m) and without Python loops over hypotheses. It must work with repeated p-values (ties receive the same adjustment) and leave the input unchanged. Structural hint: sort, multiply by mm/rank, enforce monotonicity with a cumulative minimum from the end, and cap at 1.
import numpy as np

def bh_ajustados(p):
  """Valores p ajustados de Benjamini-Hochberg, en el orden original de p."""
  p = np.asarray(p, dtype=float)
  m = len(p)
  # tu código: ordenar, escalar por m / rango, mínimo acumulado desde el final, limitar a 1, deshacer el orden
  return p.copy()
Shift+Enter to run
QuizFWER or FDR?
Which error rate is more appropriate in each situation? (a) A clinical trial with three efficacy criteria: the drug will be approved if any is demonstrated. (b) Screen 20,000 genes to pick the 100 most promising for lab validation. (c) Try 30 hyperparameter configurations and claim with assurance that the best beats baseline. (d) Explore 50 secondary A/B-test metrics to decide what hypotheses to study next.
QuizInterpreting a BH list
BH is applied to 1000 p-values at q=0.1q = 0.1 and rejects 80 hypotheses. Assume independence. Which statements are correct?

More than one answer may be correct.

QuizOne analysis, no multiplicity?
A team performs one trial analysis and obtains p=0.03p = 0.03. It previously chose to exclude three participants after seeing a box plot and focus on those under 40 because the effect seemed visible there. It tried no other analysis. Which statement is correct?

Summary

Key idea
With mm tests, individual error α\alpha no longer describes family error: the probability of any false positive is 1−(1−α)m1 - (1 - \alpha)^m. It is controlled by FWER (Bonferroni, Holm, Tukey: strict and costly) or FDR (Benjamini–Hochberg: mean false fraction, with much greater power when screening thousands of hypotheses); the most dangerous multiplicity is uncounted: analysis choices made while looking at data.
  • Multiplicity. With mm independent tests and all nulls true, P(V≥1)=1−(1−α)m\Pr(V \ge 1) = 1 - (1 - \alpha)^m; with dependence, only ≤mα\le m\alpha. With α=0.05\alpha = 0.05 and m=20m = 20 it is 64 %64\,\%. The family includes everything examined to draw a conclusion.
  • FWER. Bonferroni (α/m\alpha/m) and Holm (stepwise thresholds α/(m+1−k)\alpha/(m + 1 - k)) strongly control P(V≥1)≤α\Pr(V \ge 1) \le \alpha for any dependence; Holm dominates Bonferroni at no cost. Šidák requires independence (or favorable dependence), Tukey uses the exact studentized-range distribution for pairwise comparisons, and all are instances of closure.
  • FDR. E[V/max⁡(R,1)]≤FWER\E[V/\max(R, 1)] \le \mathrm{FWER}, with equality under the global null. It is natural for large screens: with 20,000 hypotheses and 10% effects, Bonferroni finds 11 %11\,\% of them and BH 72 %72\,\%.
  • Benjamini–Hochberg. Step-up: k∗=max⁡{k:p(k)≤kq/m}k^\ast = \max\{k : p_{(k)} \le kq/m\}. Under independence, FDR=π0q\mathrm{FDR} = \pi_0 q exactly (the proof uses RiR_i, rejections after setting pip_i to 0). Under arbitrary dependence divide the level by cm≈ln⁡m+0.58c_m \approx \ln m + 0.58 (Benjamini–Yekutieli); under positive dependence (PRDS) BH works, although each experiment’s FDP is much more variable.
  • π₀, q-values and local FDR. π^0(λ)=#{pi>λ}/(m(1−λ))\hat\pi_0(\lambda) = \#\{p_i > \lambda\}/(m(1 - \lambda)) is conservative; q^=π^0p~BH\hat q = \hat\pi_0 \tilde p^{\mathrm{BH}}; local FDR π0/f(p)\pi_0/f(p) is the probability one finding is null, and list FDR is its mean: the marginal finding is worse than average. Adaptive procedures can lose control under dependence.
  • Hidden multiplicity. The garden of forking paths: four reasonable decisions produce 320 paths and, with noise data, nearly two thirds false positives. Optional stopping (20 looks: 24.6 %24.6\,\%) and choosing the best variant on the same test set (best of 20: +2.3+2.3 accuracy points) are the same phenomenon.
  • Remedies. Preregistration, untouched held-out data, multiverse analysis, correction for the complete procedure (Westfall–Young, permuting the entire selection process), and reporting the denominator: how many metrics, models and looks.