Module contents
Lesson 14 of 27Core 95 min

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.

[ ]The 70 ways to choose four cups from eightBrowser
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 1/70≈0.0141/70 \approx 0.014 under guessing: reject at 5 %. Getting three of four has probability 16/7016/70 and, including perfect identification, the tail is 17/70≈0.24317/70 \approx 0.243: 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:

  1. What data property justifies “shuffling”? Exchangeability.
  2. How is the test constructed and calculated, and why is any statistic valid?
  3. What changes when assignments cannot all be enumerated (Monte Carlo), and what is the correct p-value?
  4. What is Fisher’s exact test, and how does it relate to the hypergeometric distribution?
  5. What role does experimental randomization play, and how are confidence intervals obtained by inverting the test?
  6. 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 ∫∏iFθ(xi)  ⁣dμ(θ)\int \prod_i F_\theta(x_i)\,\dd\mu(\theta) 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 X\vb{X} is exchangeable, conditional on observed values (their order statistics), X\vb{X} 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 x1,…,xn0x_1, \dots, x_{n_0} be control observations and y1,…,yn1y_1, \dots, y_{n_1} treatment observations, with N=n0+n1N = n_0 + n_1. The null says treatment changes nothing: samples come from the same distribution FF. Choose a discrepancy statistic such as mean difference T=yˉ−xˉT = \bar y - \bar x.

Reject H0H_0 if p≤αp \le \alpha. The statistic is freely chosen: mean, median, trimmed mean, tt 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 S={i:ri≤k}S = \{i : r_i \le k\}, assumed nonempty. Let i∗∈Si^\ast \in S have smallest tit_i. For every i∈Si \in S, ti≥ti∗t_i \ge t_{i^\ast}, so S⊆{j:tj≥ti∗}S \subseteq \{j : t_j \ge t_{i^\ast}\}, a set of ri∗≤kr_{i^\ast} \le k elements. Thus ∣S∣≤k\abs{S} \le k.

∎

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 −8-8 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.

InteractiveShuffle labels
True labels: task time (s) by group
control (8)tratamiento (8)
  • control
  • treatment
  • group mean (line)
Mean difference with these labels: −8.0−8.0
Permutation distribution of the statistic
observado
  • shuffle at least as extreme
  • less extreme shuffle
  • exact distribution
  • observed (and its symmetric counterpart)
Data
Statistic
Mean difference observed (treatment − control)−8.0
Shuffles mm | at least as extreme bb0 | 0
Monte Carlo p-value (b+1)/(m+1)(b+1)/(m+1)n/a
Exact p-value (12 870 assignments)0.0375 (482/12 870)
Monte Carlo standard errorn/a
Welch tt p-value (reference)0.0378
Labels are in their original places. Press Shuffle to see the groups redistribute.
Top: sixteen times with labels (blue control, orange treatment); each press randomly reassigns labels among the same numbers. Bottom: statistic histogram across shuffles. Red equals or exceeds observed absolute value. Grey line is the exact distribution enumerating all 12 870 assignments. Press 'Shuffle ×1' several times and see points move between rows; then use '×1000' and watch the Monte Carlo p-value stabilize around exact. Switch to 'No effect' (p-value no longer small) and 'With an outlier': mean difference loses significance, median difference does not. What does this say about choosing a statistic before seeing data?

With initial data (168)=12 870\binom{16}{8} = 12\,870 assignments exist, and 482482 have absolute mean difference at least 88: p=482/12 870=0.0375p = 482/12\,870 = 0.0375. Student tt gives 0.03540.0354, Welch tt 0.03780.0378: with normal-looking data, permutation and parametric tests nearly always agree. The next cell reproduces the exact calculation from scratch.

