Skip to content

WIP ENH: stats._random.py add simulate conditional contingency tables - #3576

Open
josef-pkt wants to merge 2 commits into
statsmodels:mainfrom
josef-pkt:random_table
Open

josef-pkt wants to merge 2 commits into
statsmodels:mainfrom
josef-pkt:random_table

Conversation

@josef-pkt

@josef-pkt josef-pkt commented Mar 25, 2017 •

Copy link
Copy Markdown
Member

see #3557 (see also #3571 for similar idea for GLM in regression setting)

a brief exercise in simulating 2-dim contingency tables with fixed margins under independence. Given the independence assumption (probabilities are product of margins), this does not allow arbitrary probability distributions and hypothesis tests.

related #2932 for Monte Carlo p-values for unconditional multinomial sampling
see #2936 for general sampling space assumptions in contingency tables, rates and proportions.

This turned out to be just a permutation structure, first version is based on Boyett, but then I added just plain permutation case.
Permutation needs the nobs arrays, but loops for one random sample are in numpython (i.e. in C, with shuffle and bincount.) Neither shuffle nor bincount can be vectorized, so we need a loop over samples in a Monte Carlo run. One function uses a generator to yield and infinite sequence of random tables.

In contrast Patefield loops over cells and computes a random count variable in each cell. That algorithm is faster for large nobs and not very large number of cells. However, the count distribution (conditional on left over items) is more difficult to compute, and I didn't figure out the shortcut that Patefield uses, which starts at the expected cell count and then loops to increase or decrease. This extra loop wouldn't be fast in python without some vectorization.

There is no application for this yet. The target would be Kim, Agresti 1997 and similar see #3557

extras

p_table : compute the probability pmf for a specific table, IIRC it's the pmf for a multivariate hypergeometric distribution. used in the unit tests to compare MC frequencies with theoretical probabilities.

This includes now chisquare_contingency as a permutation test for 2-dimensional contingency table based on Pearson's chisquare statistic. Partially tested against an example in an article.

@josef-pkt

Copy link
Copy Markdown
Member Author

This is currently private, I'm not sure about using the generator and the appropriate api for it. One idea was that we can continue the MC after a fixed number of replications, if we need more precision, e.g. for small p-values.

(Some small nobs cases are kind of silly, In my first example there were only a few unique (<5) tables, and it wouldn't make a lot of sense to simulate 100,000 of those, if we would know that. I haven't looked at enumeration, branch and bound exact algorithms that would only work up to nobs=100 or so based on the references.)

@josef-pkt

Copy link
Copy Markdown
Member Author

related #2324 @mortonjt was working on permutation tests for scipy, that stalled (and where I got absent)

see comment in #3571 for permutation tests without identical distribution assumption, which allows wider applicability of permutation tests.
(But I got detoured to contingency tables and multinomial while looking at small sample problems for binomial and Firth bias correction #3561 )

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.0007%) to 90.296% when pulling 3ceb31e on josef-pkt:random_table into c906881 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member Author

The other motivation for conditional approaches to contingency tables is that in the large sparse case, there are enough possible tables so that (approximately) exact methods are not very conservative, in contrast to 2x2 or other small tables, or to tests on proportions. #2607

@josef-pkt

josef-pkt commented Mar 25, 2017 •

Copy link
Copy Markdown
Member Author

edit I think the asymptotic p-values below are wrong. They use the wrong degrees of freedom in the chisquare distribution (i.e. given only only 1-D distribution, not two margins fixed, we have 2 times sum(probs)=1).
(They are too far away from the exact p-values given chisquare should be appropriate.)

after adding ddof asymptotic pvalues are smaller than permutation (in 3x3 table)
ddof = (table.size - 1) - np.prod(np.asarray(table.shape) - 1)

nan
Power_divergenceResult(statistic=9.8590279127471412, pvalue=0.04287048392516779)
Power_divergenceResult(statistic=9.9504132231404956, pvalue=0.041271300034118427)
0.0742

but the chisquare statistics doesn't match statsmodels contingency table (unless I messed up again)

>>> vars(sm.stats.Table(table).test_nominal_association())
{'statistic': 7.3992462809917354, 'pvalue': 0.11623505314616689, 'df': 4}

edit: Table by default adds 0.5 which makes it even more conservative than exact

tab = sm.stats.Table(table, shift_zeros=False)
tchi2 = tab.test_nominal_association()
print(vars(tchi2))
{'statistic': 9.9504132231404956, 'df': 4, 'pvalue': 0.041271300034118386}

>>> sm.stats.Table(table, shift_zeros=False).table
array([[  1.,   0.,  10.],
       [  2.,   1.,   1.],
       [  1.,   0.,   0.]])

>>> sm.stats.Table(table, shift_zeros=True).table
array([[  1.5,   0.5,  10.5],
       [  2.5,   1.5,   1.5],
       [  1.5,   0.5,   0.5]])

a quick try: permutation p-value for chisquare statistic compared to fisher_exact, and power_divergence LR and pearson chisquare

It's not very fast with 100,000 but permutation p-value is close to fisher_exact even though fisher_exact uses a different test statistic to decide on at least as extreme tables.

a bit strange: fisher_exact has in this example a smaller p-value than the asymptotic distribution. (fisher should reject less, i.e. be more conservative, but maybe not for those numbers.)

>>> runfile("try_chisquare_permute.py")
(6.666666666666667, 0.0035601915603251069)
Power_divergenceResult(statistic=8.9200891520486945, pvalue=0.030372430084761259)
Power_divergenceResult(statistic=10.102985638699923, pvalue=0.017710702382745361)
0.00365

>>> runfile("try_chisquare_permute.py")
(4.0, 0.023842453306562032) #Fisher
Power_divergenceResult(statistic=5.4738843912020858, pvalue=0.14020899071615772)  #LR
Power_divergenceResult(statistic=6.0185185185185182, pvalue=0.11071272665869539)  #chisquare
0.02423  # chisquare permutation p-value
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 25 01:38:40 2017

Author: Josef Perktold
"""

import numpy as np
from scipy import stats
from statsmodels.stats._random import (p_table, simulate_table_permutation_gen,
                                       simulate_table_conditional)

n_row = [2, 4, 1]
n_col = [4, 1, 2]
table = np.asarray([[ 1.,  0.,  1.],
                    [ 2.,  1.,  1.],
                    [ 1.,  0.,  0.]])    

table = np.asarray([[ 8,  10,],
                    [ 10,  50]]) 

n_row = table.sum(1)
n_col = table.sum(0)
nobs = n_col.sum()
p_row = n_row / nobs
p_col = n_col / nobs
prob_ind = np.outer(p_row, p_col)
count_ind = prob_ind * nobs

res_f = stats.fisher_exact(table)

res_lr = stats.power_divergence(table.ravel(), count_ind.ravel(), lambda_="log-likelihood")
res_chi2 = stats.power_divergence(table.ravel(), count_ind.ravel(), lambda_='pearson')

print(res_f)
print(res_lr)
print(res_chi2)

chi2_stat = ((table - count_ind)**2 / count_ind).sum()

res_mc = [((simulate_table_conditional(n_row, n_col) - count_ind)**2 / count_ind).sum()
          for _ in range(100000)]
res_mc = np.asarray(res_mc)
larger = (res_mc >= chi2_stat).mean()
print(larger)

another example

table0 = np.asarray([[ 1.,  0.,  10.],
                    [ 2.,  1.,  1.],
                    [ 1.,  0.,  0.]]) 

result has pvalue lower in permutation test than asymptotic:

nan
Power_divergenceResult(statistic=9.8590279127471412, pvalue=0.27506010820151705)
Power_divergenceResult(statistic=9.9504132231404956, pvalue=0.26852353170658111)
0.0702

@josef-pkt

Copy link
Copy Markdown
Member Author

approximate number of permutations required for 10% or 20% deviation at pvalue=0.01
10000 would look fine as default, and is reasonably fast

>>> import statsmodels.stats.proportion as smprop
>>> smprop.samplesize_confint_proportion(0.01, 0.001, alpha=0.05)
38030.442324871859
>>> smprop.samplesize_confint_proportion(0.01, 0.002, alpha=0.05)
9507.6105812179649

# check
>>> smprop.proportion_confint(500, 10000, method='beta')
(0.045809942198773254, 0.054454527028378719)
>>> smprop.proportion_confint(100, 10000, method='beta')
(0.0081435965676051967, 0.012149504886066143)

@josef-pkt

Copy link
Copy Markdown
Member Author

looks good with a quick function (string reformatted by hand, needs work)

in this example asymptotic p-value overrejects compared to permutation,
confint_p_value is the confidence interval for the permutation sampling which does not include p_value_chi2

>>> res = chisquare_contingency(table, n_repl=10000)
>>> print(res)
{'text': 'Chisquare test for independence with permutation pvalue', 
'confint_p_value': (0.066525335062422072, 0.076725912088647097), 
'statistic': 9.9504132231404956, 
'p_value': 0.071499999999999994, 
'nobs': 16.0, 
'p_value_chi2': 0.041271300034118427, 
'table': array([[  1.,   0.,  10.],
       [  2.,   1.,   1.],
       [  1.,   0.,   0.]])}

@josef-pkt

Copy link
Copy Markdown
Member Author

same example, adding midp pvalue

in this example midp is only a bit smaller than exact, and inside the permutation sampling confidence interval of exact p-value.

>>> res = chisquare_contingency(table, n_repl=10000)
>>> print(res)
{'statistic': 9.9504132231404956, 
 'nobs': 16.0, 
'table': array([[  1.,   0.,  10.],
       [  2.,   1.,   1.],
       [  1.,   0.,   0.]]), 
'n_repl': 10000, 
'text': 'Chisquare test for independence with permutation pvalue', 
'confint_p_value': (0.068653672079225764, 0.078996240668038453), 
'p_value': 0.073700000000000002,
'p_value_midp': 0.070899999999999991, 
'p_value_chi2': 0.041271300034118427}

(sounds about what we would expect from the literature)

aside example is far below recommended minimum size for chisquare asymptotics.
expected counts:

>>> count_ind
array([[ 2.75  ,  0.6875,  7.5625],
       [ 1.    ,  0.25  ,  2.75  ],
       [ 0.25  ,  0.0625,  0.6875]])

(example was made up as sparse unit test case, the 10 was increased to push pvalue into the 0.05 neighborhood)

@coveralls

coveralls commented Mar 27, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.002%) to 90.299% when pulling 0fd2fd5 on josef-pkt:random_table into c906881 on statsmodels:master.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants