Skip to content

WIP ENH: exact test equality of two proportions - #2608

Open
josef-pkt wants to merge 3 commits into
statsmodels:mainfrom
josef-pkt:proportion_exact
Open

josef-pkt wants to merge 3 commits into
statsmodels:mainfrom
josef-pkt:proportion_exact

Conversation

@josef-pkt

Copy link
Copy Markdown
Member

see #2607

This PR implements an unconditional exact test for the equality of two independent proportions, either based on full max or on Berger/Boos confidence interval test.

verified and unit tested with published example and website with online calculation at print precision.

work in progress, PR so I don't forget this and can go back to other things.

main Todos

  • API
  • optimize code, currently unit test are a bit slow
    • streamline code: currently expensive repeated or unnecessary calculations
    • use special properties of test like monotonicity to shortcut calculations
    • better optimization than pure grid search, looks smooth in example but many local maxima
      I didn't see any spikes yet that are described in several references.

extend:

  • basic extension is to allow for non-zero difference in the null

@josef-pkt josef-pkt added this to the 0.8 milestone Sep 3, 2015
@josef-pkt

Copy link
Copy Markdown
Member Author

Bug ?

trying some corner cases

>>> pt = ExactTwoProportion(3, 15, 0, 3, alternative='2-sided')
>>> presbb = pt.pvalue_exact_sup(grid=('bb', 0.00001, 1001))
>>> presbb[:2]
(0.49368438383787183, 0.25835193538120982)
>>> pres = pt.pvalue_exact_sup()
>>> pres[:2]
(0.493674447364086, 0.25848399999999999)

>>> pt = ExactTwoProportion(12, 15, 3, 3, alternative='2-sided')
>>> presbb = pt.pvalue_exact_sup(grid=('bb', 0.00001, 1001))
>>> presbb[:2]
(0.57343922800130653, 0.76528307249015093)
>>> pres = pt.pvalue_exact_sup()
>>> pres[:2]
(0.57342943337482533, 0.23453199999999999)

These two pvalues should be the same. The second agrees with Berger's web application.
If y2=n2=5, then both agree and agree with Berger's result

@josef-pkt

Copy link
Copy Markdown
Member Author

The only possible explanation I can come up with is floating point precision. We calculate pvalue with strict inequality of floating point numbers which might get messed up with floating point noise if we have two theoretically equal numbers. (floating point noise is not always deterministic, not always strictly reproducible)
AFAIR, Fisher's exact test in scipy had similar problems.

-> try to add buffer multiply by (1 + 1e-15) or similar to the strict inequality check.