[ ]Exact p-value by enumerating 12 870 assignmentsBrowser
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 tt test is a permutation test in disguise. With fixed total sum of squares SCT\mathrm{SCT} of NN observations, within-group sum is SCT−n0n1ND2\mathrm{SCT} - \tfrac{n_0 n_1}{N}D^2 with D=yˉ−xˉD = \bar y - \bar x, so pooled-variance Student tt is an increasing function of ∣D∣\abs{D}. Permuting tt or DD gives exactly the same p-value. This does not hold for Welch’s statistic, not monotone in DD, which therefore has its own role later. Parametric versus permutation testing differs only in threshold calibration: Student’s tt assumes normality; permutation assumes exchangeability. Compare one- and two-sample tt.
  • P-values are granular. They are multiples of 1/(Nn1)1/\binom{N}{n_1}. With N=6N = 6 and n1=3n_1 = 3 there are only 20 assignments and the smallest two-sided p-value for a continuous statistic is 2/20=0.102/20 = 0.10: 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 (3015)=155 117 520\binom{30}{15} = 155\,117\,520 assignments; with 20 and 20, about 1.4×10111.4 \times 10^{11}. Sample instead.

Monte Carlo: the correct p-value

If all MM assignments cannot be enumerated, sample mm randomly and count bb with statistic at least as extreme as observed. The natural estimate of exact p-value pp is b/mb/m. But it has a serious flaw: it can be 00, and a p-value of 00 is impossible (the observed assignment is among MM, so p≥1/Mp \ge 1/M). Worse, rejecting when b/m≤αb/m \le \alpha does not have size ≤α\le \alpha. The solution counts the observed assignment as one more.

Proof

