Chi-square (χ²) Test

The chi-square test compares counts you observed against the counts a null hypothesis predicts:

\[ \chi^2 = \sum_i \frac{(O_i - E_i)^2}{E_i} \]

The three common forms — goodness of fit, independence, and homogeneity — differ in where the expected counts come from, not in the arithmetic.

Expected counts come from the margins

import numpy as np
from scipy.stats import chi2_contingency, chi2

observed = np.array([[300, 200], [280, 220]])
res = chi2_contingency(observed, correction=False)
print(f"  observed counts\n{observed}")
print(f"  expected under independence\n{np.round(res.expected_freq, 2)}")
print(f"    chi-square = {res.statistic:.6f}   df = {res.dof}   p = {res.pvalue:.6f}")
manual = float((((observed - res.expected_freq) ** 2) / res.expected_freq).sum())
print(f"    computed from the formula directly: {manual:.6f}")
"""Expected counts come from the margins alone: row total times column total
   over the grand total. The statistic asks how far the cells stray from that."""

print(f"\n  the statistic scales with the sample, and the proportions do not:")
print(f"{'sample size':>13}{'chi-square':>13}{'p-value':>13}{'row 1 share':>14}{'row 2 share':>14}")
for k in (1, 2, 10, 100):
    table = observed * k
    r = chi2_contingency(table, correction=False)
    print(f"{table.sum():>13,}{r.statistic:>13.4f}{r.pvalue:>13.6f}"
          f"{table[0, 0] / table[0].sum():>14.4f}{table[1, 0] / table[1].sum():>14.4f}")
print("  60% against 56% in every row. Multiply the counts by a hundred and the")
print("  same difference moves from p = 0.2000 to p far below 0.05")
print("  - chi-square answers 'is it there', never 'is it large'")

print(f"\n  the expected-count rule, and what happens when it is broken:")
sparse = np.array([[12, 3, 1], [10, 4, 0]])
r = chi2_contingency(sparse, correction=False)
print(f"    a table with expected counts\n{np.round(r.expected_freq, 2)}")
print(f"    cells below 5: {(r.expected_freq < 5).sum()} of {r.expected_freq.size}")
print(f"    reported p = {r.pvalue:.6f}, but the chi-square approximation to the")
print(f"    sampling distribution needs checking; consider exact or resampling methods")

print(f"\n  and the statistic is a distance, so it never says which way:")
for name, table in (("more in the first cell", np.array([[300, 200], [200, 300]])),
                    ("mirrored", np.array([[200, 300], [300, 200]]))):
    r = chi2_contingency(table, correction=False)
    print(f"    {name:>24}: chi-square {r.statistic:.6f}")
print("  identical statistics for opposite associations - direction comes from")
print("  the residuals, and strength from a normalized measure such as Cramer's V")
#   observed counts
# [[300 200]
#  [280 220]]
#   expected under independence
# [[290. 210.]
#  [290. 210.]]
#     chi-square = 1.642036   df = 1   p = 0.200046
#     computed from the formula directly: 1.642036
#
#   the statistic scales with the sample, and the proportions do not:
#   sample size   chi-square      p-value   row 1 share   row 2 share
#         1,000       1.6420     0.200046        0.6000        0.5600
#         2,000       3.2841     0.069955        0.6000        0.5600
#        10,000      16.4204     0.000051        0.6000        0.5600
#       100,000     164.2036     0.000000        0.6000        0.5600
#   60% against 56% in every row. Multiply the counts by a hundred and the
#   same difference moves from p = 0.2000 to p far below 0.05
#   - chi-square answers 'is it there', never 'is it large'
#
#   the expected-count rule, and what happens when it is broken:
#     a table with expected counts
# [[11.73  3.73  0.53]
#  [10.27  3.27  0.47]]
#     cells below 5: 4 of 6
#     reported p = 0.549729, but the chi-square approximation to the
#     sampling distribution needs checking; consider exact or resampling methods
#
#   and the statistic is a distance, so it never says which way:
#       more in the first cell: chi-square 40.000000
#                     mirrored: chi-square 40.000000
#   identical statistics for opposite associations - direction comes from
#   the residuals, and strength from a normalized measure such as Cramer's V

The first block shows where the expected table comes from: row total times column total over the grand total, and nothing else. The statistic asks how far the observed cells stray from what the margins alone would predict, and computing the formula by hand reproduces SciPy's 1.642036 exactly.

That construction is why the test has degrees of freedom \((r-1)(c-1)\) rather than \(rc\): the margins are taken as given, so they cost information. It is also why the test says nothing about the margins themselves — only about whether the interior is consistent with them.

The statistic is an amount of evidence, not an amount of effect

The second block is the property most worth internalizing. The same two proportions — 60% against 56% — scale from 1,000 rows to 100,000. The chi-square statistic goes 1.6420, 3.2841, 16.4204, 164.2036, growing exactly in proportion to the sample. The p-value goes from 0.2000 to effectively zero.

Nothing about the relationship changed. Chi-square answers whether a difference is there, never whether it is large, and, under the test assumptions, its power to detect a fixed nonzero difference increases as the sample grows. A finite sample still does not guarantee detection. A significant chi-square on a million-row table is close to uninformative on its own; it needs an effect size such as Cramér's V beside it.

The fourth block adds the other half of that limitation. Two tables with opposite associations produce the identical statistic, 40.000000. The statistic is a squared distance, so it has no sign and no direction. Which way the association runs has to be read from the residuals — which cells exceeded their expectation and by how much.

When the approximation stops working

The third block breaks the standard rule deliberately. In a sparse table, four of six expected counts fall below 5, and SciPy still returns a p-value of 0.549729 without complaint.

The number is computable, but sparse expected counts warn that the chi-square approximation may be inaccurate. The chi-square distribution is an approximation to the true distribution of the statistic, and it holds when the expected counts are large enough — the usual guidance being at least 5 in most cells. This is a guideline for checking approximation accuracy, not a guarantee that every table below it gives a wrong p-value. A suitable exact, permutation, or Monte Carlo method can assess the sparse table; lowering the significance threshold does not repair the approximation.

Three further conditions are easy to violate without noticing. The data must be counts of independent observations, so percentages, averages and repeated measurements on the same units are all out. Each observation must fall in exactly one cell. And the counts must be raw — rescaling a table to percentages and running the test multiplies the statistic by whatever the rescaling factor was, which the second block shows is the one thing that moves the result most.

References


Discover more from Insightful Data Lab

Subscribe to get the latest posts sent to your email.

Similar Posts

Questions, corrections, or additional insights?

This site uses Akismet to reduce spam. Learn how your comment data is processed.