Skip to content

ENH: Add var_weights to GLM - #3410

Closed
thequackdaddy wants to merge 14 commits into
statsmodels:masterfrom
thequackdaddy:var_weight
Closed

thequackdaddy wants to merge 14 commits into
statsmodels:masterfrom
thequackdaddy:var_weight

Conversation

@thequackdaddy

Copy link
Copy Markdown
Member

Hello,

xref #3371

This (should) get var_weights to work for GLM. I added a Tweedie usecase against R.

I can't seem to get the Poisson with var_weights to HC0 test 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 assert

assert_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_fact brings 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!

@josef-pkt

Copy link
Copy Markdown
Member

@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.
(Stata uses different correction factors in GLM than in OLS, while we use the same across all models. more precisely: Stata uses some small sample correction factors in OLS but not in GLM. We match sandwich behavior in GLM to the one of OLS.)

@thequackdaddy

Copy link
Copy Markdown
Member Author

Update: There is a bug in the tests... the resids aren't being run (and are wrong).

I'll fix tomorrow.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.02%) to 88.12% when pulling 1a01699 on thequackdaddy:var_weight into 67dcd43 on statsmodels:master.

@thequackdaddy

thequackdaddy commented Feb 3, 2017 •

Copy link
Copy Markdown
Member Author

Turned out to be a much simpler fix than I thought, so I went ahead and did it. Note that the TestGlmPoissonAwHc tests lack resids, so those weren't checked in the first go-around of this.

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.

@josef-pkt

Copy link
Copy Markdown
Member

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,
anscombe would also need the var_weights but I didn't check how easy it is to add them.
resid_response are the raw residuals and should not have the weights.
resid_working are mainly internal for now and might need refactoring (AFAIK, they should match the weights used in IRLS but are currently not used)

@thequackdaddy

Copy link
Copy Markdown
Member Author

Thanks for the insights.

So I'm pretty close then. Right now, I'm including var_weights in resid_deviance and resid_pearson and excluding them from resid_working and resid_response. I need to include them in resid_anscombe, then.

about resids: var_weights differ from the other weights because they go inside the likelihood function while the others all just multiply it.

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 var_weights is associative--you can apply it inside the likelihood/deviance functions or outside.

So my shortcut was just to multiply np.sqrt(var_weights) * resids like I did here and here. I'd assume that I could do to same here for anscombe, if necessary.

However, if you try to calculate the deviance from the respective methods in family, this shortcut won't support that. Not sure if we need that? Adding var_weight as a parameter to a all the resid methods in family should be easy enough... I was trying to be lazy.

@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.)

@josef-pkt

Copy link
Copy Markdown
Member

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