Let g0g_0 be identity. Under randomization, the m+1m + 1 statistics T0,…,TmT_0, \dots, T_m with Tj=T(gjX)T_j = T(g_j\vb{X}) are exchangeable: to swap T0T_0 and TjT_j, rename X′=gjX\vb{X}' = g_j\vb{X} (same law as X\vb{X}) and gi′=gigj−1g_i' = g_i g_j^{-1} (still uniform, mutually independent and independent of X′\vb{X}'), giving Ti=T(gi′X′)T_i = T(g'_i\vb{X}') with roles permuted. Let ri=#{j:Tj≥Ti}r_i = \#\{j : T_j \ge T_i\} be TiT_i‘s upper rank, so p^=r0/(m+1)\hat p = r_0/(m+1). By exchangeability P(ri≤k)\Pr(r_i \le k) is the same for all ii, and the counting lemma gives ∑i1[ri≤k]≤k\sum_i \ind[r_i \le k] \le k for each realization. Taking expectations, (m+1)P(r0≤k)≤k(m+1)\Pr(r_0 \le k) \le k. With k=⌊α(m+1)⌋k = \lfloor \alpha(m+1)\rfloor, P(p^≤α)=P(r0≤α(m+1))≤k/(m+1)≤α\Pr(\hat p \le \alpha) = \Pr(r_0 \le \alpha(m+1)) \le k/(m+1) \le \alpha.

∎

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 p^\hat p also has consequences worth quantifying.

Monte Carlo error of the p-value itself

Conditional on data, bb is binomial: b∼Bin⁡(m,p)b \sim \Bin(m, p), where pp is the exact p-value, so

E ⁣[bm]=p,DT⁡ ⁣(bm)=p(1−p)m,E[p^]=mp+1m+1≥p.\E\!\left[\frac{b}{m}\right] = p, \qquad \operatorname{DT}\!\left(\frac{b}{m}\right) = \sqrt{\frac{p(1 - p)}{m}}, \qquad \E[\hat p] = \frac{mp + 1}{m + 1} \ge p.

Estimator b/mb/m is unbiased for pp but is not a valid p-value; p^\hat p is slightly upward biased (conservative) but valid. For small Monte Carlo error choose mm according to how close pp is to the threshold. This matters when pp lies nearby. Near p≈0.05p \approx 0.05, standard error is 0.00690.0069 with m=999m = 999, 0.00220.0022 with m=9 999m = 9\,999 and 0.00070.0007 with m=99 999m = 99\,999. To determine reliably which side of 0.050.05 holds, reduce error to a fraction of the distance. Accompany the estimate with a Clopper–Pearson interval for pp from (b,m)(b, m), 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 mm 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 mm and an extreme tiny-exact-p case.

[ ]Permutation-test engine: exact, Monte Carlo and blockedBrowser
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 m=99m = 99, three seeds give 0.0400.040, 0.0600.060, 0.0200.020 (exact 0.03750.0375) and Clopper–Pearson spans 0.0060.006 to 0.0860.086: we do not know which side of 0.050.05 we are on. At m=9 999m = 9\,999 the estimates are 0.0330.033–0.0360.036 and at m=99 999m = 99\,999, 0.03720.0372 and 0.03730.0373. Observed standard deviation tracks theoretical p(1−p)/m\sqrt{p(1-p)/m}. Under complete separation exact p-value is 2/(2010)=1.1×10−52/\binom{20}{10} = 1.1 \times 10^{-5}, but with m=999m = 999 the cell can only say p^=0.001\hat p = 0.001, the 1/(m+1)1/(m+1) floor. In the last example, eight pairs with one treatment per pair yield p^=0.37\hat p = 0.37 with free permutation and 0.0070.007 within blocks, matching exact sign flips (0.00780.0078) within Monte Carlo error: the permutation group must match the design, or pairing’s power is lost.

The smallest Monte Carlo p-value with mm assignments is 1/(m+1)1/(m+1). With m=999m = 999 you can report “p≤10−3p \le 10^{-3}”; never “p=0p = 0”. Another rule: fix the seed, state mm, and publish them. Otherwise results are not reproducible.

Fisher’s exact test

Return to the lady. Her experiment, and any 2×22\times 2 table, is a binary-outcome permutation test. Let rows be groups and columns outcomes:

successfailuretotal
group 1aabbn1n_1
group 0ccddn0n_0
totalm1m_1m0m_0NN

Under the null that outcome is independent of group, the m1m_1 successes could fall on any of the NN people equally likely. Conditional on margins, the only random quantity is how many m1m_1 successes fall in group 1, i.e. aa.

Proof

The joint probability of A=kA = k, C=m1−kC = m_1 - k is

(n1k)pkqn1−k(n0m1−k)pm1−kqn0−m1+k=(n1k)(n0m1−k) pm1qN−m1.\binom{n_1}{k}p^k q^{n_1-k}\binom{n_0}{m_1-k}p^{m_1-k}q^{n_0-m_1+k} = \binom{n_1}{k}\binom{n_0}{m_1-k}\,p^{m_1}q^{N-m_1}.

The sum A+CA + C is Bin⁡(N,p)\Bin(N, p), with mass (Nm1)pm1qN−m1\binom{N}{m_1}p^{m_1}q^{N-m_1} at m1m_1 (also seen by comparing coefficients of xm1x^{m_1} in (1+x)n1(1+x)n0=(1+x)N(1+x)^{n_1}(1+x)^{n_0} = (1+x)^N, Vandermonde’s identity, the binomial theorem applied twice). Division cancels pm1qN−m1p^{m_1}q^{N-m_1}, leaving (n1k)(n0m1−k)/(Nm1)\binom{n_1}{k}\binom{n_0}{m_1-k}/\binom{N}{m_1}. This is the fraction of (Nm1)\binom{N}{m_1} placements of ones with exactly kk in group 1. Cancellation of pp matters: m1m_1 is sufficient for pp 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 χ2\chi^2 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 KK is exactly hypergeometric with N=8N = 8 and n1=m1=4n_1 = m_1 = 4. The interactive lets you play, change cup count, and see what happens if the taster has real advantage ψ\psi. Under alternative odds ratio ψ=p1q0p0q1\psi = \dfrac{p_1 q_0}{p_0 q_1}, the proof’s calculation gives P(A=k∣A+C=m1)∝(n1k)(n0m1−k)ψk\Pr(A = k \given A + C = m_1) \propto \binom{n_1}{k}\binom{n_0}{m_1-k}\psi^k, Fisher’s noncentral hypergeometric: ψ=1\psi = 1 recovers the null, and ψ>1\psi > 1 moves mass toward correct answers.

InteractiveThe lady tasting tea
Round 1: 8 cups in a row. Mark the 4 you think had milk first (0/4)
  • milk first (true, after reveal)
  • tea first (true)
  • your choice (label below the cup)
Correct milk-first guesses KK (hypergeometric, N=8N = 8)
1/7016/7036/7016/701/70
  • guessing (null)
  • rejection region (tail ≤ 5%)
Number of cups NN
1 (chance)
Ways to choose 4 of 8 cups70
Probability of guessing everything correctly1/70 = 0.0143
Your result kk (milk-first cups correctly marked)n/a
P-value P(K≥k)P(K \ge k)n/a
5% rejection regionk≥4  (0.0143)k \ge 4 \;(0.0143)
Errors toleratednone: only a perfect result
Power with ψ=1.0\psi = 1.01.4 %
Mark the 4 cups you think had milk first (4 left). Because you cannot taste them, you are guessing: precisely the null hypothesis.
Mark cups you believe were served milk first and press 'Reveal': the experimenter's seed decided the true assignment. Right: hypergeometric distribution of milk-first correct guesses, with 5 % rejection region red. With 8 cups, how many errors are tolerated? Change to 12 and 16 cups. Then increase the taster's real advantage ψ\psi and inspect power: with ψ=9\psi = 9 and 8 cups it is only 31 %. Press 'Simulate 2000 rounds': with ψ=1\psi = 1 these truly shuffle marks and simulation lines match theoretical bars.

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 17/70=0.24317/70 = 0.243. With 10 cups all 10 must be correct ((105)=252\binom{10}{5} = 252 and the 4-of-5 tail is 26/252=0.10326/252 = 0.103); with 12 one pair of errors is allowed (5-of-6 tail 37/924=0.04037/924 = 0.040); with 16 still only one (with two mistaken pairs, tail 849/12 870=0.066849/12\,870 = 0.066).
  • Power does not simply grow with NN. With ψ=9\psi = 9 (odds of naming a milk-first cup “milk” are nine times those for a non-milk-first cup), power is 31 %31\,\% with 8 cups, 60 %60\,\% with 12 and 35 %35\,\% 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 1.4 %1.4\,\%, with 16 0.5 %0.5\,\%), and power has a sawtooth.
  • The test is conservative. Actual size is P(A≥kα)≤α\Pr(A \ge k_\alpha) \le \alpha, 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 χ2\chi^2, and checks the theorem by simulation: permuting outcomes and counting group 1 successes recovers hypergeometric frequencies.

