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, . Suppose none works: all null hypotheses are true. Each individual test is impeccable: its probability of mistaken rejection is exactly . 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.
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 . If the team picks the best variant and presents it as an individual test (, “significant”), the procedure followed has level , not . The last line anticipates the simplest remedy: requiring returns the error rate to .
This lesson studies how that inflation is measured, controlled and avoided. It has three acts:
- 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.
- Reading thousands of p-values. Dependence, estimation of the null proportion, -values and local FDR.
- 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 . When 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, and there is nothing more to say. With hypotheses, the first result is already unsettling.
The formula follows because “no rejection” is the intersection of independent events of probability ; the bound is Boole’s inequality: . With : gives ; , ; , . And the expected number of false positives is 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.
Two readings of the figure that we will revisit:
- Under independence, Bonferroni is almost exact. Its actual FWER is , just below ( for and any ).
- Under positive dependence it is conservative and overcorrects. Tests “count” less than independent tests. An effective size (the 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 with an “is there anything anywhere?” test and then reporting the hypothesis with minimum as a specific discovery uses weak control as if it were strong.)
Bonferroni
Proof
True-null p-values satisfy . A false positive rejects some , so by the union bound
No independence or distribution of with 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 . To detect an effect of standard errors with 80% power for requires , versus for one test: an effect almost twice as large. Second, the actual bound is , not : if a large fraction of nulls is false, effective FWER is well below and that margin is wasted (some can be recovered by estimating , as we will see).
The Bonferroni adjustment to adjusted p-values is : rejection at level is equivalent to . Adjusted p-values are useful because may be chosen afterward: “the smallest family level at which is rejected.”
Šidák
With independent tests, when each uses level , and setting that probability to gives the Šidák threshold, , slightly less strict than (for and : versus ). 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 possible true nulls, not , so threshold can be relaxed. Holm (1979) uses this observation step by step.
Thresholds are : 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 be the set of true nulls, with (if no false positives are possible). Let be the position, in the global ordering of the p-values, of the smallest with . Only false hypotheses can precede it, of which there are , so , i.e.
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 :
Since , we have proved the event inclusion
whose probability by the union bound is at most . This holds for every 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 ” 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 with and reject all preceding hypotheses; it is more powerful, but unlike Holm its control requires independence (or positive dependence, of MTP 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 , let be the hypothesis “all , , are true,” and let be a level- test of .
Proof
Let be the set of true nulls; then is true and . If some with is rejected, then by definition was rejected for every , in particular for . Thus .
∎Holm is closure with local Bonferroni tests, . To see they coincide, fix . Every has at least one with , and among sets whose smallest rank is , the hardest to reject is the largest, , of size . Rejecting every is thus equivalent to for every : 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 .
Tukey comparisons after ANOVA
The classic structured family has groups with one mean each and pairwise comparisons. With observations per group, common variance and degrees of freedom, the standardized maximum mean difference has the studentized range distribution when all means coincide. Rejecting pair when
is Tukey’s HSD test, and intervals cover all true differences simultaneously with exact probability in the balanced design. Since a false rejection requires some interval to miss, FWER is 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.
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 threshold is ; Bonferroni raises it to ; Tukey to . In the experiment, group E (shifted ) 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 , Bonferroni requires , i.e. . A gene with an effect of standard errors, a strong signal, has 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 , (if the ratio is at most 1, and if it is 0). Taking expectations, . If , every rejection is false, , and , 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 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 . Suppose a field tests hypotheses with fraction true nulls, at level and power against alternatives. What proportion of significant results are true?
With : if and power is 80%, positive predictive value is ; with 50% power, ; with 20%, . If the hypothesis is implausible, , even at 80% power it is only : 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 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.
| Situation | Rate | Why |
|---|---|---|
| Confirm a drug with several efficacy criteria; one failure approves a defective product | FWER (strong control) | Small family and irreversible decision; any false positive is costly. |
| Screen 20,000 genes to select those for validation | FDR | Candidate list followed by validation; the false fraction is what costs. |
| Explore 50 secondary A/B-test metrics to generate hypotheses | FDR | Exploratory; false results will be discarded in the next experiment. |
| Choose the best of 30 configurations and claim it beats baseline | FWER (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 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 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 and rejects everything to the left of the last point below it.
Proof
Let be the number of rejections and . Since is equivalent to , we have , and is rejected if and only if . Thus
Fix and let be the number of BH rejections when is replaced by 0; with we have . Since , ; and , because .
Lemma: , and on that event . Indeed, if , then at we have , so and, with , and is rejected. Conversely, if is rejected, .
By the lemma, and since ,
Now is a function only of and by independence is independent of . Conditioning on (with ), , with equality if is uniform. Thus the expectation is at most . Summing over gives .
∎The result has two useful readings. First, FDR is exactly , not : BH is conservative to the extent there is signal (), and equals only when all nulls are true. (This is why the figure’s mean FDP is and why estimating can improve it.) Second, when all are true (), BH is an exact level- test of the global null, the Simes test (1986): reject if any .
Regarding Holm: BH thresholds are at least Holm thresholds , because for . 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 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: does not depend on . 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 and be the number of rejections. Fix and partition into intervals and for . If is rejected, , so lies in interval with , and . Therefore
because on the right only term contributes, with value . With , the expectation on the right is rearranged by summation by parts (Abel):
where in the first term take (interval includes 0) and the inequality uses positivity of coefficients . Summing over gives . Nothing about dependence was used: only each null’s marginal distribution. (Summation by parts matters: does not imply that each interval has probability , whereas the weighted sum is bounded.)
∎The price is factor : for , for and for . 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 under a form of positive dependence, PRDS (positive regression dependence on a subset): informally, for each true null , the probability that an “increasing” set of other statistics lies in a “high” region rises with statistic . This holds for one-sided normal statistics with nonnegative correlations, 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 : mean FDR and much greater FDP standard deviation.
- Adaptive procedures are more fragile. Those estimating and raising the level to compensate (next section) can lose control under strong dependence because the estimate of 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 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 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 and alternative with , independently, p-values form a mixture with density
where nulls are uniform and is the alternative density, concentrated near 0 and decreasing. The consequence is visual: at the histogram’s right, where is almost zero, height is . This allows to be estimated by counting large p-values.
Proof
Each is independently a uniform null with probability and an alternative with probability , so . Dividing its expectation, , by gives the formula, and the second term is nonnegative.
∎Choosing balances bias and variance: small includes alternatives (upward bias), large counts few p-values (variance). Storey proposes fitting a smooth curve to and extrapolating to , or choosing by resampling. Fixing is reasonable and simple; truncate the estimator at 1.
q-values
BH controls FDR at a prespecified level . 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 . Rejecting hypotheses with is equivalent to applying BH at level (adaptive BH): gain a factor in effective level, noticeable when signal is strong. “Min over ” makes the -value monotonic: a hypothesis with a larger p-value can never have a smaller -value.
Local FDR and Efron’s empirical Bayes view
The -value concerns the list; Efron (2010) wants to address each hypothesis. For a test statistic (or the p-value itself), local FDR is the posterior probability that a hypothesis with that value is null,
where is the null density and the marginal, estimated directly from data, e.g. by smoothing the histogram. On the p-value scale, and : the flat-section height divided by histogram height at . This is the reading “in each bar.” Its relationship to the list rate is simple and revealing.
Proof
By Bayes’s rule, . And since , the numerator is , and dividing by gives the expectation of conditional on .
∎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.
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 histogram; when the two differ substantially, conclusions change completely, diagnosing the experiment rather than the method.
- Adaptive methods assume more. Estimating and local FDRs requires large (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 . One hundred hypotheses, twenty with an effect of standard errors, .
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 : Bonferroni , Šidák , Holm and Hochberg , the largest power gains (from to ). Holm costs nothing over Bonferroni.
- BH has FDR , close to , as the theorem’s equality says, with power versus Holm’s . Its FWER is : it neither controls nor claims to control probability of any false positive.
- BY pays for the worst case: FDR (far below level) and power , between Holm and BH.
- Adaptive BH (Storey) brings FDR to , near level, gaining a little more power ().
And with :
- FWER methods and BY become even more conservative (Bonferroni FWER ): positive dependence makes their correction excessive, as in the first figure.
- BH still controls: FDR .
- Adaptive BH no longer does: FDR , clearly above its target of , because with a common factor the fraction of p-values above varies enormously across experiments and the 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 ( power) and BH finds 1501, of which 70 are false ( FDP and 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 -values for a thousand hypotheses.
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 (). With a thousand hypotheses: Storey’s is (true , ); Bonferroni and Holm reject 21 hypotheses, none false; BH rejects 71, of which 9 are false (FDP , above in this realization: FDR is an average, not a guarantee per experiment); Storey’s -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 -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 and 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.
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 leaves 20 discoveries, 3 false, with 13 replicating. Two nuances prevent overreading. First, failure to replicate does not mean false: a real effect of 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 . Multiplicity is potential, not executed: there are no visible 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 ( and their mean), which outlier exclusion rule (none, or , or ), which subgroup (all, women, men, younger, older), and which covariates (none, one, the other, or both). There are paths.
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 , 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 , 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 , 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 . 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 variants with the same test set.
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, ; two, ; five, ; twenty, nearly a quarter (). 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: model variants, all with the same true accuracy of , a 1000-example test set, and the best accuracy on that test is published. Best of 5 scores ; best of 20, ; best of 100, (with accuracy standard error only per variant). This overestimates by , and points, and on a new set the winner returns to : the familiar winner’s curse, this time caused not by a significance filter but explicit selection. Overestimation is the maximum of approximately normal variables and grows slowly with according to order statistics: , with exact value for . Multiplying by standard error gives points, as observed. Choosing hyperparameters on the test set, or reusing a public benchmark for years, is hidden multiplicity with growing, uncounted . (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 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
Step 1 of 4. What event must be bounded?
Step 1 of 4. How is FDR reduced to a sum over true nulls?
bh_ajustados(p): return Benjamini–Hochberg adjusted p-values in the original order of p, at cost 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 /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()More than one answer may be correct.
Summary
- Multiplicity. With independent tests and all nulls true, ; with dependence, only . With and it is . The family includes everything examined to draw a conclusion.
- FWER. Bonferroni () and Holm (stepwise thresholds ) strongly control 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. , with equality under the global null. It is natural for large screens: with 20,000 hypotheses and 10% effects, Bonferroni finds of them and BH .
- Benjamini–Hochberg. Step-up: . Under independence, exactly (the proof uses , rejections after setting to 0). Under arbitrary dependence divide the level by (Benjamini–Yekutieli); under positive dependence (PRDS) BH works, although each experiment’s FDP is much more variable.
- π₀, q-values and local FDR. is conservative; ; local FDR 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: ) and choosing the best variant on the same test set (best of 20: 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.