Skip to content

ENH: simultaneous confidence intervals for multinomial proportions (rebased) - #2953

Merged
josef-pkt merged 1 commit into
statsmodels:masterfrom
wehlutyk:multinomial-confint
Aug 16, 2016
Merged

josef-pkt merged 1 commit into
statsmodels:masterfrom
wehlutyk:multinomial-confint

Conversation

@wehlutyk

@wehlutyk wehlutyk commented May 17, 2016 •

Copy link
Copy Markdown
Contributor

This should (at least partially) close #2895 (thanks for the help in that discussion!), implementing the "Goodman" and "Sison & Glaz" methods. No existing code was used for the implementation (aside from the MultinomialCI R package for generating test values and finding bugs by comparing intermediate values).

A few notes:

  • I just found out about the informal commit format standard, so commit messages don't all follow it; sorry about that (although rebasing+squashing could solve this I believe). I also tried to follow the general code style, but there might be fixes to do (e.g. I define several local functions for sison_glaz).
  • I didn't include this addition in docs/source/release/versionX.X.rst, I'm not sure if it qualifies for it.
  • I'm having a few problems building the docs: see Hurdles in building the docs #2952 for this
  • Another method that might be interesting to implement is Hou, Chiang, & Tai (2003), using monte-carlo simulations to find more accurate CIs. But it's too much work for me right now.
  • Another nice feature I did not implement would be some advice (in the form of warnings) on which method to use depending on what counts looks like (e.g., very high number of categories ➔ use sison_glaz). But I'd need some help in determining the exact advice to give.
  • Performance can be easily improved if necessary (e.g. with a cache on nu(c)).

@josef-pkt

Copy link
Copy Markdown
Member

very good, thanks
I'll go over it in the next few days.

I tried this also in PR #2932 but going the long generic way which didn't work out so well.
But I have MonteCarlo box probability and p-values included, but not yet MonteCarlo confidence intervals.

@wehlutyk

Copy link
Copy Markdown
Contributor Author

Great, thanks! the monte-carlo methods look really neat, great that you already have part of it.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.02%) to 85.431% when pulling 17cef19 on wehlutyk:multinomial-confint into fd90132 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member

a few general comments:

based on some comments Sison and Glaz is mainly good if the proportions are roughly equal. The width of the confidence interval is independent of the proportion, and therefore also of the variance.

One thought is to extend or correct asymptotic confidence intervals with approximately exact coverage, so the joint confidence region would also depend on the variance and not be equal width.
I didn't look at the Hu et all 2003 article yet.

One possibility to add is monte carlo calculation for the probability, so it's possible to check whether the edgeworth based approximation is good for specific cases. I started to do that but for bug hunting because my implementation didn't work correctly, and might still be incorrect in corner cases.
I was running the MC probabilities in batches up to a million replications to see the accuracy at several decimals. 50000 replication is fast an good for a quick cross-check.

@josef-pkt

Copy link
Copy Markdown
Member

about the monte carlo:

I have currently two functions, one for box probability, and one that uses a call back which I used with scipy.stats.chisquare rejection boolean for p-values. This can be used also for other statistics like Cressie-Read divergence which is also in scipy.stats (and an older version in statsmodels)
These MC functions are good for calculating probabilities once, i.e. we need only a single run through all the replications.

For confidence intervals I think we have to store the monte carlo results so we can search for the bounds. This will be more difficult to do in batches without larger memory requirement. I guess what should work is to keep only the largest and smallest alpha or similar fraction of replications. across batches.

@wehlutyk

Copy link
Copy Markdown
Contributor Author

About this:

based on some comments Sison and Glaz is mainly good if the proportions are roughly equal. The width of the confidence interval is independent of the proportion, and therefore also of the variance.

I'd like to make sure the advice in the docs is good: is it that the method is more accurate when the proportions are roughly equal (I also read that but couldn't find justification for it in the paper), or is it that, since the widths produced are all equal, it's most useful when the proportions are roughly equal?

@josef-pkt

Copy link
Copy Markdown
Member

It's now 12 days, and I looked at many other things in the meantime, so I'm not really focused on the details anymore.