[ ]Fisher from scratch versus SciPy, χ² and direct permutationBrowser
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 8/108/10 versus 3/103/10, Fisher’s two-sided p-value is 0.0700.070: no rejection at 5 %. Uncorrected Pearson χ2\chi^2 gives 0.0250.025 and would reject: with 20 data points its asymptotic approximation is optimistic. Yates correction gives 0.0720.072, almost Fisher’s value. Small tables belong to exact testing (previous lesson covers χ2\chi^2).

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 NN units has fixed Yi(0)Y_i(0) (measurement without treatment) and Yi(1)Y_i(1) (with treatment). The experimenter assigns Wi∈{0,1}W_i \in \{0, 1\} and observes only Yi=Yi(Wi)Y_i = Y_i(W_i). In a completely randomized experiment with n1n_1 treated, WW is uniform over (Nn1)\binom{N}{n_1} 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 τ^=Yˉ1−Yˉ0\hat\tau = \bar Y_1 - \bar Y_0 is unbiased for τˉ\bar\tau under randomization, with variance under that distribution
Var⁡(τ^)=S12n1+S02n0−Sτ2N,\Var(\hat\tau) = \frac{S_1^2}{n_1} + \frac{S_0^2}{n_0} - \frac{S_\tau^2}{N},

where S12S_1^2, S02S_0^2 and Sτ2S_\tau^2 are variances (divisor N−1N-1) of Yi(1)Y_i(1), Yi(0)Y_i(0) and individual effects Yi(1)−Yi(0)Y_i(1) - Y_i(0). The last term cannot be estimated (both outcomes are never observed for the same unit), so Welch estimate s12/n1+s02/n0s_1^2/n_1 + s_0^2/n_0 overestimates variance by Sτ2/NS_\tau^2/N 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.

