Skip to content

ENH: Stats robust rebased - #6526

Closed
josef-pkt wants to merge 25 commits into
statsmodels:masterfrom
josef-pkt:stats_robust_rebased
Closed

josef-pkt wants to merge 25 commits into
statsmodels:masterfrom
josef-pkt:stats_robust_rebased

Conversation

@josef-pkt

Copy link
Copy Markdown
Member

This is a rebased version of my old branch, updated to run with Python 3

master...josef-pkt:stats_robust

see #6459

I moved the examples from __main__ to the test module as a smoke tests.

@lgtm-com

lgtm-com Bot commented Feb 19, 2020

Copy link
Copy Markdown

This pull request introduces 8 alerts when merging ccead19 into 3876fad - view on LGTM.com

new alerts:

  • 5 for Unused local variable
  • 3 for Variable defined multiple times

@josef-pkt
josef-pkt force-pushed the stats_robust_rebased branch from ccead19 to 5051fb8 Compare February 19, 2020 01:12
@pep8speaks

pep8speaks commented Feb 19, 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:

Line 163:20: E999 SyntaxError: invalid syntax

Comment last updated at 2020-06-03 21:02:40 UTC

@lgtm-com

lgtm-com Bot commented Feb 19, 2020

Copy link
Copy Markdown

This pull request introduces 8 alerts when merging 5051fb8 into 3876fad - view on LGTM.com

new alerts:

  • 5 for Unused local variable
  • 3 for Variable defined multiple times

@coveralls

coveralls commented Feb 19, 2020 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.1%) to 87.885% when pulling 0e09510 on josef-pkt:stats_robust_rebased into 4f77089 on statsmodels:master.

@josef-pkt

josef-pkt commented Feb 19, 2020 •

Copy link
Copy Markdown
Member Author

most likely there are still some bugs, e.g. df in anova_welsh looks wrong (too small in a simple example)

some quick checks with an unbalanced example
Welch t_test agrees with OLS with cov_type="HC2" except for the df that are not the same as in Satterthwaite, t-values are identical

OLS nonrobust f_test and one-way anova completely agree

OLS HC2 f_test and anova_welch have large differences.

update anova_welch results look strange but correct
The code in the scipy.issue produces the same results as my anova_welch.
?
standard anova has df (4, 95.0)
welch anova has df (4.0, 6.327)
6 df_resid instead of 95?

@josef-pkt
josef-pkt force-pushed the stats_robust_rebased branch from 5051fb8 to 81493af Compare February 19, 2020 03:55
@codecov

codecov Bot commented Feb 19, 2020 •

Copy link
Copy Markdown

Codecov Report

Merging #6526 into master will increase coverage by 0.01%.
The diff coverage is 79.44%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #6526      +/-   ##
==========================================
+ Coverage   85.22%   85.24%   +0.01%     
==========================================
  Files         643      650       +7     
  Lines      103178   104108     +930     
  Branches    11236    11345     +109     
==========================================
+ Hits        87932    88745     +813     
- Misses      12798    12889      +91     
- Partials     2448     2474      +26
Impacted Files Coverage Δ
statsmodels/stats/tests/test_oneway.py 100% <100%> (ø)
statsmodels/tools/testing.py 86.2% <33.33%> (-6.11%) ⬇️
statsmodels/stats/oneway.py 45.55% <45.55%> (ø)
statsmodels/stats/robust_compare.py 75.69% <75.69%> (ø)
statsmodels/stats/tests/test_robust_compare.py 95.58% <95.58%> (ø)
statsmodels/tsa/statespace/simulation_smoother.py 85.29% <0%> (-1.75%) ⬇️
statsmodels/base/_parameter_inference.py 60.81% <0%> (-1.69%) ⬇️
...a/statespace/tests/test_exact_diffuse_filtering.py 97.46% <0%> (ø) ⬆️
...smodels/nonparametric/tests/test_kernel_density.py 100% <0%> (ø) ⬆️
statsmodels/tsa/statespace/tests/test_mlemodel.py 100% <0%> (ø) ⬆️
... and 19 more

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 65af83b...14a561d. Read the comment docs.

@lgtm-com

lgtm-com Bot commented Feb 19, 2020

Copy link
Copy Markdown

This pull request introduces 8 alerts when merging 81493af into 3876fad - view on LGTM.com

new alerts:

  • 5 for Unused local variable
  • 3 for Variable defined multiple times

