Permutation and randomization tests
Build exact and Monte Carlo permutation tests, connect Fisher’s exact test to randomization inference, invert tests for intervals and identify failures of exchangeability.
After this lesson you can
- Explain exchangeability and prove finite-sample permutation-test validity.
- Compute corrected Monte Carlo p-values and quantify simulation uncertainty.
- Derive Fisher’s exact test and match permutation groups to randomized designs.
- Invert a permutation test and recognize unequal-variance and dependence failures.
Before you start
Motivation: a lady, eight cups and no formula
In the 1920s at Rothamsted agricultural station, a lady claimed she could tell by tasting tea with milk whether milk or tea was poured first. Fisher, present according to the anecdote, asked how to design an experiment taking the claim seriously, and recounted it in chapter 2 of The Design of Experiments (1935). His answer uses no distribution, parameter or asymptotic theorem: prepare eight cups, four milk-first and four tea-first; present them in random order; ask her to identify the four “milk-first” cups.
If she cannot distinguish them, her choice is a random selection of four cups from eight, and the experimenter supplied the randomness by shuffling. Thus we know exactly how many choices exist and how many give any number correct. The next cell counts them.
from itertools import combinations
from collections import Counter
from math import comb
leche_primero = {0, 1, 2, 3} # las cuatro tazas servidas con la leche primero
posibles = list(combinations(range(8), 4)) # todas las elecciones posibles de cuatro tazas
aciertos = Counter(len(set(c) & leche_primero) for c in posibles)
print(f"elecciones posibles: {len(posibles)} = comb(8, 4) = {comb(8, 4)}")
print(" k casos P(K = k) P(K >= k)")
for k in range(4, -1, -1):
cola = sum(aciertos[j] for j in range(k, 5))
print(f"{k:2d} {aciertos[k]:5d} {aciertos[k] / 70:8.4f} {cola / 70:8.4f}")Getting all four right has probability under guessing: reject at 5 %. Getting three of four has probability and, including perfect identification, the tail is : it proves nothing. With eight cups only perfect identification is significant. No assumption on the distribution of the lady’s answers was needed: the null distribution comes from counting assignments the design made equally likely.
This is the lesson’s idea. A permutation test (or randomization test) builds any statistic’s null distribution by recalculating it over label assignments the null declares indistinguishable. No formula need be derived: enumerate or sample. It is exact, not asymptotic, provided the null truly makes those reassignments equally likely. That condition, when it holds and fails, is our thread. We need hypothesis tests, p-values, and basic permutations and combinations. Questions:
- What data property justifies “shuffling”? Exchangeability.
- How is the test constructed and calculated, and why is any statistic valid?
- What changes when assignments cannot all be enumerated (Monte Carlo), and what is the correct p-value?
- What is Fisher’s exact test, and how does it relate to the hypergeometric distribution?
- What role does experimental randomization play, and how are confidence intervals obtained by inverting the test?
- When does the method fail, and what then?
Exchangeability
A permutation test is valid because under the null, data order or labels carry no information. The exact mathematical property follows.
Exchangeability is weaker than iid, a meaningful difference:
- Iid implies exchangeable, since the joint density is a symmetric product. This is our most-used case: if two samples come from the same distribution, the pooled sample is iid and thus exchangeable.
- Exchangeable does not imply independent. Sampling without replacement from a finite urn yields exchangeable dependent variables; so does a Pólya urn; and any mixture of iid models is exchangeable (De Finetti’s theorem says that for infinite sequences all take this form).
- Independent does not imply exchangeable. Two independent groups with equal means but unequal variances are not mutually exchangeable. Nor is an autocorrelated time series, because permutation breaks neighboring dependence. The method fails there, as shown later.
Why exchangeability suffices: if is exchangeable, conditional on observed values (their order statistics), is uniformly distributed over all reorderings. That known finite conditional distribution yields any probability. It is the permutation distribution.
The two-sample permutation test
Let be control observations and treatment observations, with . The null says treatment changes nothing: samples come from the same distribution . Choose a discrepancy statistic such as mean difference .
Reject if . The statistic is freely chosen: mean, median, trimmed mean, statistic, rank sum, ROC area. Validity does not depend on that choice, but power does: a median resists an outlier that destroys the mean; no choice is best for everything.
Is it valid? The theorem
The short proof is guided exercise 1 at the end. Its ingredient is a counting fact used again for Monte Carlo:
Proof
Let , assumed nonempty. Let have smallest . For every , , so , a set of elements. Thus .
∎Notice what was not assumed: normality, variances, or large samples. Only label exchangeability under the null. This is both the method’s strength and, as we will see, its Achilles heel.
First interactive: shuffle labels
Sixteen people use an old interface (8 controls) or a new one (8 treated), and task-completion times are measured. Observed mean difference is seconds. Could assignment randomness explain it? Under the null, those sixteen values would be unchanged under any other label assignment. Shuffling labels and recalculating generates the values randomness produces.
With initial data assignments exist, and have absolute mean difference at least : . Student gives , Welch : with normal-looking data, permutation and parametric tests nearly always agree. The next cell reproduces the exact calculation from scratch.
import numpy as np
from itertools import combinations
from scipy import stats
control = np.array([41, 38, 52, 47, 35, 60, 44, 49.])
tratado = np.array([35, 31, 44, 39, 47, 33, 36, 37.])
z = np.concatenate([control, tratado])
n1, N = len(tratado), len(z)
obs = tratado.mean() - control.mean()
asignaciones = np.array(list(combinations(range(N), n1))) # (12870, 8): quién va al grupo «tratamiento»
suma = z[asignaciones].sum(axis=1)
dif = suma / n1 - (z.sum() - suma) / (N - n1) # diferencia de medias en cada reparto
extremas = np.abs(dif) >= abs(obs) - 1e-9
print(f"asignaciones posibles : {len(dif)}")
print(f"diferencia observada : {obs:.3f}")
print(f"repartos tan extremos : {extremas.sum()} -> p exacto = {extremas.mean():.5f}")
print(f"p de una cola (dif <= obs): {np.mean(dif <= obs + 1e-9):.5f}")
print(f"t de Student: p = {stats.ttest_ind(tratado, control).pvalue:.5f}; t de Welch: p = {stats.ttest_ind(tratado, control, equal_var=False).pvalue:.5f}")What lies behind it
- The permutation distribution is conditional. It uses the 16 observed values, not others that could have appeared. It asks “given what I measured, how rare is this label assignment?” Yet its size is exact averaged over all possible datasets under the null, as the theorem states.
- The two-sample test is a permutation test in disguise. With fixed total sum of squares of observations, within-group sum is with , so pooled-variance Student is an increasing function of . Permuting or gives exactly the same p-value. This does not hold for Welch’s statistic, not monotone in , which therefore has its own role later. Parametric versus permutation testing differs only in threshold calibration: Student’s assumes normality; permutation assumes exchangeability. Compare one- and two-sample .
- P-values are granular. They are multiples of . With and there are only 20 assignments and the smallest two-sided p-value for a continuous statistic is : no 5 % level is possible. With little data, a permutation test simply cannot reject.
- Enumeration is rarely possible. With 15 and 15 observations there are assignments; with 20 and 20, about . Sample instead.
Monte Carlo: the correct p-value
If all assignments cannot be enumerated, sample randomly and count with statistic at least as extreme as observed. The natural estimate of exact p-value is . But it has a serious flaw: it can be , and a p-value of is impossible (the observed assignment is among , so ). Worse, rejecting when does not have size . The solution counts the observed assignment as one more.
Proof
Let be identity. Under randomization, the statistics with are exchangeable: to swap and , rename (same law as ) and (still uniform, mutually independent and independent of ), giving with roles permuted. Let be ‘s upper rank, so . By exchangeability is the same for all , and the counting lemma gives for each realization. Taking expectations, . With , .
∎The “+1” is the Phipson–Smyth correction (2010): counting the observed assignment is not a patch but what validates the test and prevents zero p-values. The randomness of also has consequences worth quantifying.
Monte Carlo error of the p-value itself
Conditional on data, is binomial: , where is the exact p-value, so
Estimator is unbiased for but is not a valid p-value; is slightly upward biased (conservative) but valid. For small Monte Carlo error choose according to how close is to the threshold. This matters when lies nearby. Near , standard error is with , with and with . To determine reliably which side of holds, reduce error to a fraction of the distance. Accompany the estimate with a Clopper–Pearson interval for from , the exact binomial interval in proportion intervals.
The engine from scratch
The next cell implements a reusable permutation-test engine. It generates assignments as a Boolean matrix (all for exact p-value or random, optionally permuting only within blocks), computes all statistics together, and returns exact or corrected Monte Carlo p-value. Then use it to show stabilization with and an extreme tiny-exact-p case.
import numpy as np
from itertools import combinations
from scipy.stats import beta
def dif_medias(a, b):
"""Estadístico por filas: media de b menos media de a. a: (R, n0), b: (R, n1)."""
return b.mean(axis=1) - a.mean(axis=1)
def welch_t(a, b):
va, vb = a.var(axis=1, ddof=1), b.var(axis=1, ddof=1)
return (b.mean(axis=1) - a.mean(axis=1)) / np.sqrt(va / a.shape[1] + vb / b.shape[1])
def repartos(etiquetas, m=None, rng=None, bloques=None):
"""Matriz booleana (R, N) con los repartos de etiquetas.
m=None: los C(N, n1) repartos (exacto). m entero: m permutaciones aleatorias de las etiquetas observadas,
dentro de cada bloque si se dan los bloques."""
et = np.asarray(etiquetas, bool)
N, n1 = len(et), int(et.sum())
if m is None:
idx = np.array(list(combinations(range(N), n1)))
out = np.zeros((len(idx), N), bool)
out[np.arange(len(idx))[:, None], idx] = True
return out
if bloques is None:
return et[np.argsort(rng.random((m, N)), axis=1)]
bloques = np.asarray(bloques)
base = np.argsort(bloques, kind="stable") # posiciones agrupadas por bloque
orden = np.argsort(bloques[base][None, :] + 0.999 * rng.random((m, N)), axis=1) # barajado dentro de cada bloque
out = np.empty((m, N), bool)
out[:, base] = et[base[orden]]
return out
def prueba_permutacion(x, y, estadistico=dif_medias, alternativa="dos-colas", m=None, semilla=0, bloques=None):
"""Test de permutación de dos muestras. m=None -> exacto; m entero -> Monte Carlo con (b + 1) / (m + 1)."""
x, y = np.asarray(x, float), np.asarray(y, float)
z = np.concatenate([x, y])
n0, n1 = len(x), len(y)
et = np.r_[np.zeros(n0, bool), np.ones(n1, bool)]
R = repartos(et, m, np.random.default_rng(semilla), bloques)
Z = np.broadcast_to(z, R.shape)
nulo = estadistico(Z[~R].reshape(len(R), n0), Z[R].reshape(len(R), n1))
obs = estadistico(x[None, :], y[None, :])[0]
tol = 1e-9 * max(1.0, abs(obs))
if alternativa == "dos-colas":
b = int(np.sum(np.abs(nulo) >= abs(obs) - tol))
elif alternativa == "mayor":
b = int(np.sum(nulo >= obs - tol))
else:
b = int(np.sum(nulo <= obs + tol))
p = b / len(nulo) if m is None else (b + 1) / (m + 1) # exacto incluye ya el reparto observado
return {"p": p, "obs": obs, "b": b, "m": m, "nulo": nulo}
def clopper_pearson(b, m, nivel=0.95):
"""Intervalo exacto para la proporción b/m (el valor p exacto, visto desde el Monte Carlo)."""
a = (1 - nivel) / 2
return (0.0 if b == 0 else beta.ppf(a, b, m - b + 1)), (1.0 if b == m else beta.ppf(1 - a, b + 1, m - b))
control = np.array([41, 38, 52, 47, 35, 60, 44, 49.])
tratado = np.array([35, 31, 44, 39, 47, 33, 36, 37.])
exacto = prueba_permutacion(control, tratado)
p0 = exacto["p"]
print(f"exacto: p = {p0:.5f} ({exacto['b']} de {len(exacto['nulo'])} repartos)\n")
print(" m tres semillas distintas de p̂ DT observada DT teórica IC Clopper-Pearson (semilla 0)")
for m in (99, 999, 9999, 99999):
ps = [prueba_permutacion(control, tratado, m=m, semilla=s)["p"] for s in range(3)]
dts = np.std([(prueba_permutacion(control, tratado, m=m, semilla=s)["b"] / m) for s in range(10, 26)], ddof=1) if m <= 9999 else float("nan")
r = prueba_permutacion(control, tratado, m=m, semilla=0)
lo, hi = clopper_pearson(r["b"], m)
print(f"{m:6d} {ps[0]:.4f} {ps[1]:.4f} {ps[2]:.4f} {dts:10.4f} {np.sqrt(p0 * (1 - p0) / m):10.4f} [{lo:.4f}, {hi:.4f}]")
# caso extremo: la separación es total y el valor p exacto es diminuto
x = np.arange(1.0, 11.0)
y = np.arange(21.0, 31.0)
print(f"\nseparación total, exacto: p = {prueba_permutacion(x, y)['p']:.3e} (= 2/C(20, 10) = {2 / 184756:.3e})")
r = prueba_permutacion(x, y, m=999)
print(f"Monte Carlo con m = 999: b = {r['b']}, b/m = {r['b'] / 999:.3f} (inválido), p̂ = (b + 1)/(m + 1) = {r['p']:.4f}")
# permutaciones por bloques: 8 parejas con el tratamiento asignado a uno de cada pareja (solo hay 2^8 = 256 repartos posibles)
from itertools import product
rng = np.random.default_rng(1)
nivel = rng.normal(10, 3, 8) # cada bloque tiene su nivel propio
x = nivel + rng.normal(0, 0.5, 8)
y = nivel + 1.0 + rng.normal(0, 0.5, 8)
bloques = np.r_[np.arange(8), np.arange(8)] # x[i] e y[i] pertenecen al bloque i
libre = prueba_permutacion(x, y, m=9999, semilla=0)["p"]
en_bloques = prueba_permutacion(x, y, m=9999, semilla=0, bloques=bloques)["p"]
signos = np.array(list(product([-1, 1], repeat=8)))
d = y - x
por_signos = np.mean(np.abs(signos @ d) >= abs(d.sum()) - 1e-12)
print(f"\nocho parejas: permutación libre p̂ = {libre:.4f} | por bloques p̂ = {en_bloques:.4f} | cambios de signo exactos p = {por_signos:.4f}")The output shows it all. With , three seeds give , , (exact ) and Clopper–Pearson spans to : we do not know which side of we are on. At the estimates are – and at , and . Observed standard deviation tracks theoretical . Under complete separation exact p-value is , but with the cell can only say , the floor. In the last example, eight pairs with one treatment per pair yield with free permutation and within blocks, matching exact sign flips () within Monte Carlo error: the permutation group must match the design, or pairing’s power is lost.
The smallest Monte Carlo p-value with assignments is . With you can report “”; never “”. Another rule: fix the seed, state , and publish them. Otherwise results are not reproducible.
Fisher’s exact test
Return to the lady. Her experiment, and any table, is a binary-outcome permutation test. Let rows be groups and columns outcomes:
| success | failure | total | |
|---|---|---|---|
| group 1 | |||
| group 0 | |||
| total |
Under the null that outcome is independent of group, the successes could fall on any of the people equally likely. Conditional on margins, the only random quantity is how many successes fall in group 1, i.e. .
Proof
The joint probability of , is
The sum is , with mass at (also seen by comparing coefficients of in , Vandermonde’s identity, the binomial theorem applied twice). Division cancels , leaving . This is the fraction of placements of ones with exactly in group 1. Cancellation of matters: is sufficient for under the null, so conditioning removes the nuisance parameter.
∎This is the hypergeometric distribution. Fisher’s exact test uses no asymptotic approximation and does not require large expected counts. It is appropriate for small tables where Pearson fails.
The lady’s experiment, played
In the original experiment both margins are fixed by design (four cups of each type, four responses of each type), so correct count is exactly hypergeometric with and . The interactive lets you play, change cup count, and see what happens if the taster has real advantage . Under alternative odds ratio , the proof’s calculation gives , Fisher’s noncentral hypergeometric: recovers the null, and moves mass toward correct answers.
Three observations from the figure:
- Perfect identification is not always required, but is with 8 cups. The lady must answer four “milk first”. Mistaking one of each type means two wrong (6 of 8 correct) and tail . With 10 cups all 10 must be correct ( and the 4-of-5 tail is ); with 12 one pair of errors is allowed (5-of-6 tail ); with 16 still only one (with two mistaken pairs, tail ).
- Power does not simply grow with . With (odds of naming a milk-first cup “milk” are nine times those for a non-milk-first cup), power is with 8 cups, with 12 and with 16, because the threshold jumps from “5 of 6” to “7 of 8”, demanding more. This is discretization: the exact test’s size is strictly below 5 % (with 8 cups , with 16 ), and power has a sawtooth.
- The test is conservative. Actual size is , often far below. Clopper–Pearson intervals pay the same price: exact level guarantee buys above-nominal coverage. The mid-p variant subtracts half the observed table’s probability, reducing conservatism at the expense of the guarantee.
A table with real data
A team compares two model versions on 20 difficult cases: the new version solves 8 of 10, old 3 of 10. Is the difference real? The next cell implements Fisher from scratch, compares scipy.stats.fisher_exact and , and checks the theorem by simulation: permuting outcomes and counting group 1 successes recovers hypergeometric frequencies.
import numpy as np
from math import comb
from scipy.stats import fisher_exact, chi2_contingency
def hiper(k, N, K, n):
return comb(K, k) * comb(N - K, n - k) / comb(N, n)
def fisher_exacto(a, b, c, d):
"""p de una cola (mayor), de la otra (menor) y bilateral (tablas con probabilidad <= la observada)."""
n1, n0, m1 = a + b, c + d, a + c
N = n1 + n0
pk = {k: hiper(k, N, m1, n1) for k in range(max(0, m1 - n0), min(n1, m1) + 1)}
return {"mayor": sum(p for k, p in pk.items() if k >= a),
"menor": sum(p for k, p in pk.items() if k <= a),
"dos": sum(p for p in pk.values() if p <= pk[a] * (1 + 1e-7))}
for tabla in ([[3, 1], [1, 3]], [[8, 2], [3, 7]], [[1, 9], [11, 3]]):
(a, b), (c, d) = tabla
f = fisher_exacto(a, b, c, d)
sp = fisher_exact(tabla, alternative="two-sided").pvalue
sg = fisher_exact(tabla, alternative="greater").pvalue
chi = chi2_contingency(tabla, correction=False)[1]
yates = chi2_contingency(tabla)[1]
print(f"{tabla}: mayor={f['mayor']:.4f} (SciPy {sg:.4f}) dos colas={f['dos']:.4f} (SciPy {sp:.4f}) chi2={chi:.4f} chi2 Yates={yates:.4f}")
# el teorema por simulación: permutar el vector de resultados de la tabla [[8, 2], [3, 7]]
rng = np.random.default_rng(7)
y = np.r_[np.ones(8), np.zeros(2), np.ones(3), np.zeros(7)] # 20 resultados; los 10 primeros, grupo 1
orden = np.argsort(rng.random((40000, 20)), axis=1)
exitos_grupo1 = y[orden][:, :10].sum(axis=1)
print("\nk frecuencia permutada hipergeométrica")
for k in range(4, 11):
print(f"{k:2d} {np.mean(exitos_grupo1 == k):.4f} {hiper(k, 20, 11, 10):.4f}")
print(f"P(A >= 8): permutación {np.mean(exitos_grupo1 >= 8):.4f} exacta {hiper(8, 20, 11, 10) + hiper(9, 20, 11, 10) + hiper(10, 20, 11, 10):.4f}")With versus , Fisher’s two-sided p-value is : no rejection at 5 %. Uncorrected Pearson gives and would reject: with 20 data points its asymptotic approximation is optimistic. Yates correction gives , almost Fisher’s value. Small tables belong to exact testing (previous lesson covers ).
Randomization inference
So far randomness justifying the test was an assumption on data (“samples come from the same distribution”). Fisher proposed something more radical: the experimenter supplies randomness. Even if subjects are not a sample from anything, random treatment assignment suffices to calibrate a test.
Formalize with potential outcomes. Each of units has fixed (measurement without treatment) and (with treatment). The experimenter assigns and observes only . In a completely randomized experiment with treated, is uniform over assignments: this is the only random element and is known.
The sharp null implies the weak, not conversely: effects can cancel on average. A permutation test built on the sharp null need not calibrate the weak null, as Behrens–Fisher shows later. The two objects also have different interpretations.
- Fisher’s test asks “is this assignment compatible with treatment doing nothing to anyone?” This concerns experimental units. Validity comes from randomization, not normal-looking data.
- Neyman’s estimator is unbiased for under randomization, with variance under that distribution
where , and are variances (divisor ) of , and individual effects . The last term cannot be estimated (both outcomes are never observed for the same unit), so Welch estimate overestimates variance by and is exact only for constant effect. This is upward error: the resulting interval is conservative.
The next cell verifies Neyman’s formula by exact enumeration in a population of 10 units.
import numpy as np
from itertools import combinations
rng = np.random.default_rng(5)
N, n1 = 10, 4
n0 = N - n1
y0 = rng.normal(0, 1, N) # resultados potenciales sin tratamiento
tau = rng.normal(1.0, 1.5, N) # efectos individuales, distintos para cada unidad
y1 = y0 + tau
est = []
for tratados in combinations(range(N), n1):
w = np.zeros(N, bool)
w[list(tratados)] = True
est.append(y1[w].mean() - y0[~w].mean())
est = np.array(est)
S1, S0, St = y1.var(ddof=1), y0.var(ddof=1), tau.var(ddof=1)
print(f"asignaciones: {len(est)}")
print(f"E[tau_hat] = {est.mean():.4f} efecto medio = {tau.mean():.4f}")
print(f"Var exacta = {est.var():.4f}")
print(f"S1^2/n1 + S0^2/n0 - St^2/N = {S1 / n1 + S0 / n0 - St / N:.4f} (Neyman)")
print(f"S1^2/n1 + S0^2/n0 = {S1 / n1 + S0 / n0:.4f} (lo que estima Welch: conservador)")Analyze as randomized
The permutation group is not chosen for convenience: it is the randomization actually performed. If assignment differed, the test must permute accordingly.
| Design | Randomization | Valid reassignment | Number of assignments |
|---|---|---|---|
| Two completely randomized groups | of units treated | permute all unit labels | |
| Paired data (two treatments per pair, or before and after) | randomize treated member within each pair (before/after has no draw: validity relies on null symmetry around zero for each difference) | flip each difference’s sign | |
| Blocked design | independent randomization in each block | permute labels within each block | |
| Clustered | randomize whole classes or hospitals | permute cluster labels |
Pairing deserves its formula. With differences for each pair , the sharp null says randomizing which member receives treatment changes only the sign of . Statistic is compared with for sign vectors . This is the permutation version of the paired test, reused in the final lab.
Intervals by inverting a permutation test
A test answers yes or no. To estimate how much, invert it as in test–interval duality: a confidence interval is the set of values not rejected. The sharp null says effect zero, not , but an additive effect model for every gives a clean solution: if , subtract from treated outcomes to obtain control outcomes, for which the sharp null holds.
Proof
If , adjusted data are , with uniform assignment and true sharp null; validity gives , i.e. with probability at least . For monotonicity, let be an assignment, the mean difference of unadjusted data under , and , where counts units assigned treatment by that were actually treated. The adjusted-data statistic under is , observed is (with ). Condition is equivalent to when , i.e. every assignment other than observed. Thus is nondecreasing in with jumps at ; similarly is nonincreasing. The set is an interval.
∎“Additive effect model” is a warning: the interval is valid only for constant effect on the chosen scale. With heterogeneous effects it describes something other than average effect; for the average with heterogeneous units use Neyman’s estimator or bootstrap. In exchange, it needs no error distribution.
Endpoints are concrete: with initial data, 95 % permutation mean-difference interval endpoints are and s (observed difference ). The next cell computes them two ways: bisection on one-sided p-values and closed-form jumps .
import numpy as np
from itertools import combinations
from scipy import stats
control = np.array([41, 38, 52, 47, 35, 60, 44, 49.])
tratado = np.array([35, 31, 44, 39, 47, 33, 36, 37.])
y = np.concatenate([control, tratado])
n0, n1, N = 8, 8, 16
W = np.r_[np.zeros(n0, bool), np.ones(n1, bool)]
alfa = 0.05
idx = np.array(list(combinations(range(N), n1)))
R = np.zeros((len(idx), N), bool)
R[np.arange(len(idx))[:, None], idx] = True # los 12870 repartos
M = len(R)
def dif(datos, reparto):
s = reparto @ datos
return s / n1 - (datos.sum() - s) / n0
def p_unilaterales(delta):
ya = y - delta * W # restar el efecto hipotético a los tratados
nulo, obs = dif(ya, R.astype(float)), ya[W].mean() - ya[~W].mean()
return np.mean(nulo >= obs - 1e-9), np.mean(nulo <= obs + 1e-9)
def biseccion(f, lo, hi, creciente):
for _ in range(50):
mid = (lo + hi) / 2
if (f(mid) > alfa / 2) == creciente:
hi = mid
else:
lo = mid
return (lo + hi) / 2
inf = biseccion(lambda d: p_unilaterales(d)[0], -60, 60, True) # p_>= crece con delta0
sup = biseccion(lambda d: p_unilaterales(d)[1], -60, 60, False) # p_<= decrece con delta0
print(f"intervalo por bisección : [{inf:.3f}, {sup:.3f}]")
# fórmula cerrada: los extremos son estadísticos de orden de g_pi = (A_pi - A_obs) / (c_pi - 1)
k = (R & W).sum(axis=1) # tratados reales que el reparto deja en tratamiento
A = dif(y, R.astype(float))
Aobs = y[W].mean() - y[~W].mean()
c = k / n1 - (n1 - k) / n0
g = np.sort(((A - Aobs) / (c - 1))[k < n1])
cnt = int(np.floor(alfa / 2 * M))
print(f"intervalo con los saltos : [{g[cnt - 1]:.3f}, {g[::-1][cnt - 1]:.3f}] (cnt = {cnt})")
ic_w = stats.ttest_ind(tratado, control, equal_var=False).confidence_interval()
print(f"intervalo t de Welch : [{ic_w.low:.3f}, {ic_w.high:.3f}]")When it fails: the null does not imply exchangeability
A permutation test is exact under randomization. If the null you actually want to test does not imply exchangeability, the guarantee disappears silently. Two cases recur.
Unequal variances: the Behrens–Fisher problem
Suppose the target is only , saying nothing about variances (the population version of Neyman’s weak null and Welch’s null). With unequal variances, group laws differ and are not exchangeable: the observed assignment is not one of equally likely ones. How badly does the mean difference fail? Surprisingly, it can be calculated.
Proof
Random assignment is sampling values without replacement from the finite population of values with variance . Sample mean variance is . Since overall mean is fixed, and therefore . With equal means (no between-group term), and substitution gives .
∎Sizes are crossed: permutation variance weights by instead of . Equal sizes cause no problem because matches in both. Otherwise:
- The smaller group is more dispersed (, ): true variance exceeds permutation variance, reference is too narrow and over-rejection results. This is dangerous.
- The larger group is more dispersed: the reverse occurs and the test is overly conservative.
The interactive measures actual size, which should be .
Studentization
The remedy is a statistic whose permutation distribution does not depend on variance. Permute the Welch statistic, dividing by its own standard error.
The proof idea (fully developed by Chung and Romano, 2013) starts from the calculation above. After reassignment, both “permuted” groups have sample variance , so squared denominator of estimates , exactly : studentized permutation variance tends to one by construction and Hoeffding’s (1951) combinatorial CLT gives a standard-normal permutation limit. Under the true law, by CLT and Slutsky. Both limits match, validating permutation quantiles. This also explains the general recipe: choose an asymptotically pivotal statistic (limiting law independent of nuisance parameters) and its permutation distribution learns to mimic it.
Do not ask more than it gives. The word is asymptotic. With and very skewed data, the interactive shows studentization still over-rejects 5 %: it fixes unequal variance, not small-sample tail shape. The test remains exact under exchangeability when the null is “same distribution”.
import numpy as np
def tamano(n1, n0, s1, R=400, B=199, semilla=3):
"""Fracción de rechazos al 5 % con la nula cierta (medias 0), para los dos estadísticos permutados."""
rng = np.random.default_rng(semilla)
N = n1 + n0
rechazos = np.zeros(2)
for _ in range(R):
z = np.r_[rng.normal(0, s1, n1), rng.normal(0, 1, n0)] # grupo 1 primero
zp = z[np.argsort(rng.random((B, N)), axis=1)] # B repartos de las etiquetas
a, b = zp[:, :n1], zp[:, n1:]
D = np.abs(a.mean(1) - b.mean(1))
T = D / np.sqrt(a.var(1, ddof=1) / n1 + b.var(1, ddof=1) / n0)
g1, g0 = z[:n1], z[n1:]
d_obs = abs(g1.mean() - g0.mean())
t_obs = d_obs / np.sqrt(g1.var(ddof=1) / n1 + g0.var(ddof=1) / n0)
rechazos += [(1 + np.sum(D >= d_obs)) / (B + 1) <= 0.05, (1 + np.sum(T >= t_obs)) / (B + 1) <= 0.05]
return rechazos / R
print(f"margen de Monte Carlo (95 %) en torno al 5 %: ±{1.96 * np.sqrt(0.05 * 0.95 / 400):.3f}\n")
print("n1 n0 sigma1 var real / var permutación rechazo con D rechazo con T")
for n1, n0, s1 in ((25, 25, 3), (10, 40, 3), (40, 10, 3)):
razon = (s1**2 / n1 + 1 / n0) / (s1**2 / n0 + 1 / n1)
rD, rT = tamano(n1, n0, s1)
print(f"{n1:2d} {n0:2d} {s1:5.1f} {razon:12.2f} {rD:8.3f} {rT:8.3f}")With equal sizes both tests are well calibrated ( is compatible with 5 % within error). With the small noisy group (), permutation of rejects , nearly six times nominal, as variance ratio predicted. With the large noisy group, permutation never rejects in these 400 studies: useless. Permuting yields and , near 5 % with samples as small as 10.
Dependence: permuting is not exchangeability
The second case is subtler. An autocorrelated time series is not exchangeable: today resembles yesterday, and random permutation breaks that structure, making generated assignments implausible under the null. Testing “did the mean change between first and second halves?” by permuting time points compares real dependent data with shuffled independent series, and real mean differences vary much more.
import numpy as np
def ar1(rng, R, n, rho):
e = rng.normal(size=(R, n))
x = np.empty((R, n))
x[:, 0] = e[:, 0] / np.sqrt(1 - rho**2)
for t in range(1, n):
x[:, t] = rho * x[:, t - 1] + e[:, t]
return x
def rechazos(rho, R=400, n=60, B=199, semilla=11):
"""Tamaño del test «media de la 1.ª mitad = media de la 2.ª» con la nula cierta (serie estacionaria sin cambio)."""
rng = np.random.default_rng(semilla)
X = ar1(rng, R, n, rho)
h = n // 2
r_perm = r_circ = 0
for x in X:
obs = abs(x[:h].mean() - x[h:].mean())
zp = x[np.argsort(rng.random((B, n)), axis=1)] # permutación libre
d = np.abs(zp[:, :h].mean(1) - zp[:, h:].mean(1))
r_perm += (1 + np.sum(d >= obs)) / (B + 1) <= 0.05
c = np.concatenate([[0.0], np.cumsum(np.r_[x, x])]) # desplazamientos circulares
s = rng.integers(1, n, B)
m1 = (c[s + h] - c[s]) / h
m2 = (c[s + n] - c[s + h]) / (n - h)
r_circ += (1 + np.sum(np.abs(m1 - m2) >= obs)) / (B + 1) <= 0.05
return r_perm / R, r_circ / R
print(f"margen de Monte Carlo (95 %): ±{1.96 * np.sqrt(0.05 * 0.95 / 400):.3f}\n")
print("rho permutación libre desplazamientos circulares")
for rho in (0.0, 0.5, 0.8):
a, b = rechazos(rho)
print(f"{rho:3.1f} {a:8.3f} {b:8.3f}")The output is clear (400 series per row, error around points). With (independence) free permutation maintains 5 %; with it rejects and with more than half. Circular shifts preserve neighbor dependence and greatly improve size (7.7 % and 10.7 %) but do not fix strong dependence. No recipe is universal: the permutation group must be justified by design or a symmetry genuinely implied by the null. Common options:
- Permute independent units, not observations. With repeated measurements on subjects, permute whole subjects (or within-subject treatment labels), not individual measurements.
- Block permutations for blocked designs, and sign flips when the null implies symmetry around zero (paired data).
- Block resampling for time series: advanced bootstrap covers dependence.
Using libraries: scipy.stats.permutation_test
SciPy implements the engine: permutation_test(data, statistic, permutation_type=..., n_resamples=...), with three designs ('independent' for two or more samples, 'samples' for paired observations, 'pairings' for association) and n_resamples=np.inf for exact values. Its Monte Carlo p-value uses . One detail: SciPy’s two-sided value doubles the smaller one-sided value (capped at 1), rather than counting ; they coincide when the permutation distribution is symmetric, as here with . The cell compares with our engine.
import numpy as np
from scipy import stats
control = np.array([41, 38, 52, 47, 35, 60, 44, 49.])
tratado = np.array([35, 31, 44, 39, 47, 33, 36, 37.])
def dm(x, y, axis=-1):
return np.mean(y, axis=axis) - np.mean(x, axis=axis)
def permutacion(*args, semilla=0, **kw):
try:
return stats.permutation_test(*args, rng=semilla, **kw)
except TypeError: # versiones antiguas de SciPy
return stats.permutation_test(*args, random_state=semilla, **kw)
# dos muestras independientes: exacto y Monte Carlo
ex = permutacion((control, tratado), dm, vectorized=True, n_resamples=np.inf, permutation_type="independent")
mc = permutacion((control, tratado), dm, vectorized=True, n_resamples=9999, permutation_type="independent")
mio = prueba_permutacion(control, tratado)["p"] # el motor de la celda anterior
mio_mc = prueba_permutacion(control, tratado, m=9999, semilla=0)["p"]
print(f"exacto : SciPy {ex.pvalue:.5f} propio {mio:.5f}")
print(f"Monte Carlo: SciPy {mc.pvalue:.5f} propio {mio_mc:.5f} (m = 9999)")
# datos pareados: 'samples' intercambia los dos valores de cada pareja (equivale a cambiar el signo de la diferencia)
antes = np.array([12.1, 14.3, 11.8, 15.2, 13.0, 12.7, 16.1, 14.9, 13.4, 12.2])
despues = antes + np.array([0.8, 1.4, -0.3, 0.9, 1.1, 0.2, 1.6, 0.7, -0.1, 1.0])
par = permutacion((despues, antes), lambda x, y, axis=-1: np.mean(x - y, axis=axis), vectorized=True,
n_resamples=np.inf, permutation_type="samples")
d = despues - antes
signos = np.array([[1 if (k >> i) & 1 else -1 for i in range(len(d))] for k in range(2 ** len(d))])
propio_par = np.mean(np.abs(signos @ d / len(d)) >= abs(d.mean()) - 1e-12)
print(f"pareado exacto: SciPy {par.pvalue:.5f} cambios de signo propios {propio_par:.5f} t pareado {stats.ttest_rel(despues, antes).pvalue:.5f}")
# asociación: permuta una variable respecto de la otra (nula de independencia)
rng = np.random.default_rng(2)
u = rng.normal(size=25)
v = 0.5 * u + rng.normal(size=25)
def correlacion(a, b, axis=-1):
a = a - a.mean(axis=axis, keepdims=True)
b = b - b.mean(axis=axis, keepdims=True)
return (a * b).sum(axis=axis) / np.sqrt((a * a).sum(axis=axis) * (b * b).sum(axis=axis))
cor = permutacion((u, v), correlacion, permutation_type="pairings", n_resamples=4999, vectorized=True)
print(f"correlación: r = {stats.pearsonr(u, v)[0]:.3f} p de permutación = {cor.pvalue:.4f} p de Pearson = {stats.pearsonr(u, v)[1]:.4f}")Two practical tips: pass vectorized=True and a statistic with axis so SciPy calculates assignments in batches (otherwise a Python loop), and use n_resamples=np.inf only when is manageable. Our engine does the same with block and seed control.
Lab: does the new model improve?
Two classifiers are evaluated on the same 500 benchmark examples. Examples are blocks: each gives paired outcomes and within-pair differences matter. The paired design makes sign flips the valid assignment. This is recommended for comparing systems on the same inputs.
Each outcome is correct or incorrect, so differences are . Ties () contribute nothing to , and among discordant examples the sum is with under the null: sign-flip testing of correct/incorrect outcomes is exactly McNemar’s exact binomial test. The cell checks this.
import numpy as np
from itertools import product
from scipy import stats
rng = np.random.default_rng(14)
n = 500
dificultad = rng.normal(0, 1, n) # cada ejemplo tiene su dificultad
p_a = 1 / (1 + np.exp(-(1.2 - dificultad)))
p_b = 1 / (1 + np.exp(-(1.2 + 0.25 - dificultad))) # B es algo mejor
ok_a = rng.random(n) < p_a
ok_b = rng.random(n) < p_b
d = ok_b.astype(int) - ok_a.astype(int) # diferencia por ejemplo en {-1, 0, 1}
def cambios_de_signo(d, m=None, semilla=0):
"""Test de cambios de signo de la media de d. Exacto (2^n) si m es None y n <= 16; si no, Monte Carlo con (b + 1)/(m + 1)."""
d = np.asarray(d, float)
obs = abs(d.mean())
if m is None:
s = np.array(list(product([-1.0, 1.0], repeat=len(d))))
return np.mean(np.abs(s @ d / len(d)) >= obs - 1e-12)
s = np.where(np.random.default_rng(semilla).random((m, len(d))) < 0.5, -1.0, 1.0)
b = np.sum(np.abs(s @ d / len(d)) >= obs - 1e-12)
return (b + 1) / (m + 1)
b_solo, a_solo = int(np.sum(d == 1)), int(np.sum(d == -1))
print(f"exactitud A = {ok_a.mean():.3f}, B = {ok_b.mean():.3f}; discordantes: solo B acierta {b_solo}, solo A acierta {a_solo}")
print(f"cambios de signo (Monte Carlo, m = 19999, sin los empates): p = {cambios_de_signo(d[d != 0], m=19999):.4f}")
print(f"McNemar exacto (binomial {b_solo} de {a_solo + b_solo}) : p = {stats.binomtest(b_solo, a_solo + b_solo, 0.5).pvalue:.4f}")
print(f"t pareado sobre las diferencias : p = {stats.ttest_1samp(d, 0).pvalue:.4f}")
# con pocos discordantes se puede enumerar: la igualdad es exacta, no solo aproximada
dd = np.array([1] * 8 + [-1] * 4 + [0] * 30)
print(f"\n12 discordantes (8 contra 4), enumerando 2^42 es inviable, pero los 30 ceros no cuentan:")
print(f" cambios de signo sobre los 12 discordantes: {cambios_de_signo(dd[dd != 0]):.6f} binomial exacta: {stats.binomtest(8, 12, 0.5).pvalue:.6f}")The same test works for continuous per-example metrics (log-likelihood, error, length): calculate on the chosen metric and flip signs. With many examples it approaches paired , with the advantage of not depending on normal differences.
import numpy as np
from scipy import stats
rng = np.random.default_rng(21)
n = 40
base = rng.gamma(2.0, 1.0, n) # error por ejemplo del modelo A (asimétrico, con cola)
mejora = rng.standard_t(3, n) * 0.25 + 0.20 # el modelo B reduce el error 0.20 de media, con colas pesadas
err_a, err_b = base, np.maximum(base - mejora, 0.0)
d = err_a - err_b # positivo = B mejor
def cambios_de_signo(d, m, semilla=0):
s = np.where(np.random.default_rng(semilla).random((m, len(d))) < 0.5, -1.0, 1.0)
obs = abs(d.mean())
return (1 + np.sum(np.abs(s @ d / len(d)) >= obs - 1e-12)) / (m + 1)
print(f"diferencia media de error: {d.mean():.3f} desviación típica: {d.std(ddof=1):.3f}")
print(f"cambios de signo (m = 19999): p = {cambios_de_signo(d, 19999):.4f}")
print(f"t pareado : p = {stats.ttest_1samp(d, 0).pvalue:.4f}")
print(f"Wilcoxon de rangos con signo: p = {stats.wilcoxon(d).pvalue:.4f} (lo veremos en la lección de tests no paramétricos)")Common mistakes
Exercises
Step 1 of 4. How is , the p-value of data reordered by , expressed using the ?
fisher_p(tabla, alternativa), receiving a table [[a, b], [c, d]] (rows groups, columns success and failure) and returning Fisher's exact-test p-value with fixed margins. alternativa is 'mayor' (), 'menor' (), or 'dos-colas' (sum of probabilities of tables no more likely than observed, relative tolerance ). Enumerate tables with fixed margins using hypergeometric mass and math.comb; do not use SciPy.from math import comb
def fisher_p(tabla, alternativa="dos-colas"):
(a, b), (c, d) = tabla
n1, n0, m1 = a + b, c + d, a + c
N = n1 + n0
# tu código: soporte de k, probabilidades hipergeométricas y suma según la alternativa
return 1.0Summary
- Exchangeability. If for finite group under , p-value satisfies for any statistic. Choose it beforehand; it affects power, not level.
- Monte Carlo. With random assignments the correct p-value is , valid and never zero. is invalid. Standard error is : report , seed, and if needed a Clopper–Pearson interval.
- Fisher. Conditional permutation test on a table: with fixed margins, group 1 success count is hypergeometric regardless of the common rate. Discreteness makes it conservative and useful for small tables. With 8 cups only perfect identification is significant ().
- Randomization. Validity comes from assignment, not a sampling model. Fisher’s sharp null fixes potential outcomes and gives an exact test; Neyman’s weak null concerns average effect. The permutation group matches design: sign flips for pairs, within blocks for blocks.
- Inversion intervals. With additive effect , covers with probability at least ; for mean difference endpoints are jumps of monotone step functions.
- Failures. With equal means and unequal variances, permutation variance is instead of ; studentization (permuting Welch statistic) asymptotically fixes level. Under dependence permute independent units or blocks.