[ ]Neyman's variance by enumerating 210 assignmentsBrowser
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.

DesignRandomizationValid reassignmentNumber of assignments
Two completely randomized groupsn1n_1 of NN units treatedpermute all unit labels(Nn1)\binom{N}{n_1}
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 sign2n2^n
Blocked designindependent randomization in each blockpermute labels within each block∏b(Nbn1b)\prod_b \binom{N_b}{n_{1b}}
Clusteredrandomize whole classes or hospitalspermute cluster labels(Gg1)\binom{G}{g_1}

Pairing deserves its formula. With differences di=yi(tratamiento)−yi(control)d_i = y_i(\text{tratamiento}) - y_i(\text{control}) for each pair i=1,…,ni = 1, \dots, n, the sharp null says randomizing which member receives treatment changes only the sign of did_i. Statistic T=∑idiT = \sum_i d_i is compared with ∑isidi\sum_i s_i d_i for 2n2^n sign vectors s∈{±1}ns \in \{\pm 1\}^n. 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 δ0\delta_0, but an additive effect model Yi(1)=Yi(0)+δY_i(1) = Y_i(0) + \delta for every ii gives a clean solution: if δ=δ0\delta = \delta_0, subtract δ0\delta_0 from treated outcomes to obtain control outcomes, for which the sharp null holds.

Proof