(randomized pvalue would have better size, but would not be welcome by statisticians, and we wouldn't get correctly randomized floating point noise :)

@josef-pkt

Copy link
Copy Markdown
Member Author

That does it
reject_mask = pv <= pvo * (1 + 1e-15)

>>> pt0 = ExactTwoProportion(3, 15, 00, 3, alternative='2-sided')
>>> presbb0 = pt0.pvalue_exact_sup(grid=('bb', 0.00001, 1001))
>>> presbb0[:2]
(0.57343922800130664, 0.23471692750979817)

>>> pres0 = pt0.pvalue_exact_sup()
>>> pres0[:2]
(0.57342943337482533, 0.23453199999999999)

Berger:

confidence interval for common p: (0.0018, 0.6971) 
test statistic = -0.8485 
Unconditional p-value = 0.5734 
Maximum p-value occurred at common p = 0.2344 

I get essentially the same, small difference in probability point of maximum

>>> presbb0[-1][1, 0], presbb0[-1][-1, 0]
(0.0018425852473596455, 0.69698987558299708)
>>> pt0.statistic_base
array([ 0.72])
>>> np.sqrt(pt0.statistic_base)
array([ 0.84852814])
>>> presbb0[:2]
(0.57343922800130664, 0.23471692750979817)
>>> pres0[:2]  # max over entire space, open interval (0,1)
(0.57342943337482533, 0.23453199999999999)

general rule: no equality or strict inequality checks with floating points

@josef-pkt

Copy link
Copy Markdown
Member Author

and the extreme corner, all endog identical
table
0, 15
0, 3

confidence interval for common p: (0.0000, 0.4923) 
Fisher's exact conditional p-value = 1.0000 
test statistic = 0.0000 
Unconditional p-value = 1.0000 
Maximum p-value occurred at common p = 0.1389 

Below is what I have right now,
sup test is essentially the same
Clopper-Pearson confidence interval for BB test has a nan -> Fix it in statsmodels.stats.proportions or in scipy
pvalue > 1 needs clipping (floating point noise or because of BB additive term)

import statsmodels.stats.proportion as smprop
>>> smprop.proportion_confint(0, 18, method = 'beta', alpha=0.01)
(nan, 0.25498502848277477)

>>> smprop.proportion_confint(18, 18, method = 'beta', alpha=0.01)
(0.74501497151722496, nan)
>>> pt00 = ExactTwoProportion(0, 15, 00, 3, alternative='2-sided')
>>> presbb00 = pt00.pvalue_exact_sup(grid=('bb', 0.00001, 1001))
C:\programs\WinPython-64bit-3.4.3.1\python-3.4.3.amd64\lib\site-packages\scipy\stats\_discrete_distns.py:42: RuntimeWarning: invalid value encountered in greater_equal
  return (n >= 0) & (p >= 0) & (p <= 1)
C:\programs\WinPython-64bit-3.4.3.1\python-3.4.3.amd64\lib\site-packages\scipy\stats\_discrete_distns.py:42: RuntimeWarning: invalid value encountered in less_equal
  return (n >= 0) & (p >= 0) & (p <= 1)

>>> presbb00[:2]
(nan, nan)
>>> presbb00[-1][1, 0], presbb00[-1][-1, 0]
(nan, 0.49242720857566308)
>>> pt00.statistic_base
array([ 0.])
>>> pt00.pvalue_base
array([ 1.])
>>> pres00 = pt00.pvalue_exact_sup()
>>> pres00[:2]
(1.0000000000000047, 0.75648599999999999)
>>> pt00 = ExactTwoProportion(15, 15, 3, 3, alternative='2-sided')
>>> presbb00 = pt00.pvalue_exact_sup(grid=('bb', 0.00001, 1001))
>>> presbb00[-1][1, 0], presbb00[-1][-1, 0]
(nan, nan)
>>> presbb00[:2]
(nan, nan)
>>> pres00 = pt00.pvalue_exact_sup()
>>> pres00[:2]
(1.0000000000000047, 0.75648599999999999)
>>> pt00.statistic_base
array([ 0.])
>>> pt00.pvalue_base
array([ 1.])

@josef-pkt

Copy link
Copy Markdown
Member Author

Possible complication:

bb uses closed interval for grid search, sup uses open interval (0, 1)
I haven't checked behavior at the prob = 0 or 1 bounds.

I'm still missing the method that calculates exact distribution pvalue as a function for a given probability. (It's currently duplicated in two methods.)

edit:

corners prob = 0 and prob = 1 look fine. I can reuse grid for single probability

>>> pres01 = pt00.pvalue_exact_sup(grid=np.linspace(0,1,6))
>>> pres01[-1]
array([[ 1. ,  1. ],
       [ 0. ,  1. ],
       [ 0.2,  1. ],
       [ 0.4,  1. ],
       [ 0.6,  1. ],
       [ 0.8,  1. ],
       [ 1. ,  1. ]])
>>> pt00.pvalue_exact_sup(grid=np.array([0]))
(1.0, 1.0, 0, array([[ 1.,  1.],
       [ 0.,  1.]]))
>>> pt00.pvalue_exact_sup(grid=np.array([1]))
(1.0, 1.0, 0, array([[ 1.,  1.],
       [ 1.,  1.]]))

As mentioned before, we never reject equality of proportions at observations (0,0) or (1,1) which are the only ones as extreme as the observed (0,0) or (1,1)

@josef-pkt

Copy link
Copy Markdown
Member Author

Taking reject mask out of loop is large speedup (7 times)

Replacing mask with evaluating at rejection points yields only a smaller speedup in example 0.25 -> 0.21 seconds (fancy indexing is more costly than broadcasting and will only pay off if rejection region is small enough compared to full sample space)

This looks like the best we can do, without exploiting monotonicity and a fast cdf/sf if available.
Also, I'm not using symmetry yet (if or when it applies).
Using monotonicity to infer the rejection region from the boundary, would also save on calculating the test statistic for the entire sample space. But that's not in a loop for max pvalue and won't save much (relative to cost of max loop).

@josef-pkt

Copy link
Copy Markdown
Member Author

still not improved: I'm using a 1000 point grid search for maximum pvalue, which sounds overkill in smooth cases with just a few local maxima.

@josef-pkt

Copy link
Copy Markdown
Member Author

example with spike (in one sided test case)

replicates example and Figure 3 in Berger 1996 "More Powerful Tests from Confidence Interval p Values", The American Statistician Vol. 50 No. 4

>>> pt0 = ExactTwoProportion(21, 33, 14, 17, alternative='1s')
>>> pres0 = pt0.pvalue_exact_sup()
>>> pres0[:2]
(0.15486659938560585, 0.025950000000000001)
>>> presbb = pt0.pvalue_exact_sup(grid=('bb', 0.001, 1001))
>>> presbb[:2]
(0.095585405499373846, 0.83055193942804006)
>>> import matplotlib.pyplot as plt
>>> plt.plot(pres0[-1][1:, 0], pres0[-1][1:, 1])