@josef-pkt

josef-pkt commented Feb 19, 2020 •

Copy link
Copy Markdown
Member Author

some problems in verifying the trim functions against R WRS2
I'm not sure whether I made mistakes or used different definitions.

var_winsorized is likely wrong (and might have mixed in computation for std_mean_trimmed

tm.std_mean_trimmed looks strange in WRS2

WRS2 uses
np.sqrt(tm.var_winsorized / tm.nobs) / (1 - 2 * tm.fraction)
while I also have the nobs correction implicitly (1 - 2 * tm.fraction) inside the sqrt.
but I'm also using the actual number of non-trimmed observations.

another problem is desired fraction to cut is not the actual fraction to cut because of integer rounding/truncation

e.g. in the WRS2 vignette example, fraction to trim is 0.1, we trim one observation on each side which is 1/19

len(timevec), tm.nobs_reduced, tm.nobs * (1 - 2 * tm.fraction)
(19, 17, 15.2)

(AFAIR, I didn't look at WRS2 or the book of Wilcox when I wrote my versions, but I used several articles by Wilcox as reference)

The code also has a comment # formula from an old SAS manual page, simplified

I guess, I don't want to match WRS2 in some of the results.

The difference in tm.std_mean_trimmed between my version and WRS2 is large, so a MonteCarlo should show which is better.
(It's not a quick walk in the park)

update

workaround for unit test for integer trimming, use trimming fraction that corresponds to integer number of observations, eg fraction=1/19

len(timevec), tm.nobs_reduced, tm.nobs * (1 - 2 * tm.fraction)
(19, 17, 17.0)
> trimse(timevec, 0.1)
[1] 103.2685520957588
> trimse(timevec, 1/19)
[1] 92.33423481503138

this still leaves the difference in the sqrt for std_mean_trimmed
I have 87.33944235323739 for trimse

@josef-pkt

Copy link
Copy Markdown
Member Author

:(
Nist dataplot also has the trim fraction outside of the sqrt
https://www.itl.nist.gov/div898/software/dataplot/refman2/auxillar/trimmse.htm
they reference Wilcox book

another one Medcalc
https://www.medcalc.org/manual/note-trimmedmean.php
This uses integer truncated fraction k and has corrected nobs n - 2 k in sqrts
reference to original 1963 article
(It looks like they also have the ddof the var_winsorized when it is used for std_trimmed_mean.
That looks the same as what I have in the repo version, but I changed it locally to have var_winsorized independent of the std_trimmed_mean use and matching WRS2)

@josef-pkt

Copy link
Copy Markdown
Member Author

R psych and WRS2 don't agree on winsorized statistics

 winsor.var(timevec, trim = 1/19)  # psych
[1] 137017.5818632456
> winvar(timevec, 1/19)  # WRS2
[1] 129679.0292397661
> winmean(timevec, 0.1)
[1] 380.1578947368421
> winmean(timevec, 1/19)
[1] 380.1578947368421

> winsor.mean(timevec, trim = 0.1)
[1] 326.0105263157894
> winsor.mean(timevec, trim = 1/19)
[1] 383.7340720221608
> winsor.mean(timevec, trim = 1/19 + 0.00001)
[1] 383.721841495845
> winsor.mean(timevec, trim = 1/19 - 0.00001)
[1] 383.7463025484766

Does psych do interpolation for fractional observations?

@josef-pkt

josef-pkt commented Feb 19, 2020 •

Copy link
Copy Markdown
Member Author

a quick monte carlo
my std_mean_trimmed underestimate the std a little bit 0.216 instead of 0.230 (around 6%)
larger sample size, nobs, doesn't make much difference for the underestimation (0.02199 / 0.0234 = -0.06 if nobs=1900)

And it's essentially the same if I use non-integer truncation fraction TrimmedMean(x, 0.1), i.e. we use actual truncation instead of desired fraction.

nobs = 19
n_rep = 10000
res = []
for i in range(n_rep):
    x = 1 + np.random.randn(nobs)
    tm_mc = TrimmedMean(x, 1/19)
    res.append([tm_mc.mean_trimmed, tm_mc.std_mean_trimmed])
    
res = np.asarray(res)
print(res.mean(0))
print(np.median(res, axis=0))
print(res.std(0, ddof=1))
[0.99653986 0.21589923]
[0.99973779 0.2148905 ]
[0.23064505 0.04012118]

If we want to do a "bias" correction, i.e. change df, then it would have to be proportional to nobs and nobs_reduced, i.e. correct something like 5 or 6 %

update maybe the sqrt in Wilcox helps (but I use actual trimming fraction)
res[:, 1] / np.sqrt(tm_mc.nobs_reduced / tm_mc.nobs)
is close to Monte Carlo std of the trimmed mean
for example nobs = 1900 trim fraction = 0.9
MC std of mean = 0.0243551676
mean of my current std_mean_trimmed = 0.01899661
mean of corrected std_mean_trimmed 0.02452452347621275
and very similar results for nobs=19

cross-check:
without trimming, TrimmedMean(x, 0), estimated std_mean and MonteCarlo standard error agree, e.g. both around 0.227 for nobs=19

@josef-pkt

Copy link
Copy Markdown
Member Author

Ok, given that Wilcox version of sqrt works better in the MC:
equ. (3.9) p. 61 has the formula from the vignette appendix, and before that is the derivation that takes account of the correlation between trimmed observations. Because trimming is based on the order statistic, trimmed observations are not independent of each other anymore.

Wilcox, Rand R. 2012. Introduction to Robust Estimation and Hypothesis Testing. 3rd ed. Statistical Modeling and Decision Science. Amsterdam ; Boston: Academic Press.

@josef-pkt

Copy link
Copy Markdown
Member Author

aside: the mean function with trimming used in the WRS2 vignette, is from R base. ( I didn't find it in the WRS2 documentation)
https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/mean

another aside: Wilcox briefly mentions trimming based on interpolation. There was also an old R-help question why R base mean trimming doesn't interpolate.

I will stick with integer trimming, that's simpler, and used in most references that I looked at a long time ago (AFAIR)

@josef-pkt

Copy link
Copy Markdown
Member Author

I don't have a trimmed variance function, and neither does WRS2.
var is in R stats and does not have trimming

chemometrics in R has
sd_trim https://rdrr.io/cran/chemometrics/man/sd_trim.html
They also have a correction factor to make it consistent with normal distribution. I guess similar to mad and iqr.
I might have seen that before in robust estimation (but maybe that was based on statistical trimming and not on fixed percentage trimming. maybe in another ancient PR of mine, ELTS)

WRS2 lists under the trimse header the following functions

mean(self, 0.1) ## .10 trimmed mean
trimse(self, 0.1) ## se trimmed mean
winmean(self, 0.1) ## Winsorized mean (.10 Winsorizing amount)
winse(self, 0.1) ## se Winsorized mean
winvar(self, 0.1) ## Winsorized variance
median(self) ## median
msmedse(self) ## se median
mest(self) ## Huber M-estimator
mestse(self)
onestep(self) ## one-step M-estimator
mom(self) ## modified one-step M-estimator

Huber are in statsmodels.robust
I don't know about the median functions, we (including scipy.stats) don't have std_median/se_median
trimming and winsorizing are in this PR

@josef-pkt

josef-pkt commented Feb 20, 2020 •

Copy link
Copy Markdown
Member Author

and another problem, standard error of winsorized mean has currently a term under sqrt, that WRS2 has outside

std_mean_winsorized(self):
       ...
        # formula from an old SAS manual page, simplified
        std_ = np.sqrt(tm.var_winsorized / (tm.nobs_reduced - 1) *
                       (tm.nobs - 1.) / tm.nobs)

to match WRS2, I need
np.sqrt(tm.var_winsorized / tm.nobs) * (tm.nobs - 1) / (tm.nobs_reduced - 1)

What's "an old SAS manual page, simplified"?
:)

Bugs, or computed under different assumptions or approximations?

@josef-pkt

Copy link
Copy Markdown
Member Author

chasing R functions and packages is a bit tiresome

One sample trimmed t-test
WRS2 doesn't have it, only for 2 and more sample comparisons,
DescTools has it but results don't match up
finally PairedData package has also yuen test that works for one and two samples

> library(PairedData)
> yuen.t.test(timevec, y = NULL, tr = 1/19)

        One sample Yuen test, trim=0.0526315789473684

data:  x
t = 3.7115798169494, df = 16, p-value = 0.00189544440273
alternative hypothesis: true trimmed means is not equal to 0
95 percent confidence interval:
 146.9660486690165 538.4457160368659
sample estimates:
trimmed mean of x 
342.7058823529412 

@josef-pkt
josef-pkt force-pushed the stats_robust_rebased branch from 81493af to 254e265 Compare February 20, 2020 16:44
@lgtm-com

lgtm-com Bot commented Feb 20, 2020

Copy link
Copy Markdown

This pull request introduces 9 alerts when merging 254e265 into 3876fad - view on LGTM.com

new alerts:

  • 5 for Unused local variable
  • 3 for Variable defined multiple times
  • 1 for Unreachable code

@josef-pkt

Copy link
Copy Markdown
Member Author

and it continues with anova problems
it looks like WRS2 and PairedData which largely copied from Wilcox) only have Welsh-Yuen, but no Yuen with same variance assumption.

running my anova_welch, I get the same Satterthwaite df as WRS2, but the test statistic and p-value differ :(

Also, AFAICS, in the vignette appendix Yuen/Welch standard deviation for the mean diff don't just use the std of individual trimmed means,
The correction factor from the one sample case is different or doesn't show up.

aside: the example that I use from the WRS2 docs is balanced, so the only difference between Welch and standard anova is in the degrees of freedom.

@josef-pkt

Copy link
Copy Markdown
Member Author

R is sooo nice, I found another package
https://www.rdocumentation.org/packages/onewaytests/versions/2.4/topics/welch.test

My welch test, agrees (at 1e-16) with those R packages when there is not trimming, also in unbalance sample case.

The 3 R packages agree with each other when there is trimming.

@josef-pkt

Copy link
Copy Markdown
Member Author

what's the difference between anova_bfm and anova_welch?
They produce the same result..
The scale/dispersion conversion is handled in anova_scale. Is anova_bfm just anova_welch?
(That would be logical, variance anovas like levene just use transformed data with regular anova.)

anova_welch([y0, y1[:-2]], trim_frac=1/12)
(2.2698412698412698, 0.15097418919782005, (1.0, 16.363527692920712))
anova_bfm([y0, y1[:-2]], trim_frac=1/12)
(2.2698412698412698,
 0.15097418919782002,
 0.15097418919782002,
 (1, 16.363527692920705, 1.0))

anova_welch([y0, y1[:-2]], trim_frac=0)
(2.1725749902610048, 0.15806721017979877, (1.0, 17.686748013960173))

anova_bfm([y0, y1[:-2]], trim_frac=0)
(2.1725749902610048,
 0.15806721017979877,
 0.15806721017979877,
 (1, 17.686748013960173, 1.0000000000000004))

However, levene with trimmed mean as center, doesn't do any further trimming and uses standard anova. In Yuen, trimmed anova we use the properties of the trimming and order statistics to compute the std_mean_trimmed (e.g. use var_winsorized and not regular var).

I guess, using levene with trimmed mean and trimming in anova does double trimming.
Once to get the center for the data transformation z =abs(x - mean_trimmed_x) and then standard trimmed anova on z, i.e. we throw away the largest and smallest z.

anova_scale does not do the double trimming. It only optionally uses the mean_trimmed as center but then calls the untrimmed anova.
(We could add a second trim_frac keyword for double trimming in anova_scale.)

Maybe:
anova_bfm has this sentence
"This currently returns both Brown-Forsythe and Mehrotra adjusted pvalues."
At least part of the code of bfm and welch differ, so it's not completly copy-paste.
So maybe it's just that BF used standard anova and mehrotra extended it to use Welch anova.

And we haven't even added Kruskal yet in the mix, i.e. rank_transformed data.

@josef-pkt

josef-pkt commented Feb 21, 2020 •

Copy link
Copy Markdown
Member Author

more info on Welsh ANOVA:
This is not just heteroscedasticity, i.e. compute mean under unequal variance assumption.
There is also a correction term in the statistic to give a better approximation to F distribution,
df correction in Satterthwaite style is extra

OLS HC2 agrees with welch t-test and Welch Anova in two sample case
OLS HC2 test statistic agrees with welch anova without the extra correction term, when there are 3 or more samples in the comparison.

Welsh correction factor is 1, i.e. no effect, in two sample case. It only corrects when we have 3 or more samples. That's why Welch two sample t-test is the same as HC2

Welsh 1951 refences James 1951 which has higher order expansion and correction for the heteroscedastic ANOVA. Welch corresponds to the first higher order expansion.

the following article compares bootstrap with Welch and James second order expansion
Krishnamoorthy, K., Fei Lu, and Thomas Mathew. 2007. “A Parametric Bootstrap Approach for ANOVA with Unequal Variances: Fixed and Random Models.” Computational Statistics & Data Analysis 51 (12): 5731–42. https://doi.org/10.1016/j.csda.2006.09.039.

@josef-pkt

Copy link
Copy Markdown
Member Author

And now the question is whether the variation with different transformation (trimmed, variane/Levene-Welch, equivalence Wellek-Welch) use the same correction factor that james/Welch derived for the standard mean comparison.
???

At least my trimmed Yuen-Welch doesn't match up with Yuen-Welsh in R, so some correction factor differs.

(I will add an extra option to Welch type anova to compute the HC2 solution, i.e. unequal var, but no Welch/Satterthwaite correction.)

@josef-pkt

Copy link
Copy Markdown
Member Author

A pain, two hours debugging because I had forgotten about a typo in a NCSS dataset.

I have some test cases in 1 or 2 month old notebook try_welsh_anova
That also includes a confint_median function checked with R DescTools MedianCI. Not sure whether I already put this somewhere.

According to that notebook, the following is similar Bartlett test for equality of variances, but pvalue doesn't match exactly, maybe F versus chisquare problem
anova_scale(arrs, method=method, center="mean", transform="square")[0]
method='equal` (or originally "levene" comes closest

aside: I don't remember if I have this already somewhere.
Under the null of equal variance and given normal distribution, the 4th moment are also constant, so "equal" would be justified by this.
But we don't use that variance of variance is sigma^4 under normality.

@lgtm-com

lgtm-com Bot commented May 23, 2020

Copy link
Copy Markdown

This pull request introduces 12 alerts when merging 9fbbcdf into 0551e89 - view on LGTM.com

new alerts:

  • 7 for Unused local variable
  • 3 for Variable defined multiple times
  • 1 for Wrong name for an argument in a call
  • 1 for Unreachable code

@josef-pkt

Copy link
Copy Markdown
Member Author

transformation for oneway scale test:

abs is in Levene BF
square is standard normal model
others:
exp I don't remember from where I got the idea of adding exp. I will remove it again, but I now allow for a user provided transform function.
log x*2 : I'm using this as test case for user provided function

brief search

Md. Khairul Islam TRANSFORMED TESTS FOR HOMOGENEITY OF VARIANCES AND MEANS
PhD thesis, compares several transforms including log-square and sqrt-abs for Levene type, and some transformation for Bartlett type tests
https://etd.ohiolink.edu/!etd.send_file?accession=bgsu1150727264&disposition=inline

aside: this is now generic anova with transformed data. testing variance is just a special case.
We can do standard anova using identity transform, or anova with arbitrary other transforms.
E.g. we could use variance stabilizing transform for non-normal data.
This needs checking for reuse, but should be easy. (transform of proportions or poisson counts)

Also, center can no be a number. Trivial case is setting it to 0., i.e. don't center. There might be other usecases if we have already given estimates or a null hypothesis of the center or mean.

@lgtm-com

lgtm-com Bot commented May 25, 2020

Copy link
Copy Markdown

This pull request introduces 12 alerts when merging 7f127f0 into d4d46c8 - view on LGTM.com

new alerts:

  • 7 for Unused local variable
  • 3 for Variable defined multiple times
  • 1 for Wrong name for an argument in a call
  • 1 for Unreachable code

@josef-pkt

Copy link
Copy Markdown
Member Author

TrimmedMean class has almost complete unit test coverage, but needs docstrings and maybe cached properties.

There are still some workflow problems, when I want to do more with oneway analysis.
e.g. I have an OLS for two sample case, How do I get effectsize and non-centrality for the equivalent anova_oneway analysis?
It's not "obvious" how to get everything I want or need.

side objective: I'm trying to get noncentrality and requirements for power analysis out of (OLS) Results instance from models and compare with standalone stats analysis.

@josef-pkt

Copy link
Copy Markdown
Member Author

and I'm getting confused again: When do we divide by nobs and when by df_resid to compute f2 effect size and noncentrality index?

for power we use scaled nc / nobs, but f2 from f_stat is dividing by df_resid.
FtestAnovaPower computes df_resid from nobs and uses that for df, but uses nobs to get noncentrality
pow_ = stats.ncf.sf(crit, df_denom, df_num, effect_size**2 * nobs)

also a bit annoying: confint_effectsize_oneway does not include the estimated effect size, only confint

@josef-pkt

Copy link
Copy Markdown
Member Author

inconsistency between two functions
(I think the problem is in the literature, _fstat2effectsize was written based on the appendix of a different article than what I used for power and similar)

effectsize_oneway was written to target power computation, and corresponds now also to my draft for effectsize/noncentrality computation for OLS

smo._fstat2effectsize(ta.statistic, *ta.df)
<class 'statsmodels.tools.testing.Holder'>
f2 = 0.3427001684846128
eta2 = 0.2552320886884138
omega2 = 0.11579441565136984
eps2 = 0.20203438073758623
eps2_ = 0.2020343807375862
omega2_ = 0.19851421368305308

es_f2 = smo.effectsize_oneway(means, vars_, nobs, use_var="equal")  # at estimated params
es_f2
0.31290015383377695

es_f2 * nobs_t / ta.df_denom
0.3427001684846128

@lgtm-com

lgtm-com Bot commented May 29, 2020

Copy link
Copy Markdown

This pull request introduces 12 alerts when merging 2e5f7f2 into 856385a - view on LGTM.com

new alerts:

  • 7 for Unused local variable
  • 3 for Variable defined multiple times
  • 1 for Wrong name for an argument in a call
  • 1 for Unreachable code

@lgtm-com

lgtm-com Bot commented Jun 2, 2020

Copy link
Copy Markdown

This pull request introduces 12 alerts when merging 68a6d27 into b19df42 - view on LGTM.com

new alerts:

  • 7 for Unused local variable
  • 3 for Variable defined multiple times
  • 1 for Wrong name for an argument in a call
  • 1 for Unreachable code

@josef-pkt

josef-pkt commented Jun 2, 2020 •

Copy link
Copy Markdown
Member Author

_fstat2effectsize is still missing unit tests, it doesn't fully match the rest, and might need unit tests based on anova_lm
otherwise only individual lines some options are uncovered

I still need to check Steiger again to see what denominator effect size confint use.
I think it's nobs and we need the corresponding effect size, instead of the ones in _fstat2effectsize

@josef-pkt

josef-pkt commented Jun 3, 2020 •

Copy link
Copy Markdown
Member Author

It looks messy to validate my confint for effect size with R
package effect size uses a different way to compute confint and I'm not sure that's correct.
I can replicate it using an fstat implied by the nc confint.

package MBESS produces the same eta2 confint as I have.
ci.pvaf(45.8, 3, 35, N=39, conf.level = 0.9)

My original unit test verify with an example from Steiger, but that covers only parts of confint function

package sjstats just calls package effectsize, identical results at all decimals
sjstats takes a model object, e.g. aov and adds effectsizes and optionally confint

package groupstats also takes model object

Lakens spss http://daniellakens.blogspot.com/2014/06/calculating-confidence-intervals-for.html
matches package MBESS in one of the examples
ci.pvaf(5.7200, 1, 198, N=200, conf.level = 0.9)
packages effect size differs

@josef-pkt

josef-pkt commented Jun 3, 2020 •

Copy link
Copy Markdown
Member Author

I had forgotten about Stata.
stata for eta2 matches my confint at around 5 decimals and also MBESS

esizei 2 40 7.47403193349075, level(90)

looks like between Stata 14 (that I have) and docs of Stata 16
they added epsilon2 effectsize
they dropped omega2 confint, esizei in 16 only has confint for eta2 (no confint for omega nor epsilon)

@lgtm-com

lgtm-com Bot commented Jun 3, 2020

Copy link
Copy Markdown

This pull request introduces 11 alerts when merging 0e09510 into ee9f5c0 - view on LGTM.com

new alerts:

  • 6 for Unused local variable
  • 3 for Variable defined multiple times
  • 1 for Wrong name for an argument in a call
  • 1 for Unreachable code

@josef-pkt

Copy link
Copy Markdown
Member Author

robust_descriptive.py is only added in the first commit, no changes to it in other commits
diff of commits without first:
https://github.com/statsmodels/statsmodels/pull/6526/files/077c07fe0c98b1962b5896d6afe7ab7676cddce9..7f127f0ecad5f27308425c95726d7c771a35cc01

so I can just drop that commit to remove it

@josef-pkt

josef-pkt commented Jun 5, 2020 •

Copy link
Copy Markdown
Member Author

vectorized for adding effectsize and confint to, e.g., anova_lm result

r = _fstat2effectsize(res_f["F"], df1, df2) works fine with pandas, no asarray, so everything remains in pandas

confint_effectsize_oneway breaks with shape mismatch when calling special function for ncF inversion.

requires broadcasting with column vector, and numpy broad casting and extra dimension for confint bounds will not easily work with pandas.
need asarray, maybe split ci = ncfdtrinc(df1, df2, [1 - alpha1s, alpha1s], f_stat) into low and upp.

confint_effectsize_oneway(res_f["F"].values[:, None], df1[:,None], df2 * np.ones(len(df1))[:, None], alpha=0.05)
m:\josef_new\eclipse_ws\statsmodels\statsmodels_py37\statsmodels\statsmodels\stats\oneway.py:194: RuntimeWarning: divide by zero encountered in true_divide
  eta2 = 1 / (1 + 1 / f2)
<class 'statsmodels.tools.testing.Holder'>
f2 = [[0.         0.29686364]
 [0.18547894 1.05552203]
 [0.         0.13313091]]
eta2 = [[0.         0.22890891]
 [0.15645908 0.51350558]
 [0.         0.11748943]]
ci_omega2 = [[-0.01818182  0.2116078 ]
 [ 0.12329088  0.4910632 ]
 [-0.03636364  0.08344021]]
ci_nc = [[ 0.         16.62436397]
 [10.57229986 60.16475591]
 [ 0.          7.58846163]]
ci_f = [[0.         0.54485195]
 [0.43067267 1.02738602]
 [0.         0.36487108]]
ci_eta = [[0.         0.47844426]
 [0.39554909 0.71659304]
 [0.         0.34276731]]
ci_f_corrected = [[0.         0.77053701]
 [0.52746414 1.25828576]
 [0.         0.44687399]]

not clear to me:
anova_lm results table has only one df in each row. In type 3, the second df should be df_resid.
However, for type 1 and some type 2, the second df shouldn't be the full model df_resid, AFAIU.

Even typ="I" uses the full df_resid in computing the f p-value, based on computing the p-value outside of function.
???

@josef-pkt

Copy link
Copy Markdown
Member Author

a bit of sightseeing on github

two applications with anova
https://github.com/CancerRxGene/gdsctools/blob/master/gdsctools/anova.py
a lot of application specific code around anova

https://github.com/sunshineDrizzle/CommonTools/blob/master/commontool/stats.py
a nice wrapper around anova_lm using formulas for oneway and two-way anova, add eta_squared and omega_squared as effect sizes to the anova table
(no license but straightforward usage of statsmodels.)

@josef-pkt

Copy link
Copy Markdown
Member Author

temporary storage, for udocstring

>>> from statsmodels.stats.oneway import effectsize_oneway
>>> from statsmodels.stats.power import FTestAnovaPower
>>>
>>> nobs = np.array([10, 12, 13, 15])
>>> delta = 0.5
>>> means_alt = np.array([-1, 0, 0, 1]) * delta
>>> vars_ = np.arange(1, len(means_alt) + 1)
>>>
>>> f2_alt = effectsize_oneway(means_alt, vars_, nobs, use_var="equal")
>>> f2_alt
0.04581300813008131
>>>
>>> kwds = {'effect_size': np.sqrt(f2_alt), 'nobs': 100, 'alpha': 0.05, 'k_group
s': 4}
>>> power = FTestAnovaPower().power(**kwds)
>>> power
0.39165892158983273
>>>
>>> f2_alt = effectsize_oneway(means_alt, vars_, nobs, use_var="unequal")
>>> f2_alt
0.060640138408304504
>>>
>>> kwds['effect_size'] = np.sqrt(f2_alt)
>>> power = FTestAnovaPower().power(**kwds)
>>> power
0.5047366512800622
>>>
>>> f2_alt = effectsize_oneway(means_alt, vars_, nobs, use_var="bf")
>>> f2_alt
0.04391324307956788
>>>
>>> kwds['effect_size'] = np.sqrt(f2_alt)
>>> power = FTestAnovaPower().power(**kwds)
>>> power
0.3765792117047725

@josef-pkt

Copy link
Copy Markdown
Member Author

the first commit with robust_descriptive is now in PR #6790

The oneway part continues with cleanup in PR #6789

This PR is now only for the record with background information about methods and design decisions.

@josef-pkt josef-pkt closed this in 1788248 Jun 30, 2020
@josef-pkt
josef-pkt deleted the stats_robust_rebased branch February 21, 2021 13:36
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