If δ0=δ\delta_0 = \delta, adjusted data are Yi(0)Y_i(0), with uniform assignment and true sharp null; validity gives P(p(δ)≤α)≤α\Pr(p(\delta) \le \alpha) \le \alpha, i.e. δ∈IC\delta \in \mathrm{IC} with probability at least 1−α1-\alpha. For monotonicity, let π\pi be an assignment, AπA_\pi the mean difference of unadjusted data under π\pi, and cπ=kπ/n1−(n1−kπ)/n0c_\pi = k_\pi/n_1 - (n_1 - k_\pi)/n_0, where kπk_\pi counts units assigned treatment by π\pi that were actually treated. The adjusted-data statistic under π\pi is Aπ−δ0cπA_\pi - \delta_0 c_\pi, observed is Aobs−δ0A_{\mathrm{obs}} - \delta_0 (with c=1c = 1). Condition Aπ−δ0cπ≥Aobs−δ0A_\pi - \delta_0 c_\pi \ge A_{\mathrm{obs}} - \delta_0 is equivalent to δ0≥gπ:=(Aπ−Aobs)/(cπ−1)\delta_0 \ge g_\pi := (A_\pi - A_{\mathrm{obs}})/(c_\pi - 1) when cπ<1c_\pi < 1, i.e. every assignment other than observed. Thus p≥(δ0)=(1+#{π≠id:gπ≤δ0})/Mp_{\ge}(\delta_0) = \big(1 + \#\{\pi \ne \mathrm{id} : g_\pi \le \delta_0\}\big)/M is nondecreasing in δ0\delta_0 with jumps at gπg_\pi; similarly p≤p_{\le} is nonincreasing. The set {p≥>α/2}∩{p≤>α/2}\{p_\ge > \alpha/2\} \cap \{p_\le > \alpha/2\} 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.

InteractiveInterval by inversion
Adjusted data y′=y−δ0Wy' = y - \delta_0 W with δ0=0.0\delta_0 = 0.0
controltratamiento ajustado
Permutation distribution of T∗T^* at δ0\delta_0 (1999 assignments)
observado
Permutation p-value versus hypothetical effect δ0\delta_0 (drag)
p = 0.05estimación
  • p(δ0)p(\delta_0) permutation
  • permutation interval
  • Welch tt interval
  • your δ0\delta_0
Two-sided p-value p(δ0)=2min⁡(p≥,p≤)p(\delta_0) = 2\min(p_\ge, p_\le): the interval is where both tails exceed 0.025.
Data
Statistic
0.0
Estimate (mean difference)−8.0
Permutation p-value at δ0\delta_00.0410
Permutation interval (95%)[−15.4, −0.7]
Welch tt interval (95%)[−15.5, −0.5]
Does it contain 0 (null effect)?no: significant at 5%
At δ0=0.0\delta_0 = 0.0 reject (p=0.0410p = 0.0410): this effect is incompatible with the data. The red tail on the observed side, doubled, is the p-value.
Drag hypothetical effect δ0\delta_0 on the curve (or use the slider). Top left: adjusted data; orange points move δ0\delta_0 units; below: permutation distribution recalculated on adjusted data. Right: permutation p-value versus δ0\delta_0: region above p=0.05p = 0.05 is the effect confidence interval. Compare Welch tt interval in violet. With 'Moderate effect' bars nearly coincide. Switch to 'With an outlier' (92 s in the new group) and compare means and medians: which statistic yields a more informative interval and why? Does it contain zero?

Endpoints are concrete: with initial data, 95 % permutation mean-difference interval endpoints are −15.4-15.4 and −0.67-0.67 s (observed difference −8-8). The next cell computes them two ways: bisection on one-sided p-values and closed-form jumps gπg_\pi.

[ ]Permutation interval by inversion: bisection and jump valuesBrowser
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 H0:μ1=μ0H_0: \mu_1 = \mu_0, 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 (Nn1)\binom{N}{n_1} equally likely ones. How badly does the mean difference fail? Surprisingly, it can be calculated.

Proof

Random assignment is sampling n1n_1 values without replacement from the finite population of NN values with variance S2S^2. Sample mean variance is S2(1/n1−1/N)S^2(1/n_1 - 1/N). Since overall mean zˉ\bar z is fixed, D∗=zˉ1−zˉ0=Nn0(zˉ1−zˉ)D^\ast = \bar z_1 - \bar z_0 = \dfrac{N}{n_0}(\bar z_1 - \bar z) and therefore Var⁡π(D∗)=N2n02S2n0Nn1=S2Nn0n1=S2(1n1+1n0)\Var_\pi(D^\ast) = \dfrac{N^2}{n_0^2}S^2\dfrac{n_0}{N n_1} = S^2\dfrac{N}{n_0 n_1} = S^2\left(\dfrac1{n_1}+\dfrac1{n_0}\right). With equal means S2≈n1σ12+n0σ02NS^2 \approx \dfrac{n_1\sigma_1^2 + n_0\sigma_0^2}{N} (no between-group term), and substitution gives n1σ12+n0σ02N⋅Nn1n0=σ12n0+σ02n1\dfrac{n_1\sigma_1^2+n_0\sigma_0^2}{N}\cdot\dfrac{N}{n_1 n_0} = \dfrac{\sigma_1^2}{n_0}+\dfrac{\sigma_0^2}{n_1}.

∎

Sizes are crossed: permutation variance weights σ12\sigma_1^2 by 1/n01/n_0 instead of 1/n11/n_1. Equal sizes cause no problem because σ12/n+σ02/n\sigma_1^2/n + \sigma_0^2/n matches in both. Otherwise:

  • The smaller group is more dispersed (n1<n0n_1 < n_0, σ1>σ0\sigma_1 > \sigma_0): 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 5 %5\,\%.

InteractiveWhen permutation is not enough
Rejection rate under the true null (nominal 5%)
26.6 %5.5 %Mean differenceStudentizedpermuted statistic
  • nominal 5% level
  • Monte Carlo margin
P-value histogram: if the test is valid, it is flat (10% per bar)
  • permutation of DD (mean difference)
  • permutation of TT (studentized)
  • uniform (exact test)
10
40
3.00
Data shape
True variance of DD: σ12/n1+σ02/n0\sigma_1^2/n_1 + \sigma_0^2/n_00.925
Permutation distribution variance ≈σ12/n0+σ02/n1\approx \sigma_1^2/n_0 + \sigma_0^2/n_10.325
True / permutation ratio×2.85
Actual size, permutation of DD (1500 studies)26.6 %
Actual size, permutation of studentized TT5.5 %
Monte Carlo margin (95%) around 5%±1.1 points
The smaller group is more dispersed: the true variance of DD is 2.85 times the permutation variance. It over-rejects (26.6 % instead of 5%).
Means are equal: the null is true, so each rejection is false positive. Each configuration simulates 1500 studies with 199 permutations each. Left bars: rejection rate (nominal 5 %) for permuted mean difference (red) and permuted studentized Welch statistic (blue). Right: p-value histogram, flat for a valid test. Try 'Small and noisy': what is mean-difference rejection and what true-to-permutation variance ratio does theory predict? Switch to 'Large and noisy': the test becomes conservative. Equalize sizes and the difference disappears. Then use skewed data, still with n1=10n_1 = 10: does studentization fix everything?

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 ≈S2\approx S^2, so squared denominator of TT estimates S2(1/n1+1/n0)S^2(1/n_1 + 1/n_0), exactly Var⁡π(D∗)\Var_\pi(D^\ast): studentized permutation variance tends to one by construction and Hoeffding’s (1951) combinatorial CLT gives a standard-normal permutation limit. Under the true law, T→N(0,1)T \to \Normal(0,1) 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 n1=10n_1 = 10 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”.

[ ]Actual size of mean-difference and studentized permutationBrowser
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 (6 %6\,\% is compatible with 5 % within error). With the small noisy group (n1=10n_1 = 10), permutation of DD rejects 28.5 %28.5\,\%, nearly six times nominal, as variance ratio 2.852.85 predicted. With the large noisy group, DD permutation never rejects in these 400 studies: useless. Permuting TT yields 7.7 %7.7\,\% and 3.3 %3.3\,\%, 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.

[ ]Permuting an autocorrelated series: test size explodesBrowser
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 ±2\pm 2 points). With ρ=0\rho = 0 (independence) free permutation maintains 5 %; with ρ=0.5\rho = 0.5 it rejects 24 %24\,\% and with ρ=0.8\rho = 0.8 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 (b+1)/(m+1)(b+1)/(m+1). One detail: SciPy’s two-sided value doubles the smaller one-sided value (capped at 1), rather than counting ∣T∗∣≥∣T∣\abs{T^\ast} \ge \abs{T}; they coincide when the permutation distribution is symmetric, as here with n0=n1n_0 = n_1. The cell compares with our engine.

