AI Wiki中文/EN

Permutation tests: which shuffles are legal?

置换检验

Enumerate exact group assignments, preserve ties and distinguish two-sided conventions and experimental designs.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

What would the labels look like under the null?

Six recorded scores are 1,2,3,4,5,6. Group A received 4,5,6; group B received 1,2,3. Their mean difference is 3. Instead of choosing a normal approximation, ask which other assignments of three observations to A would have been possible under the null. There are twenty. Only one gives a difference at least 3; two give an absolute difference at least 3.

The permission to exchange labels is the key assumption. Shuffling data is easy; justifying the shuffle is the statistical work. The permute project guide grounds the method in exchangeability: the allowed transformations leave the null distribution unchanged. Read p-values and probability axioms first.

Write down the legal assignments

For two independent samples from the same distribution under the null, pooled observations can be assigned to either group while preserving group sizes. Conditional on the pooled values, assignments to labeled observation indices are equally likely. With n observations and k in A, the statistic and assignment count are:

T(S)=1k∑i∈Sxi−1n−k∑i∉Sxi,∣S∣=(nk).T(S)=\frac{1}{k}\sum_{i\in S}x_i- \frac{1}{n-k}\sum_{i\notin S}x_i, \qquad |\mathcal S|=\binom nk.

The count binomial(n,k)=n!/[k!(n−k)!] chooses which k of n labeled units enter A.

Here S is a k-element set of indices, not a set of distinct score values. If two people both scored 1, they remain two people. Collapsing equal-valued assignments into a set without multiplicity changes the probabilities.

For the prespecified larger-A question, include every assignment whose statistic is at least the observed value:

pgreater=#{S∈S:T(S)≥T(Sobs)}(nk).p_{\mathrm{greater}}= \frac{\#\{S\in\mathcal S:T(S)\ge T(S_{\mathrm{obs}})\}} {\binom nk}.

The observed assignment is included. Thus exhaustive enumeration cannot return zero. Ties count as equally extreme and can make the attainable rejection rate conservative. If assignments are uniform under the null, ranking the observed statistic among these assignments gives a super-uniform tail p-value. This is exact calibration for the specified randomization model, not proof that the sample represents a wider population.

Two-sided is a definition, not a button

Our second option uses |T| as the statistic. It counts assignments with absolute mean difference at least the observed absolute difference. SciPy’s versioned manual instead defines its two-sided option by doubling the smaller one-sided p-value, capped at one. The conventions agree for some symmetric assignment distributions but need not agree in general.

The exercise below gives an asymmetric four-observation counterexample.

Randomization has to match the design

In a randomized experiment, uniformly assigning a fixed number of units to treatment justifies the same enumeration under the sharp null that treatment changes no unit’s outcome. A null of zero average effect alone does not generally make individual outcomes fixed under reassignment. With matched pairs, swap only within each pair; with clustered treatment assignment, randomize clusters. For unrelated observational groups, equal means with different distributions do not generally justify free label permutation.

If only B uniformly sampled assignments are used instead of all assignments, a common valid randomized construction counts b extreme draws and includes the observation:

pMC=b+1B+1.p_{\mathrm{MC}}=\frac{b+1}{B+1}.

This describes the standard random-permutation construction under its exchangeability conditions, not a universal correction for arbitrary resampling. The program below performs exhaustive enumeration and does not use this approximation. The versioned SciPy documentation explains the distinction and discusses floating-point ties.

Enumerate index sets with exact arithmetic

Run this complete Python 3.12 standard-library program. It supports nonempty rational-valued groups with at most twelve total observations. This small bound keeps exhaustive enumeration practical; the code intentionally has no hidden sampling fallback.

from fractions import Fraction as F
from itertools import combinations
from math import comb


def permutation_test(a, b, alternative='greater'):
    a, b = list(a), list(b)
    values = a+b; n = len(values); k = len(a)
    if not a or not b or n > 12:
        raise ValueError('nonempty groups, at most twelve total observations')
    if any(type(x) not in (int, F) for x in values):
        raise ValueError('rational observations required')
    if alternative not in ('greater', 'absolute'):
        raise ValueError('choose greater or absolute')
    values = list(map(F, values)); total = sum(values, F(0))
    def difference(indices):
        part = sum((values[i] for i in indices), F(0))
        return part/k - (total-part)/(n-k)
    observed = difference(range(k))
    threshold = observed if alternative == 'greater' else abs(observed)
    extreme = 0
    for indices in combinations(range(n), k):
        statistic = difference(indices)
        score = statistic if alternative == 'greater' else abs(statistic)
        extreme += score >= threshold
    count = comb(n,k)
    return observed, F(extreme,count), extreme, count


