Fast implementation of Fisher's exact test (two-tailed). Returns the significance for the given 2x2 contingency table: < 0.05: significant < 0.01: very significant The following test shows a very significant correlation between gender & dieting: -------------
(a, b, c, d, **kwargs)
| 670 | #--- FISHER'S EXACT TEST --------------------------------------------------------------------------- |
| 671 | |
| 672 | def fisher_exact_test(a, b, c, d, **kwargs): |
| 673 | """ Fast implementation of Fisher's exact test (two-tailed). |
| 674 | Returns the significance for the given 2x2 contingency table: |
| 675 | < 0.05: significant |
| 676 | < 0.01: very significant |
| 677 | The following test shows a very significant correlation between gender & dieting: |
| 678 | ----------------------------- |
| 679 | | | men | women | |
| 680 | | dieting | 1 | 9 | |
| 681 | | non-dieting | 11 | 3 | |
| 682 | ----------------------------- |
| 683 | fisher_exact_test(a=1, b=9, c=11, d=3) => 0.0028 |
| 684 | """ |
| 685 | _cache = {} |
| 686 | # Hypergeometric distribution. |
| 687 | # (a+b)!(c+d)!(a+c)!(b+d)! / a!b!c!d!n! for n=a+b+c+d |
| 688 | def p(a, b, c, d): |
| 689 | return C(a + b, a) * C(c + d, c) / C(a + b + c + d, a + c) |
| 690 | # Binomial coefficient. |
| 691 | # n! / k!(n-k)! for 0 <= k <= n |
| 692 | def C(n, k): |
| 693 | if len(_cache) > 10000: |
| 694 | _cache.clear() |
| 695 | if k > n - k: # 2x speedup. |
| 696 | k = n - k |
| 697 | if 0 <= k <= n and (n, k) not in _cache: |
| 698 | c = 1.0 |
| 699 | for i in range(1, int(k + 1)): |
| 700 | c *= n - k + i |
| 701 | c /= i |
| 702 | _cache[(n, k)] = c # 3x speedup. |
| 703 | return _cache.get((n, k), 0.0) |
| 704 | # Probability of the given data. |
| 705 | cutoff = p(a, b, c, d) |
| 706 | # Probabilities of "more extreme" data, in both directions (two-tailed). |
| 707 | # Based on: http://www.koders.com/java/fid868948AD5196B75C4C39FEA15A0D6EAF34920B55.aspx?s=252 |
| 708 | s = [cutoff] + \ |
| 709 | [p(a+i, b-i, c-i, d+i) for i in range(1, min(b, c) + 1)] + \ |
| 710 | [p(a-i, b+i, c+i, d-i) for i in range(1, min(a, d) + 1)] |
| 711 | return sum(v for v in s if v <= cutoff) or 0.0 |
| 712 | |
| 713 | fisher_test = fisher_exact_test |
| 714 |
no test coverage detected
searching dependent graphs…