Skip to content

ENH: add two independent proportion inference rebased - #6675

Merged
josef-pkt merged 16 commits into
statsmodels:masterfrom
josef-pkt:proportion_2indep_rebased
May 4, 2020
Merged

josef-pkt merged 16 commits into
statsmodels:masterfrom
josef-pkt:proportion_2indep_rebased

Conversation

@josef-pkt

Copy link
Copy Markdown
Member

rebased version of #4829

@josef-pkt

Copy link
Copy Markdown
Member Author

rebased, one minor merge conflict, no additional changes compared to old PR

Comment thread statsmodels/stats/proportion.py Outdated
from statsmodels.stats.weightstats import _zstat_generic2


class Holder(object):

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.

use generic holder class now, currently tools/testing

Comment thread statsmodels/stats/proportion.py Outdated


def confint_proportion_2indep(count1, nobs1, count2, nobs2, method=None,
compare='diff', alpha=0.05, correction=True):

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.

function looks fine to me when skimming the code

@josef-pkt

Copy link
Copy Markdown
Member Author

code duplication

plus contingency table version for some of it.

This contains power function for normal with alternative dependent variance as extra enhancement.

@josef-pkt

josef-pkt commented Apr 30, 2020 •

Copy link
Copy Markdown
Member Author

notebook ex_proportion_2indep_short.ipynb for old PR is not up-to-date with code

return of test_proportions_2indep is now Holder instance and
TypeError: 'Holder' object is not subscriptable

confint function returns tuple

@josef-pkt

Copy link
Copy Markdown
Member Author

from notebook, this seems to be what's currently implemented in the test and confint functions

                           statistic    pvalue     lower      upper
compare    method                                                  
diff       agresti-caffo    2.106741  0.035140  0.011612   0.321722
           newcomb               NaN       NaN  0.018921   0.340369
           score            2.241651  0.024984       NaN        NaN
           wald             2.348087  0.018870  0.029169   0.323772
odds-ratio logit            1.951278  0.051024  0.990490  73.900302
           logit-adjusted   1.941318  0.052220  0.982796  37.748599
           logit-smoothed   1.950483  0.051119  0.990102  60.488353
           score            2.241651  0.024984       NaN        NaN
ratio      log              1.868966  0.061628  0.909606  53.869506
           log-adjusted     1.868374  0.061710  0.924135  27.052314
           score            2.241651  0.024984  1.208568  43.032972

@coveralls

coveralls commented Apr 30, 2020 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.06%) to 87.733% when pulling 4af9f37 on josef-pkt:proportion_2indep_rebased into 09475a2 on statsmodels:master.

@josef-pkt
josef-pkt force-pushed the proportion_2indep_rebased branch from 20c0ba2 to 776a8b0 Compare April 30, 2020 03:39
@josef-pkt

Copy link
Copy Markdown
Member Author

rebased after merging meta-analysis into master

-----
Status: experimental, API and defaults might still change.
Insufficiently tested, more ``methods`` will be added.

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.

References is missing
need description of methods

@josef-pkt

Copy link
Copy Markdown
Member Author

codacy complains about some unused variables, 2 in proportions.py and several in unit tests

Comment thread statsmodels/stats/proportion.py Outdated
raise ValueError('method not recognized')

elif compare == 'ratio':
ratio = p1 / p2

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.

lint: not used

Comment thread statsmodels/stats/proportion.py Outdated
raise ValueError('method not recognized')

elif compare == 'odds-ratio':
odds_ratio = p1 / (1 - p1) / p2 * (1 - p2)

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.

lint: not used

