#109Chi-Square Test of IndependenceMedium

Chi-Square Test of Independence

Background

The chi-square test of independence asks whether two categorical variables (e.g. arm vs converted) are statistically independent. It compares the observed contingency-table counts to those expected under independence; large discrepancies imply dependence.

Problem statement

Implement chi_square_independence(observed) returning (chi2, df) where:

Eij  =  (row total i)(col total j)grand total,χ2  =  i,j(OijEij)2Eij,df=(R1)(C1)E_{ij} \;=\; \frac{(\text{row total } i) \cdot (\text{col total } j)}{\text{grand total}},\qquad \chi^2 \;=\; \sum_{i, j}\frac{(O_{ij} - E_{ij})^2}{E_{ij}},\qquad \mathrm{df} = (R - 1)(C - 1)

Input

  • observednp.ndarray shape (R,C)(R, C) of non-negative integer counts.

Output

Returns a tuple (chi2: float, df: int). chi2 >= 0; df = (R-1)(C-1).

Examples

Example 1 — independent counts

Input:  [[10, 20], [10, 20]]
Output: (~0.0, 1)

Explanation: rows are scaled copies of each other → exactly independent → χ20\chi^2 \approx 0.

Example 2 — strong dependence

Input:  [[100, 0], [0, 100]]
Output: large chi2, df = 1

Example 3 — three-by-three table

Input:  [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output: small chi2, df = 4

Constraints

  • Cells with Eij=0E_{ij} = 0 are skipped (otherwise dividing by zero).
  • Returns plain Python float and int.
  • For small expected counts (E<5E < 5), the chi-square approximation breaks; this problem does not enforce that — caller's responsibility.

Notes

  • Yates correction. For 2×2 tables some statisticians subtract 0.5 from OE|O - E| before squaring (Yates' continuity correction). Out of scope here.
  • Reads with scipy. Combine with scipy.stats.chi2.sf(stat, df) to get a pp-value.
Python
Loading...

▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.

  • reference: independent counts give chi2 near zero
  • example: 3x3 table has df = (3-1)(3-1) = 4
  • sample: chi2 on [[10,20],[30,40]]