Repository navigation
ENH: Add var_weights to GLM - #3410
thequackdaddy wants to merge 14 commits into
Conversation
|
@thequackdaddy Thanks, I look at it soon (as soon as I can ignore 0.8) If the bse is off by a proportional factor, then there is just a factor to be used to correct this. In some cases I changed our code to match Stata's correction factors, in other cases I adjusted the unit tests so we are more consistent across models than Stata is. I usually reverse engineered the correction factor from the Stata test case with the help, as far as possible, of the Stata documentation. |
|
Update: There is a bug in the tests... the resids aren't being run (and are wrong). I'll fix tomorrow. |
|
Turned out to be a much simpler fix than I thought, so I went ahead and did it. Note that the R multiplies the deviance residuals and the pearson residuals by the weights (but doesn't for working or response). I'm unclear whether anscombe ought be multiplied. (I'd be curious if stata also multiples variance weights by these residuals as well...) I recall that we went back on forth whether resids should be multiplied by frequency weights... but I think frequency weights and variance weights are different. It makes some sense to me that the variance weights should be included in resids, while not so for frequency (as frequency weights is essentially a shortcut to duplicating records)... Anyways, I'll pipe down while 0.8 is finalized. That a far bigger milestone. |
|
about resids: var_weights differ from the other weights because they go inside the likelihood function while the others all just multiply it. resid_deviance and resid_pearson need the var_weights, |
|
Thanks for the insights. So I'm pretty close then. Right now, I'm including
This makes sense to me conceptually. I don't know if we have to worry about this practically, though. For all the families, it appears that So my shortcut was just to multiply However, if you try to calculate the deviance from the respective methods in @josef-pkt Would it be possible (easy) to add the resids to for TestGlmPoissonAwHc here. Otherwise, I won't have a unittest to compare against anscombe (I don't know how to get anscombe residuals from R's glm.) |
|
I just ran the Stata file again to check residuals, parameter estimates and similar are independent of the cov_type. IIRC that was the reason not to include the same residuals several times To avoid having to adjust the tests, you could add at the end of the results module, related asides:
|
|
Oh duh. I hadn't looked at those, and now it shows an inconsistency. Based on that, stata does not utilize In [4]: from statsmodels.genmod.tests.results import results_glm_poisson_weight
...: s as res
In [5]: x = res.results_poisson_aweight_nonrobust.resids
In [6]: y = res.results_poisson_fweight_nonrobust.resids
In [7]: from numpy.testing import assert_allclose
In [8]: assert_allclose(x, y)
In [9]:Options:
|
|
And to recap: the only real differences I see so far in
Other than that, they appear to be functionally the same. |
|
We follow R in this. At least in my recent thinking that is the more obvious use case for var_weights. i.e. those resids are approximately standard normal without heteroscedasticity. Binomial variance function includes |
|
Based on what I remember from the SPSS documentation, they have a few places where freq_weights and var_weights are handled differently. Also, given the recent discussion, we need unit tests with noncanonical links. Does tweedie cover that enough? |
Cool. If you stumble across that again, it would be good to spot check that we are doing it the same way.
I'm using a tweedie/non-canonical link in the test I added (var_power is 1.55 in the model, so the canonical link is I have an R script that generated the Tweedie result. Should be trivial to get others tests incorporated. I'll do gamma and gaussian with log link. If you have any others, let me know. |
1a01699 to
633df41
Compare
|
I am struggling to remember something... For gamma/gaussian, I feel like I studied the reason for this earlier, but can't find it at the moment. Besides that, the tests, look good. They will fail here, however, because of this limitation. |
|
no, deviance = - 2 (loglike(model) - loglike(saturated model)) saturated model has (It's like a likelihood ratio test statistic against the saturated model, but it's not valid as standard LR test unless there are only a fixed finite number of unique exog combinations. AFAIR) edit it could be that loglike(saturated model) = 0 |
|
Thanks for the comments. I think the issue is that loglikelihood appears to be different for gamma/gaussian between R/stata/statsmodels. Here's some R code: > data <- read.csv("c:/users/pquackenbush/git/statsmodels/statsmodels/datasets/cpunish/cpunish.csv")
> data$INCOME <- data$INCOME / 1000
> model <- glm(EXECUTIONS ~ INCOME + SOUTH, data = data, family = Gamma(link = "log"))
> summary(model)
Call:
glm(formula = EXECUTIONS ~ INCOME + SOUTH, family = Gamma(link = "log"),
data = data)
Deviance Residuals:
Min 1Q Median 3Q Max
-1.5203 -0.7113 -0.4504 -0.0993 2.0244
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.52963 2.63861 -0.201 0.8438
INCOME 0.02915 0.07053 0.413 0.6857
SOUTH 1.61720 0.68678 2.355 0.0337 *
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
(Dispersion parameter for Gamma family taken to be 1.671754)
Null deviance: 25.680 on 16 degrees of freedom
Residual deviance: 15.449 on 14 degrees of freedom
AIC: 81.462
Number of Fisher Scoring iterations: 8
> logLik(model)
'log Lik.' -36.73083 (df=4)And here's the same thing in statsmodels: In [1]: import numpy as np
In [2]: import statsmodels.api as sm
In [3]: import statsmodels.formula.api as smf
In [4]: data = sm.datasets.cpunish.load_pandas().exog
In [5]: data['EXECUTIONS'] = sm.datasets.cpunish.load_pandas().endog
In [6]: data['INCOME'] /= 1000
In [7]: model = smf.glm('EXECUTIONS ~ INCOME + SOUTH', family=sm.families.Gamma
...: (link=sm.families.links.log()), data=data)
In [8]: result = model.fit(atol=0, rtol=1e-25)
In [10]: result.llf
Out[10]: -38.99740362821273
In [12]: result.aic
Out[12]: 83.99480725642546All the (Notice AIC and loglike are different) There's some commentary about this in the test file here as well... As for gaussian, I would guess there are inconsistencies as well, although its not noted. Notice we use a very relaxed match tolerance. For Gamma, R appears to really use |
|
Bookmarking this stata manual for reference, pages 31-32: |
|
OK this is why I've come to get frustrated with R. They have all sorts of weird algebra going on that is rarely (read, never) well documented. R saves an AIC score in its model objects, and loglikelihoods are backed into using the saved AIC score. For gamma, its relatively straightforward once you re-state the gamma pdf in exponential form. (Use 1 / scale for gamma's shape and mu * scale for gamma's scale.) Additionally, So I'm leaning towards thinking loglike is somewhat "special" compared to the other metrics we have. I have some questions on how we proceed then...
I suggest the following...
|
|
Changes Unknown when pulling 295ada3 on thequackdaddy:var_weight into ** on statsmodels:master**. |
295ada3 to
bc69d5e
Compare
|
@thequackdaddy I see you are having fun :) One problem is that open source packages don't have the army of professional documentation writers like Stata, SAS and SPSS. R is ok when there is a full description of the methods and formulas in a book or vignette, but the documentation itself is usually not very complete. Neither is the one of statsmodels. However, in general we stick much closer to text book definitions even giving up some computational shortcuts. For loglike, we always use the full loglikelihood function and not dropping any terms that are constant during optimization. For aic and bic we inherited some inconsistent definitions #1733 Also, after figuring out what other packages are doing, we still have to decide what we want to do. (I expect that it will still take some time before I work through all the details here, and try to figure out how to adjust the cov_type sandwiches.) |
|
Sounds good. I'll eagerly await your review/insights. |
|
You can also skip some of the test for those extra results if it's difficult to work around conflicting definitions or shortcut. E,g. one test for loglike would be that irls which doesn't use the loglike and the scipy optimizers which do use loglike converge to the same parameter estimates. Gaussian can also be compared with WLS. If those work, then it means we have, at least, the main results correct. (I'm commenting without having looked at your code yet.) |
|
another one: |
|
bookmarking this: I tried to use Trying to get my head around pweights/iweights vs the rest. (This PR might be a decent opportunity to include them).
It seems reasonable (to me) to assume that weights should all result in (nearly) the same params, the difference will be |
|
Very good resource. Thanks for sharing that. I went ahead and updated the notebook in the PR with your changes. Let me know if you need anything else. Again, I'm happy (and relatively comfortable) with rebasing this #3543 on master and then rebasing this on that new branch, solving the merge conflicts, and making a new PR to get all of this. Thanks, Josef. |
|
I will go back to it on Sundary. No time until then. I didn't see any new problems, so we just leave llf, deviance and pearson_chi2 as open issue. |
|
(just a note while trying to get an overview of proportions again) |
refactored Gaussian loglike to factor and pull out a 1/2... makes it more succinct.
…py to csv, setupClass -> setup_class, misc smaller changes
Add test for pearson_chi2 Adjust pearson_chi2 for binomial
coerce weights to arrays Test weight formats
I wrote a test to specifically test this. Looks like loglikelihood and deviance are too different in the formula interpretaiton between 1d and 2d for this to work. But |
That's good, estimation based on mean and variance is correct. The difficult decisions are in the "extras". I think we should merge #3543 and this PR fast with the warnings that we already have and then fiddle with some details. It will be easier to tell what's missing if both are merged. (*) I'm still not sure about loglike and llf, it's difficult for me to figure out what we really want when we don't have full QMLE overdispersion support yet. (There are still bugs with loglike in this PR but maybe fewer in combination with #3543, families loglike will have to treat var_weights different from the other weights.) (*) Another testcase where loglike/llf will fail is comparing GLM Gaussian and var_weights and WLS, based on a missing term in this PR in the families.Gaussian.loglike, AFAICS. This might or might not be fixed in 3543. (I am also slow in adjusting to think about Binomial as a proportion endog instead of a count distribution.) |
Hello,
xref #3371
This (should) get
var_weightsto work for GLM. I added a Tweedie usecase against R.I can't seem to get the Poisson with
var_weightstoHC0test that was added (but disabled because of the lack of functionality) to work. The test is here:https://github.com/thequackdaddy/statsmodels/blob/var_weight/statsmodels/genmod/tests/test_glm_weights.py#L142
It fails on the following
assertassert_allclose(res1.bse, corr_fact * res2.bse, atol= 1e-6, rtol=2e-6)Its relatively close... consistently off by a factor of
0.98574...corr_factbrings it much closer... I'm wondering if another adjustment is necessary?Honestly, I don't really understand much about sandwiches (except PBJ, meatball, and bánh mì).
Rest of the test seem to work pretty well.
I'd be happy to have this merged relatively soon, so thanks for the feedback and review!