[ ]scipy.stats.permutation_test versus our engineBrowser
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 (Nn1)\binom{N}{n_1} 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 di∈{−1,0,+1}d_i \in \{-1, 0, +1\}. Ties (di=0d_i = 0) contribute nothing to ∑isidi\sum_i s_i d_i, and among ndn_d discordant examples the sum is 2U−nd2 U - n_d with U∼Bin⁡(nd,12)U \sim \Bin(n_d, \tfrac12) under the null: sign-flip testing of correct/incorrect outcomes is exactly McNemar’s exact binomial test. The cell checks this.

[ ]Sign flips on a benchmark: identical to exact McNemarBrowser
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 did_i on the chosen metric and flip signs. With many examples it approaches paired tt, with the advantage of not depending on normal differences.

[ ]Continuous per-example differences: sign flips versus paired tBrowser
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

ProofPermutation-test size is at most α
Prove: Let G\mathcal{G} be a finite transformation group with ∣G∣=M\abs{\mathcal{G}} = M such that under H0H_0, gX=dXg\vb{X} \overset{d}{=} \vb{X} for every g∈Gg \in \mathcal{G}. For statistic TT and p(x)=1M#{h∈G:T(hx)≥T(x)}p(\vb{x}) = \frac1M\#\{h \in \mathcal{G} : T(h\vb{x}) \ge T(\vb{x})\}, PH0(p(X)≤α)≤α\Pr_{H_0}(p(\vb{X}) \le \alpha) \le \alpha for every α∈[0,1]\alpha \in [0,1].
0
Fix data x\vb{x} and write th=T(hx)t_h = T(h\vb{x}) for h∈Gh \in \mathcal{G}. Use that G\mathcal{G} is a group: as hh runs over G\mathcal{G}, so does hghg for any gg.