With two-sided alternative, both pvalues, bb and sup, are around 0.021 (i.e. no spike to drive up sup)

@josef-pkt

Copy link
Copy Markdown
Member Author

I think this should go in with some cleanup/docstrings even if we haven't settled on an API or a new all-in-one approach.

similar PR #2723 with also essentially finished functions, but different API.

@josef-pkt josef-pkt modified the milestones: 0.9, 0.8 Feb 9, 2017
@coveralls

coveralls commented May 20, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.02%) to 90.45% when pulling 3facf93 on josef-pkt:proportion_exact into 90e2af8 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member Author

rebased (no merge conflicts)

alternative=alternative)


def statistic(self, y1, y2, prob_var=None, alternative='2-sided'):

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no docstring

Currently the p-value when (p1, p2) is either (0, 0) or (1, 1) is one, i.e.
it is never in the rejection region. This implies that the pvalue is
always conservative if the both true probabilities approach zero or one.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no Parameter section

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no References in docstrings

@josef-pkt

josef-pkt commented May 20, 2017 •

Copy link
Copy Markdown
Member Author

API maybe there should be a helper function with method argument to have a standard function API

returns are numbers and tuples not results instances,

everything is in a class, so it might be possible to extend to add conf_int later.

class name: ExactTwoProportion maybe reverse names to Proportions2sampExact or porportions_2samp_exact for function. Do we use 2samp similar to scipy.stats?

Also this is in a private module and needs to be added to a public module proportions and to api.py

@josef-pkt

Copy link
Copy Markdown
Member Author

cross-ref #3952 R DescTools also has BinomDiffCI and BinomRatioCI with several methods
#2605 has reference to R PropCI with permission to translate it.

@josef-pkt

Copy link
Copy Markdown
Member Author

rebased, no merge conflicts

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.03%) to 81.917% when pulling fecdd8d on josef-pkt:proportion_exact into 5b8f20d on statsmodels:master.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.03%) to 81.917% when pulling fecdd8d on josef-pkt:proportion_exact into 5b8f20d on statsmodels:master.

pval_asymp = pt.pvalue_base
assert_allclose(pval_asymp, pval_lj_asymp, rtol=0, atol=5e-5)
pval_mle = pt.pvalue_exactdist_mle()
#assert_allclose(pval_mle, pval_lj_mle, rtol=0, atol=5e-5)

@josef-pkt josef-pkt Nov 1, 2017 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why is this commented out?

Ling Yang don't have the mle version?

@josef-pkt josef-pkt modified the milestones: 0.9, 0.10 Jul 20, 2018
@josef-pkt

Copy link
Copy Markdown
Member Author

bump for 0.10
It's better to get this in than waiting for a clear API forever.

Maybe a general entry-point function like test_two_proportions that delegates to various special method classes or functions. (i.e. something easy to use that hides all the details, but doesn't reuse intermediate results if several results are requested).

Need also more of the other tests equivalent to confidence interval methods for #2605

if alternative == '2-sided':
pvalue = stats.chi2.sf(stat, 1)
else:
pvalue = stats.norm.sf(stat)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this needs to distinguish larger or smaller

@josef-pkt

Copy link
Copy Markdown
Member Author

PR/docstrings are missing references, e.g. Berger web site and what is Ling Yang?
What references did I use to write the code?

Is it easy to extend to non-zero "value"?

prob2 = stats.binom.pmf(np.arange(n2 + 1), n1, self.prob_pooled)

prob = prob1[None, :] * prob2[:, None]
pvemp = prob[pv < pvo].sum()

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why does this use strict inequality?

@josef-pkt

Copy link
Copy Markdown
Member Author

This only allows for equality null hypothesis, H0: prop1 = prop2
If we change it to be similar to the poisson etest implementation, then we can add value for nonzero null hypothesis.
We need constrained mle for value !=0, "score" method.

I'm not sure about using a class based implementation. In poisson, I only used functions.
Also, I could make the class private initially and have the public access through a method argument.
e.g. etest_poisson is a separate function, but can be used through test_poisson_2indep.
poisson etest has option compare, ratio and diff

(In my recent round of stats for poisson rates, I didn't look at exact methods for 2indep.) for nonzero null.

try to target exact methods for proportion and rates for 2indep for 0.15

@josef-pkt josef-pkt modified the milestones: 0.14, 0.15 Jun 23, 2022
@josef-pkt josef-pkt mentioned this pull request Jun 23, 2022
6 tasks
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