Returns (X2, P) for the n x m observed and expected data (containing absolute frequencies). If expected is None, an equal distribution over all classes is assumed. If df is None, it is the number of classes-1 (i.e., len(observed[0]) - 1). P < 0.05: significant P < 0.
(observed=[], expected=[], df=None, tail=UPPER)
| 745 | return [[n[i] * m[j] / s for j in range(len(O[i]))] for i in range(len(O))] |
| 746 | |
| 747 | def pearson_chi_squared_test(observed=[], expected=[], df=None, tail=UPPER): |
| 748 | """ Returns (X2, P) for the n x m observed and expected data (containing absolute frequencies). |
| 749 | If expected is None, an equal distribution over all classes is assumed. |
| 750 | If df is None, it is the number of classes-1 (i.e., len(observed[0]) - 1). |
| 751 | P < 0.05: significant |
| 752 | P < 0.01: very significant |
| 753 | This means that if P < 5%, the data is unevenly distributed (e.g., biased). |
| 754 | The following test shows that the die is fair: |
| 755 | --------------------------------------- |
| 756 | | | 1 | 2 | 3 | 4 | 5 | 6 | |
| 757 | | rolls | 22 | 21 | 22 | 27 | 22 | 36 | |
| 758 | --------------------------------------- |
| 759 | chi2([[22, 21, 22, 27, 22, 36]]) => (6.72, 0.24) |
| 760 | """ |
| 761 | # The P-value (upper tail area) is obtained from the incomplete gamma integral: |
| 762 | # P(X2 | v) = gammai(v/2, x/2) with v degrees of freedom. |
| 763 | # See: Cephes, https://github.com/scipy/scipy/blob/master/scipy/special/cephes/chdtr.c |
| 764 | O = observed |
| 765 | E = expected or _expected(observed) |
| 766 | df = df or (len(O) > 0 and len(O[0])-1 or 0) |
| 767 | X2 = 0.0 |
| 768 | for i in range(len(O)): |
| 769 | for j in range(len(O[i])): |
| 770 | if O[i][j] != 0 and E[i][j] != 0: |
| 771 | X2 += (O[i][j] - E[i][j]) ** 2.0 / E[i][j] |
| 772 | P = gammai(df * 0.5, X2 * 0.5, tail) |
| 773 | return (X2, P) |
| 774 | |
| 775 | chi2 = chi_squared = pearson_chi_squared_test |
| 776 |
no test coverage detected
searching dependent graphs…