Skip to content

ENH: add prob(x1 > x2) effect size measure, inference based on brunner munzel - #6971

Merged
josef-pkt merged 6 commits into
statsmodels:masterfrom
josef-pkt:brunner_munzel
Sep 1, 2020
Merged

josef-pkt merged 6 commits into
statsmodels:masterfrom
josef-pkt:brunner_munzel

Conversation

@josef-pkt

Copy link
Copy Markdown
Member

see #6960 stochastically larger, with notes and references leading to this PR
and #3575 brunner-munzel test

includes

  • standard brunner munzel test
  • brunner-munzel type test for non-zero (not equal 0.5) null hypothesis for stochastically-larger probability, including one-sided
  • equivalence test, tost version of above
  • confidence interval for the probability

location: new module stats.nonparametric

@pep8speaks

pep8speaks commented Aug 15, 2020 •

Copy link
Copy Markdown

Hello @josef-pkt! Thanks for updating this PR. We checked the lines you've touched for PEP 8 issues, and found:

There are currently no PEP 8 issues detected in this Pull Request. Cheers! 🍻

Comment last updated at 2020-09-01 15:52:52 UTC

@coveralls

coveralls commented Aug 15, 2020 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.02%) to 88.34% when pulling c33d27c on josef-pkt:brunner_munzel into 54f7c05 on statsmodels:master.

@lgtm-com

lgtm-com Bot commented Aug 15, 2020

Copy link
Copy Markdown

This pull request introduces 1 alert when merging 9e64ae0 into 1c82e3a - view on LGTM.com

new alerts:

  • 1 for Unused local variable

@lgtm-com

lgtm-com Bot commented Aug 18, 2020

Copy link
Copy Markdown

This pull request introduces 1 alert when merging 1cbcdfb into b6af426 - view on LGTM.com

new alerts:

  • 1 for Unused local variable

@josef-pkt

Copy link
Copy Markdown
Member Author

We reverse the direction compared to brunnermunzel and followup literature, we compute prob x1 > x2, instead of prob x1 < x2.
The motivation for x1 < x2 was "smaller is better" (e.g. decease indicator/index) in some of the literature.

But we want larger is better as in most other fields.

Some signs in unit tests need to be reversed to match numbers, e.g. interchange x1, x2.
Relation ship is just p versus 1-p (e.g. flipping 1- p confint)

@josef-pkt

Copy link
Copy Markdown
Member Author

currently still a hybrid that implements hypothesis test twice, once in main function for brunnermunzel and once as method in the results class.

The main function is based on mean rank differences and not on p directly. (they are just transformation of each other for p=0.5 null)

The function returns a HolderTuple, so brunnermunzel statistic and p-value are immediately available.

@josef-pkt

josef-pkt commented Aug 21, 2020 •

Copy link
Copy Markdown
Member Author

refactoring and dropping the scipy alternative version causes test failure.
my alternative is reversed to scipy and lawstat brunnermunzel

neither scipy nor lawstat say what "less" means.
weird thing is that their test statistic is large in the first unit test case and less uses the upper tail.

my guess is that the are mixing up prob(x less y) with the "less" in the alternative.

my version in the results method just uses my generic test and confint code.

aside: lawstat prints the two-sided confint even if alternative is one-sided

in r:

> brunner.munzel.test(x, y, alternative="less")

        Brunner-Munzel Test

data:  x and y
Brunner-Munzel Test Statistic = 3.137467482303, df = 17.682841979482,
p-value = 0.002893104333076
95 percent confidence interval:
 0.5952168642537365 0.9827052136683416
sample estimates:
  P(X<Y)+.5*P(X=Y) 
0.7889610389610391 

compare with R t.test, reversed variables, so we get a positive test statistic
The diff and test statistic are large, so we cannot reject in favor that the alternative that diff is negative (smaller/less than 0).

> t.test(y, x, alternative="less")

        Welch Two Sample t-test

data:  y and x
t = 2.9486153015726, df = 15.915568793934, p-value = 0.9952605491564
alternative hypothesis: true difference in means is less than 0
95 percent confidence interval:
              -Inf 2.181651777316802
sample estimates:
        mean of x         mean of y 
2.727272727272727 1.357142857142857 

@josef-pkt

Copy link
Copy Markdown
Member Author

cross checking with Welch t-test on ranks: in large samples results are essentially identical to brunner-munzerl

for diff in np.linspace(0, 0.2, 11):
    y1, y2 = np.random.randn(2, 10000) + np.array([[0, diff]]).T
​
    rank1, rank2, _, _ = rankdata_2samp(y1, y2)
    res = rank_compare_2indep(y1, y2, use_t=True)
    tr = res.test_prob_superior()
    tt = ws.ttest_ind(rank1, rank2, usevar="unequal")
    #print(res.summary())
    print("mean diff =", diff)
    print(tr)
    print(res.tuple, res.df)
    print(tt)
    
mean diff = 0.0
(0.6330889852927066, 0.5266827777799017)
(0.6330889852927172, 0.5266827777798953) 19987.821508917084
(0.6331212459632303, 0.5266617097403544, 19995.45388665269)
mean diff = 0.02
(-2.707270892728522, 0.006789649801408663)
(-2.7072708927285225, 0.00678964980140866) 19997.819238629832
(-2.70690699195412, 0.0067970937014443684, 19997.95483364355)
mean diff = 0.04
(-2.352601204919562, 0.018652257057405957)
(-2.3526012049195644, 0.018652257057405856) 19985.29083346516
(-2.352536129674668, 0.018655515618796338, 19994.821544860446)
mean diff = 0.06
(-3.404525126257076, 0.0006640933660853339)
(-3.4045251262570817, 0.0006640933660853188) 19996.48588777765
(-3.4042813819902675, 0.0006646858681892425, 19997.62155884264)
mean diff = 0.08
(-7.022956462009803, 2.241937342868426e-12)
(-7.022956462009806, 2.2419373428683857e-12) 19992.361555755906
(-7.01683732831687, 2.3420370652411686e-12, 19996.594997873428)

@josef-pkt

josef-pkt commented Aug 22, 2020 •

Copy link
Copy Markdown
Member Author

corner case, full separation, all x2 > x1, prob1=0, prob2=1
found in simulation

rank1, rank2
(array([4., 2., 1., 5., 3.]), array([ 8.,  6.,  7.,  9., 10.]))

y1, y2
(array([-0.46033188, -0.8026103 , -1.0363547 , -0.11726762, -0.56056166]),
 array([ 2.09131261, -0.08353725,  0.84335249,  2.99857968,  3.95316162]))

rank_compare_2indep(y1, y2, use_t=True)
<class 'statsmodels.stats.nonparametric.RankCompareResult'>
statistic = -inf
pvalue = nan
s1 = 0.0
s2 = 0.0
var1 = 0.0
var2 = 0.0
var = 0.0
var_prob = 0.0
nobs1 = 5
nobs2 = 5
nobs = 10
mean1 = 3.0
mean2 = 8.0
prob1 = 0.0
prob2 = 1.0
somersd1 = -1.0
somersd2 = 1.0
df = nan
tuple = (-inf, nan)
False

rank_compare_2indep(y1, y2, use_t=False)
<class 'statsmodels.stats.nonparametric.RankCompareResult'>
statistic = -inf
pvalue = 0.0
s1 = 0.0
s2 = 0.0
var1 = 0.0
var2 = 0.0
var = 0.0
var_prob = 0.0
nobs1 = 5
nobs2 = 5
nobs = 10
mean1 = 3.0
mean2 = 8.0
prob1 = 0.0
prob2 = 1.0
somersd1 = -1.0
somersd2 = 1.0
df = None
tuple = (-inf, 0.0)
r = rank_compare_2indep(y1, y2, use_t=True)
print(r.summary())
                 Probability sample 1 is stochastically larger                 
===============================================================================
                  coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------
prob(x1>x2)          0          0       -inf        nan         nan         nan
===============================================================================

ttest on ranks still works in this case ?
results: (-5.0, 0.001052825793366539, 8.0)

@josef-pkt

Copy link
Copy Markdown
Member Author

a quick MC

nobs1=nobs2 = 100
unequal variance, scale 1 and 2.
observations normal distributed

size at 5% alpha:
Brunner munzel is good, 0.0515,
Welch on ranks has a bit higher rejection rate, 0.0601
mannwhitneyu overrejects, 0.1132

scales = np.array([[1, 2]]).T
res_mc = []
diff = 0.0
np.random.seed(987456)
for _ in range(10000):
    y1, y2 = np.random.randn(2, 100) * scales + np.array([[0, diff]]).T
​
    rank1, rank2, _, _ = rankdata_2samp(y1, y2)
    res = rank_compare_2indep(y1, y2, use_t=True)
    tr = res.test_prob_superior()
    tt = ws.ttest_ind(rank1, rank2, usevar="unequal")
    tmw = stats.mannwhitneyu(y1, y2)
    res_mc.append([tr[1], tt[1], tmw.pvalue])
    
res_mc = np.asarray(res_mc)
(res_mc <= 0.05).mean(0)
array([0.0515, 0.0601, 0.1132])

reducing nobs1, nobs2 to 10, with 20000 MC replications
there is one nan in my rank_compare/brunnermunzel test method
size is similar to nobs1=100 case

np.isnan(res_mc).sum(0)
array([1, 0, 0])

(res_mc[np.isfinite(res_mc[:, 0]), :] <= 0.05).mean(0)
array([0.05460273, 0.05815291, 0.09930497])

@josef-pkt josef-pkt mentioned this pull request Aug 23, 2020
@josef-pkt

Copy link
Copy Markdown
Member Author

one travis failure in statespace, everything else is green
RankCompareResult doesn't have a unit test

hypothesis test methods still return tuple instead of HolderTuple

missing bonus:
confint for somersd
normal equivalent cohensd (in which reference did I see that?)

