Algorithmintro
Chi-squared test of independence
Also called contingency table chi-squared test, chi-squared test of association.
Tests whether two categorical variables are independent by comparing a contingency table with the product of its margins, with (r - 1)(c - 1) degrees of freedom.
- Time
- Θ(r·c) worst · best
- Space
- Θ(r·c) extra
- Where
- c = the number of columns; r = the number of rows
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Karl Pearson, Ronald A. Fisher, Frank Yates, William G. Cochran, 1900
The chi-squared test of independence checks whether two categorical variables are related, from an table of counts. If the variables are independent, the count in cell should be close to , the product of its row and column totals divided by the grand total. The test adds up over all cells. Under independence and for large samples this sum has approximately the chi-square law with degrees of freedom.
In plain words
Give 100 patients one of two treatments and record whether each one improved, stayed the same or got worse. If the treatment makes no difference, the share of patients who improved should be about the same in both groups, and also in the whole sample. So the overall shares tell you what each cell of the table should contain. The test measures how far the real table is from that "no difference" table. The degrees of freedom count how many cells you can fill in freely once the row and column totals are fixed: , which is 2 for a table with 2 rows and 3 columns.
The problem
Model. Three sampling schemes give the same test:
- units are sampled and classified by both variables; the table is multinomial.
- The row totals are fixed by design, as in a trial with set group sizes; each row is an independent multinomial sample.
- Both margins are fixed, as in Fisher's tea tasting experiment; the table is multiple hypergeometric under the null.
Hypotheses. : independence, in scheme 1, or equal row distributions (homogeneity) in scheme 2. : any other table of probabilities. There is no direction.
Statistic.
The likelihood-ratio form is . For a table, Yates's corrected statistic subtracts from each (but not below 0).
Null distribution. Asymptotic: tends to . The table has free cell probabilities, and the null fits of them from the margins, which leaves .
Rejection rule and size. Reject when , that is when . The size tends to (proved for scheme 1). For finite it is not controlled. The exact computations below show sizes close to even with small expected counts, and show that Yates's correction is very conservative.
P-values. , the upper tail only.
Sensitivity and power. For a fixed dependent table the power tends to 1. For alternatives near independence, is approximately noncentral chi-square with noncentrality . As with the goodness-of-fit test, the power is spread over all directions, so for ordered categories a trend test is more powerful against a trend.
The algorithm
CHI-SQUARED-INDEPENDENCE(O[1..r][1..c])- 1
R[i] ← row totals; C[j] ← column totals; n ← total ▷ every R[i] and C[j] must be positive - 2
for i ← 1 to r, j ← 1 to c do - 3
E ← R[i] · C[j] / n - 4
add (O[i][j] - E)^2 / E to the sum ▷ or 2 O log(O / E); Yates: (max(0, |O - E| - 1/2))^2 / E - 5
X2 ← the sum - 6
df ← (r - 1)(c - 1) - 7
return (X2, df, P(χ²_df > X2))
Line L7 uses chi2_sf from the shared helper module. The code raises an error for a table with an empty row or column, because then some is 0; such a row or column carries no information about the association, and dropping it gives the right table.
Example
Treatment and outcome. One hundred patients get treatment A (40) or B (60). The outcomes are:
| improved | same | worse | total | |
|---|---|---|---|---|
| A | 20 | 15 | 5 | 40 |
| B | 10 | 20 | 30 | 60 |
| total | 30 | 35 | 35 | 100 |
The expected counts are , and in full
| improved | same | worse | |
|---|---|---|---|
| A | 12 | 14 | 14 |
| B | 18 | 21 | 21 |
The cell terms are , and for A, and , and for B. So on degrees of freedom, and . The likelihood-ratio form gives and . The adjusted residuals are , and for row A, so the association is in the "improved" and "worse" columns: A patients improved more often and got worse less often.
A 2 x 2 table. With rows and , :
- and .
- This is for the two-proportion comparison against .
- With Yates's correction, and .
- The two-sided Fisher exact test gives .
The tests check these numbers, and check against exact rational arithmetic for 300 random tables of up to .
Correctness
The full proof is in proofs/correctness.md. The expected counts are the maximum likelihood fit of the independence model, so this is a goodness-of-fit test with fitted parameters. The proof writes the residual matrix as a fixed linear map of the standardized counts plus a term that tends to 0. In the limit the linear map becomes , where is a matrix of independent standard normals and and project out the square roots of the row and column probabilities. This is an orthogonal projection of rank , so tends to . For the table every cell has , which gives the closed form above.
Proof: Under independence the Pearson statistic with expected counts from the margins tends to chi-square with (r - 1)(c - 1) degrees of freedomfull
Model. independent units are classified by a row variable with levels and a column variable with levels. Cell has probability , and the counts are multinomial. Write and for the row and column totals. The null hypothesis of independence is for all , where and are the marginal probabilities. The expected counts are , and
Claim 1 (lines L1 to L7 compute the statistic). Line L1 forms the row totals, the column totals and . Lines L2 and L3 visit every cell and form , which is positive because the code rejects a table with an empty row or column. Line L4 adds the cell's term: , or with the Yates correction, or for (zero when ). Line L5 sums the terms with math.fsum, line L6 sets , and line L7 returns the upper tail from the regularized incomplete gamma function.
The value is , where and are the maximum likelihood estimates of the margins under independence. (The log-likelihood separates, and each part is maximized by the observed proportions.) So the test is the goodness-of-fit test of the family , which has free parameters, fitted from the counts.
Claim 2 (the limit law). Under , with and fixed and , converges in distribution to .
Proof. Put and . Then . Treat arrays as matrices and use the Frobenius norm .
Step 1: the standardized counts. Let and . The cell counts are multinomial with probabilities , so the argument of the goodness-of-fit proof (the counts are a sum of iid unit vectors, and the multivariate central limit theorem applies) gives in distribution, where , a unit vector. Equivalently, in distribution, where is an matrix of iid standard normals and . Note .
Step 2: the residuals are a linear map of . Let and . Then
Let . Dividing term by term, and using and ,
Each and is bounded in probability (they are linear in ), so .
Step 3: the limit of the residuals. Let , a fixed linear map. By Step 1, the continuous mapping theorem and Slutsky's theorem, in distribution with . Write , , and the same for . A direct expansion gives . For :
- and ;
- , because .
So in distribution.
Step 4: the law of the limit. The map is linear, symmetric for the inner product , and idempotent, so it is an orthogonal projection on the space of matrices. Its range is the set of matrices whose columns are orthogonal to and whose rows are orthogonal to . Taking orthonormal bases of and of , the matrices with form an orthonormal basis of that range, so it has dimension . As in the goodness-of-fit proof, the squared norm of the projection of a standard normal vector onto a subspace of dimension is a sum of squared iid standard normals, so .
Step 5: the statistic. . By the law of large numbers, in probability, so , and by Step 3, Step 4 and the continuous mapping theorem, in distribution.
Claim 3 (the size). For fixed the size of the test that rejects when tends to , because the limit law is continuous and the p-value is a strictly decreasing function of .
Claim 4 (the 2 x 2 table). For the table with rows and , row totals , column totals and :
- .
- , where is the pooled two-proportion statistic, with , and .
- The Yates statistic is .
Proof. . The margins of are zero, so in a table every cell has . Also . Multiplying gives part 1, and with in place of it gives part 3. For part 2, and , so .
Part 1 shows that, given all four margins, is an increasing function of . Given the margins, is hypergeometric under the null, so the chi-squared test of a table approximates a two-sided Fisher exact test that orders the tables by their distance from the expected count.
Other sampling schemes (cited). With the row totals fixed in advance (independent multinomial samples, one per row), the null hypothesis is that the rows have the same distribution, and has the same limit. The same holds when both margins are fixed, by the limit of the multiple hypergeometric law. Agresti's book treats both cases. For with fixed rows, part 2 of Claim 4 gives the limit directly from the normal limit of the two-proportion statistic.
The G statistic. The Taylor bound of the goodness-of-fit proof, applied with in place of and with , gives , so has the same limit.
Cost. Line L1 takes additions. Lines L2 to L4 do work per cell, so in all. The code keeps the terms for the exact summation in line L5, so it uses extra space; a running sum would use for the margins. Line L7 is one incomplete gamma evaluation.
Complexity
The margins take additions and the statistic takes work per cell, so the time is . The code keeps the terms for an exactly rounded sum, so it uses extra space; a running sum needs only for the margins. The p-value is one incomplete gamma evaluation.
Properties
-
Size for small samples (computed exactly). Under multinomial sampling with independent variables, summing over all tables gives the true size at . A table with an empty row or column has no test and counts as not rejected.
table margins smallest expected count size of size with Yates 20 and 5 0.0512 0.0128 40 and 10 0.0508 0.0206 40 and 1.6 0.0417 15 and 1.2 0.0420 The tests compute these values and check the last one against a simulation (seed 6, 20000 tables).
-
Yates's correction is conservative. It brings the statistic close to the conditional exact test, which is itself conservative under multinomial sampling, so it loses power. Many authors now advise against it.
-
Symmetric. Transposing the table, or permuting its rows or columns, does not change .
-
Scales with . Multiplying every count by multiplies by . So measures evidence, not the strength of the association. Cramér's is a measure of strength; it is in the treatment example.
-
The 2 x 2 test is the two-proportion z test. for the pooled two-proportion statistic, so the two-sided tests are the same.
Variants and improvements
- Fisher's exact test. For a table with small counts, the Fisher exact test conditions on both margins and has size at most . The Freeman-Halton extension does the same for tables.
- Monte Carlo and permutation p-values. Fix both margins, draw random tables with those margins (by permuting one variable against the other), and compare with the simulated values, as in a permutation test.
- Likelihood-ratio statistic . The code computes it with
statistic="g". It splits into parts for nested tables, which is the basis of log-linear models. - Ordered categories. The Cochran-Armitage trend test and the linear-by-linear association test use one degree of freedom and have more power against a trend.
- Stratified tables. With a third variable, the Cochran-Mantel-Haenszel test combines tables across strata.
- Paired data. For the same units measured twice, use McNemar's test, not this test.
When to use it
Use it to test association between two unordered categorical variables from independent units, when most expected counts are not tiny. Cochran's rule (no expected count below 1, and at most 20% of them below 5) is a common guide, and the exact sizes above show that the Pearson statistic does well even near those limits. For tables with small counts, or whenever an exact level is needed, use Fisher's exact test or a Monte Carlo p-value.
Pitfalls
- Units that are not independent. Repeated measurements on the same subjects, or several answers from one person, break the multinomial model. For two measurements on the same units, use McNemar's test.
- Percentages instead of counts. The test needs counts. Percentages change .
- Reading or as the strength of the association. A tiny p-value with a large can come from a very weak association. Report a measure such as a difference of proportions, an odds ratio or Cramér's .
- Merging categories after seeing the data. Choosing which cells to combine to get significance changes the null law.
- Simpson's paradox. An association in the combined table can reverse inside each level of a third variable. Stratify when a confounder is known.
- Expecting the test to say which cells matter. A significant result says only that the table is not independent. Look at the adjusted residuals.
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-test-of-independence/. The authors are listed in prov/E5V169.jsonl.
import math
from collections.abc import Sequence
from stdist import chi2_sf
def chi_squared_independence(
table: Sequence[Sequence[int]],
statistic: str = "pearson",
yates: bool = False,
) -> tuple[float, int, float]:
"""Pearson's chi-squared test of independence for an r x c contingency table.
The expected count of cell (i, j) is (row total i)(column total j)/n.
statistic "pearson" gives X^2 = sum (O - E)^2 / E; "g" gives the
likelihood-ratio statistic G = 2 sum O log(O / E). yates=True applies
Yates's continuity correction, (|O - E| - 1/2)^2 / E with |O - E| - 1/2
floored at 0, and is allowed only for a 2 x 2 table with statistic "pearson".
Returns (statistic, (r - 1)(c - 1), upper chi-square tail p-value).
"""
r = len(table)
if r < 2 or any(len(row) != len(table[0]) for row in table) or len(table[0]) < 2:
raise ValueError("need a rectangular table with at least two rows and two columns")
if any(not isinstance(o, int) or o < 0 for row in table for o in row):
raise ValueError("counts must be non-negative integers")
if statistic not in ("pearson", "g"):
raise ValueError("unknown statistic")
c = len(table[0])
if yates and (r, c, statistic) != (2, 2, "pearson"):
raise ValueError("the Yates correction is for the Pearson statistic of a 2 x 2 table")
rows = [sum(row) for row in table] # @line L1
cols = [sum(table[i][j] for i in range(r)) for j in range(c)]
n = sum(rows)
if min(rows) == 0 or min(cols) == 0:
raise ValueError("every row and column total must be positive")
terms = []
for i in range(r): # @line L2
for j in range(c):
o, e = table[i][j], rows[i] * cols[j] / n # @line L3
if statistic == "g": # @line L4
if o > 0:
terms.append(2.0 * o * math.log(o * n / (rows[i] * cols[j])))
else:
d = abs(o - e)
if yates:
d = max(0.0, d - 0.5)
terms.append(d * d / e)
x2 = math.fsum(terms) # @line L5
df = (r - 1) * (c - 1) # @line L6
return x2, df, chi2_sf(x2, df) # @line L7
chi_squared_test_of_independence.py 9 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chi-squared-test-of-independence/. The authors are listed in prov/E5V169.jsonl.
"""Entry point named after the slug. The code lives in chi_squared_independence.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""
from chi_squared_independence import chi_squared_independence
__all__ = ["chi_squared_independence"]
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)
test_chi_squared_test_of_independence.py 170 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chi-squared-test-of-independence/. The authors are listed in prov/E5V169.jsonl.
import math
import random
from fractions import Fraction
import pytest
from chi_squared_test_of_independence import chi_squared_independence
TREATMENT = [[20, 15, 5], [10, 20, 30]]
def exact_pearson(table: list[list[int]]) -> Fraction:
rows = [sum(row) for row in table]
cols = [sum(col) for col in zip(*table)]
n = sum(rows)
return sum(
(Fraction(table[i][j]) - Fraction(rows[i] * cols[j], n)) ** 2 / Fraction(rows[i] * cols[j], n)
for i in range(len(rows))
for j in range(len(cols))
)
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 rejects(table: list[list[int]], **kw) -> bool:
# A table with an empty row or column has no test; count it as not rejected.
try:
return chi_squared_independence(table, **kw)[2] <= 0.05
except ValueError:
return False
def exact_size(n: int, pr: list[float], pc: list[float], **kw) -> float:
r, c = len(pr), len(pc)
w = [pr[i] * pc[j] for i in range(r) for j in range(c)]
total = 0.0
for cnt in compositions(n, r * c):
if rejects([list(cnt[i * c : (i + 1) * c]) for i in range(r)], **kw):
total += multinomial_pmf(cnt, w)
return total
def test_page_examples() -> None:
x2, df, p = chi_squared_independence(TREATMENT)
assert (df, x2) == (2, pytest.approx(18.650794, abs=1e-6))
assert p == pytest.approx(8.9132e-05, rel=1e-4)
g2, df, p = chi_squared_independence(TREATMENT, statistic="g")
assert (df, g2) == (2, pytest.approx(19.899774, abs=1e-6))
assert p == pytest.approx(4.7733e-05, rel=1e-4)
x2, df, p = chi_squared_independence([[12, 5], [7, 16]])
assert (df, x2, p) == (1, pytest.approx(6.319892, abs=1e-6), pytest.approx(0.011939, abs=1e-6))
x2, df, p = chi_squared_independence([[12, 5], [7, 16]], yates=True)
assert (x2, p) == (pytest.approx(4.812286, abs=1e-6), pytest.approx(0.028258, abs=1e-6))
def test_statistic_against_fractions() -> None:
assert exact_pearson(TREATMENT) == Fraction(1175, 63)
rng = random.Random(3)
for _ in range(300):
r, c = rng.randint(2, 5), rng.randint(2, 5)
table = [[rng.randint(0, 30) for _ in range(c)] for _ in range(r)]
if min(map(sum, table)) == 0 or min(map(sum, zip(*table))) == 0:
continue
x2, df, _ = chi_squared_independence(table)
assert df == (r - 1) * (c - 1)
assert x2 == pytest.approx(float(exact_pearson(table)), rel=1e-12, abs=1e-12)
def test_two_by_two_closed_forms() -> None:
rng = random.Random(4)
for _ in range(300):
a, b, c, d = (rng.randint(0, 25) for _ in range(4))
r1, r2, c1, c2 = a + b, c + d, a + c, b + d
if 0 in (r1, r2, c1, c2):
continue
n = r1 + r2
den = r1 * r2 * c1 * c2
x2 = chi_squared_independence([[a, b], [c, d]])[0]
assert x2 == pytest.approx(n * (a * d - b * c) ** 2 / den, rel=1e-12, abs=1e-12)
# The square of the pooled two-proportion z statistic.
p1, p2, pooled = a / r1, c / r2, c1 / n
z = (p1 - p2) / math.sqrt(pooled * (1 - pooled) * (1 / r1 + 1 / r2))
assert x2 == pytest.approx(z * z, rel=1e-9, abs=1e-12)
yates = chi_squared_independence([[a, b], [c, d]], yates=True)[0]
excess = max(0.0, abs(a * d - b * c) - n / 2)
assert yates == pytest.approx(n * excess**2 / den, rel=1e-12, abs=1e-12)
def test_one_degree_of_freedom_tail() -> None:
for table in ([[12, 5], [7, 16]], [[40, 10], [30, 20]], [[3, 9], [8, 1]]):
x2, _, p = chi_squared_independence(table)
assert p == pytest.approx(math.erfc(math.sqrt(x2 / 2)), rel=1e-9)
def test_invariance() -> None:
rng = random.Random(5)
for _ in range(100):
table = [[rng.randint(1, 20) for _ in range(4)] for _ in range(3)]
base = chi_squared_independence(table)
transposed = [list(col) for col in zip(*table)]
assert chi_squared_independence(transposed)[0] == pytest.approx(base[0], rel=1e-12)
shuffled = [row[:] for row in table]
rng.shuffle(shuffled)
order = list(range(4))
rng.shuffle(order)
shuffled = [[row[j] for j in order] for row in shuffled]
assert chi_squared_independence(shuffled)[0] == pytest.approx(base[0], rel=1e-12)
scaled = [[3 * o for o in row] for row in table]
assert chi_squared_independence(scaled)[0] == pytest.approx(3 * base[0], rel=1e-12)
# A table equal to the product of its margins gives X^2 = 0 and p = 1.
x2, _, p = chi_squared_independence([[2, 4, 6], [3, 6, 9]])
assert x2 == pytest.approx(0.0, abs=1e-12)
assert p == pytest.approx(1.0)
def test_exact_size_by_enumeration() -> None:
# Multinomial sampling of n units with independent row and column variables.
assert exact_size(20, [0.5, 0.5], [0.5, 0.5]) == pytest.approx(0.051201, abs=1e-6)
assert exact_size(40, [0.5, 0.5], [0.5, 0.5]) == pytest.approx(0.050821, abs=1e-6)
assert exact_size(20, [0.5, 0.5], [0.5, 0.5], yates=True) == pytest.approx(0.012779, abs=1e-6)
assert exact_size(40, [0.5, 0.5], [0.5, 0.5], yates=True) == pytest.approx(0.020629, abs=1e-6)
assert exact_size(40, [0.8, 0.2], [0.8, 0.2]) == pytest.approx(0.041699, abs=1e-6)
assert exact_size(15, [0.4, 0.6], [0.2, 0.3, 0.5]) == pytest.approx(0.041959, abs=1e-6)
def test_enumeration_against_brute_force_sampling() -> None:
rng = random.Random(6)
pr, pc = [0.4, 0.6], [0.2, 0.3, 0.5]
cells = [(i, j) for i in range(2) for j in range(3)]
weights = [pr[i] * pc[j] for i, j in cells]
runs, rejected = 20000, 0
for _ in range(runs):
table = [[0, 0, 0], [0, 0, 0]]
for i, j in rng.choices(cells, weights, k=15):
table[i][j] += 1
rejected += rejects(table)
size = exact_size(15, pr, pc)
assert abs(rejected / runs - size) < 4 * math.sqrt(size * (1 - size) / runs)
def test_errors() -> None:
with pytest.raises(ValueError):
chi_squared_independence([[1, 2]])
with pytest.raises(ValueError):
chi_squared_independence([[1, 2], [3]])
with pytest.raises(ValueError):
chi_squared_independence([[1, -2], [3, 4]])
with pytest.raises(ValueError):
chi_squared_independence([[0, 0], [3, 4]])
with pytest.raises(ValueError):
chi_squared_independence([[1, 2, 3], [3, 4, 5]], yates=True)
with pytest.raises(ValueError):
chi_squared_independence([[1, 2], [3, 4]], statistic="z")
History
Karl Pearson published the statistic in 1900 and applied it to contingency tables in 1904. He used degrees of freedom. In 1922 Ronald Fisher showed that the expected counts use the margins, which removes degrees of freedom and leaves ; Pearson did not accept this at first. Frank Yates (1934) proposed the continuity correction for tables, and Fisher (1935) gave the exact conditional test. William Cochran (1952, 1954) reviewed the test and gave the rules for small expected counts that are still in common use.
References
- 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 of a contingency table)
- 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)
- William G. Cochran, Some methods for strengthening the common χ² tests, Biometrics 10(4), 1954, the recommendations on the smallest expected counts
- Alan Agresti, Categorical Data Analysis, third edition, Wiley, 2013, Chapter 3 (inference for two-way contingency tables, with the sampling schemes and residuals)
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 E5V169 Edit this page History Report an error Markdown