Skip to content

ENH: add two independent proportion inference - #4829

Closed
josef-pkt wants to merge 10 commits into
statsmodels:masterfrom
josef-pkt:proportion_2indep
Closed

josef-pkt wants to merge 10 commits into
statsmodels:masterfrom
josef-pkt:proportion_2indep

Conversation

@josef-pkt

@josef-pkt josef-pkt commented Aug 3, 2018 •

Copy link
Copy Markdown
Member

update rebased version of this PR is #6675

see #4828

consolidating some experimental code from past weeks, continuation of #2605 (comment)

see also #2607

@coveralls

coveralls commented Aug 3, 2018 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.07%) to 83.932% when pulling 7c0978f on josef-pkt:proportion_2indep into 7a152a3 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member Author

first commit fails on python 2.7, most likely integer division.

@codecov-io

codecov-io commented Aug 3, 2018 •

Copy link
Copy Markdown

Codecov Report

Merging #4829 into master will increase coverage by 0.03%.
The diff coverage is 88.24%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #4829      +/-   ##
==========================================
+ Coverage   81.38%   81.41%   +0.03%     
==========================================
  Files         581      581              
  Lines       90194    90611     +417     
  Branches    10077    10133      +56     
==========================================
+ Hits        73406    73774     +368     
- Misses      14498    14527      +29     
- Partials     2290     2310      +20
Impacted Files Coverage Δ
statsmodels/stats/tests/test_proportion.py 99.47% <100%> (+0.16%) ⬆️
statsmodels/stats/power.py 80.3% <82.6%> (+0.22%) ⬆️
statsmodels/stats/proportion.py 86.21% <85%> (-1.38%) ⬇️
statsmodels/iolib/tests/test_table_econpy.py 100% <0%> (ø) ⬆️

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 7a152a3...7c0978f. Read the comment docs.

@josef-pkt

josef-pkt commented Aug 3, 2018 •

Copy link
Copy Markdown
Member Author

I added future division to the first commit in a rebase
now all green, but insufficient unit tests

naming order is reversed from one sample case
proportion_confint versions confint_proportion_2indep
score_test uses 2samp instead of 2 indep

related to existing functions:
proportions_ztest includes the two sample diff case with pooled or user provided proportion to compute variance. variance is not consistent with null hypothesis if value != 0. I guess it's the same as score_test for hypothesis if value=0.

bug/limitation of odds_ratio OR value=1 is not supported in Miettinen, Nurminen formula for constrained estimator. current workaround is using default value = 1 + 1e-10

@josef-pkt

Copy link
Copy Markdown
Member Author

adding two more old functions, script is from 2015-08-30, earlier version is in #2605 (comment)

Koopmans score confint for risk ratio for independent and paired samples
currently private functions because API is not clear yet and inconsistent with other functions.

paired case has no verified numbers in unit tests

@josef-pkt

josef-pkt commented Aug 3, 2018 •

Copy link
Copy Markdown
Member Author

related aside: heteroscedasticity versus binomial, or don't be so negative about wald test with variance that doesn't satisfy null hypothesis.

proportions_ztest uses wald with pooled variance, score_tests use variance using proportions under the null.

If we allow for heteroscedasticity, e.g. unequal excess dispersion in different samples, then the binomial assumption does not hold and using HC variance, e.g. unpooled empirical variance as in t_test with separate variance would be more robust (AFAIU).

The Monte Carlo simulations in the articles that compare small sample performance of different methods all use binomial assumption, AFAIK.
e.g. #2632

I'm not sure whether we can actually estimate an "empirical" variance or dispersion in the two sample case, i.e. we would need repeated or multiple counts for each group, e.g. can we identify a beta-binomial dispersion parameter from the sample.
If not, then we still have variance just as a function of the probability/proportion, and excess in dispersion might not be directly related to the mean.

@josef-pkt

josef-pkt commented Aug 3, 2018 •

Copy link
Copy Markdown
Member Author

last commit added draft for test_proportions_2indep in analogy to confint_proportion_2indep

mostly copy-paste-adjust from the confint function
includes wald test variants and not yet the score_test versions.

only smoke test

@josef-pkt

josef-pkt commented Aug 4, 2018 •

Copy link
Copy Markdown
Member Author

question: consistency of methods across compare
Fagerland et al. doesn't look very consistent across compare

  • names, e.g. wald-adjusted is more generic than agresti-caffo, logit-adjusted, log-adjusted
  • do we need option for how much extra observations to add in adjusted, e.g.
    • "diff" agresti-caffo adds 1 to each cell,
    • "odds-ratio" logit-adjusted adds 0.5 to each cell,
    • "ratio" log-adjusted adds 0.5 only to counts (and not to the "fail" cells)
  • should we add an option to replace zeros by small number, e.g. 0.1, to avoid non-existing or degenerate results
    NCSS documentation mentions somewhere that that works well.

