Algorithmcore
Permutation test
Also called randomization test, Fisher-Pitman permutation test.
Get the null distribution of a statistic by recomputing it over permutations of the labels, which are exchangeable under the null. The test is exact at any sample size.
- Time
- Θ(b n) worstΘ(n · n!/(m! (n - m)!)) exact
- Space
- Θ(n) extra
- Where
- b = the number of random permutations; m = the size of the first group; n = the pooled sample size
- Model
- Real RAM
- Properties
- randomizedexactofflinerandomizediterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- R. A. Fisher, E. J. G. Pitman, 1935
A permutation test gets the null distribution of a test statistic from the data themselves. Under the null hypothesis some rearrangements of the data are equally likely, for example all ways to split a pooled sample into two groups of the given sizes. The test recomputes the statistic on each rearrangement and reports the fraction that is at least as extreme as the observed value. This p-value is exact for every sample size and every statistic, and a Monte Carlo version with random permutations and the p-value keeps the exact level.
In plain words
Seven mice get a new drug and nine do not. The treated mice live longer on average. Is the drug the reason, or did the lucky mice fall into the treated group by chance?
If the drug does nothing, the labels "treated" and "control" are only names. Each mouse would have lived the same time with the other label. So write each survival time on a card, shuffle the 16 cards, deal 7 into a "treated" pile and 9 into a "control" pile, and compute the difference of the averages. Do this for every possible deal, or for a few thousand random deals. If the real difference is larger than almost all of the shuffled differences, the labels matter, and the drug probably has an effect. If many shuffled deals give a difference as large as the real one, chance explains the data well.
The problem
Data. A pooled sample . In the two-sample case the first values come from group 1 and the other from group 2. In the paired case the data are differences .
Null hypothesis. The randomization hypothesis of Lehmann and Romano: there is a finite group of transformations of the data such that has the same distribution as for every under .
- Two samples: says that are exchangeable, for example independent and identically distributed with any common distribution. is the group of the permutations, and a statistic of the two groups depends only on which values fall in group 1, so it takes at most values.
- Paired data: says that each is symmetric about 0, independently. is the group of the sign changes .
- Independence of and in pairs : permute the values against the fixed values.
Statistic. Any function of the data for which large values are evidence against , for example the difference of the means . Use for a two-sided test.
P-value. The exact p-value is
The Monte Carlo p-value with independent uniform draws from is
The algorithm
PERMUTATION-TEST(z_1, ..., z_n, m, T, b) ▷ group 1 is z_1 .. z_m- 1
t ← T(z_1 .. z_m ; z_{m+1} .. z_n) - 2
c ← 0 - 3
for j ← 1 to b do - 4
w ← a uniform random permutation of z ▷ Fisher-Yates shuffle - 5
t_j ← T(w_1 .. w_m ; w_{m+1} .. w_n) - 6
if t_j ≥ t then c ← c + 1 - 7
return (1 + c) / (1 + b) EXACT-PERMUTATION-TEST(z_1, ..., z_n, m, T)- 8
c ← 0 - 9
for each set S ⊆ {1, ..., n} with |S| = m do - 10
if T(z_S ; z_{not S}) ≥ t then c ← c + 1 ▷ t from line L1 - 11
return c / C(n, m)
Line L4 uses a Fisher-Yates shuffle, which gives each of the orders probability , so each split has probability . Line L9 lists the splits once each, in lexicographic order of the index sets. Listing all permutations, as in generating all permutations, gives the same p-value, because each split appears times. The "+1" in line L7 counts the observed data as one of the permutations; it is what makes the Monte Carlo test valid. For a two-sided test, compare . With floating-point data, two splits with the same multiset of values can give statistics that differ in the last bit, so the code accepts in lines L6 and L10.
The paired version is the same with sign vectors in place of splits: line L4 draws each sign independently with probability , and line L9 lists the sign vectors.
Example
A trace. Take group 1 and group 2 , so , and splits. For a fixed and the difference of the means is an increasing function of the sum of group 1, so the test can rank the splits by that sum. The observed sum is 46 (line L1, difference of means ). The largest sums are 48 (), 46 (the observed split), then 45. Line L10 counts 2 splits, and line L11 returns . The two-sided p-value is .
The mouse data. Efron and Tibshirani (Table 2.1) give survival times in days for 7 treated mice, 94, 197, 16, 38, 99, 141, 23, and 9 controls, 52, 104, 146, 10, 51, 30, 40, 27, 46. The difference of the means is . Of the splits, 1613 give a difference at least as large, so the exact one-sided p-value is ; the two-sided value is . The Monte Carlo test with and random.Random(1) counted and returned . Its standard error is about , so the difference from the exact value is normal noise. The drug effect is not significant.
Darwin's plants. Darwin grew 15 pairs of Zea mays plants, one cross-fertilized and one self-fertilized in each pair. Fisher used the differences in height, in eighths of an inch: 49, , 8, 16, 6, 23, 28, 41, 14, 29, 56, 24, 75, 60, , with sum 314. Under each difference is symmetric about 0, so each of the sign vectors is equally likely. Exactly 1726 of them give , so the two-sided p-value is , the value that Fisher reported. The one-sided p-value is .
Correctness
The full proof is in proofs/correctness.md. Under the randomization hypothesis, the observed data and the transformed data have the same law. Condition on the orbit . Given the orbit, the observed point is uniform on it, so the rank of among the values is uniform, with ties broken against rejection. Hence for every , and the same bound holds without conditioning. For the Monte Carlo version, are exchangeable under , because given is a sample of uniform points of the orbit and is itself a uniform point. So the rank of among the values is uniform, and for every .
The bound is the true size, not only an upper bound, when is an integer and the values are distinct. The tests check both claims: all splits of an 8-point sample give exactly the size at , and 3000 Monte Carlo tests with on normal data and seed 11 rejected at in of cases.
Proof: The permutation test and its Monte Carlo version have exact levelfull
We use the pseudocode of the page. is a finite group of transformations of the sample space, with . The randomization hypothesis is that under the data and have the same distribution for every . For two samples, is the group of permutations of the coordinates and the hypothesis is exchangeability. For paired data, is the group of sign changes and the hypothesis is that the are independent and symmetric about 0. The statistic is a fixed function .
For a point define the exact p-value
Lemma (ranks). Let be real numbers and , which counts itself. Then for every .
Proof. Let . If is empty there is nothing to prove. Otherwise pick with the smallest value . Every has , so and .
Claim 1 (the algorithm computes ). In the two-sample case depends on only through the set of the indices that moves into the first group. Each such set arises from exactly permutations, so the fraction of permutations with equals the fraction of the sets, which lines L8 to L11 count. In the paired case the code lists the sign vectors directly.
Claim 2 (exact level). Under the randomization hypothesis, for every .
Proof. Let be uniform on and independent of . For each fixed , , so also , and it suffices to bound .
Fix . Because is a group, is the same multiset as for each . So , where is the rank count of the value among the values . By the lemma with ,
This holds for every . Since is independent of , averaging over gives .
If the values , , are distinct and is an integer, the set in the lemma has exactly elements, and the size is exactly . In general, a test that also rejects with a suitable probability when equals the boundary value has size exactly ; this is the randomized permutation test.
Claim 3 (the Monte Carlo p-value is valid). Let be independent and uniform on and independent of , and let . Under the randomization hypothesis, for every and every .
Proof. Let be uniform on , independent of and of the , and put . Since and the are independent of both, the tuple has the same law as . So the p-value has the same law when it is computed from , that is, from the values and for .
Condition on . The elements are independent and uniform on : given , each is uniform because is a bijection of , and the are independent of each other and of . So are independent and identically distributed given , and in particular exchangeable.
Let . The p-value is . By exchangeability for each , so with and the lemma,
This holds given for every , so it holds without conditioning.
The proof also shows why is not a valid p-value. For a continuous statistic, has probability under , so the rule "reject when " has size at least for every .
Claim 4 (cost). The Monte Carlo loop does shuffles of swaps each and evaluations of . The exact loop evaluates on splits. With the difference of the means, each evaluation costs , which gives and . Both keep one copy of the data, so the extra space is .
Complexity
Let be the cost of the statistic; for the difference of the means .
- Monte Carlo. Each of the rounds shuffles in and computes the statistic, so the time is for the mean difference. The space is for one copy of the data.
- Exact. splits at each, or sign vectors for the paired test. This is feasible up to about . A revolving-door order of the subsets changes one element per step and updates the sum in , which removes the factor .
- Integer data. For a sum statistic with integer values of total size , a dynamic program counts the subsets of size with each sum in time, which is much less than for large balanced groups.
The Monte Carlo p-value estimates the exact with standard error , so gives two correct decimals for near .
Properties
- Exact level. for every sample size, every statistic and every . No normal or large-sample approximation is used.
- Conditional. The test is conditional on the observed set of values (the order statistics in the two-sample case), which is a sufficient statistic under . The null distribution changes from one data set to the next.
- Discrete. The p-value takes only the values , so the size is at most and can be below it. A randomized test that rejects with a suitable probability at the boundary value has size exactly .
- Any statistic. The level does not depend on the choice of ; only the power does. Choose the statistic for the alternative you care about.
- Power. Hoeffding (1952) showed that the permutation test based on the mean difference has asymptotically the same power as the two-sample t-test under normality, so little is lost when the t-test is right.
Variants and improvements
- Sign-flip test. For paired data or a one-sample test of symmetry, flip signs instead of permuting labels, as in the Darwin example. The sign test and the Wilcoxon signed-rank test are sign-flip tests on signs and on signed ranks.
- Rank tests. The Mann-Whitney U test is the permutation test with the rank sum as the statistic. Its null law does not depend on the data, so it can be tabled.
- Tests of independence. Permute the values against the values and recompute a correlation. With ranks this is Spearman's rank correlation test; on a table it is Fisher's exact test.
- Randomization tests in experiments. In a randomized experiment, the sharp null hypothesis of no effect on any unit fixes all potential outcomes. Then the known randomization scheme, not a model, gives the null distribution, and the units need not be a random sample.
- Studentized statistics. With unequal variances, the permutation distribution of a studentized statistic, such as Welch's , is asymptotically valid for equal means, and it stays exact under full exchangeability (Janssen 1997; Chung and Romano 2013).
- Multiple testing. Permuting whole rows keeps the dependence between many statistics. The Westfall-Young procedure uses the permutation law of the maximum statistic to control the family-wise error rate.
- Comparison with the bootstrap. A bootstrap test resamples with replacement from an estimate of the null distribution and is only approximate. The permutation test resamples without replacement and is exact, but it needs a null hypothesis that makes the data exchangeable. See the bootstrap method.
When to use it
Use it when the null hypothesis states that the labels do not matter: two groups that come from the same distribution, a randomized treatment with no effect, or two variables that are independent. Use it when the sample is small or the distribution is skewed and you do not trust a t-test or a normal approximation, and when the statistic has no known null distribution, such as a difference of medians or of trimmed means. If you want a confidence interval for an effect, invert a family of shifted permutation tests (test-interval duality), or use the bootstrap.
Pitfalls
- The wrong null hypothesis. The test checks that the distributions are equal, not that the means are equal. With group 1 of size 5 and standard deviation 4 and group 2 of size 20 and standard deviation 1, both with mean 0, the two-sided test of the mean difference at level rejected in of 1000 runs (, seed 21). Use a studentized statistic, or use Welch's t-test, when the variances can differ.
- A p-value of 0. The estimate can be 0 and is not a valid p-value: it rejects too often for small . Use (Phipson and Smyth 2010).
- Data that are not exchangeable. Time series, clustered data and paired data are not exchangeable as single values. Permute whole clusters, flip signs within pairs, or use a block method. A plain permutation of positively autocorrelated data can give a size far above .
- A biased shuffle. Swapping each position with a uniform position in does not give uniform permutations. Use the Fisher-Yates shuffle.
- Ties in floating point. The observed split must count as "at least as extreme" as itself. Compare with a small tolerance, or with exact arithmetic, as the code does.
- Reusing the same random permutations. For one test this is fine. But to compare the power of two statistics, use the same permutations for both, or the comparison has extra noise.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/permutation-test/. The authors are listed in prov/KSN49K.jsonl.
import itertools
import math
import random
from fractions import Fraction
from typing import Callable, Sequence
ALTERNATIVES = ("greater", "less", "two-sided")
Statistic = Callable[[Sequence, Sequence], float]
def mean_difference(x: Sequence, y: Sequence):
"""The mean of x minus the mean of y. Exact when the values are int or Fraction."""
sx, sy = sum(x), sum(y)
if all(isinstance(v, (int, Fraction)) for v in (sx, sy)):
return Fraction(sx) / len(x) - Fraction(sy) / len(y)
return sx / len(x) - sy / len(y)
def _exact(v) -> bool:
return isinstance(v, (int, Fraction))
def _at_least_as_extreme(t, t_obs, alternative: str) -> bool:
"""t is at least as extreme as t_obs. Floats get a small relative tolerance,
because the same split can give a statistic that differs in the last bit."""
if alternative == "two-sided":
t, t_obs = abs(t), abs(t_obs)
elif alternative == "less":
t, t_obs = -t, -t_obs
if _exact(t) and _exact(t_obs):
return t >= t_obs
return t >= t_obs - 1e-9 * max(1.0, abs(t_obs))
def permutation_test(
x: Sequence,
y: Sequence,
statistic: Statistic = mean_difference,
alternative: str = "greater",
b: int | None = None,
rng: random.Random | None = None,
) -> Fraction:
"""Two-sample permutation test of H0: the pooled values are exchangeable.
With b = None the test is exact: it lists all C(N, m) ways to choose the
first group and returns the fraction of splits whose statistic is at least
as extreme as the observed one. With an integer b it draws b uniform random
permutations with rng and returns the Monte Carlo p-value (1 + c)/(1 + b).
"""
if alternative not in ALTERNATIVES:
raise ValueError("unknown alternative")
z = list(x) + list(y)
n_total, m = len(z), len(x)
if m == 0 or m == n_total:
raise ValueError("both groups must be non-empty")
t_obs = statistic(z[:m], z[m:]) # @line L1
if b is None:
count = 0 # @line L8
for chosen in itertools.combinations(range(n_total), m): # @line L9
inside = set(chosen)
first = [z[i] for i in chosen]
second = [z[i] for i in range(n_total) if i not in inside]
if _at_least_as_extreme(statistic(first, second), t_obs, alternative): # @line L10
count += 1
return Fraction(count, math.comb(n_total, m)) # @line L11
if rng is None:
raise ValueError("pass rng=random.Random(seed) for the Monte Carlo test")
if b < 1:
raise ValueError("b must be at least 1")
count = 0 # @line L2
for _ in range(b): # @line L3
w = z[:]
rng.shuffle(w) # @line L4
t = statistic(w[:m], w[m:]) # @line L5
if _at_least_as_extreme(t, t_obs, alternative): # @line L6
count += 1
return Fraction(1 + count, 1 + b) # @line L7
def sign_flip_test(
d: Sequence,
alternative: str = "two-sided",
b: int | None = None,
rng: random.Random | None = None,
) -> Fraction:
"""Paired permutation test of H0: each difference is symmetric about 0.
The statistic is the sum of the differences. With b = None all 2^n sign
vectors are listed; with an integer b, b random sign vectors are drawn and
the p-value is (1 + c)/(1 + b).
"""
if alternative not in ALTERNATIVES:
raise ValueError("unknown alternative")
d = list(d)
t_obs = sum(d)
if b is None:
count = 0
for signs in itertools.product((1, -1), repeat=len(d)):
if _at_least_as_extreme(sum(s * v for s, v in zip(signs, d)), t_obs, alternative):
count += 1
return Fraction(count, 2 ** len(d))
if rng is None:
raise ValueError("pass rng=random.Random(seed) for the Monte Carlo test")
count = 0
for _ in range(b):
t = sum(v if rng.random() < 0.5 else -v for v in d)
if _at_least_as_extreme(t, t_obs, alternative):
count += 1
return Fraction(1 + count, 1 + b)
permutation_test.py 8 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/permutation-test/. The authors are listed in prov/KSN49K.jsonl.
"""Entry point named after the slug. The code lives in permutation_core.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""
from permutation_core import ALTERNATIVES, mean_difference, permutation_test, sign_flip_test
__all__ = ["ALTERNATIVES", "mean_difference", "permutation_test", "sign_flip_test"]
test_permutation_test.py 130 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/permutation-test/. The authors are listed in prov/KSN49K.jsonl.
import itertools
import math
import random
from fractions import Fraction
import pytest
from permutation_test import mean_difference, permutation_test, sign_flip_test
# Darwin's Zea mays data from Fisher, The Design of Experiments, Section 21:
# crossed minus self-fertilized height in each of 15 pairs, in eighths of an inch.
DARWIN = [49, -67, 8, 16, 6, 23, 28, 41, 14, 29, 56, 24, 75, 60, -48]
# Survival times in days of 16 mice, Efron and Tibshirani (1993), Table 2.1.
TREATMENT = [94, 197, 16, 38, 99, 141, 23]
CONTROL = [52, 104, 146, 10, 51, 30, 40, 27, 46]
def all_permutations_p(x, y, alternative):
"""Brute force: the fraction of all N! orderings whose statistic is at least as extreme."""
z, m = list(x) + list(y), len(x)
t_obs = mean_difference(z[:m], z[m:])
hits = total = 0
for w in itertools.permutations(z):
t = mean_difference(w[:m], w[m:])
if alternative == "greater":
hits += t >= t_obs
elif alternative == "less":
hits += t <= t_obs
else:
hits += abs(t) >= abs(t_obs)
total += 1
return Fraction(hits, total)
@pytest.mark.parametrize("alternative", ["greater", "less", "two-sided"])
def test_exact_matches_all_permutations(alternative):
rng = random.Random(3)
for n_total in range(2, 8):
for m in range(1, n_total):
z = [Fraction(rng.randint(-6, 6), rng.randint(1, 3)) for _ in range(n_total)]
got = permutation_test(z[:m], z[m:], alternative=alternative)
assert got == all_permutations_p(z[:m], z[m:], alternative)
def test_darwin_sign_flip():
assert sum(DARWIN) == 314
assert sign_flip_test(DARWIN) == Fraction(1726, 32768)
assert sign_flip_test(DARWIN, alternative="greater") == Fraction(863, 32768)
def test_sign_flip_brute_force():
rng = random.Random(5)
for n in range(1, 9):
d = [rng.randint(-5, 5) for _ in range(n)]
hits = sum(abs(sum(s * v for s, v in zip(signs, d))) >= abs(sum(d))
for signs in itertools.product((1, -1), repeat=n))
assert sign_flip_test(d) == Fraction(hits, 2**n)
def test_mouse_data_exact():
assert mean_difference(TREATMENT, CONTROL) == Fraction(1930, 63)
assert permutation_test(TREATMENT, CONTROL) == Fraction(1613, 11440)
assert permutation_test(TREATMENT, CONTROL, alternative="two-sided") == Fraction(3184, 11440)
def test_monte_carlo_formula():
b = 1000
got = permutation_test(TREATMENT, CONTROL, b=b, rng=random.Random(1))
rng = random.Random(1)
z, m = TREATMENT + CONTROL, len(TREATMENT)
t_obs = mean_difference(TREATMENT, CONTROL)
count = 0
for _ in range(b):
w = z[:]
rng.shuffle(w)
count += mean_difference(w[:m], w[m:]) >= t_obs
assert got == Fraction(1 + count, 1 + b)
assert got == Fraction(134, 1001)
assert got > 0
def test_exact_level_by_enumeration():
"""Under H0 every split is equally likely; P(p <= alpha) <= alpha for every alpha."""
z = [Fraction(v) for v in (3, 8, 1, 9, 4, 12, 7, 5)]
m = 4
splits = list(itertools.combinations(range(8), m))
pvals = []
for chosen in splits:
x = [z[i] for i in chosen]
y = [z[i] for i in range(8) if i not in chosen]
pvals.append(permutation_test(x, y))
k = len(splits)
assert k == math.comb(8, 4)
for alpha in (Fraction(1, 70), Fraction(1, 20), Fraction(1, 10), Fraction(1, 4), Fraction(1, 2)):
size = Fraction(sum(p <= alpha for p in pvals), k)
assert size <= alpha
# Distinct sums except for ties: the size at an attainable level is exact.
assert Fraction(sum(p <= Fraction(1, 70) for p in pvals), k) == Fraction(1, 70)
def test_monte_carlo_size():
rng = random.Random(11)
r, b, alpha = 3000, 19, 0.05
rejections = 0
for _ in range(r):
z = [rng.gauss(0.0, 1.0) for _ in range(10)]
p = permutation_test(z[:5], z[5:], b=b, rng=rng)
rejections += p <= alpha
rate = rejections / r
assert rate <= alpha + 4 * math.sqrt(alpha * (1 - alpha) / r)
assert rate >= alpha - 4 * math.sqrt(alpha * (1 - alpha) / r) - 1 / math.comb(10, 5)
def test_float_tolerance_keeps_observed_split():
x, y = [0.1, 0.2, 0.3], [0.7, 0.05, 0.4]
p = permutation_test(x, y, alternative="two-sided")
assert p >= Fraction(1, math.comb(6, 3))
def test_errors():
with pytest.raises(ValueError):
permutation_test([1], [2], alternative="bigger")
with pytest.raises(ValueError):
permutation_test([], [1, 2])
with pytest.raises(ValueError):
permutation_test([1], [2], b=10)
History
R. A. Fisher gave the idea in The Design of Experiments (1935). In Section 21 he took Darwin's 15 pairs of plants, assumed under the null hypothesis that each difference was equally likely to have either sign, and counted that 1726 of the 32768 sign combinations gave a total at least as large as the observed 314 in absolute value. The result, , was close to the -test's value, and Fisher used it to argue that the t-test is a good approximation to the exact test. E. J. G. Pitman (1937) gave the two-sample test for samples from any populations and computed the moments of its permutation distribution. Hoeffding (1952) proved the large-sample equivalence with the t-test. With fast computers, the Monte Carlo version became a standard method; Phipson and Smyth (2010) showed why the "+1" correction is necessary.
References
- R. A. Fisher, The Design of Experiments, Oliver and Boyd, Edinburgh, 1935, Chapter III, Section 21 (the test of a wider hypothesis on Darwin's Zea mays data, 1726 of 32768 sign combinations)
- E. J. G. Pitman, Significance tests which may be applied to samples from any populations, Supplement to the Journal of the Royal Statistical Society 4(1), 1937, pp. 119 to 130 (the two-sample test on all divisions of the pooled sample, and its moments)
- E. L. Lehmann and Joseph P. Romano, Testing Statistical Hypotheses, third edition, Springer, 2005, Section 15.2 (permutation and randomization tests, the randomization hypothesis and the exact level)
- Bradley Efron and Robert J. Tibshirani, An Introduction to the Bootstrap, Chapman and Hall, 1993, Chapter 15 (permutation tests, on the mouse survival data of Table 2.1)
- Belinda Phipson and Gordon K. Smyth, Permutation p-values should never be zero, Statistical Applications in Genetics and Molecular Biology 9(1), 2010, Article 39 (the Monte Carlo p-value (1 + c)/(1 + b) and why c/b is not valid)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag KSN49K Edit this page History Report an error Markdown