Step 1 of 4. How is p(gx)p(g\vb{x}), the p-value of data reordered by gg, expressed using the tht_h?

NumericGetting all eight cups right by chance
In the lady's experiment with 8 cups (4 milk-first, 4 tea-first), she marks exactly 4 as milk-first. If she cannot tell and chooses randomly, what is the probability of correctly classifying all 8?
NumericCorrected p-value with no extreme permutations
In a Monte Carlo permutation test with m=999m = 999 random assignments, none (b=0b = 0) has a statistic at least as extreme as observed. What is corrected p-value (b+1)/(m+1)(b+1)/(m+1)?
NumericHow many permutations are needed?
An exact permutation p-value is near 0.050.05 and you want Monte Carlo estimator b/mb/m standard error at most 0.0010.001. How many permutations mm are needed (with p=0.05p = 0.05)?
CodeFisher's exact test for 2×2 tables
Complete fisher_p(tabla, alternativa), receiving a 2×22\times 2 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' (P(A≥a)\Pr(A \ge a)), 'menor' (P(A≤a)\Pr(A \le a)), or 'dos-colas' (sum of probabilities of tables no more likely than observed, relative tolerance 10−710^{-7}). 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.0
Shift+Enter to run
QuizChoosing the permutation group
Three analyses: (A) 30 patients' pressure before and after treatment; (B) a trial in 6 hospitals, with half of patients randomized to treatment within each; (C) 500 days of strategy returns, testing positive mean. Which statement about valid permutation groups is correct?
QuizWhen does over-rejection occur?
Equal means, independent groups. In which configuration does unstudentized mean-difference permutation reject more than 5 % of the time?

Summary

Key idea
A permutation test calibrates any statistic by recalculating under label reassignments the null declares indistinguishable: exact in finite samples without shape assumptions while those assignments are equally likely, but silently invalid when the null (equal means, dependence) does not imply exchangeability.
  • Exchangeability. If gX=dXg\vb{X} \overset{d}{=} \vb{X} for finite group G\mathcal{G} under H0H_0, p-value 1M#{h:T(hX)≥T(X)}\frac1M\#\{h : T(h\vb{X}) \ge T(\vb{X})\} satisfies P(p≤α)≤α\Pr(p \le \alpha) \le \alpha for any statistic. Choose it beforehand; it affects power, not level.
  • Monte Carlo. With mm random assignments the correct p-value is (b+1)/(m+1)(b+1)/(m+1), valid and never zero. b/mb/m is invalid. Standard error is p(1−p)/m\sqrt{p(1-p)/m}: report mm, seed, and if needed a Clopper–Pearson interval.
  • Fisher. Conditional permutation test on a 2×22\times 2 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 (1/701/70).
  • 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 δ\delta, {δ0:p(δ0)>α}\{\delta_0 : p(\delta_0) > \alpha\} covers with probability at least 1−α1 - \alpha; for mean difference endpoints are jumps of monotone step functions.
  • Failures. With equal means and unequal variances, permutation variance is σ12/n0+σ02/n1\sigma_1^2/n_0 + \sigma_0^2/n_1 instead of σ12/n1+σ02/n0\sigma_1^2/n_1 + \sigma_0^2/n_0; studentization (permuting Welch statistic) asymptotically fixes level. Under dependence permute independent units or blocks.