Compute the chi-square test of independence for a contingency table

Why it matters Chi-square tests check whether conversion depends on a segment, whether a feature is related to a label, and whether two annotator schemes agree beyond chance.

Are two categorical variables related, for example device type and whether a user converts? The chi-square test compares observed counts with the counts you would expect if they were independent.

Write chi2_independence(table). table is a 2D list of non-negative counts with r rows and c columns, every row and column sum positive. Expected counts are E_ij = row_i * col_j / total. Return (stat, dof, expected) where stat = sum (O_ij - E_ij)^2 / E_ij as a float, dof = (r - 1)(c - 1) as an int, and expected the float array of E_ij.

Signaturedef chi2_independence(table)

Example

table [[30, 10], [20, 40]] gives stat 16.666667, dof 1 and expected [[20, 20], [30, 30]].

Understand the idea

If device type and conversion were unrelated, the share of converters would be the same on every device. The chi-square test measures how far the real counts are from that 'no relationship' table.

Worked example: 40 mobile users (30 convert, 10 do not) and 60 desktop users (20 convert, 40 do not). Overall 50 of 100 convert, so independence predicts 20 mobile converters (40 * 50 / 100) and 30 desktop converters. Expected table: [[20, 20], [30, 30]]. Each cell's contribution: 100/20 = 5, 100/20 = 5, 100/30 = 3.33, 100/30 = 3.33, total 16.67. With dof = 1, any value above about 3.84 is significant at the 5% level, so the relationship is real.

Rule: E_ij = row_i * col_j / total, stat = sum (O - E)^2 / E, dof = (r - 1)(c - 1).

The test needs raw counts, not percentages, and expected counts should not be tiny (a common rule is at least 5). It is a standard tool for A/B tests with categories and for feature selection.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplechi2_independence([[30, 10], [20, 40]])
  • Sample 2: independentchi2_independence([[10, 20], [30, 60]])
  • Test 3: 3 by 3chi2_independence([[12, 5, 3], [7, 9, 4], [2, 6, 12]])
  • Test 4: 2 by 4chi2_independence([[5, 0, 3, 2], [1, 4, 2, 3]])