should I add also prob2, i.e. p(x2 > x1) to summary?

I'm skipping power and sample size computation for now

@josef-pkt

josef-pkt commented Aug 24, 2020 •

Copy link
Copy Markdown
Member Author

this vectorized with little work

example from UCLA stats, reading and writing skills of female versus male highschool students

print(rc.summary(xname=["read"]))
                   Probability sample 1 is stochastically larger                    
====================================================================================
                       coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------------
prob(x1>x2) read     0.5343      0.041      0.833      0.406       0.453       0.616
====================================================================================

rc2 = rank_compare_2indep(df_female[["read","write"]], df_male[["read","write"]])
<class 'statsmodels.stats.nonparametric.RankCompareResult'>
statistic = [ 0.8334161  -3.43098807]
pvalue = [0.4056698  0.00075819]
s1 = [1048.56312576 1145.99218559]
s2 = [655.9775739  471.00237853]
var1 = [0.08825546 0.09645587]
var2 = [0.07921478 0.05687748]
var = [0.33931626 0.31635326]
var_prob = [0.00169658 0.00158177]
nobs1 = 91
nobs2 = 109
nobs = 200
mean1 = [104.24175824  85.62637363]
mean2 = [ 97.37614679 112.91743119]
prob1 = [0.53432806 0.36354471]
prob2 = [0.46567194 0.63645529]
somersd1 = [ 0.06865611 -0.27291058]
somersd2 = [-0.06865611  0.27291058]
df = [187.62345121 166.74833785]
tuple = (array([ 0.8334161 , -3.43098807]), array([0.4056698 , 0.00075819]))

rc2.test_prob_superior()
(array([ 0.8334161 , -3.43098807]), array([0.4056698 , 0.00075819]))

print(rc2.summary(xname=["read", "write"]))
                    Probability sample 1 is stochastically larger                    
=====================================================================================
                        coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------------
prob(x1>x2) read      0.5343      0.041      0.833      0.406       0.453       0.285
prob(x1>x2) write     0.3635      0.040     -3.431      0.001       0.616       0.442
=====================================================================================

still a bug in summary, confint is transposed

@josef-pkt

josef-pkt commented Aug 24, 2020 •

Copy link
Copy Markdown
Member Author

edit this example and the following has male and female reversed, female is coded as 1

df_female = hsb2.loc[hsb2["female"]==0, :]
df_male = hsb2.loc[hsb2["female"]==1, :]

original comment:

In this sample the only significant result is that boys have higher writing grades than girls.
We cannot reject stochastic equality for "read", "math", "science".
Girls have higher grades in science is almost statistically significant. 95% confint [0.498, 0.661]

names = ["read","write", "math", "science"]
rc3 = rank_compare_2indep(df_female[names], df_male[names])
print(rc3.summary(xname=names))
                     Probability sample 1 is stochastically larger                     
=======================================================================================
                          coef    std err          t      P>|t|      [0.025      0.975]
---------------------------------------------------------------------------------------
prob(x1>x2) read        0.5343      0.041      0.833      0.406       0.453       0.616
prob(x1>x2) write       0.3635      0.040     -3.431      0.001       0.285       0.442
prob(x1>x2) math        0.5136      0.041      0.328      0.743       0.432       0.595
prob(x1>x2) science     0.5795      0.041      1.922      0.056       0.498       0.661
=======================================================================================

@josef-pkt

Copy link
Copy Markdown
Member Author

aside: I'm fixing Holder str and repr for nested cases as in tost, add an intend of 4 spaces.
In the master version it is difficult to distinguish attributes of main instance with attributes of attributes (e.g. nested results in TOST) because they all started an the beginning of the line.

new results for repr

res.tost_prob_superior(0.45, 0.55)
<class 'statsmodels.stats.base.HolderTuple'>
statistic = -2.505026112598482
pvalue = 0.006512753894336686
results_larger = <class 'statsmodels.stats.base.HolderTuple'>
    statistic = 0.15351382128216023
    pvalue = 0.43907230923278956
    df = 204.29842398679557
    distribution = 't'
    tuple = (0.15351382128216023, 0.43907230923278956)
results_smaller = <class 'statsmodels.stats.base.HolderTuple'>
    statistic = -2.505026112598482
    pvalue = 0.006512753894336686
    df = 204.29842398679557
    distribution = 't'
    tuple = (-2.505026112598482, 0.006512753894336686)
title = 'Equivalence test for Prob(x1 > x2) + 0.5 Prob(x1 = x2) '
tuple = (-2.505026112598482, 0.006512753894336686)

@josef-pkt

josef-pkt commented Aug 26, 2020 •

Copy link
Copy Markdown
Member Author

all green, full unit test coverage except when raising ValueError
time to wrap up, and open a follow-up issue (more methods for standard errors, improve summary, extension to oneway analysis)

@josef-pkt

Copy link
Copy Markdown
Member Author

added to docs stats.rst but not to stats.api see #7013

merging when green enough

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