The function looks good and straight to the point of providing the confidence intervals. Unit test coverage looks also good.
I won't be able to get into this for at least another week and would prefer to merge it as is, than let it wait longer because it implements two standard methods.

@wehlutyk I also saw your issue/PR for Julia. I guess there are still small sample cases with counts close to zero where neither goodman nor sison-glaz will be very accurate.
I read some articles for small sample confidence regions, but those regions are elliptical or have other difficult shapes that cannot be easily summarized by confidence intervals. My best guess right now is that parametric bootstrap/monte carlo will be the best for those cases. However, I didn't manage yet to finish my PR for that.

I still don't have any better or more precise recommendation for the choice of method than sison-glaz is appropriate when the proportions are similar in magnitude, based on what I read.

Do you think we can merge as is, or is there a part or case that I should specifically look at?

About location and api: I think it fits well in proportions for users, but if there is more extra (largely internal) code, then I think we can keep it in an internal modul _multinomial as I started in my PR.

@josef-pkt josef-pkt added this to the 0.8 milestone May 30, 2016
Comment thread statsmodels/stats/proportion.py Outdated

Returns
-------
array of [float, float] arrays

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

should start with some descriptive name similar to Parameters, e.g.
confint : ndarray

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

proportion_confint returns a tuple, What's our convention for the shape/type of confint?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

  • confint : ndarray: ok, will do
  • shape/type of confint: since proportion_confint returns a tuple, I returned an array of such confints. It can be an array of tuples to be closer to that conventions, or (as now) a 2D ndarray which is more efficient. You tell me.

