Algorithmintro
Pearson's chi-squared goodness-of-fit test
Also called chi-squared goodness-of-fit test, Pearson chi-squared test.
Compares observed category counts with expected counts by the sum of (O - E)^2 / E, which is asymptotically chi-squared under the null.
- Time
- Θ(k) worst · best
- Space
- Θ(k) extra
- Where
- k = the number of categories
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Karl Pearson, Ronald A. Fisher, Herman Chernoff, Erich L. Lehmann, 1900
Pearson's chi-squared goodness-of-fit test asks whether counts in categories agree with a stated set of category probabilities. It compares each observed count with the count that the null hypothesis expects and adds up . Under the null, for large samples, this sum has approximately the chi-square law with degrees of freedom, less one for each parameter fitted from the counts. The test is approximate: its size is close to only when the expected counts are not too small.
In plain words
Roll a die 60 times. If it is fair, each face should come up about 10 times. You never get exactly 10 of each, so the question is whether the differences are larger than chance would give. For each face, square the difference between what you saw and what you expected, and divide by what you expected, so that a miss of 5 counts more when you expected 10 than when you expected 1000. Add the six numbers. A fair die gives a total near 5 on average. A total of 13.4 happens by chance only about 2% of the time.
The problem
Model. independent observations, each falling in one of categories. Category has probability . The counts are multinomial with .
Hypotheses. Simple null : for given . Composite null: for some in an -dimensional family. The alternative is any other . There is no direction: every kind of misfit increases the statistic.
Statistic. With (or ),
The likelihood-ratio form is , with .
Null distribution. Asymptotic only: as with fixed, tends to . If is estimated by maximum likelihood from the grouped counts, the limit is . If is estimated from the raw, ungrouped observations, the limit lies between and (Chernoff and Lehmann 1954).
Rejection rule and size. Reject when , that is when , the upper point. The size tends to (proved for a simple null). For finite the size is not controlled: it can be above or below , as the exact computations below show.
P-values. , the upper tail only.
Sensitivity and power. Under a fixed alternative , the power tends to 1. For alternatives near the null, is approximately noncentral chi-square with noncentrality . The test spreads its power over all directions, so a test aimed at one kind of departure (a trend over ordered categories, for example) can be much more powerful against that departure.
The algorithm
CHI-SQUARED-GOF(O[1..k], p[1..k], s)- 1
n ← O[1] + ... + O[k] - 2
for i ← 1 to k do E[i] ← n · p[i] - 3
X2 ← Σ (O[i] - E[i])^2 / E[i] ▷ or G ← 2 Σ over O[i] > 0 of O[i] log(O[i] / E[i]) - 4
df ← k - 1 - s ▷ s = number of parameters fitted from these counts - 5
return (X2, df, P(χ²_df > X2))
The caller passes the null probabilities. If parameters were fitted, the caller computes from the grouped counts and passes . Line L5 uses chi2_sf from the shared helper module, the regularized upper incomplete gamma function .
Example
A suspect die. Sixty rolls give the counts for faces 1 to 6. Each expected count is 10.
| face | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| 5 | 8 | 9 | 8 | 10 | 20 | |
| 2.5 | 0.4 | 0.1 | 0.4 | 0 | 10 |
on 5 degrees of freedom, and . The upper 5% point is , so the test rejects at . Most of the statistic comes from face 6.
Mendel's peas. Mendel's dihybrid cross gave 315 round yellow, 108 round green, 101 wrinkled yellow and 32 wrinkled green seeds, 556 in all. The theory predicts the ratio 9 : 3 : 3 : 1, so the expected counts are . Then on 3 degrees of freedom and . The likelihood-ratio statistic gives and . The data agree with the theory.
A fitted parameter. A sample of 1000 people has genotype counts , , . Under Hardy-Weinberg equilibrium the genotype probabilities are , and for an unknown allele frequency . The maximum likelihood estimate from these counts is , so the expected counts are . Then . One parameter was fitted, so there are degree of freedom, and . With the wrong count of 2 degrees of freedom the p-value would be .
The tests check these numbers. They also check against exact rational arithmetic for 300 random tables.
Correctness
The full proof is in proofs/correctness.md. Write the counts as a sum of iid unit vectors. The scaled vector with entries has covariance with , a unit vector. So by the multivariate central limit theorem, tends to a normal vector whose covariance is the projection onto the dimensional subspace orthogonal to . Then tends to a sum of squared independent standard normals, which is . For the statistic is exactly , the square of the score statistic of the binomial test. A third-order Taylor bound shows in probability, so has the same limit, as Wilks's theorem also predicts.
Proof: Under a simple null the Pearson statistic is the squared length of a projected normal vector in the limit, so it tends to chi-square with k - 1 degrees of freedomfull
Model. independent observations fall into categories. Category has probability , with . The counts are multinomial. The simple null hypothesis fixes . Write and
Claim 1 (lines L1 to L3 compute the statistics). Line L1 sets , line L2 sets , and line L3 sums the terms of or of . In a cell with contributes , which is the limit of as . The sum uses math.fsum, so the only rounding is in the terms. Line L4 sets the degrees of freedom to , where is the argument fitted, and line L5 returns from the regularized upper incomplete gamma function of the helper module.
Claim 2 (the mean and covariance of the counts). Under , , and for .
Proof. Write , where is the category of observation and is the -th unit vector. The vectors are iid with mean . Their second moment is , because has a single 1, on the diagonal at . So each has covariance , and the sum of independent copies has times this covariance.
Claim 3 (the limit law under a simple null). Under , converges in distribution to as , with and fixed.
Proof. Let and , so the -th entry is and . By Claim 2, is times a sum of iid centred vectors with covariance
The multivariate central limit theorem gives in distribution, with . (The multivariate form follows from the one-dimensional form by the Cramér-Wold device: for each fixed vector , is a normalized sum of iid scalars with variance .) The map is continuous, so in distribution.
Now find the law of . Since , the matrix is the orthogonal projection onto the hyperplane , of rank . Choose an orthonormal basis of and let . The vector is normal with covariance , so it has the law of . Also , so . The are jointly normal with covariance , so they are iid standard normal, and has the law.
Claim 4 (the size tends to the nominal level). For a fixed , the test that rejects when has .
Proof. Rejecting when is rejecting when , where is the upper point of , because the tail function is continuous and strictly decreasing. The limit law is continuous, so .
The convergence is not uniform in . If some is small, the multinomial law is far from its normal limit, and the true size can be above or below . The tests compute the exact size by summing the multinomial probabilities of all outcomes for several small cases.
Claim 5 (two categories). For , with , the score statistic of the binomial test.
Proof. Let . Then , so , which is .
Claim 6 (the G statistic has the same limit). Under , in probability, so also tends to .
Proof. Let for . Then and , so for , and Taylor's theorem gives there. Put and . Then and when . Summing over and using ,
By Claim 3, each is bounded in probability, so . On the event that all (all then), whose probability tends to 1, . Slutsky's theorem gives the limit of .
Fitted parameters (cited, not proved here). Suppose the null is a family with , and is the maximum likelihood estimate from the grouped counts (or the minimum chi-square estimate). Under smoothness and rank conditions, with tends to . Fisher (1922, 1924) gave the result, and Cramér's 1946 book has a complete proof. The idea is the same as in Claim 3: the estimate removes more dimensions, and tends to a normal vector on a subspace of dimension . If instead is the maximum likelihood estimate from the ungrouped observations, Chernoff and Lehmann (1954) showed that the limit is with iid standard normal and , so it lies between and . The tests check this by simulation.
Cost. Lines L1 to L4 do arithmetic operations and store the expected counts. Line L5 is one evaluation of the incomplete gamma function, which we count as one operation of the real-RAM model.
Complexity
The statistic takes arithmetic operations, and the expected counts take extra space (the code builds a list of them; a streaming version needs ). The p-value is one evaluation of the incomplete gamma function. Counting the observations into categories, if the caller has raw data, is a separate pass.
Properties
-
Size for small samples (computed exactly). Under the null the outcome is a finite multinomial, so the true size of the test at can be found by summing over all outcomes. The tests do this and also check it against a simulation.
smallest size of test size of test 10 3.33 0.0590 0.0565 30 10 0.0478 0.0597 20 5 0.0415 0.0528 20 2 0.0491 0.0624 50 5 0.0513 0.0567 The Pearson statistic stays close to 0.05 even with expected counts of 2. The statistic is more liberal in these cases.
-
Fitted parameters lower the degrees of freedom. Each parameter fitted by maximum likelihood from the grouped counts removes one degree of freedom.
-
Estimates from raw data. The Chernoff-Lehmann limit lies between the two chi-square laws. In a simulation (seed 5, 4000 samples of standard normal values, six fixed bins, mean and standard deviation estimated from the raw values), the test with degrees of freedom rejected 5.5% of the time, and the test with 5 degrees of freedom rejected 1.1% of the time. The theory says the first is slightly liberal, and the simulation agrees within its standard error of 0.35%. The second is very conservative.
-
Power. For the die with and a loaded face 6 (, the others ), the power at was 0.698 for and 0.663 for in a simulation (seed 9, 20000 samples). The noncentral chi-square approximation with gives 0.769, which is too high at this sample size.
-
Invariant to the order of the categories. The statistic ignores any order. This is a weakness when the categories are ordered.
Variants and improvements
- Likelihood-ratio statistic . The code computes it with
statistic="g". It has the same limit, and it adds up over nested models, which does not do exactly. - Power-divergence family. Cressie and Read (1984) put and in one family indexed by , with at and at . They recommend .
- Exact multinomial test. For small , sum the multinomial probabilities of all outcomes at least as unlikely as the observed one, or as large in , by enumeration as in the tests. For this is the binomial test.
- Monte Carlo p-value. Simulate multinomial samples under and use , where the count is the number of simulated values at least the observed one.
- Continuous data. For a fully specified continuous distribution, tests based on the empirical distribution function, such as the Kolmogorov-Smirnov and Anderson-Darling tests, do not need bins and usually have more power.
When to use it
Use it for counts in categories that have no order, with a null hypothesis that gives the category probabilities or a model with a few parameters. Typical uses are genetic ratios, checks of a random number generator, and checks of a discrete model. A common rule asks for all expected counts of at least 5. The table above shows that the Pearson test holds its size well with expected counts near 2, so Cochran's rule (no expected count below 1, and at most 20% below 5) is a better guide. For smaller counts, use the exact or Monte Carlo test.
Pitfalls
- Percentages instead of counts. The statistic must use counts. Using percentages changes to 100 and gives a wrong p-value.
- Observations that are not independent. Repeated measurements on the same people, or clustered data, make the variance larger than the multinomial variance, and the test rejects too often.
- Wrong degrees of freedom. Subtract one degree of freedom for each parameter fitted from the counts. If the parameters came from the raw data, degrees of freedom make the test slightly liberal and make it conservative.
- Choosing bins after seeing the data. Choosing bins to make the fit look good or bad changes the null law.
- Reading a large p-value as proof of the model. A large p-value means only that the test did not detect a misfit. With small the power is low. A p-value very close to 1 can also be a warning: Fisher (1936) argued that the totals of Mendel's experiments agreed with theory too well.
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/chi-squared-goodness-of-fit-test/. The authors are listed in prov/B43M8J.jsonl.
import math
from collections.abc import Sequence
from stdist import chi2_sf
def chi_squared_gof(
observed: Sequence[int],
probs: Sequence[float] | None = None,
fitted: int = 0,
statistic: str = "pearson",
) -> tuple[float, int, float]:
"""Pearson's chi-squared goodness-of-fit test.
observed holds the counts of k categories; probs holds the null cell
probabilities (equal cells when None). fitted is the number s of
parameters estimated by maximum likelihood from these grouped counts,
which lowers the degrees of freedom to k - 1 - s. statistic "pearson"
gives X^2 = sum (O - E)^2 / E; "g" gives the likelihood-ratio statistic
G = 2 sum O log(O / E). Returns (statistic, degrees of freedom, p-value),
where the p-value is the upper tail of the chi-square law.
"""
k = len(observed)
if k < 2 or any(not isinstance(o, int) or o < 0 for o in observed):
raise ValueError("need at least two non-negative integer counts")
if probs is None:
probs = [1.0 / k] * k
if len(probs) != k or any(not p > 0 for p in probs) or abs(math.fsum(probs) - 1.0) > 1e-9:
raise ValueError("probs must be k positive numbers that sum to 1")
if statistic not in ("pearson", "g"):
raise ValueError("unknown statistic")
n = sum(observed) # @line L1
if n == 0:
raise ValueError("need at least one observation")
expected = [n * p for p in probs] # @line L2
if statistic == "pearson": # @line L3
x2 = math.fsum((o - e) ** 2 / e for o, e in zip(observed, expected))
else:
x2 = 2.0 * math.fsum(o * math.log(o / e) for o, e in zip(observed, expected) if o > 0)
df = k - 1 - fitted # @line L4
if df < 1:
raise ValueError("need k - 1 - fitted >= 1")
return x2, df, chi2_sf(x2, df) # @line L5
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)
chi_squared_goodness_of_fit_test.py 9 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chi-squared-goodness-of-fit-test/. The authors are listed in prov/B43M8J.jsonl.
"""Entry point named after the slug. The code lives in chi_squared_gof.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""
from chi_squared_gof import chi_squared_gof
__all__ = ["chi_squared_gof"]
test_chi_squared_goodness_of_fit_test.py 166 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chi-squared-goodness-of-fit-test/. The authors are listed in prov/B43M8J.jsonl.
import math
import random
from fractions import Fraction
from statistics import NormalDist
import pytest
from chi_squared_goodness_of_fit_test import chi_squared_gof
from stdist import chi2_sf
MENDEL = [315, 108, 101, 32]
MENDEL_P = [9 / 16, 3 / 16, 3 / 16, 1 / 16]
def exact_pearson(observed: list[int], probs: list[Fraction]) -> Fraction:
n = sum(observed)
return sum((Fraction(o) - n * p) ** 2 / (n * p) for o, p in zip(observed, probs))
def compositions(n: int, k: int):
if k == 1:
yield (n,)
return
for first in range(n + 1):
for rest in compositions(n - first, k - 1):
yield (first, *rest)
def multinomial_pmf(counts: tuple[int, ...], probs: list[float]) -> float:
coef = math.factorial(sum(counts))
for c in counts:
coef //= math.factorial(c)
return coef * math.prod(p**c for p, c in zip(probs, counts))
def test_page_examples() -> None:
x2, df, p = chi_squared_gof([5, 8, 9, 8, 10, 20])
assert (df, x2) == (5, pytest.approx(13.4))
assert p == pytest.approx(0.019905, abs=1e-6)
x2, df, p = chi_squared_gof(MENDEL, MENDEL_P)
assert (df, x2, p) == (3, pytest.approx(0.470024, abs=1e-6), pytest.approx(0.925426, abs=1e-6))
g2, df, p = chi_squared_gof(MENDEL, MENDEL_P, statistic="g")
assert (df, g2, p) == (3, pytest.approx(0.475445, abs=1e-6), pytest.approx(0.924252, abs=1e-6))
def test_statistic_against_fractions() -> None:
assert exact_pearson([5, 8, 9, 8, 10, 20], [Fraction(1, 6)] * 6) == Fraction(67, 5)
assert exact_pearson(MENDEL, [Fraction(9, 16), Fraction(3, 16), Fraction(3, 16), Fraction(1, 16)]) == Fraction(
19600, 41700
)
rng = random.Random(7)
for _ in range(300):
k = rng.randint(2, 7)
weights = [rng.randint(1, 9) for _ in range(k)]
probs = [Fraction(w, sum(weights)) for w in weights]
observed = [rng.randint(0, 40) for _ in range(k)]
if sum(observed) == 0:
continue
x2, df, _ = chi_squared_gof(observed, [float(p) for p in probs])
assert df == k - 1
assert x2 == pytest.approx(float(exact_pearson(observed, probs)), rel=1e-12, abs=1e-12)
def test_two_cells_is_the_squared_z_statistic() -> None:
# With k = 2, X^2 = (x - n p)^2 / (n p (1 - p)) = z^2, and the 1 df tail is erfc(|z| / sqrt 2).
for x, n, p0 in ((60, 100, 0.5), (3, 40, 0.2), (17, 20, 0.6), (0, 9, 0.3)):
z = (x - n * p0) / math.sqrt(n * p0 * (1 - p0))
x2, df, p = chi_squared_gof([x, n - x], [p0, 1 - p0])
assert df == 1
assert x2 == pytest.approx(z * z, rel=1e-12)
assert p == pytest.approx(math.erfc(abs(z) / math.sqrt(2)), rel=1e-9)
def test_g_statistic_close_to_pearson_for_large_counts() -> None:
# G - X^2 tends to 0 under the null; for counts near their expected values the two agree closely.
for scale in (10, 100, 1000):
obs = [9 * scale + 1, 3 * scale - 1, 3 * scale + 1, scale - 1]
x2 = chi_squared_gof(obs, MENDEL_P)[0]
g2 = chi_squared_gof(obs, MENDEL_P, statistic="g")[0]
assert abs(g2 - x2) < 0.6 / scale
def exact_size(n: int, probs: list[float], alpha: float = 0.05) -> float:
return math.fsum(
multinomial_pmf(c, probs) for c in compositions(n, len(probs)) if chi_squared_gof(list(c), probs)[2] <= alpha
)
def test_exact_size_by_enumeration() -> None:
# The null law is a finite multinomial, so the true size of the asymptotic test can be computed exactly.
assert exact_size(10, [1 / 3] * 3) == pytest.approx(0.058985, abs=1e-6)
assert exact_size(30, [1 / 3] * 3) == pytest.approx(0.047786, abs=1e-6)
assert exact_size(20, [0.25] * 4) == pytest.approx(0.041518, abs=1e-6)
assert exact_size(20, [0.7, 0.1, 0.1, 0.1]) == pytest.approx(0.049088, abs=1e-6)
assert exact_size(50, [0.7, 0.1, 0.1, 0.1]) == pytest.approx(0.051288, abs=1e-6)
def test_enumeration_against_brute_force_sampling() -> None:
# Brute force: draw multinomial samples cell by cell and count rejections.
rng = random.Random(11)
probs = [1 / 3] * 3
runs, rejected = 20000, 0
for _ in range(runs):
counts = [0, 0, 0]
for _ in range(10):
counts[rng.choices(range(3), probs)[0]] += 1
rejected += chi_squared_gof(counts, probs)[2] <= 0.05
size = exact_size(10, probs)
assert abs(rejected / runs - size) < 4 * math.sqrt(size * (1 - size) / runs)
def test_fitted_parameter_hardy_weinberg() -> None:
obs = [298, 489, 213]
n = sum(obs)
theta = (2 * obs[0] + obs[1]) / (2 * n)
assert theta == 0.5425
probs = [theta * theta, 2 * theta * (1 - theta), (1 - theta) ** 2]
x2, df, p = chi_squared_gof(obs, probs, fitted=1)
assert df == 1
assert x2 == pytest.approx(0.221490, abs=1e-6)
assert p == pytest.approx(0.637907, abs=1e-6)
assert chi_squared_gof(obs, probs)[2] == pytest.approx(0.895167, abs=1e-6)
def test_chernoff_lehmann_raw_data_estimates() -> None:
# Mean and standard deviation estimated from the raw normal data, six fixed bins.
# The true law lies between chi2 with k - 1 - s = 3 and k - 1 = 5 degrees of freedom.
rng = random.Random(5)
cuts = [-1.5, -0.75, 0.0, 0.75, 1.5]
std = NormalDist()
runs, rej3, rej5 = 4000, 0, 0
for _ in range(runs):
x = [rng.gauss(0, 1) for _ in range(100)]
m = math.fsum(x) / len(x)
s = math.sqrt(math.fsum((v - m) ** 2 for v in x) / len(x))
counts = [0] * 6
for v in x:
counts[sum(v > c for c in cuts)] += 1
cdf = [0.0] + [std.cdf((c - m) / s) for c in cuts] + [1.0]
probs = [cdf[i + 1] - cdf[i] for i in range(6)]
x2, _, p = chi_squared_gof(counts, probs, fitted=2)
rej3 += p <= 0.05
rej5 += chi2_sf(x2, 5) <= 0.05
assert rej3 / runs == pytest.approx(0.055, abs=1e-12)
assert rej5 / runs == pytest.approx(0.01125, abs=1e-12)
assert rej5 < 0.05 * runs
def test_errors() -> None:
with pytest.raises(ValueError):
chi_squared_gof([5])
with pytest.raises(ValueError):
chi_squared_gof([1, -1])
with pytest.raises(ValueError):
chi_squared_gof([1, 2], [0.5, 0.6])
with pytest.raises(ValueError):
chi_squared_gof([1, 2], [1.0, 0.0])
with pytest.raises(ValueError):
chi_squared_gof([0, 0])
with pytest.raises(ValueError):
chi_squared_gof([1, 2, 3], fitted=2)
with pytest.raises(ValueError):
chi_squared_gof([1, 2], statistic="z")
History
Karl Pearson published the statistic in 1900 as a criterion for deciding whether a set of deviations could come from random sampling, and gave its chi-square reference law with degrees of freedom. For tables with estimated margins and for fitted parameters, Pearson kept . Fisher showed in 1922 and 1924 that each parameter fitted efficiently from the counts removes one degree of freedom. This was a long argument with Pearson. Cramér's 1946 book gave a complete proof of the limit. Chernoff and Lehmann (1954) showed that estimates from the ungrouped data give a limit that is not chi-square. Cochran (1952, 1954) studied small expected counts and gave the rules that are still in use. Cressie and Read (1984) put the Pearson and likelihood-ratio statistics into one family.
References
- Karl Pearson, On the criterion that a given system of deviations from the probable in the case of a correlated system of variables is such that it can be reasonably supposed to have arisen from random sampling, Philosophical Magazine, series 5, 50(302), 1900, pp. 157 to 175 (the statistic and its chi-square reference)
- Ronald A. Fisher, On the interpretation of χ² from contingency tables, and the calculation of P, Journal of the Royal Statistical Society 85(1), 1922, pp. 87 to 94 (the degrees of freedom when parameters are estimated)
- Herman Chernoff and Erich L. Lehmann, The use of maximum likelihood estimates in χ² tests for goodness of fit, Annals of Mathematical Statistics 25(3), 1954, pp. 579 to 586 (the limit law with estimates from ungrouped data)
- Alan Agresti, Categorical Data Analysis, third edition, Wiley, 2013, Chapter 1 (inference for multinomial parameters, the Pearson and likelihood-ratio statistics)
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 B43M8J Edit this page History Report an error Markdown