PROBABILITY & STATISTICS / 10. CHI-SQUARED TEST
Chi-Squared Test
Testing categorical data — goodness of fit and independence
EXPLANATION
The Chi-squared (χ²) test works on categorical data — counts and frequencies. Two main uses: 1. Goodness of Fit test: "Does my observed data fit the expected distribution?" H₀: data follows the expected distribution χ² = Σ (Observed - Expected)² / Expected 2. Test of Independence: "Are two categorical variables related?" H₀: the two variables are independent χ² = Σ (Oᵢⱼ - Eᵢⱼ)² / Eᵢⱼ where Eᵢⱼ = (row total × col total) / grand total Degrees of freedom: • Goodness of fit: df = k - 1 (k = number of categories) • Independence: df = (rows-1) × (cols-1) Large χ² → observed data is far from expected → evidence against H₀. Rule of thumb: expected frequency in each cell should be ≥ 5 for the test to be valid. In ML: used for feature selection — is this feature statistically associated with the target? sklearn's chi2 selector uses this.
DIAGRAM
Goodness of fit — is a die fair?
Observed: [18, 22, 15, 20, 17, 28] (n=120)
Expected: [20, 20, 20, 20, 20, 20] (uniform)
χ² = (18-20)²/20 + (22-20)²/20 + ... = 4.90
df = 6-1 = 5
p-value = 0.428 → fail to reject → die appears fair
Independence test — contingency table:
Spam Ham
Contains $ [ 80 | 10 ] = 90
No $ [ 20 | 90 ] = 110
─────────────
100 100 200
E[spam,$] = 100×90/200 = 45
Large deviation from expected → reject independenceCODE