quote from NCSS "Two Proportions" documentation

Zero Count Adjustment Value
Zero cell counts cause many calculation problems. To compensate for this, a small value may be added either to
all cells or to all zero cells. The Zero Count Adjustment Value is the amount that is added. Adding a small value
is controversial, but may be necessary. Some statisticians recommend adding 0.5 while others recommend 0.25.
We have found that adding values as small as 0.0001 may also work well.

Fagerland et al. don't have all analogous versions across compare, e.g. "mid-p" adjustment for exact is only in "odds-ratio"

@josef-pkt

Copy link
Copy Markdown
Member Author

question: should we add compare = "log-ratio" and "log-odds-ratio"?
That would make it easier to directly compare to the parameters in GLM Binomial with log or logit link.

@josef-pkt

Copy link
Copy Markdown
Member Author

about score confint for ratio:
Nam's computation of Koopman does not have the nobs / (nobs - 1) term of Miettinen/Nurminen in the variance.
AFAICS, we can adjust z_{alpha / 2} (i. e. norm.ppf(alpha/2) in the computation by nobs / (nobs - 1) and the rest should be the same in the Nam computation.

@josef-pkt

josef-pkt commented Aug 5, 2018 •

Copy link
Copy Markdown
Member Author

question: What works vectorized?

everything except for score confint?
confint_risk_ratio_koopman uses np.roots for cubic equation which requires 1-D (i.e. not vectorized)
other score confint will require explicit rootfinding

All (semi-)exact methods will most likelily not be vectorized (most likely because of memory consumption, broadcasting to an extra dimension for sample space might work in some cases).

score tests,and constrained parameter estimation, score_test_proportion_2indep, use analytical formulas and are (should be) vectorized.
wald versions can always be vectorized.

I'm not planning (for now) on adding internal loop vectorizing, so allowed argument shape will depend on the method, which IIIRC is similar to some other functions.

@josef-pkt

Copy link
Copy Markdown
Member Author

question: API for hypothesis test of equality, i.e. no value option ?

some hypothesis tests are only available for equality p1 = p2 tests. Should we add those to the general tests with value=0 or add them as separate functions.
compare is not really relevant in this case because diff=0, ratio=1 and odds-ratio=1 are the same hypothesis (although maybe not identical results if hypothesis test method is not invariant to nonlinear transformation. But the transformation of the test statistic should be a method option and does not constitute a substantially different Null Hypothesis)

@josef-pkt

Copy link
Copy Markdown
Member Author

Notes (just as reminder): asymmetry, skewness and score confint

Score confint are generally defined through two one-sided hypothesis tests at alpha / 2
In GLM score confint naive I use the two sided test at alpha and look at either the upper or lower tail. This is only correct if we have symmetric tails. GLM score_test uses chisquare which is always two-sided and treats both tails symmetrically.

confint for comparing two proportions use explicit formulas, but it will be relevant when we compare confint with the hypothesis tests. For example, Gart/Nam use skewness correction and I guess we get asymmetric tails when inverting the two one-sided score tests to get confint.
I guess the same will apply if we use two one-sided score tests for (quasi-)exact confidence intervals.

@josef-pkt

Copy link
Copy Markdown
Member Author

BUG: value in test_proportions_2indep looks wrong
easily fixed for 'diff', but not for other ones

I'm checking value equal to the upper confidence interval.
possible problem wald confints for ratio are based on nonlinear transformation log/exp.

@josef-pkt

Copy link
Copy Markdown
Member Author

I had forgotten to take log in the test version to match the confidence intervals.
Now I use for ratio and odds-ratio
diff_stat = (np.log(ratio_) - np.log(value))

Also, score confint for ratio uses NAM without the Miettinen/Nurminen correction, so confint and test only match if correction=False

Then:

restci = []
for co, method in resc_df.T:
    r = test_proportions_2indep(count1, nobs1, count2, nobs2, compare=co, method=method, 
                                value=resc_df.loc[(co, method), 'upper'], correction=False)
    restci.append([co, method, r[0], r[1]])
    print([co, method, r[0], r[1]]) 

['diff', 'agresti-caffo', -1.9599639845400543, 0.050000000000000003]
['diff', 'wald', -1.9599639845400545, 0.049999999999999954]
['odds-ratio', 'logit', -1.9599639845400545, 0.049999999999999954]
['odds-ratio', 'logit-adjusted', -1.9599639845400543, 0.050000000000000003]
['odds-ratio', 'logit-smoothed', -1.9599639845400543, 0.050000000000000003]
['ratio', 'log', -1.9599639845400547, 0.049999999999999933]
['ratio', 'log-adjusted', -1.9599639845400547, 0.049999999999999933]
['ratio', 'score', -1.9599639845400625, 0.049999999999999004]

@josef-pkt

Copy link
Copy Markdown
Member Author

and the same for one-sided test, i.e. inferiority or superiority (after fixing another bug)

Does the direction 'lower' - 'larger' and 'upper' - 'smaller' match?
TODO: check interpretation (sign of diff_stat) again.

restci = []
for co, method in resc_df.T:
    r = test_proportions_2indep(count1, nobs1, count2, nobs2, compare=co, method=method, 
                                value=resc_df.loc[(co, method), 'upper'], correction=False,
                                alternative='smaller')
    restci.append([co, method, r[0], r[1]])
    print([co, method, r[0], r[1]])

['diff', 'agresti-caffo', -1.9599639845400543, 0.025000000000000001]
['diff', 'wald', -1.959963984540054, 0.025000000000000001]
['odds-ratio', 'logit', -1.9599639845400549, 0.024999999999999946]
['odds-ratio', 'logit-adjusted', -1.9599639845400543, 0.025000000000000001]
['odds-ratio', 'logit-smoothed', -1.959963984540054, 0.025000000000000001]
['ratio', 'log', -1.959963984540054, 0.025000000000000001]
['ratio', 'log-adjusted', -1.9599639845400547, 0.024999999999999967]
['ratio', 'score', -1.9599639845400527, 0.025000000000000074]

@josef-pkt

Copy link
Copy Markdown
Member Author

travis test run fails

it looks to me pytest is trying to run a regular function that starts with test as a test function.
I don't get this locally when running just the test function.
But I also get it when running the test module (which I didn't try again before pushing)

__________________ ERROR at setup of test_proportions_2indep ___________________
file /home/travis/build/statsmodels/statsmodels/statsmodels/stats/proportion.py, line 1292
  def test_proportions_2indep(count1, nobs1, count2, nobs2, value=None,
E       fixture 'count1' not found
>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, monkeypatch, pytestconfig, record_property, record_xml_attribute, record_xml_property, recwarn, tmpdir, tmpdir_factory, worker_id
>       use 'pytest --fixtures [testpath]' for help on them.

@josef-pkt

Copy link
Copy Markdown
Member Author

my mistake (kind of)
In my last commit I explicitly import test_proportions_2indep. So it's now in the test module namespace and treated as test function.
There was no problem before when I used the explicit namespace
smprop.test_proportions_2indep

@josef-pkt

josef-pkt commented Aug 15, 2018 •

Copy link
Copy Markdown
Member Author

This includes now some power calculations #1197
Not integrated into a new Power class yet.
This includes two function for generic normal power and one-tail sample size computation with caller provided std_null and std_alternative.
The same type of functions are added for the special case of comparing two independent proportions.
Those currently are only for equality testing, i.e. Null has value=0. and assumes pooled variance under the Null.

no unit tests yet for nobs ratio different from 1 in power/samplesize (need R or Stata again)

@josef-pkt

Copy link
Copy Markdown
Member Author

I'm getting close to the end, I have some uncommitted docstring and cleanup work

todo/tocheck:

  • unit test coverage, nobs-ratio?
  • name conflict ? risk-ratio versus nobs-ratio i.e. compare='ratio' and ratio=1 keyword in power/sample size
    not yet because I don't have power calculation for non-equality Null (and other than 'diff')
  • add score confint for diff (from R package) ?
  • score confint for odds-ratio ? (I guess not now)
  • do we have other "cheap" additions, options, enhancments?
  • API review: return_results in test_proportions_2indep and maybe others
  • add to rst docs
  • comparison to contingency table functions/methods - notebook ?

unit tests for vectorized - maybe not (see comment above: it works but not in all cases or for all methods)

@josef-pkt

Copy link
Copy Markdown
Member Author

reminder: my notebooks are in
"...\statsmodels\misc_josef\misc\notebooks\ex_proportion_2indep.ipynb"
"...\statsmodels\misc_josef\misc\notebooks\ex_proportion_2indep_short.ipynb"
(uses outdated API, I didn't rerun after latest several commits)

@josef-pkt josef-pkt added this to the 0.10 milestone Nov 17, 2018
@josef-pkt

Copy link
Copy Markdown
Member Author

needs rebase
add to docs and api

should essentially be ready for 0.10, but I don't remember if there is anything left to do before merging.

@josef-pkt

Copy link
Copy Markdown
Member Author

this PR does not link to #2608 (from 2015)
needs checking for overlap
#2608 has class based implementation, i.e. the usual API choice for this type of functionality is still open

@josef-pkt

Copy link
Copy Markdown
Member Author

merged as rebased version #6675

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.

3 participants