Comment thread statsmodels/stats/proportion.py Outdated
"""Compute mu_r, the r-th factorial moment of a poisson random
variable of parameter `l` truncated to `interval = (b, a)`."""
b, a = interval
return l ** r * (1 - ((poisson_interval((a - r + 1, a), l) -

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

l is not a good name because it looks too much like 1
I was reading 1**r

@wehlutyk wehlutyk Jun 18, 2016 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Right, changed to p. (Although I remember this problem appears pretty often, GitHub's rendering on my browser is particularly bad at this (might be my available fonts). In my terminal 1 and l look really different (DejaVu Sans Mono).)

@wehlutyk

Copy link
Copy Markdown
Contributor Author

@josef-pkt sorry for the lag, I've been swamped with work in the last two weeks. I was going to say I wanted to review the doc a little before you could merge, but now that you've reviewed thoroughly (which is awesome thanks!) I'll do the corrections to it all starting today.

@wehlutyk

Copy link
Copy Markdown
Contributor Author

Don't hesitate for more comments if you want other changes (I'll react faster this time). Otherwise I think it's ready to merge.

@coveralls

coveralls commented Jun 18, 2016 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.007%) to 85.42% when pulling 614f158 on wehlutyk:multinomial-confint into fd90132 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member

@wehlutyk Thanks, I'll try to go through it tonight, when I have time again, so we can merge it soon.

@josef-pkt

Copy link
Copy Markdown
Member

(too tired today to finish up checking)

overall changes look good

the only thing to check is whether there is a convention for the return shape or type of confint
I'm still not sure about the explanation in the notes, but it's fine. Maybe I have time to look at sison-glaz paper again.
(The main point of sison-glaz I think is that it's an (asymptotic) approximation to the exact small sample multinomial distribution/probabilities instead of depending on normal or chisquare asymptotic distribution of a test statistic.)

@wehlutyk

Copy link
Copy Markdown
Contributor Author

Okay, I'll leave #3006 to you, you know the codebase with its conventions a lot better.

About the explanation notes (which I'd like to be good, so let's take the time to get it right): there's two approximations in the paper:

  • the edgeworth expansion lets them compute P(b_i <= X_i <= a_i, i = 1 ... k) with an approximation that converges with k going to infinity (i.e. the number of categories)
  • then they can look for an integer c that make intervals at the right confidence level. But to do that in theory they need access to the real p_i (eq. (6)), and so to get around that they approximate eq. (6) with eq. (7), an approximation that stands on a Central Limit Theorem-like result, converging for n going to infinity (so number of observations)

This is what I meant in the explanation, admittedly not very clear (here either I guess).

@josef-pkt

Copy link
Copy Markdown
Member

shape of confint is good, it's the same as OLS(...).fit().conf_int(). So no convention problem here (which doesn't rule out inconsistent pattern in other stats, especially with respect to unpacking into lower, upper)

fails if there are zero counts (It's not a reason to block merge, I don't think I have seen mention of that case in the articles, in some cases for contingency tables there is an option to make counts/proportions stay away from boundaries)

import statsmodels.stats.proportion as smprop

methods = ['goodman', 'sison_glaz']

p = [56, 72, 73, 59, 62, 87, 58]
p = [56, 0.5, 73, 59, 62, 87, 58]
p = [1, 1, 3, 2, 4]
#p = [1, 0, 3, 2, 4]  #error "Exception: Couldn't find a value for `c` ..."
for method in methods:
    ci = smprop.multinomial_proportions_confint(p, 0.05, method=method)
    print(ci)
    print()

@josef-pkt

Copy link
Copy Markdown
Member

to finish up: I would rewrite the notes to mention the approximation to the exact multinomial probability and that the probability is evaluated using the maximum likelihood estimate of the proportions.
That would avoid getting into the details for justifying MLE convergence.

Also this needs a rebase before merging.

This includes tests. There are a number of todos added here and there,
and in the documentation, corresponding to what comes next (Goodman
method and advice on what to use when).

DOCS: explain where the multinomial CI tests come from

TST: add missing test from Sison & Glaz paper

Also define precision for the tests in the results file, and do some
code style fixes.

DOCS: cleanup before a real pass on method advice

EHN: implement goodman method for multinomial CIs

This includes tests.

REF: refactor to fix function name

FIX: integer division don't behave the same under py2 and py3

DOC: reduce 'TODO' ambitions a little

The Hou-Chiang-Tai method would be interesting to implement, but would
take a lot more time.

DOC: fill docstring for multinomial_proportions_confint

FIX: assert_raises_regex is not available in numpy < 1.9

FIX: allow null values in `counts`

DOC: Formatting, and include multinomial_confint docstring in docs

DOC: formatting and phrasing

BUG: str.format() does not exist in python < 2.7

DOC: formatting

DOC: a few more details and coming closer to conventions

STY: variable names and performance

* Don't use `l`, which can be mixed up with `1`
* Use exp sum log instead of product division
* Use `np.minimum` and `np.maximum`

EHN: update method name matching and checks on `counts`

In particular, counts can't have 0-valued entries, as the behavior is
undefined in that case.

DOC: clarify details of the sison-glaz method
@wehlutyk
wehlutyk force-pushed the multinomial-confint branch from 50ec157 to 44dc808 Compare June 27, 2016 08:17
@wehlutyk

Copy link
Copy Markdown
Contributor Author

Right, so:

  • added a 0-valued counts check, which raises an exception with proper explanation and suggestion
  • fixed the method name handling so only check if it starts with 'sison'
  • fixed notes about sison-glaz method, mentioning approximation+MLE, and convergence conditions
  • rebased and squashed

I think we're good to go now, unless I missed anything!

@wehlutyk

Copy link
Copy Markdown
Contributor Author

(pending completion of the tests of course)

@coveralls

coveralls commented Jun 27, 2016 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.01%) to 88.825% when pulling 44dc808 on wehlutyk:multinomial-confint into 032a9ab on statsmodels:master.

@wehlutyk wehlutyk changed the title ENH(WIP): simultaneous confidence intervals for multinomial proportions ENH: simultaneous confidence intervals for multinomial proportions (rebased) Jun 30, 2016
@wehlutyk

Copy link
Copy Markdown
Contributor Author

Any chance we can merge this? I think all concerns have been addressed :)

@josef-pkt

Copy link
Copy Markdown
Member

We can merge it into master (for 0.9).
I added the backport tag as reminder for me to go over it (in the next few days).
Because it's all new functionality, there is no serious reason not to still add it to 0.8

@wehlutyk

Copy link
Copy Markdown
Contributor Author

Great, thanks!

@josef-pkt

Copy link
Copy Markdown
Member

I checked out the branch that I had before, from 2016-06-18 05:55:31, and I don't see the problem with zero counts/proportions in that case anymore.
Also goodman should always work with zero counts.
So, I think raising an exception is too strong.

