Chi-Square Test
Chi-Square Test
Given an r×c contingency table C, compute the chi-square test statistic and expected frequency table for testing independence.
Chi-Square Test for Independence:
Test Statistic:
χ2=∑E(O−E)2Expected Frequencies:
Eij=totalrowi⋅coljFunction Arguments
C: 2D array- Contingency table (observed frequencies)
Examples
Input: C=[[10,20],[20,10]]
Output: chi2=6.667, expected=[[15,15],[15,15]]
Input: C=[[20,30],[40,60]]
Output: chi2=0.0, expected=[[20,30],[40,60]]
Input: C=[[25,25],[25,25]]
Output: chi2=0.0, expected=[[25,25],[25,25]]
Hint 1
Use np.sum() with axis parameter for row/column totals.
Hint 2
Use np.outer() to compute expected frequencies matrix.
Hint 3
Chi-square: np.sum((C - expected) ** 2 / expected).
Requirements
- Return tuple: (chi2, expected)
- chi2: scalar float
- expected: NumPy array (same shape as C)
- Vectorized computation (no nested loops)
Constraints
- C is 2D array with positive integers
- NumPy only; time limit: 300ms
Log in to take notes on this problem
Accepts: array
Chi-Square Test
Chi-Square Test
Given an r×c contingency table C, compute the chi-square test statistic and expected frequency table for testing independence.
Chi-Square Test for Independence:
Test Statistic:
χ2=∑E(O−E)2Expected Frequencies:
Eij=totalrowi⋅coljFunction Arguments
C: 2D array- Contingency table (observed frequencies)
Examples
Input: C=[[10,20],[20,10]]
Output: chi2=6.667, expected=[[15,15],[15,15]]
Input: C=[[20,30],[40,60]]
Output: chi2=0.0, expected=[[20,30],[40,60]]
Input: C=[[25,25],[25,25]]
Output: chi2=0.0, expected=[[25,25],[25,25]]
Hint 1
Use np.sum() with axis parameter for row/column totals.
Hint 2
Use np.outer() to compute expected frequencies matrix.
Hint 3
Chi-square: np.sum((C - expected) ** 2 / expected).
Requirements
- Return tuple: (chi2, expected)
- chi2: scalar float
- expected: NumPy array (same shape as C)
- Vectorized computation (no nested loops)
Constraints
- C is 2D array with positive integers
- NumPy only; time limit: 300ms
Log in to take notes on this problem
Accepts: array