>>> results_poisson_aweight_nonrobust.resids - results_poisson_aweight_hc1.resids
array([[ 0.,  0.,  0.,  0.,  0.,  0.],
....

To avoid having to adjust the tests, you could add at the end of the results module,
the colnames and rownames might not be needed

################  not autogenerated
results_poisson_aweight_hc1.resids = results_poisson_aweight_nonrobust.resids
results_poisson_aweight_hc1.resids_colnames = results_poisson_aweight_nonrobust.resids_colnames
results_poisson_aweight_hc1.resids_rownames = results_poisson_aweight_nonrobust.resids_rownames

related asides:

  • hat or predict_hat in predicted is not available after robust cov_types in Stata (including when pweights are used)
  • the est results are not in the same order when I run the Stata do file again, that's irrelevant for the code but messes up the file comparison between new and old version

@thequackdaddy

Copy link
Copy Markdown
Member Author

Oh duh. I hadn't looked at those, and now it shows an inconsistency.

Based on that, stata does not utilize aweights (or fweights) in any of the resids.

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:

  • Follow R - Include var_weights in resid_deviance, resid_pearson, and presumably resid_anscombe.
  • Follow stata - Don't include var_weights

@thequackdaddy

Copy link
Copy Markdown
Member Author

And to recap: the only real differences I see so far in freq_weights and var_weights is:

  • freq_weights alters the degrees of freedom of the residual (impact on scale mainly)
  • var_weights (presumably) is incorporated in some of the resids.

Other than that, they appear to be functionally the same.

@josef-pkt

Copy link
Copy Markdown
Member

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.
(Whether it's the best for other use cases like producing sandwich covariances or hypothesis testing is a different issue, and we can work around or even change again later.)

Binomial variance function includes n, and so also those resids, which would be a similar normalization as var_weights.

@josef-pkt

Copy link
Copy Markdown
Member

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?
Gamma and Gaussian with log-link might be useful candidates. Probit is more common, but I ran into some precision problems comparing GLM-Binomial-Probit and discrete.Probit in the Hessian that I couldn't figure out. NegativeBinomial defaults to a non-canonical link but uses dispersion.

@thequackdaddy

thequackdaddy commented Feb 3, 2017 •

Copy link
Copy Markdown
Member Author

Based on what I remember from the SPSS documentation, they have a few places where freq_weights and var_weights are handled differently.

Cool. If you stumble across that again, it would be good to spot check that we are doing it the same way.

Also, given the recent discussion, we need unit tests with noncanonical links. Does tweedie cover that enough?

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 mu ** -0.55 / -0.55 but I'm using log(mu)). In my larger datasets (5.4 million records) I'm getting MUCH closer matching (res.mu * model.var_weights).sum() == (model.endog * model.var_weights).sum() within 1%. Still off by a tad... not sure I really care (or should care?). The hessian is positive definite.

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.

@thequackdaddy

Copy link
Copy Markdown
Member Author

I am struggling to remember something...

For gamma/gaussian, loglike != -2 * deviance, while R sort of assumes that it does.

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.

@josef-pkt

josef-pkt commented Feb 7, 2017 •

Copy link
Copy Markdown
Member

no, deviance = - 2 (loglike(model) - loglike(saturated model))
I'm not sure I remember the sign correctly
I just used this in a unit test for fixing poisson deviance

saturated model has mu = endog (with bounds handling)

(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

@thequackdaddy

thequackdaddy commented Feb 7, 2017 •

Copy link
Copy Markdown
Member Author

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.99480725642546

All the param, cov_params, and resids and deviance appear to be the same between each.

(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 dgamma(endog, sum(var_weight) / deviance, scale=mu * deviance/ sum(var_weight), log=TRUE) * var_weight. I'm thinking I'll have to do some algebra to incorporate this into our loglike function.

@thequackdaddy

Copy link
Copy Markdown
Member Author

@thequackdaddy

Copy link
Copy Markdown
Member Author

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, scale is calculated as deviance / nobs for these 2 families, while statsmodels (and presumably stata) use deviance / df_resid. For gaussian, they've identified a bunch of constants in the summation and simply removed them and multiplied by the number of records (nobs) presumably to make the computation cheaper. Seems a little overkill because it makes the readability really poor. In my mind, it would be far, far easier to just use dgamma, dNormal etc. as that is far more readable (in my mind) and shouldn't be a much more expensive computation.

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...

  • stata uses a very simple formula (who's documentation I cannot find) for loglike weights. Essentially, its weights = freq_weights when freq_weights are specified and weights = nobs * var_weights / sum(var_weights) when var_weights are specified. Then just multiply these values by the basic loglike function. The stata manual is very helpful for this. Note that based on the language, it sounds like stata only supports freq_weights or var_weights, and not both.
  • R doesn't really have support for freq_weights... and the designers spent a good amount of time re-writing and simplifying their aid (and hence, loglike) functions to minimize calculations.
  • For both tools, it appears deviance is calculated the same and is simply sum(iweights * resid_dev) and there are no noticeable (as far as I see) differences between them

I suggest the following...

  • For loglike, follow stata more than R.
  • I think stata limits to either var_weights or freq_weights using their formula. I'm wondering if we could get the same effect with the formula sum(freq_weights) * iweights / sum(iweights) (recall iweights = freq_weights * var_weights

@coveralls

coveralls commented Feb 9, 2017 •

Copy link
Copy Markdown

Coverage Status

Changes Unknown when pulling 295ada3 on thequackdaddy:var_weight into ** on statsmodels:master**.

@coveralls

coveralls commented Feb 9, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.03%) to 90.185% when pulling bc69d5e on thequackdaddy:var_weight into dcff8e6 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member

@thequackdaddy I see you are having fun :)
It reminds me of what Skipper was complaining about during the initial rewrite of GLM and comparison to R and other packages.

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
SPSS manual has explicit formulas for both the full loglike and the loglike used during optimization which drops the terms that are irrelevant when estimating the mean function parameters.

Also, after figuring out what other packages are doing, we still have to decide what we want to do.
E.g. Stata uses the normalized weights for most things, which we started to avoid for variance weights.
#1170

(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.)

@thequackdaddy

Copy link
Copy Markdown
Member Author

Sounds good. I'll eagerly await your review/insights.

@josef-pkt

Copy link
Copy Markdown
Member

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.)

@josef-pkt

Copy link
Copy Markdown
Member

another one:
information criteria like aic and bic across different definitions/shortcuts should only differ in an additive constant, so ranking is preserved (the correction term is the same for different numbers of explanatory variables).
One extra possible variation is whether aic, ... are normalized by nobs or not, i.e. differ by a factor that is independent of the number of explanatory variables.
(In general, we default to full llf in the information criteria, but there are variations across packages on dropping items that are irrelevant for ranking alternative models within one model class with the same endog.)

@thequackdaddy

thequackdaddy commented Feb 9, 2017 •

Copy link
Copy Markdown
Member Author

bookmarking this:

http://www.cpc.unc.edu/research/tools/data_analysis/statatutorial/sample_surveys/weight_syntax

I tried to use fit(method='bfgs') to check the loglikelihoods, and it flat didn't work outside of Poisson. Need to re-think some of this. I think I need to understand how the loglikelihood would change with different weight assumptions. I don't understand them all, to be frank.

Trying to get my head around pweights/iweights vs the rest. (This PR might be a decent opportunity to include them).

  • pweights - I'm not at all familiar with survey data but from what I can tell if I have a dataset with 10 records (observations) and these observations represent 10 different groups/samples, pweights would be used to assign higher credibility to the groups. I'm not sure of the mechanics here.
  • fweights - Frequency weights. How many times the same observations (endog/exog inclusive) occurs in data. The mechanics here are that the scale parameter will be updating (assuming that freq_weights are integers >= 1, I would expect it to increase df_resid and lower scale. This will be used to calculate the bse and cov_params.
  • aweights - Analytic (variance) weights. Used for modeling on mean (and rate?) data. A larger weight implies that increased sampling accuracy. I presume the difference here is that a larger pweight might really mean unchanged (or lower?) sampling accuracy because a larger pweight means that the observation reflects a larger, potentially more heterogeneous group. I had thought they work by scaling loglikelihoods, but its not just var_weight * loglike or else stata is wrong (doubtful).
  • iweights - user-defined, so I think they can do whatever you want them to do. Not sure we need to include them?

It seems reasonable (to me) to assume that weights should all result in (nearly) the same params, the difference will be scale, cov_params, resids and the descendants thereof. (Not totally sure about pweights.)

@thequackdaddy

Copy link
Copy Markdown
Member Author

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.

@josef-pkt

Copy link
Copy Markdown
Member

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.
I don't remember the details and references for example for #3101 well enough to figure out now what the proper behavior for "weird" cases should be.

@coveralls

coveralls commented Apr 21, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.05%) to 90.346% when pulling 806a999 on thequackdaddy:var_weight into a218660 on statsmodels:master.

@coveralls

coveralls commented May 14, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.05%) to 90.46% when pulling 2a90a8f on thequackdaddy:var_weight into 86496a3 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member

(just a note while trying to get an overview of proportions again)
GLM binomial with counts (2-D endog) converts internally to proportion, and fittedvalues are proportions.
So there should be an equivalence: using endog=proportion plus var_weights should be equivalent to 2-dim endog counts in the way glm binomial is implemented.
And most likely 2-dim endog with proportions of (success, fail) plus var_weights for number of trials is also equivalent. If it works this would test that internal binomial weights and var_weights are correctly combined.
(I'm not sure we already looked at those cases.)

@thequackdaddy

Copy link
Copy Markdown
Member Author

(just a note while trying to get an overview of proportions again)
GLM binomial with counts (2-D endog) converts internally to proportion, and fittedvalues are proportions.
So there should be an equivalence: using endog=proportion plus var_weights should be equivalent to 2-dim endog counts in the way glm binomial is implemented.
And most likely 2-dim endog with proportions of (success, fail) plus var_weights for number of trials is also equivalent. If it works this would test that internal binomial weights and var_weights are correctly combined.
(I'm not sure we already looked at those cases.)

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 params and bse seem to match.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.07%) to 90.493% when pulling 19cf3a4 on thequackdaddy:var_weight into aed3187 on statsmodels:master.

@josef-pkt

josef-pkt commented May 23, 2017 •

Copy link
Copy Markdown
Member

But params and bse seem to match.

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.)

@coveralls

coveralls commented May 23, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.05%) to 90.476% when pulling 19cf3a4 on thequackdaddy:var_weight into aed3187 on statsmodels:master.

@josef-pkt josef-pkt closed this in cc3fd16 Jun 20, 2017
@thequackdaddy
thequackdaddy deleted the var_weight branch June 24, 2017 15:24
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