if __name__ == '__main__':
    for direction in ('greater','absolute'):
        print(direction, permutation_test([4,5,6],[1,2,3],direction))
    print('tied values:', permutation_test([1,1],[0,0]))
    print('unequal groups, absolute:', permutation_test([0],[1,3],'absolute'))
    print('all equal:', permutation_test([2,2],[2]))

Output:

greater (Fraction(3, 1), Fraction(1, 20), 1, 20)
absolute (Fraction(3, 1), Fraction(1, 10), 2, 20)
tied values: (Fraction(1, 1), Fraction(1, 6), 1, 6)
unequal groups, absolute: (Fraction(-2, 1), Fraction(2, 3), 2, 3)
all equal: (Fraction(0, 1), Fraction(1, 1), 3, 3)

The first result has one extreme assignment out of twenty; the absolute rule has two. For tied values (1,1) versus (0,0), there are six index assignments, not merely three possible group sums. The one-sided p-value is 1/6. When every observation equals 2, all statistics are zero and all assignments count, so p=1.

With M=binomial(n,k), the loop takes O(Mk) rational additions and uses O(n) working storage. It computes each assignment rather than storing a full null distribution. Rational arithmetic prevents a mathematically tied value from being missed through rounding; integer bit lengths still affect cost. This is an original enumerator, not a claim that SciPy was executed.

Exact computation can answer the wrong question

A permutation test does not remove confounding, selection bias or leakage. Preprocessing learned using outcomes may need to be repeated inside each valid permutation; holding a label-informed feature selection fixed can make the null comparison unfair. Multiple outcomes also create a multiple-testing problem.

Small assignment spaces limit resolution. With twenty assignments, our one-sided minimum is 1/20. More shuffles cannot create new independent observations or a finer exhaustive assignment space. Bootstrap resampling answers different questions: it usually samples observations with replacement to approximate sampling uncertainty, rather than retaining pooled values and moving labels under a null.

Check counts before trusting the p-value

  1. Why do two groups of three require twenty assignments rather than 720?

Answer 1: The statistic ignores order inside each group. Each of the binomial(6,3)=20 index subsets represents 3!×3! full permutations with the same statistic.

  1. What happens if all observations are equal?

Answer 2: All assignments tie the observed zero difference, giving p=1 for both implemented alternatives.

  1. For A=(1), B=(0,2,8), compare absolute and doubled-smaller-tail p-values.

Answer 3: The four differences are −11/3, −7/3, −1, 7. The observed −7/3 has absolute p=3/4. The smaller one-sided tail is 2/4, so doubling and capping gives 1. The conventions differ.

  1. In an approximate random-permutation test with B=999 and b=0, does no extreme draw prove p=0?

Answer 4: No. The stated plus-one construction gives 1/1000. This is distinct from the exhaustive result for the whole assignment space.

A design-aware route into resampling

The permute guide develops exchangeability and restricted designs; SciPy separates independent, paired-sample and pairing permutations in a practical API. Use those distinctions to read methods papers carefully: identify the null, the allowed transformations and whether the theorem is finite-sample or asymptotic.

A useful next project is to enumerate within-pair swaps and compare them with an intentionally incorrect unrestricted shuffle. Preserve the original pairs, report the two assignment spaces, and explain which one the experiment authorized. Continue with sampling bias to separate internal randomization from population representation.

Make a prediction, then check

In exhaustive enumeration, should the observed assignment be included?

Choose one answer

Learning objectives

  • Justify an assignment space from the null and design.
  • Count exact tails with ties and a specified extremeness rule.

Prerequisites & connections

Explore related knowledge →

References

  1. permute 0.2 — User Guide
    K. Jarrod Millman; Kellie Ottoboni; Philip B. Stark
  2. SciPy 1.14.1 — permutation_test
    SciPy developers

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-06 · Codex single-agent authored technical review: primary-source locations, explicit assumptions, exact/literal and numerical checks, and bilingual review; not independent human or second-agent review.

  • Single-agent authored technical review: cited primary-source locations, explicit assumptions, original derivations and examples, bilingual equations and four matching exercises. Not independent human or second-agent review.
  • Four focused CPython3.12.4 tests passed: literal reference cases, mathematical invariants or full finite-design calibration, invalid inputs and bilingual structure. Rational arithmetic is separated from floating logarithms. R/SciPy documentation was read without claiming those runtimes were executed.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

  • permute 0.2 — User Guide · User Guide exchangeability, index permutation invariance and conditional randomization calibration. No source example reproduced.
  • SciPy 1.14.1 — permutation_test · 1.14.1 Notes: independent partitions, paired restrictions, exact versus randomized plus-one p-values, alternative definitions and floating-point ties. API read, not executed.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.