Algorithmcore
Kruskal-Wallis test
Also called Kruskal-Wallis H test, one-way ANOVA on ranks.
Extends the Mann-Whitney test to k groups by comparing the mean ranks of the groups in the pooled sample. The statistic is roughly chi-squared with k - 1 degrees of freedom.
- Time
- Θ(N log N) worst · best
- Space
- Θ(N) extra
- Where
- N = the total number of observations; k = the number of groups
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- William H. Kruskal, W. Allen Wallis, 1952
The Kruskal-Wallis test compares independent groups. It ranks all observations together, computes the mean rank of each group, and measures how far these means are from the overall mean rank . The statistic is the one-way analysis of variance F idea applied to ranks: up to a constant, it is the between-group sum of squares of the ranks. Under the null hypothesis that all groups come from one distribution, is approximately chi-square with degrees of freedom; its exact law, given the ranks, comes from counting all ways to split the ranks into groups of the given sizes. For it is the two-sided Mann-Whitney test.
In plain words
Several groups of students learn by different methods and then take one test. Put all the scores in one list, sort it, and give each student a place number. If the methods do not matter, each group should get a fair mix of low and high place numbers, so the average place number of every group should be near the middle.
The test adds up how far each group's average place is from the middle, giving bigger groups more weight. A large total means some group sits mostly at the top or the bottom of the list. The test then asks how often a total this large would appear if the group labels were handed out at random.
The problem
Model. There are groups. Group has observations , independent with distribution , and the groups are independent. .
Hypotheses. : . The alternative is that the are not all equal. The test is designed for, and consistent against, alternatives where some group tends to give larger or smaller values than the others, such as a location shift with not all equal.
Statistic. Rank the pooled sample from to , with midranks for ties. Let be the rank sum and the mean rank of group . Then
and the tie-corrected statistic is with , where are the sizes of the tie groups. With midranks, , where and are the between-group and total sums of squares of the ranks.
Null distribution. Under the pooled sample is exchangeable, so given the pooled values every split of the positions into groups of sizes has probability . This conditional law of is exact. As , converges in law to chi-square with degrees of freedom, with or without ties (asymptotic).
P-values. The test is one-sided in : large values are evidence against . The asymptotic p-value is . The exact p-value is the share of splits whose is at least the observed value. There is no two-sided version; already measures departures in every direction.
Rejection rule and size. Reject at level when . The exact p-value gives size at most . The chi-square p-value is only approximate: for three groups of 3 the exact 5% critical value is against the chi-square value , and , so the chi-square test is conservative there.
Sensitivity and power. For a location shift the efficiency against one-way ANOVA is for normal errors and at least for every continuous law, as for the Mann-Whitney test. A Monte Carlo run with three groups of 10, a shift of 1 in one group, samples per law and gave power for the Kruskal-Wallis test against for ANOVA with normal errors (seed 41), and against with Cauchy errors (seed 42).
The algorithm
KRUSKAL-WALLIS(groups X_1, ..., X_k, method)- 1
r ← midranks of the pooled sample, computed after one sort - 2
R_i ← sum of r over group i, for i = 1, ..., k - 3
H' ← 12 / (N(N + 1)) · (R_1^2 / n_1 + ... + R_k^2 / n_k) - 3(N + 1) - 4
C ← 1 - Σ_j (t_j^3 - t_j) / (N^3 - N); H ← H' / C - 5
if method = asymptotic then return H, P(χ²_{k-1} ≥ H) - 6
count all splits of the pooled ranks into groups of sizes n_1, ..., n_k, by their rank sums - 7
A ← number of splits with Σ_i R_i^2 / n_i ≥ the observed value - 8
return H, A · n_1! ··· n_k! / N!
The code computes as an exact fraction from doubled midranks, so it has no rounding error, and evaluates the chi-square tail with the shared stdist.py. For the exact method, line L6 is a dynamic program over the pooled values: its state is the number of values placed in each group so far and the doubled rank sum of each group. Given the tie pattern, is an increasing function of , so line L7 compares the integer with , which is exact.
Example
Three groups. Take , and , so . The pooled ranks are for , for and for . The rank sums are , and , and they add up to . Line L3 gives
There are no ties, so . The chi-square tail with 2 degrees of freedom gives . The exact count over all splits gives , three times smaller. One-way ANOVA on the raw values gives and .
Ties. For the groups , then , then , the tie correction gives . The chi-square p-value is and the exact conditional p-value is .
Two groups. For and , the Kruskal-Wallis statistic is , which is the square of the Mann-Whitney without the continuity correction.
Correctness
The proof is in proofs/correctness.md. The two expressions for agree because . With midranks the total sum of squares of the ranks is , so dividing by gives . Under , exchangeability makes every split of the positions equally likely given the pooled values, so the exact p-value is a tail probability of a discrete law and is valid. The chi-square limit follows from the multivariate central limit theorem for the vector of mean ranks, whose covariance has rank .
Proof: The Kruskal-Wallis statistic, its exact conditional p-value, and why both are validfull
We use the pseudocode of the page. The pooled sample has values with midranks (line L1), group has size and rank sum (line L2), and .
Claim 1 (the two forms of ). .
Proof. Midranks keep the total rank sum: , because replacing the ranks of a tie group by their mean does not change their sum. Expand: . Multiply by .
Claim 2 (the tie correction). With midranks, , so with , whenever .
Proof. Without ties . A tie group covering ranks has mean . Replacing these ranks by keeps their sum and lowers by . So . Then . If all values are tied, and the code returns .
Claim 3 (the null law). Under , conditional on the multiset of pooled values, the assignment of the sorted positions to the groups is uniform over the splits with the given sizes.
Proof. Under the observations are independent with one law, so their joint law is invariant under permutations of the observations. Given the multiset of values, every way of placing the observations in the sorted slots that is consistent with it is equally likely, so the set of slots of each group is a uniform split. The midranks depend only on the multiset.
Claim 4 (the dynamic program). After line L6 has processed the first pooled values, the count stored for the state (sizes , doubled rank sums ) is the number of ways to assign these values to the groups so that group gets of them with doubled rank sum , and .
Proof. Induction on . At only the empty assignment exists. Each assignment of the first values extends in one way for each group with , adding 1 to and the doubled rank of value to ; the code makes exactly these moves and adds the counts. At every state has , and the code sums the counts over the sizes to get the number of splits for each vector of rank sums.
Claim 5 (the ordering). Given the tie pattern, is a strictly increasing function of , and exactly when the integer is at least its observed value, where .
Proof. By Claim 1, with fixed by the tie pattern. Multiplying by the positive integer keeps the order and makes every term an integer, because divides .
Claim 6 (validity of the exact p-value). For every , .
Proof. By Claims 3 to 5, line L8 returns under the uniform law of splits, given the pooled values. The set of values with is empty or has a least element , and the conditional probability of rejection is . Averaging over the pooled values keeps the bound.
The chi-square limit (the asymptotic p-value). Under the uniform law of splits without ties, , and for , from sampling without replacement. So the vector has covariance with , a projection of rank , and . When every with bounded away from 0, the central limit theorem for linear rank statistics (Hájek's theorem for sampling without replacement) makes asymptotically normal with this covariance, and the squared length of such a vector is . With ties the same argument applies to midranks with the variance multiplied by , which is why is used. The page's Monte Carlo runs show the size of the chi-square test approaching as the groups grow. This part gives an approximation, not a bound, and the page says so.
Cost. Lines L1 to L4 cost one sort and further work. The exact branch keeps at most states, because the last group's size and rank sum are fixed by the others, and each of the steps updates each state in at most ways.
Complexity
Lines L1 to L4 sort once and then scan, so the asymptotic test costs time and space, plus a fixed number of steps for the chi-square tail. The exact count of line L6 is much more expensive. After the first values, the sizes placed so far sum to and the rank sums add up to a known total, so the last group is determined by the others, and the number of states is at most . Each value updates each state in ways, so the time is , polynomial in for fixed . For the example with it took s of CPU time.
Properties
- Distribution-free. Given the tie pattern, the exact null law depends only on the group sizes.
- Invariant. does not change under an increasing transformation of the data.
- Two groups. For , , where is the standardized Mann-Whitney statistic with the tie-corrected variance and no continuity correction.
- Chi-square accuracy. Monte Carlo runs with normal data and samples gave chi-square sizes at of for three groups of 3 (seed 31), for three groups of 5 (seed 32) and for three groups of 10 (seed 33).
- Robust power. With Cauchy errors and three groups of 10, the test kept power for a shift of 1 while ANOVA had (Monte Carlo, , seed 42).
Variants and improvements
- Exact and Monte Carlo p-values. For small groups use the exact count; when it is too large, sample random splits and report , a valid permutation test p-value.
- Follow-up comparisons. A significant says that some groups differ, not which. Dunn's test compares mean ranks of pairs with the pooled variance; pairwise Mann-Whitney tests need a multiple-comparison correction such as Bonferroni. Tukey's method for means is Tukey HSD.
- Ordered alternatives. When the groups have a natural order, the Jonckheere-Terpstra test, which adds Mann-Whitney counts over ordered pairs of groups, has more power against monotone trends.
- Blocks. For a randomized block design, where observations are related within blocks, use the Friedman test.
- The F approximation. Running ANOVA on the ranks gives an F statistic that is a monotone function of ; its F p-value is another approximation to the same exact law.
When to use it
Use it to compare three or more independent groups when the data are ordinal, skewed or contain outliers, and the question is whether some group tends to give larger values. When the groups are close to normal with equal variances, ANOVA has slightly more power. For two groups use the Mann-Whitney test directly, which also has one-sided versions.
Pitfalls
- The chi-square approximation at small sizes. For three groups of 3 the chi-square test had size in the Monte Carlo run, and for the example with it gave against the exact . Use the exact count when the groups are small.
- Not a test of medians. As for the Mann-Whitney test, groups with equal medians but different shapes can give large , and groups with different spreads but do not control the size.
- Missing tie correction. Without dividing by the statistic is too small and the test conservative.
- Related groups. Measurements on the same subjects under several conditions are not independent groups; use the Friedman test.
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/kruskal-wallis-test/. The authors are listed in prov/DCECK4.jsonl.
import math
from fractions import Fraction
from stdist import chi2_sf
def doubled_midranks(values: list[float]) -> list[int]:
"""Return 2 x (midrank of each value), in input order. Doubling keeps midranks integers."""
n = len(values)
order = sorted(range(n), key=values.__getitem__)
r2 = [0] * n
i = 0
while i < n:
j = i
while j + 1 < n and values[order[j + 1]] == values[order[i]]:
j += 1
for t in range(i, j + 1):
r2[order[t]] = i + j + 2 # 2 x the mean of the ranks i + 1, ..., j + 1
i = j + 1
return r2
def tie_sizes(values: list[float]) -> list[int]:
"""Sizes of the groups of equal values."""
counts: dict[float, int] = {}
for v in values:
counts[v] = counts.get(v, 0) + 1
return list(counts.values())
def h_statistic(groups: list[list[float]]) -> Fraction:
"""The tie-corrected Kruskal-Wallis H as an exact Fraction (the inputs are compared only)."""
sizes = [len(g) for g in groups]
big_n = sum(sizes)
pooled = [v for g in groups for v in g]
r2 = doubled_midranks(pooled) # @line L1
sums, start = [], 0
for size in sizes: # @line L2
sums.append(Fraction(sum(r2[start:start + size]), 2))
start += size
h = Fraction(12, big_n * (big_n + 1)) * sum(s * s / size for s, size in zip(sums, sizes))
h -= 3 * (big_n + 1) # @line L3
c = 1 - Fraction(sum(t**3 - t for t in tie_sizes(pooled)), big_n**3 - big_n) # @line L4
return h / c if c > 0 else Fraction(0)
def labeling_counts(r2: list[int], sizes: list[int]) -> dict[tuple[int, ...], int]:
"""Number of ways to split the pooled doubled ranks into groups of the given sizes,
by the vector of doubled rank sums of the groups. A DP over the pooled values whose
state is (group sizes filled so far, rank sums so far)."""
k = len(sizes)
states: dict[tuple[tuple[int, ...], tuple[int, ...]], int] = {((0,) * k, (0,) * k): 1}
for r in r2:
nxt: dict[tuple[tuple[int, ...], tuple[int, ...]], int] = {}
for (filled, sums), cnt in states.items():
for i in range(k):
if filled[i] < sizes[i]:
key = (filled[:i] + (filled[i] + 1,) + filled[i + 1:],
sums[:i] + (sums[i] + r,) + sums[i + 1:])
nxt[key] = nxt.get(key, 0) + cnt
states = nxt
out: dict[tuple[int, ...], int] = {}
for (_, sums), cnt in states.items():
out[sums] = out.get(sums, 0) + cnt
return out
def kruskal_wallis(
groups: list[list[float]], method: str = "asymptotic", exact: bool = False
) -> tuple[float, float | Fraction]:
"""Kruskal-Wallis test of H0: the k groups come from the same distribution.
Returns (H, p). method "asymptotic" uses the upper tail of chi-square with
k - 1 degrees of freedom. method "exact" counts every split of the pooled
ranks into groups of the given sizes (the permutation null, exact and
conditional on the ties); the p-value is the share of splits whose
sum of R_i^2 / n_i is at least the observed one. exact=True returns a Fraction.
"""
if len(groups) < 2 or any(len(g) == 0 for g in groups):
raise ValueError("need at least two nonempty groups")
if method not in ("asymptotic", "exact"):
raise ValueError("unknown method")
h = h_statistic(groups)
k = len(groups)
if method == "asymptotic": # @line L5
return float(h), chi2_sf(float(h), k - 1)
sizes = [len(g) for g in groups]
pooled = [v for g in groups for v in g]
r2 = doubled_midranks(pooled)
lcm = math.lcm(*sizes)
def score(sums: tuple[int, ...]) -> int:
# (4 lcm) x sum R_i^2 / n_i, an integer, increasing in H.
return sum(s * s * (lcm // size) for s, size in zip(sums, sizes))
observed, start = [], 0
for size in sizes:
observed.append(sum(r2[start:start + size]))
start += size
target = score(tuple(observed))
counts = labeling_counts(r2, sizes) # @line L6
hits = sum(cnt for sums, cnt in counts.items() if score(sums) >= target) # @line L7
total = math.factorial(sum(sizes))
for size in sizes:
total //= math.factorial(size)
p = Fraction(hits, total)
return float(h), (p if exact else float(p)) # @line L8
stdist.py 238 lines
# SPDX-License-Identifier: MIT
# Shared helper of the pe1 statistics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Normal, chi-square, t and F distribution functions in the standard library.
The incomplete gamma and beta functions return a lower tail and an upper
tail, and each tail is computed directly where it is small, so an upper tail
such as chi2_sf(200, 3) does not come from 1 - cdf and does not cancel.
Quantiles use a safeguarded bisection on the CDF (lower half) or on the upper
tail (upper half); the bracket shrinks until floating point stops it, so the
probability error is that of the CDF, below 1e-12 for moderate parameters.
"""
import math
from statistics import NormalDist
_STD = NormalDist()
_EPS = 1e-16
_TINY = 1e-300
_MAXIT = 10000
def norm_cdf(x: float) -> float:
"""P(Z <= x) for a standard normal Z."""
return 0.5 * math.erfc(-x / math.sqrt(2.0))
def norm_sf(x: float) -> float:
"""P(Z > x), computed with erfc, so it is accurate for large x."""
return 0.5 * math.erfc(x / math.sqrt(2.0))
def norm_ppf(p: float) -> float:
"""The lower p-quantile z_p of the standard normal, 0 < p < 1."""
if not 0.0 < p < 1.0:
raise ValueError("p must be in (0, 1)")
return _STD.inv_cdf(p)
def _gamma_tails(a: float, x: float) -> tuple[float, float]:
"""(P(a, x), Q(a, x)), the regularized lower and upper incomplete gamma."""
if a <= 0.0 or x < 0.0:
raise ValueError("need a > 0 and x >= 0")
if x == 0.0:
return 0.0, 1.0
if math.isinf(x):
return 1.0, 0.0
front = math.exp(-x + a * math.log(x) - math.lgamma(a))
if x < a + 1.0:
# Series: P = front * sum_{j >= 0} x^j / (a (a + 1) ... (a + j)).
ap, term = a, 1.0 / a
total = term
for _ in range(_MAXIT):
ap += 1.0
term *= x / ap
total += term
if abs(term) < abs(total) * _EPS:
break
p = front * total
return p, 1.0 - p
# Continued fraction for Q, modified Lentz.
b = x + 1.0 - a
c = 1.0 / _TINY
d = 1.0 / b
h = d
for i in range(1, _MAXIT):
an = -i * (i - a)
b += 2.0
d = an * d + b
if abs(d) < _TINY:
d = _TINY
c = b + an / c
if abs(c) < _TINY:
c = _TINY
d = 1.0 / d
step = d * c
h *= step
if abs(step - 1.0) < _EPS:
break
q = front * h
return 1.0 - q, q
def gamma_p(a: float, x: float) -> float:
"""Regularized lower incomplete gamma P(a, x)."""
return _gamma_tails(a, x)[0]
def gamma_q(a: float, x: float) -> float:
"""Regularized upper incomplete gamma Q(a, x) = 1 - P(a, x)."""
return _gamma_tails(a, x)[1]
def _beta_cf(a: float, b: float, x: float) -> float:
"""The continued fraction of I_x(a, b), modified Lentz."""
qab, qap, qam = a + b, a + 1.0, a - 1.0
c = 1.0
d = 1.0 - qab * x / qap
if abs(d) < _TINY:
d = _TINY
d = 1.0 / d
h = d
for m in range(1, _MAXIT):
m2 = 2 * m
aa = m * (b - m) * x / ((qam + m2) * (a + m2))
d = 1.0 + aa * d
if abs(d) < _TINY:
d = _TINY
c = 1.0 + aa / c
if abs(c) < _TINY:
c = _TINY
d = 1.0 / d
h *= d * c
aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
d = 1.0 + aa * d
if abs(d) < _TINY:
d = _TINY
c = 1.0 + aa / c
if abs(c) < _TINY:
c = _TINY
d = 1.0 / d
step = d * c
h *= step
if abs(step - 1.0) < _EPS:
break
return h
def _beta_tails(a: float, b: float, x: float, y: float | None = None) -> tuple[float, float]:
"""(I_x(a, b), 1 - I_x(a, b)), each computed directly where it is small.
y is 1 - x; pass it when it is known more accurately than 1 - x.
"""
if a <= 0.0 or b <= 0.0:
raise ValueError("need a > 0 and b > 0")
if y is None:
y = 1.0 - x
if x <= 0.0:
return 0.0, 1.0
if y <= 0.0:
return 1.0, 0.0
front = math.exp(
math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b)
+ a * math.log(x) + b * math.log(y)
)
if x < (a + 1.0) / (a + b + 2.0):
low = front * _beta_cf(a, b, x) / a
return low, 1.0 - low
# Symmetry: I_x(a, b) = 1 - I_(1-x)(b, a).
up = front * _beta_cf(b, a, y) / b
return 1.0 - up, up
def beta_inc(a: float, b: float, x: float) -> float:
"""Regularized incomplete beta function I_x(a, b)."""
return _beta_tails(a, b, x)[0]
def chi2_cdf(x: float, k: float) -> float:
"""P(X <= x) for X chi-square with k > 0 degrees of freedom."""
return 0.0 if x <= 0.0 else gamma_p(k / 2.0, x / 2.0)
def chi2_sf(x: float, k: float) -> float:
"""P(X > x) for X chi-square with k degrees of freedom, without 1 - cdf."""
return 1.0 if x <= 0.0 else gamma_q(k / 2.0, x / 2.0)
def t_sf(x: float, k: float) -> float:
"""P(T > x) for T Student t with k > 0 degrees of freedom."""
if math.isfinite(x):
s = k + x * x
half = 0.5 * _beta_tails(k / 2.0, 0.5, k / s, x * x / s)[0] # P(|T| > |x|) / 2
else:
half = 0.0
return half if x >= 0.0 else 1.0 - half
def t_cdf(x: float, k: float) -> float:
"""P(T <= x) for T Student t with k degrees of freedom."""
return t_sf(-x, k)
def f_cdf(x: float, k1: float, k2: float) -> float:
"""P(F <= x) for F with (k1, k2) degrees of freedom."""
if x <= 0.0:
return 0.0
return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[1]
def f_sf(x: float, k1: float, k2: float) -> float:
"""P(F > x) = I_(k2 / (k2 + k1 x))(k2 / 2, k1 / 2)."""
if x <= 0.0:
return 1.0
return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[0]
def _quantile(cdf, sf, p: float, lo: float, hi: float) -> float:
"""The x with cdf(x) = p, by bisection on cdf (p <= 1/2) or on sf (p > 1/2).
lo must satisfy cdf(lo) <= p; hi is doubled until cdf(hi) >= p.
"""
if not 0.0 < p < 1.0:
raise ValueError("p must be in (0, 1)")
if p <= 0.5:
g = lambda x: cdf(x) - p # increasing in x
else:
q = 1.0 - p
g = lambda x: q - sf(x) # increasing in x, and no cancellation in sf
while g(hi) < 0.0:
lo, hi = hi, 2.0 * hi if hi > 0.0 else 1.0
for _ in range(400):
mid = 0.5 * (lo + hi)
if mid <= lo or mid >= hi:
break
if g(mid) < 0.0:
lo = mid
else:
hi = mid
return 0.5 * (lo + hi)
def chi2_ppf(p: float, k: float) -> float:
"""The lower p-quantile chi^2_(k, p)."""
return _quantile(lambda x: chi2_cdf(x, k), lambda x: chi2_sf(x, k), p, 0.0, max(1.0, k))
def t_ppf(p: float, k: float) -> float:
"""The lower p-quantile t_(k, p)."""
if p == 0.5:
return 0.0
if p < 0.5:
return -t_ppf(1.0 - p, k)
return _quantile(lambda x: t_cdf(x, k), lambda x: t_sf(x, k), p, 0.0, 1.0)
def f_ppf(p: float, k1: float, k2: float) -> float:
"""The lower p-quantile F_(k1, k2, p)."""
return _quantile(lambda x: f_cdf(x, k1, k2), lambda x: f_sf(x, k1, k2), p, 0.0, 1.0)
kruskal_wallis_test.py 10 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kruskal-wallis-test/. The authors are listed in prov/DCECK4.jsonl.
"""Entry point named after the slug. The code lives in kruskal_wallis_core.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""
from kruskal_wallis_core import (
doubled_midranks, h_statistic, kruskal_wallis, labeling_counts, tie_sizes,
)
__all__ = ["doubled_midranks", "h_statistic", "kruskal_wallis", "labeling_counts", "tie_sizes"]
test_kruskal_wallis_test.py 139 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kruskal-wallis-test/. The authors are listed in prov/DCECK4.jsonl.
import itertools
import math
import random
from fractions import Fraction
import pytest
from kruskal_wallis_test import doubled_midranks, h_statistic, kruskal_wallis, labeling_counts
A = [27, 31, 22, 35]
B = [19, 24, 20, 18, 26]
C = [33, 38, 29, 40]
def h_direct(groups: list[list[float]]) -> Fraction:
"""H = (N - 1) SSB / SST on the midranks: a second formula, tie-corrected by itself."""
pooled = [v for g in groups for v in g]
big_n = len(pooled)
ranks = []
for v in pooled:
ranks.append(sum(1 for t in pooled if t < v) + Fraction(sum(1 for t in pooled if t == v) + 1, 2))
mean = Fraction(big_n + 1, 2)
sst = sum((r - mean) ** 2 for r in ranks)
ssb, start = Fraction(0), 0
for g in groups:
part = ranks[start:start + len(g)]
ssb += len(g) * (sum(part) / len(g) - mean) ** 2
start += len(g)
return (big_n - 1) * ssb / sst if sst else Fraction(0)
def brute_force_p(groups: list[list[float]]) -> Fraction:
"""Share of all distinct assignments of the pooled values to the groups with H >= observed."""
sizes = [len(g) for g in groups]
pooled = [v for g in groups for v in g]
h_obs = h_direct(groups)
hits = total = 0
for perm in itertools.permutations(range(len(pooled))):
cut, start, ok = [], 0, True
for size in sizes:
block = perm[start:start + size]
if list(block) != sorted(block): # one representative per assignment of positions
ok = False
break
cut.append([pooled[i] for i in block])
start += size
if not ok:
continue
total += 1
hits += h_direct(cut) >= h_obs
return Fraction(hits, total)
def test_page_example() -> None:
assert h_statistic([A, B, C]) == Fraction(3699, 455)
assert kruskal_wallis([A, B, C], "exact", exact=True)[1] == Fraction(4, 715)
assert kruskal_wallis([A, B, C])[1] == pytest.approx(0.0171658, abs=1e-7)
g2 = [[1, 2, 2, 3], [2, 3, 4, 4], [3, 4, 5, 5]]
assert h_statistic(g2) == Fraction(1727, 273)
assert kruskal_wallis(g2, "exact", exact=True)[1] == Fraction(19, 525)
def test_two_formulas_agree() -> None:
rng = random.Random(1)
for _ in range(200):
k = rng.randint(2, 4)
groups = [[rng.randint(0, 6) for _ in range(rng.randint(1, 5))] for _ in range(k)]
if len(set(v for g in groups for v in g)) == 1:
continue # all values tied: H is 0 by convention
assert h_statistic(groups) == h_direct(groups)
def test_two_groups_is_mann_whitney_squared() -> None:
rng = random.Random(2)
for _ in range(100):
m, n = rng.randint(1, 7), rng.randint(1, 7)
x = [rng.randint(0, 5) for _ in range(m)]
y = [rng.randint(0, 5) for _ in range(n)]
pooled = x + y
big_n = m + n
ties = sum(pooled.count(v) ** 3 - pooled.count(v) for v in set(pooled))
var = Fraction(m * n, 12) * ((big_n + 1) - Fraction(ties, big_n * (big_n - 1)))
if var == 0:
continue
r2 = doubled_midranks(pooled)
u = Fraction(sum(r2[:m]), 2) - Fraction(m * (m + 1), 2)
assert h_statistic([x, y]) == (u - Fraction(m * n, 2)) ** 2 / var
def test_exact_against_all_assignments() -> None:
rng = random.Random(3)
for _ in range(25):
sizes = rng.choice([(2, 2, 2), (1, 2, 3), (3, 3), (2, 2, 3), (1, 1, 2, 2)])
groups = [[rng.randint(0, 4) for _ in range(s)] for s in sizes]
if len(set(v for g in groups for v in g)) == 1:
continue
assert kruskal_wallis(groups, "exact", exact=True)[1] == brute_force_p(groups)
def test_labeling_counts_total() -> None:
r2 = doubled_midranks([1, 2, 2, 3, 5, 5, 7, 8, 9])
counts = labeling_counts(r2, [2, 3, 4])
assert sum(counts.values()) == math.factorial(9) // (2 * 6 * 24)
assert all(sum(s) == sum(r2) for s in counts)
def test_exact_critical_value_333() -> None:
# Sizes 3, 3, 3 without ties: P(H >= 5.6) = 0.05 exactly, and P(H >= 5.991) = 0.0107.
r2 = [2 * i for i in range(1, 10)]
counts = labeling_counts(r2, [3, 3, 3])
total = sum(counts.values())
def h(sums: tuple[int, ...]) -> Fraction:
return Fraction(12, 90) * sum(Fraction(s, 2) ** 2 / 3 for s in sums) - 30
assert total == 1680
assert Fraction(sum(c for s, c in counts.items() if h(s) >= Fraction(28, 5)), total) == Fraction(1, 20)
assert Fraction(sum(c for s, c in counts.items() if h(s) >= Fraction(5991, 1000)), total) == Fraction(18, 1680)
def test_chi_square_size_monte_carlo() -> None:
rng = random.Random(33)
r, alpha = 1500, 0.05
hits = sum(kruskal_wallis([[rng.gauss(0.0, 1.0) for _ in range(10)] for _ in range(3)])[1] <= alpha
for _ in range(r))
assert abs(hits / r - alpha) <= 4 * math.sqrt(alpha * (1 - alpha) / r)
def test_edges() -> None:
with pytest.raises(ValueError):
kruskal_wallis([[1.0]])
with pytest.raises(ValueError):
kruskal_wallis([[1.0], []])
with pytest.raises(ValueError):
kruskal_wallis([[1.0], [2.0]], method="other")
assert h_statistic([[1.0, 1.0], [1.0]]) == 0
History
William Kruskal and W. Allen Wallis published the test in 1952 as an extension of the Wilcoxon and Mann-Whitney two-sample test, with the chi-square approximation, the tie correction, tables of the exact distribution for three small groups, and a survey of earlier work on rank tests. The efficiency results of Hodges and Lehmann (1956) for the Wilcoxon test carry over to it.
References
- Myles Hollander, Douglas A. Wolfe and Eric Chicken, Nonparametric Statistical Methods, third edition, Wiley, 2014, Chapter 6 (the one-way layout), the section on the Kruskal-Wallis test
- E. L. Lehmann, Nonparametrics, Statistical Methods Based on Ranks, revised edition, Springer, 2006, The chapter on the comparison of more than two treatments (the Kruskal-Wallis test and its limit law)
- William H. Kruskal and W. Allen Wallis, Use of ranks in one-criterion variance analysis, Journal of the American Statistical Association 47(260), 1952, pp. 583 to 621 (the statistic H, the chi-square approximation, the tie correction and tables for three groups)
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 DCECK4 Edit this page History Report an error Markdown