Baptista–Pike exact conditional 1.00 195 5.28
Baptista–Pike mid-p 1.33 99 4.31
Agresti–Min exact unconditional 1.19 72 4.10
'''

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.

pointless-string-statement
try # pylint: disable=W0105

x = x0 + x1
n = n0 + n1
p0 = x0 / n0
p1 = x1 / n1

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.

4 unused variable

Comment thread statsmodels/stats/proportion.py Resolved
@josef-pkt

josef-pkt commented Apr 30, 2020 •

Copy link
Copy Markdown
Member Author

This PR is missing the equivalence TOST tests
this should work generically. i.e. just call test_proportions_2indep for the one-sided tests.
see NCSS documentation chapter 516

see binom_tost for one sample case, but only with binom_test, no methods option
and proportions_ztost using proportions_ztest

note, proportions_ztest is not vectorized, supports either one- or two-sample "diff" case, and raises if size of data is > 2


def _std_2prop_power(diff, p2, ratio=1, alpha=0.05, value=0):
"""compute standard error under null and alternative for 2 proportions

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.

only for "diff" ?
nobs_ratio would be more explicit, if it is ratio of nobs

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.

in power computation, I always use ratio for nobs-ratio.

but for 2sample proportion, we also have risk-ratio and odds-ratio

@josef-pkt

josef-pkt commented Apr 30, 2020 •

Copy link
Copy Markdown
Member Author

from notebook: check consistency between confint and hypothesis test:
compute pvalue at upper confint bound

score method for risk ratio is inconsistent
edit I didn't use "correction=True". with it score round is consistent


                           statistic    pvalue
compare    method                             
diff       agresti-caffo   -1.959964  0.050000
           wald            -1.959964  0.050000
odds-ratio logit           -1.959964  0.050000
           logit-adjusted  -1.959964  0.050000
           logit-smoothed  -1.959964  0.050000
ratio      log             -1.959964  0.050000
           log-adjusted    -1.959964  0.050000
           score           -1.974536  0.048321

Comment thread statsmodels/stats/proportion.py Resolved
@josef-pkt

josef-pkt commented May 1, 2020 •

Copy link
Copy Markdown
Member Author

what is _confint_riskratio_paired_nam(table, alpha=0.05) ?
It says paired, but I thought I only have code for two independent samples

It has unit test coverage but is not available through a non-private function.
(I guess I just wrote the code at the same time as the indep koopman score confint)

@josef-pkt

josef-pkt commented May 1, 2020 •

Copy link
Copy Markdown
Member Author

current methods
I didn't check what's in power

edit added Y for score confint

statistic method confint test power
diff 'wald' Y Y Y
'agresti-caffo' Y Y -
'newcomb' Y NA -
score Y Y -
ratio 'log' Y Y -
'log-adjusted' Y Y -
score Y Y -
odds-ratio 'logit' Y Y -
'logit-adjusted' Y Y -
'logit-smoothed' - Y -
score Y Y -

in meta-analysis effect size,
we have wald diff, log risk ratio, log odds ratio and arcsine
no backtransform for log-rr and log-or
more flexible options for adding fake observations, i.e. continuity corrections.
includes standard errors

not yet checked:

overlap with contingency tables: at least wald versions should be there e.g. log-or and log-rr
overlap with GLM: I guess all wald versions can be obtained through GLM, and additionally the semi-public score_test.

@josef-pkt

Copy link
Copy Markdown
Member Author

This PR does not include any exact methods, see #6676 but only for equality testing (AFAIR).

All methods here are asymptotic with small sample adjustments, transformation and artificial observations.

@josef-pkt

Copy link
Copy Markdown
Member Author

score_test_proportion_2indep is a public function.
is also included as option in test_proportions_2indep, just delegating to the score_test function

Returns:
confint_proportion_2indep
It just returns confint (low, upp), most intermediate results are method specific, e.g. standard errors for log or logit transformed statistic, with or without continuity correction. newcomb method doesn't have any standard errors
I guess there is not much point in adding additional results

test_proportions_2indep and score_test_proportion_2indep return a Holder results instance by default, keyword return_results=True

score_test_proportion_2indep returns the constrained MLE for p1 and p2 in the holder instance

@josef-pkt

josef-pkt commented May 1, 2020 •

Copy link
Copy Markdown
Member Author

score confidence interval
updated link josef-pkt#5 (comment)
https://ncss-wpengine.netdna-ssl.com/wp-content/themes/ncss/pdf/Procedures/PASS/Confidence_Intervals_for_the_Ratio_of_Two_Proportions.pdf

looks like rootfinding and not a direct implementation:
"Miettinen and Nurminen (1985) proposed inverting their score test to find the confidence interval. The lower limit is found by solving ..."

see also #2722 for GLM

update inverting score test works fine in my example, One problem is how robust we make the rootfinder. Right now I'm using brentq with some approximate bounds which might fail to produce opposite signs. Also there might be problems with corner solutions, e.g. values going to zero.

@josef-pkt

Copy link
Copy Markdown
Member Author

valid input ranges

I used the wrong value, and variance is negative
v=59 is from risk ratio, but that doesn't work for "diff".

There should be a check that the user provides a valid value, or we truncate props to [0, 1]
Constrained MLE for score_test has negative proportion.
However, we don't know in advance what are the feasible "diff" values for constrained MLE.

# check 
rt0 = test_proportions_2indep(count1, nobs1, count2, nobs2, 
                                 value=v, compare="diff", method='score',
                                 alternative="two-sided")
vars(rt0)
{'statistic': nan,
 'pvalue': nan,
 'compare': 'diff',
 'method': 'score',
 'variance': -100.59951372870873,
 'alternative': 'two-sided',
 'prop1_null': 58.54406793461139,
 'prop2_null': -0.7123891759497276,
 'diff': 0.1764705882352941,
 'ratio': 7.0,
 'odds_ratio': 8.555555555555555}
v
59.256457110561115

@josef-pkt

Copy link
Copy Markdown
Member Author

another issue:
The currently implemented confint are always two-sided. There is no option for one-sided confint.
In this case, confint are symmetric in the underlying (transformed) random variable and we use normal distribution. So, one-sided is just one confint bound at alpha * 2

@josef-pkt

Copy link
Copy Markdown
Member Author

another consistency check:
tost evaluated using equivalence margin from confint with alpha=0.05

                           pvalue
compare    method                
diff       agresti-caffo    0.025
           score            0.025
           wald             0.025
odds-ratio logit            0.025
           logit-adjusted   0.025
           logit-smoothed   0.025
           score            0.025
ratio      log              0.025
           log-adjusted     0.025
           score            0.025

@josef-pkt

Copy link
Copy Markdown
Member Author

next question: Can I get the power generically, i.e. for any method available in the test and tost function?

the power_proportion_2indep function in this PR uses new normal_power_het for explicit computation but has only "diff" "wald" (?)

If I have the props under the alternative, then I could do the full binomial power version, but would need to evaluate (run hypothesis test on) all points on grid. That's what I was doing for "exact" power.
(simplest version would be when I have the rejection region in terms of counts, but that might not be easy to get analytically.)

If I cannot do it generically this way, then I need mean and variance of the test statistic under the alternative (i.e. noncentrality) for each method similar to the current one for diff-wald.

test_proportions_2indep works vectorized for all compare and methods
(why does constrained MLE work for score test in vectorized way?)
Not all confint will work vectorized because of the root finding (in score confint)

PASS Superiority by a Margin for two proportions chapter 205 (printed several years ago) uses
binomial exact power after computing rejection region in terms of counts.
Large sample power is based on normal distribution. However, "the results for the odds-ration have not (to our knowledge) been published. In this case, we substitute the calculations based on the ratio."

I guess my naming with compare="ratio" came from NCSS/PASS. Newer version as in meta-analysis uses "risk ratio" or "rr", and "rd" as abbreviation for risk difference ("diff").

@josef-pkt

Copy link
Copy Markdown
Member Author

getting close, I have most of what I want in this round, I'm skipping power this time

now also equivalence TOST tests

'logit-smoothed' for odds-ratio is available in hypothesis test and tost but not in confint.

needs another check for method names
e.g. "agresti-caffo" should maybe become "wald-adjusted"
maybe we need "continuity correction", i.e. which "adjustment"
maybe wald-cc and wald-ac, or separate keyword that applies to wald tests

also need to check that we have consistent use of abbreviation for the compare statistic, e.g. "or" for "odds-ratio"

docs and references, e.g. do methods have explanation, author names?

corner cases, AFAIR, I never checked corner cases counts=0 or counts=nobs

test noise: I get some warnings when running the unit tests, e.g.

statsmodels/stats/tests/test_proportion.py::test_equivalence_2indep
  ...\python-3.7.4.amd64\lib\site-packages\scipy
\stats\_distn_infrastructure.py:1892: RuntimeWarning: invalid value encountered
in less_equal
    cond2 = cond0 & (x <= _a)

@josef-pkt

Copy link
Copy Markdown
Member Author

silly naming mistake:
test_proportions_2indep,

proportion is singular:
confint_proportion_2indep, power_proportion_2indep score_test_proportion_2indep samplesize_proportion_2indep_onetail

name should be plural for 2 and k-sample tests

@josef-pkt

josef-pkt commented May 3, 2020 •

Copy link
Copy Markdown
Member Author

replicating 2 sample tests using GLM works, but not with irls, see #3703

Note: endog in GLM binomial is (success, failure) and not (counts, nobs) as in stats.proportions.
Initially, I made a mistake and numbers didn't match up.

en = np.array([[count1, nobs1 - count1], [count2, nobs2 - count2]])
ex = np.array([[1., 1], [1, 0]])
mod_glm = GLM(en, ex, family=families.Binomial())
res_glm = mod_glm.fit(method='bfgs', tol=1e-10, max_start_irls=0)
res_glm.params[-1]
np.exp(res_glm.conf_int())[1]  # Wald confidence interval for odds-ratio

using identity link replicated compare="diff"

related aside: what's the status of the eform method, issue #2235, PR #2296 or somewhere else?

@josef-pkt

Copy link
Copy Markdown
Member Author

azure py 3.6 failed in statsmodels/tsa/statespace/tests/test_exact_diffuse_filtering.py::test_nondiagonal_obs_cov

this PR is green

@josef-pkt

Copy link
Copy Markdown
Member Author

eform after glm, function has been merged already

r = test_proportions_2indep(count1, nobs1, count2, nobs2, compare="odds-ratio", method="logit")
vars(r)
{'statistic': 1.9512781246582152,
 'pvalue': 0.05102396984084286,
 'compare': 'odds-ratio',
 'method': 'logit',
 'diff': 0.1764705882352941,
 'ratio': 7.0,
 'odds_ratio': 8.555555555555555,
 'variance': 1.2101972101972103,
 'alternative': 'two-sided',
 'value': 1}

confint_proportions_2indep(count1, nobs1, count2, nobs2, compare="odds-ratio", method="logit")
(0.9904902816539896, 73.90030192115287)
np.exp(res_glm.conf_int())[1]
array([ 0.99049029, 73.90030122])
from statsmodels.genmod._prediction import params_transform_univariate
​
pres = params_transform_univariate(res_glm.params, res_glm.cov_params())
print(pres.summary_frame().loc[1:])
       mean   mean_se  mean_ci_lower  mean_ci_upper
1  8.555568  9.411897       0.990491      73.900488

@josef-pkt

Copy link
Copy Markdown
Member Author

standard errors for two sample proportions ? and/or for transformed statistics

None of the functions in this PR provides standard errors.
Using GLM we get standard errors for the parameters, e.g. log-odds-ratio, and backtransformed exp (and predict/link) versions.
In meta_analysis, we have standard errors for the effect size, which are transformed statistics like log-odds-ratio and log-risk ratio, but not for the backtransformed statistics.
In contingency_tables we have both, transformed and backtransformed statistics.

Can we get everything together in one place?

Not now, or at most partially.
The point here is to be able to add several methods to a single functions, e.g. confint.
Adding all functions together makes it more difficult to add idiosyncratic methods, e.g. newcomb mover confidence interval doesn't have analogues for other functions.

maybe a wrapper class or function to provide summary for params, hypo test and confint.

@josef-pkt

Copy link
Copy Markdown
Member Author

great when things just work

GLM fit_constrained + score_test == 2 proportion test with score and correction=False (Farrington-Manning)

v0 = np.log(0.8)
v0
-0.2231435513142097

mod_glm = GLM(en, ex, family=families.Binomial())
res_glm = mod_glm.fit_constrained("x1=-0.2231435", method='bfgs', tol=1e-10, max_start_irls=0)
print(
print(res_glm.summary())
                 Generalized Linear Model Regression Results                  
==============================================================================
Dep. Variable:           ['y1', 'y2']   No. Observations:                    2
Model:                            GLM   Df Residuals:                        1
Model Family:                Binomial   Df Model:                            0
Link Function:                  logit   Scale:                          1.0000
Method:                          IRLS   Log-Likelihood:                -6.3191
Date:                Sun, 03 May 2020   Deviance:                       7.0896
Time:                        15:37:09   Pearson chi2:                     6.58
No. Iterations:                     1                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
const         -1.9081      0.377     -5.066      0.000      -2.646      -1.170
x1            -0.2231          0       -inf      0.000      -0.223      -0.223
==============================================================================

Model has been estimated subject to linear equality constraints.


mod_glm.score_test(res_glm.params, k_constraints=1)
(array([6.57854016]), array([0.01032155]), 1)  # pvalue same as below at 7 decimals


r = test_proportions_2indep(count1, nobs1, count2, nobs2, value=0.8, compare="odds-ratio", method="score", correction=False)
vars(r)
{'statistic': 2.564867604246601,
 'pvalue': 0.010321518062695179,
 'compare': 'odds-ratio',
 'method': 'score',
 'variance': 0.5715431729016758,
 'alternative': 'two-sided',
 'prop1_null': 0.10609821391325566,
 'prop2_null': 0.1291959037338032,
 'diff': 0.1764705882352941,
 'ratio': 7.0,
 'odds_ratio': 8.555555555555555,
 'value': 0.8}

res_glm.predict()
array([0.10609832, 0.12919602])    # prop_null under constraint

@josef-pkt

Copy link
Copy Markdown
Member Author

Holdertuple doesn't work by default for other than test results, e.g. power, confint. Also power returns a single value if not return_results.
Holder class will get repr and str in another open PR. (in robust/anova PR ?)

I'm about ready to stop and merge.
One more check to see if I forgot about something.

@josef-pkt

Copy link
Copy Markdown
Member Author

I will merge when green

@josef-pkt

Copy link
Copy Markdown
Member Author

I still only have a partial overview of what we have for proportions # 6399

partial overlap with existing functions

sample method function(s)
value hyp test_proportions_2indep
proportions_ztest
equivalence tost_proportions_2indep
proportions_ztost

@josef-pkt

Copy link
Copy Markdown
Member Author

completely green, merging

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