(I haven't tried the current version of this PR yet.)

for p = [1, 0, 3, 2, 4] I get

goodman
[[ 0.0118515   0.50723177]
 [ 0.          0.39885409]
 [ 0.07956632  0.67997532]
 [ 0.04013115  0.5991813 ]
 [ 0.12793056  0.75184026]]

sison_glaz
[[ 0.         0.4794962]
 [ 0.         0.3794962]
 [ 0.1        0.6794962]
 [ 0.         0.5794962]
 [ 0.2        0.7794962]]

@josef-pkt

Copy link
Copy Markdown
Member

Because sison-glatz uses uniform width, there shouldn't be inherent problems with 0 counts.
Wald based intervals, or intervals that use the MLE, which is zero for zero counts, will have problems, including my bootstrap version, IIRC, (at least if it is based on wald interval shapes).

(BTW: I might be using now more recent versions of dependencies, numpy, scipy, than I did in June.)

@josef-pkt

Copy link
Copy Markdown
Member

The rootfinding problem is independent of the zero count


---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
<ipython-input-8-c179edb7a491> in <module>()
----> 1 smprop.multinomial_proportions_confint([1, 0.5, 3, 2, 4], 0.05, method='sison_glaz')

m:\josef_new\eclipse_ws\statsmodels\statsmodels_py34_pr\statsmodels\stats\proportion.py in multinomial_proportions_confint(counts, alpha, method)
    292         while not (nu(c) <= (1 - alpha) < nu(c + 1)):
    293             if c > n:
--> 294                 raise Exception("Couldn't find a value for `c` that "
    295                                 "solves nu(c) <= 1 - alpha < nu(c + 1)")
    296             c += 1

Exception: Couldn't find a value for `c` that solves nu(c) <= 1 - alpha < nu(c + 1)

In the old version (from previous comment), the rootfinding worked for the zero count but not for a small positive count.

eg.
smprop.multinomial_proportions_confint([56, 0, 73, 59, 62, 87, 58], 0.05, method='sison_glaz') works and gives result identical to R with verbose=TRUE for "LOWER(C+1)" "UPPER(C+1)" but R reports slightly shifted values, which are "LOWER(SG)" "UPPER(SG)" in verbose mode.
smprop.multinomial_proportions_confint([56, 0.5, 73, 59, 62, 87, 58], 0.05, method='sison_glaz') raised an exception in the old version, but succeeds in R.

smprop.multinomial_proportions_confint([56, 1, 73, 59, 62, 87, 58], 0.05, method='sison_glaz') succeeds in old and new version, and is close to R (lower confint at 8 decimals ( which is my print precision) and at around 3 to 4 decimals for upper confint)

@josef-pkt

Copy link
Copy Markdown
Member

my conclusion for this:
we should not raise an exception, and just add a comment that there are (still) numerical problems with zero counts or counts < 1.

# Find the value of `c` that will give us the confidence intervals
# (solving nu(c) <= 1 - alpha < nu(c + 1).
c = 1.0
while not (nu(c) <= (1 - alpha) < nu(c + 1)):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

you are doing double work here for calculating nu.
when this goes through the loop, then nu(x) is calculated once for c+1 when c = x-1 and then again for nu(c) when c=x.

@josef-pkt

josef-pkt commented Aug 15, 2016 •

Copy link
Copy Markdown
Member

another observation: sison-glaz doesn't work for fractional counts. If counts are not integer values, then nu(c) is always inf (adding a debug print), so the while condition is never satisfied and raises. (int dtype is not required)

so the common trick of adding 0.5 to the zero counts doesn't work in this case.

@josef-pkt

Copy link
Copy Markdown
Member

OK, got it: scipy.stats.poisson.pmf returns zero for decimal values but scipy.stats.poisson._pmf does not
using it in the last line of approximated_multinomial_interval(intervals) makes it work for decimal counts.
np.log(stats.poisson._pmf(n, n)) but that doesn't have a check for n >= 0

smprop.multinomial_proportions_confint([56, 0.001, 73, 59, 62, 87, 58], 0.05, method='sison_glaz')

array([[ 0.09367065,  0.18988168],
       [ 0.        ,  0.04811242],
       [ 0.13670851,  0.23291955],
       [ 0.10126557,  0.1974766 ],
       [ 0.10886048,  0.20507152],
       [ 0.17215146,  0.2683625 ],
       [ 0.09873393,  0.19494496]])

which is again the same as R "LOWER(C+1)" "UPPER(C+1)" but shifted compared to the reported result in R

@josef-pkt

Copy link
Copy Markdown
Member

an alternative adjustment is to force counts to be integer valued in the call to

approximated_multinomial_interval(
                [(np.maximum(count - c, 0), np.minimum(count + c, n)) 
                 for count in counts])

so we evaluate the interval for integer counts, even when the user observed "counts" are not integer valued. This will "round" (down) the interval for the probability calculation.
I'm not sure that's good.

@josef-pkt

Copy link
Copy Markdown
Member

R multinomialCI seems to have a discontinuity, that we don't have, and causes a discrepancy when one count gets close to zero

ci change slowly except for the transition 0.0563 to 0.0562 (3rd decimal, that's where we disagree)
result in my current version stays at around 0.09367089 for the first value with 1e-6
ci_0 = smprop.multinomial_proportions_confint([56, 1e-6, 73, 59, 62, 87, 58], 0.05, method='sison_glaz')

> multinomialCI(c(56, 0.0564, 73, 59, 62, 87, 58), 0.05, verbose=FALSE)
           [,1]       [,2]
[1,] 0.09365751 0.18984637
[2,] 0.00000000 0.04823723
[3,] 0.13668934 0.23287820
[4,] 0.10125137 0.19744023
[5,] 0.10884522 0.20503408
[6,] 0.17212732 0.26831618
[7,] 0.09872008 0.19490894
> multinomialCI(c(56, 0.0563, 73, 59, 62, 87, 58), 0.05, verbose=FALSE)
           [,1]       [,2]
[1,] 0.09365754 0.18984638
[2,] 0.00000000 0.04823695
[3,] 0.13668938 0.23287822
[4,] 0.10125139 0.19744024
[5,] 0.10884525 0.20503409
[6,] 0.17212737 0.26831621
[7,] 0.09872011 0.19490895
> multinomialCI(c(56, 0.0562, 73, 59, 62, 87, 58), 0.05, verbose=FALSE)
           [,1]       [,2]
[1,] 0.09618885 0.19237768
[2,] 0.00000000 0.05076796
[3,] 0.13922070 0.23540953
[4,] 0.10378270 0.19997154
[5,] 0.11137656 0.20756539
[6,] 0.17465869 0.27084753
[7,] 0.10125142 0.19744025
> multinomialCI(c(56, 0.0561, 73, 59, 62, 87, 58), 0.05, verbose=FALSE)
           [,1]       [,2]
[1,] 0.09618887 0.19237770
[2,] 0.00000000 0.05076769
[3,] 0.13922073 0.23540957
[4,] 0.10378273 0.19997156
[5,] 0.11137659 0.20756542
[6,] 0.17465874 0.27084757
[7,] 0.10125144 0.19744028
> 

It's nothing to worry about much, just puzzling because for larger counts agreement is very high.

@josef-pkt

Copy link
Copy Markdown
Member

@wehlutyk Given that I already have everything open and partially finished, I will make the changes and push to a new PR for merging.

@josef-pkt

Copy link
Copy Markdown
Member

new PR is #3161

@josef-pkt
josef-pkt merged commit 44dc808 into statsmodels:master Aug 16, 2016
josef-pkt added a commit that referenced this pull request Aug 16, 2016
ENH: Multinomial confidence interval closes #2953
@josef-pkt

Copy link
Copy Markdown
Member

@wehlutyk I merged #3161 with some changes

Thanks for the contribution
I'm planning to go back to this topic when I have time for stats again.

@wehlutyk

Copy link
Copy Markdown
Contributor Author

@josef-pkt great, thanks for taking over! Very happy to see it merged (first contribution to scipy ecosystem :) )

josef-pkt added a commit to josef-pkt/statsmodels that referenced this pull request Aug 19, 2016
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.

ENH: simultaneous confidence intervals for multinomial proportions

3 participants