Skip to content

ENH: confidence intervals for two proportions, difference, odds ratio and risk ratio #2605

Closed

Description

@josef-pkt

see josef-pkt#5 for issue, initial discussion and some references

Activity

  1. added this to the 0.8 milestone on Aug 29, 2015
  2. josef-pkt commented on Aug 29, 2015

    @josef-pkt
    MemberAuthor

    copying part of the discussion: (not copied: discussion on unit tests and license)

    Josef
    I think the functions would make a good addition to statsmodels.

    about the unit tests: We used rpy directly in the first year of statsmodels, but it's faster and more reliable to hard code the verified results, so we stopped using rpy. Also we have unit tests that are compared to other packages like Stata or Gretl.
    If you look at our test suite, then you see that we hardcode short results in ( often semi-automatically generated) modules and long results in csv files.

    About the functions I started to brows the pdf documentation of ProbCI on CRAN, and found http://www.ncss.com/wp-content/themes/ncss/pdf/Procedures/PASS/Confidence_Intervals_for_Two_Proportions.pdf which has a good collection of formulas and different definitions for the CIs. I used a similar list, most likely from the SAS documentation, to implement most of the one sample proportion confidence intervals.

    Two related things

    If you have comments on existing code, e.g. about usability, or enhancements requests, then you can open issues in github statsmodels.

    Maybe also of interest to you: Kerby @kshedden has a pull request for contingency tables, that I expect will be merged this Fall #2418 . It brings together some of the existing tests and also include many new features.

    Josef
    one more reference:

    http://smm.sagepub.com/content/24/2/224.short
    Based on the ungated version http://www.ms.uky.edu/~mai/sta635/FagerlandLydersenLaake2011---RecommendedCIsForTwoIndependent....pdf
    this looks like a useful comparison, overview and recommendations, including a table (table 8) with what's available in different statistical packages
    confidence intervals for difference in two proportions, ratio of two proportions and odds ratio.

    Andrew
    Looks like a terrific summary! Those could be good test cases as well.

    It sounds like these CIs and tests do belong in the @kshedden PR, but I don't want to slow it down.

    Josef
    I'm not sure yet where we want to put the different tests, confidence intervals and similar, or we might keep separate function and integrate them with the contingency tables through delegation.
    I'd like to keep base statistics and tests in stats for different statistics, like location, variance/dispersion, proportions, higher moments and so on.

    Two comments to the overview by Fagerland et al

    • calculation: table 8 also shows which confidence intervals have a closed form expression, and some of the other ones have comments that they are difficult to calculate.
    • size of tests: it's similar to the single proportion confidence intervals. CI that maintain their size, like the exact tests, can be very conservative. CI's that don't require this (similar to tests/CIs that target average size for a single proportion) can be quite liberal in some cases.
  3. josef-pkt commented on Aug 29, 2015

    @josef-pkt
    MemberAuthor

    I did some spot reading and browsing of some of the original articles.

    Most of the test should be relatively easy to implement, especially if we have unit tests to correct typos in translating formulas to code. Many of the confidence intervals invert tests that require selected roots from polynomial equations (which should be easy with np.polynomial) or non-linear equation solving (easy with scipy.optimize if we can find the right bounds).

    Some of the exact methods will be difficult to implement. A brute force method with enumerating all cases might be slow and work only with very small samples. I didn't check whether there would be efficient methods like Fisher's exact test in scipy. (But those are always difficult.)

    another extension: besides the "simple" two sample, two proportion tests, there are also the corresponding statistical tests and confidence intervals for paired and clustered data, e.g. several articles by Hardin and co-authors on clustered matched pairs like
    Zhao Yang, Xuezheng Sun, James W. Hardin, Testing non-inferiority for clustered matched-pair binary data in diagnostic medicine, Computational Statistics & Data Analysis, Volume 56, Issue 5, 1 May 2012, Pages 1301-1320, ISSN 0167-9473, http://dx.doi.org/10.1016/j.csda.2011.06.019.
    (http://www.sciencedirect.com/science/article/pii/S0167947311002222)

  4. josef-pkt commented on Aug 29, 2015

    @josef-pkt
    MemberAuthor

    as background: here is another article by Agresti on conservative exact versus good size on average or with small violations of size, applied to this case
    Agresti, A. 2003. “Dealing with Discreteness: Making `exact’ Confidence Intervals for Proportions, Differences of Proportions, and Odds Ratios More Exact.” Statistical Methods in Medical Research 12 (1): 3–21. doi:10.1191/0962280203sm311ra.

  5. josef-pkt commented on Aug 30, 2015

    @josef-pkt
    MemberAuthor

    example: quick implementation of Koopman's interval as described in Nam. 2 equations plus explanations which roots to use

    """
    Created on Sat Aug 29 21:57:55 2015
    
    Author: Josef Perktold
    License: BSD-3
    """
    
    from __future__ import division
    
    import numpy as np
    
    #example Koopman, based on Nam 1995
    
    x0, n0 = 16, 80
    x1, n1 = 36, 40
    x = x0 + x1
    n = n0 + n1
    p0 = x0 / n0
    p1 = x1 / n1
    
    class Holder(object):
        pass
    
    results_nam = Holder()
    results_nam.p0_roots = [0.1278, 0.2939, 0.4876]
    results_nam.conf_int = [2.940, 7.152]
    
    
    alpha = 0.05
    
    from scipy import stats
    z = stats.norm.isf(alpha / 2)**2
    #z = stats.chi2.isf(alpha, 1)
    #equ 6 in Nam 1995
    a1 = n0 * (n0 * n * x1 + n1 * (n0 + x1) * z)
    a2 = - n0 * (n0 * n1 * x +  2 * n * x0 * x1 + n1 * (n0 + x0 + 2 * x1) * z)
    a3 = 2 * n0 * n1 * x0 * x + n * x0 * x0 * x1 + n0 * n1 * x * z
    a4 = - n1 * x0 * x0 * x
    
    p_roots_ = np.sort(np.roots([a1, a2, a3, a4]))
    print(p_roots_)
    p_roots = p_roots_[:2][::-1]
    
    # equ 5
    ci = (1 - (n1 - x1) * (1 - p_roots) / (x0 + n1 - n * p_roots) ) / p_roots
    
    print(ci)
    
    from numpy.testing import assert_allclose
    
    assert_allclose(p_roots_, results_nam.p0_roots, atol=4)
    assert_allclose(ci, results_nam.conf_int, atol=3)
    
  6. josef-pkt commented on Aug 30, 2015

    @josef-pkt
    MemberAuthor

    similar review and recommendation for the confidence intervals with paired data
    Fagerland, M. W., Lydersen, S. and Laake, P. (2014), Recommended tests and confidence intervals for paired binomial proportions. Statist. Med., 33: 2850–2875. doi: 10.1002/sim.6148
    http://onlinelibrary.wiley.com/doi/10.1002/sim.6148/abstract

    and specific to odds ratio there is a R package https://cran.r-project.org/web/packages/ORCI/index.html

  7. agartland commented on Sep 15, 2015

    @agartland

    I had correspondence with the author of PropCI, the CRAN package that I translated a few functions from. Citing this wikipedia article he believes the GPL license he used to release his code should be compatible with my translation released under BSD-3. I see that the article says they are "compatible" but I don't exactly understand why? Can you advise, @josef-pkt ?

    If so then I could imagine setting up a branch for these functions, writing unit tests using results from the R-package and then translation as I have time to get to it. Sound reasonable?

  8. josef-pkt commented on Sep 15, 2015

    @josef-pkt
    MemberAuthor

    @agartland The license compatibility is asymmetric. GPL licensed packages can include BSD code (so BSD is GPL compatible), but not the other way around. BSD or MIT licensed packages are not allowed to include GPL code (or they would have to switch to GPL themselves).

    So, he needs give us explicit permission to include a translation of his code under BSD-3 to get around his current GPL license. He doesn't need to change his license if we get his permission, but he could also dual license the code with GPL and BSD/MIT if he doesn't want to impose any restrictions on use, and possible translation also to Julia or other languages.

    However, I was reading around for a while, and I think we can implement most things easily from scratch. (Except, as I mentioned, some of the exact or quasi-exact methods might be tricky and be fast only for very small samples.)

    If you can make a list of functions and order them by your priorities and can work on unit tests, then it should be possible to build this over the next months.
    For example I started with unconditional exact tests (pvalues) for the difference of proportions in #2608 (no confidence interval yet for this.) Tested against published results.

  9. agartland commented on Sep 15, 2015

    @agartland

    That makes sense, thanks for clarifying. Below is an email from Ralph Scherer (@shearer), author of the PropCIs package that I translated, giving us explicit permission to include my translation in statsmodels and to license under BSD-3:

    Dear Andrew, with this E-Mail I give the permission to translate the R-Code from PropCIs to Python and include it in the statsmodels library.
    The permission of Alan Agresti, which is the original owner of most of the contained R-Code is given in the included E-Mail correspondence.

    Best Wishes and much success, Ralph

    Dear Ralph, I have no objections to these programs being used other places, like that. Best wishes, Alan

    Dear Alan, I got a question from a biostatistician working at Fred Hutchinson Cancer Research Center. He wants to translate parts of the confidence intervals to Python and package them into the statsmodels library of python. I am not sure if this would be a problem for you and therefore I preferred to ask you before. It would be nice if you could give me feedback to this topic. Best Wishes from Germany Ralph

  10. agartland commented on Sep 15, 2015

    @agartland

    @josef-pkt with your strategy and beginnings in #2608 we can use translated code or new code to chip away. Thanks for your help!

  11. josef-pkt commented on Sep 16, 2015

    @josef-pkt
    MemberAuthor

    Very good, that clears up the license issue.

    About the API and how the functions will be exposed:

    Is your use case running one type of test or confidence interval on many datasets or to get full results for a single or a few datasets?

    In the first case we want to have simple functions with low overhead, which also have the advantage of being easy to use. (for example I reused confint_proportion in Berger Boos exact p-values.)

    However, for looking at a specific hypothesis and research question, I think we should eventually expand the hypothesis test to provide everything (similar to model results t_tests) effect size, test statistic, standard errors, p-values and confidence intervals, plus power and sample size calculations, plus variation of the hypothesis tests for inferiority, superiority and equivalence. This is on my long term wishlist and plan for statsmodels.stats.

    Specifically, here we could get those things for the asymptotic score tests (which are reasonably good for medium large sample sizes) for difference in proportion, odds ratio and risk ratio in the case of two independent proportions. For other approaches we might only get some of the results.

    (overall, conditional exact test with mid-p p-values seem to become popular as small sample default. I didn't find a StatXact manual but they seem to be advertising mid-p approaches)

  12. agartland commented on Sep 16, 2015

    @agartland

    I often wonder about these API philosophies myself. Is it common ever to have multiple APIs? I could certainly imagine scenarios when I want just the p-value or just the estimate. The best examples of this involve bootstraps, permutation tests or nested cross-validation where I really don't want to be wasting time calculating everything (on the other hand there isn't usually much time wasted with these stats...)

    But there is a clear advantage organizationally to have a single entry point for all functions around a single statistic (e.g. difference of ratios).

    Does it make sense to work on the individual functions for now and then expose a more organized API later when things are complete?

  13. josef-pkt commented on Sep 16, 2015

    @josef-pkt
    MemberAuthor

    Is it common ever to have multiple APIs?

    It's not a first choice, but common enough. models and formulas, some statsmodels.stats classes are wrapped in a function, for some cases scipy provides the simpler API,...

    Does it make sense to work on the individual functions for now and then expose a more organized API later when things are complete?

    Definitely. It often takes me a while to figure out a pattern when there is no established pattern yet.
    If there is a clear entry point like
    proportion_confint or multipletests then options and, possibly private, functions can be added over time.

  14. josef-pkt commented on Sep 25, 2015

    @josef-pkt
    MemberAuthor

    A reference: Stata epitab in st manual seems to have similar functionality for comparing proportions.
    (found by chance)

  15. josef-pkt commented on May 21, 2017

    @josef-pkt
    MemberAuthor

    What's the status here?
    I thought we already have some code for 2-sample comparison of proportion and confidence intervals. But I don't find anything similar to the Koopman/Nan confidence interval in the earlier comment.
    Specifically, I am looking for score confidence interval and constrained MLE for difference or ratio of two proportions.

  16. modified the milestones: 0.8, 0.10 on Jul 16, 2018
  17. josef-pkt commented on Jul 16, 2018

    @josef-pkt
    MemberAuthor

    bump for 0.10, where are these functions?
    I'm looking at score confidence interval for GLM (naive implementation using #4716, fit_constrained + score_test) and would like some comparison for binomial 2-sample case.

  18. josef-pkt commented on Jul 17, 2018

    @josef-pkt
    MemberAuthor

    I think we can create a single entry point function for this, something like
    confint_two_proportion(success1, nobs1, success2, nobs2, comparison='diff', method='score', alpha=0.5)
    maybe additionally with alternative='2-sided'

    comparison: diff, ratio, odds-ratio/odds/or (something better than 'comparison'?)
    method: TBA, extend as available

  19. josef-pkt commented on Jul 20, 2018

    @josef-pkt
    MemberAuthor

    parking a script (before hitting the sea side)
    mainly based on Fagerland, Lydersen and Laake 2015 Recommended confidence intervals for two independent binomial proportions,
    referenced in second comment above

    only some easy to compute confint for diff
    score intervals are available from PropCI, exact/BB is in #2608
    here it is based on an entry point function, that can include risk ratio and odds ratio and delegate for more complicated confints.

    # -*- coding: utf-8 -*-
    """
    Created on Fri Jul 20 11:30:39 2018
    
    Author: Josef Perktold
    """
    
    import numpy as np
    
    from scipy import stats
    import statsmodels.stats.proportion as smprob
    
    
    def confint_proportion_2indep(count1, nobs1, count2, nobs2, method='newcomb',
                                  compare='diff', alpha=0.05):
        """Confidence intervals for comparing two independent proportions
        
        This assumes that we have two independent binomial samples.
        
        Parameters
        ----------
        count1, nobs1 : 
            count and sample size for first sample
        count2, nobs2 :
            count and sample size for the second sample
        method='newcomb'
        compare : string in ['diff', 'ratio' 'odds-ratio']
            If compare is diff, then the confidence interval is for diff = p1 - p2
            If compare is ratio, then the confidence interval is for the risk ratio
            defined by ratio = p1 / p2.
            If compare is odds-ratio, then the confidence interval is for the
            odds-ratio defined by or = p1 / (1 - p1) / (p2 / (1 - p2)
            
        alpha : float
            significance leverl for the confidence interval, default is 0.05.
            The nominal coverage probability is 1 - alpha.
                                  
        """
        
        method = method.lower()
        if method.startswith('agr'):
            method = 'agresti-caffo'
        
        p1 = count1 / nobs1
        p2 = count2 / nobs2
        diff = p1 - p2
        addone = 1 if method == 'agresti-caffo' else 0
        
        if compare == 'diff':
            if method in ['wald', 'agresti-caffo']:
                count1_, nobs1_ = count1 + addone, nobs1 + 2 * addone
                count2_, nobs2_ = count2 + addone, nobs2 + 2 * addone
                p1_ = count1_ / nobs1_
                p2_ = count2_ / nobs2_
                diff_ = p1_ - p2_
                var = p1_ * (1 - p1_) / nobs1_ + p2_ * (1 - p2_) / nobs2_
                z = stats.norm.isf(alpha / 2)
                d_wald = z * np.sqrt(var)
                low = diff_ - d_wald
                upp = diff_ + d_wald
                
                
            elif method.startswith('newcomb'):
                low1, upp1 = smprob.proportion_confint(count1, nobs1, 
                                                       method='wilson',
                                                       alpha=alpha)
                low2, upp2 = smprob.proportion_confint(count2, nobs2, 
                                                       method='wilson',
                                                       alpha=alpha)
                d_low = np.sqrt((p1 - low1)**2 + (upp2 - p2)**2)
                d_upp = np.sqrt((p2 - low2)**2 + (upp1 - p1)**2)
                low = diff - d_low
                upp = diff + d_upp
            else:
                raise ValueError('method not recognized')
        
        elif compare == 'ratio':
            raise NotImplementedError
            
        elif compare in ['or', 'odds-ratio']:
            raise NotImplementedError
            
        else:
            raise ValueError('compare not recognized, should be "diff", "ratio"'
                             'or "odds-ratio"')
                
                
        return low, upp
    
    
    alpha = 0.05
    count1, nobs1 = 7, 34
    count2, nobs2 = 1, 34
    
    low1, upp1 = smprob.proportion_confint(count1, nobs1, method='wilson')
    low2, upp2 = smprob.proportion_confint(count2, nobs2, method='wilson')
    
    p1 = count1 / nobs1
    p2 = count2 / nobs2
    #p2, p1 = 0.029, 0.21
    diff = p1 - p2
    print('diff', diff)
    
    d_low = np.sqrt((p1 - low1)**2 + (upp2 - p2)**2)
    d_upp = np.sqrt((p2 - low2)**2 + (upp1 - p1)**2)
    low = diff - d_low
    upp = diff + d_upp
    print(low, upp)
    
    addone = False
    if addone:
        count1, nobs1 = count1 + 1, nobs1 + 2
        count2, nobs2 = count2 + 1, nobs2 + 2
    
    var = p1 * (1 - p1) / nobs1 + p2 * (1 - p2) / nobs2
    z = stats.norm.isf(alpha / 2)
    d_wald = z * np.sqrt(var)
    low_wald = diff - d_wald
    upp_wald = diff + d_wald
    print('wald', low_wald, upp_wald)
    
    print()
    ci = confint_proportion_2indep(count1, nobs1, count2, nobs2, method='newcomb',
                                   compare='diff', alpha=0.05)
    print('newcomb      ', ci)
    ci = confint_proportion_2indep(count1, nobs1, count2, nobs2, method='wald',
                                   compare='diff', alpha=0.05)
    print('wald         ', ci)
    ci = confint_proportion_2indep(count1, nobs1, count2, nobs2, method='agresti-caffo',
                                   compare='diff', alpha=0.05)
    print('agresti-caffo', ci)
    
    # based on example in PASS/NCSS documentation
    confint_proportion_2indep(9, 10, 3, 10, method='newcomb')
    #(0.17052272393450291, 0.80901797353548799)
    confint_proportion_2indep(9, 10, 3, 10, method='wald')
    # (0.26052427977714854, 0.93947572022285164)
    confint_proportion_2indep(9, 10, 3, 10, method='agresti-caffo')
    # (0.16000080110040027, 0.83999919889959973)
    
    '''
    Wald 0.029 0.32 0.29
    Agresti–Caffo 0.012 0.32 0.31
    Newcombe hybrid score 0.019 0.34 0.32
    Miettinen–Nurminen asymptotic score 0.028 0.34 0.31
    Santner–Snell exact unconditional -0.069 0.41 0.48
    Chan–Zhang exact unconditional 0.019 0.36 0.34
    Agresti–Min exact unconditional 0.024 0.35 0.33
    '''
    
  20. josef-pkt commented on May 4, 2020

    @josef-pkt
    MemberAuthor

    merged as rebased version #6675, original was #4829

    see #4828 for a SUMM issue

  21. modified the milestones: 0.10, 0.12 on May 5, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions