Repository navigation
ENH: GLM Weights - #2805
ENH: GLM Weights#2805thequackdaddy wants to merge 17 commits into
Conversation
|
Looks good overall, There are a few places where I don't see how the changes work, e.g. Binomial, or where it's not clear to me yet how it's supposed to work. In terms of unit tests: e.g. df_resid will need adjustment and it will be used in the scale/Pearson estimates. It will also be used for F/Wald and t-tests when using t and f distribution |
|
Thanks for your review. I'll get cracking on the unit tests. I'm a little confused with your comment "calculated with weights and will full number of observations" are you suggesting that I build a dataset and assign each record a frequency of "n" (with different n's for each record), then create a dataset with n-many records for each observation in the original dataset and every record now with weight 1? I'm not opposed but I seem to recall this might not result in the same deviance for every record. However, the parameter estimated should be the same. |
Yes, I used np.repeat for this here Observation/record specific statistics like residuals will not be the same (without extra weighting), but the aggregate statistics, deviance, llf, ..., and the parameter estimates, standard errors, ..., should be the same in the weighted and the "repeated" version. There are a few Those things will be easier to find when we have a unit test that compares two equivalent models. The As an example |
| """ | ||
| return scale * np.sum(-mu + endog*np.log(mu)-special.gammaln(endog+1)) | ||
| loglike = np.sum(np.log(data_weights) - mu + endog * np.log(mu) - | ||
| special.gammaln(endog+1)) |
There was a problem hiding this comment.
When you change lines like this, you could add spaces around all operator except power ** endog + 1
|
fit_irls also has |
|
Thanks. I think I figured out the pickle thing. Needed to make sure that My TODO is really to write some tests. |
|
Hello, Well as I anticipated, I've run into some roadblocks that I need some better minds for. First, I realized that my math making the log-likelihood functions was completely wrong. So, AIC/Loglikelihood tests and all deviants aren't working in what I've committed. I know that. Next, and most critically, I'm not able to match what R is doing. In fact, R doesn't match itself in some cases on a duplicated dataset vs. the weighted dataset. I was thinking we weren't expecting that. Right now, I'm only really looking at Poisson, Gaussian, and Gamma with their canonical links. Poisson Looks great. Matching R, and duplicated data matching weighted data for the following: Parameters, parameter covariances, loglikihood, deviance, and AIC. Gaussian Things fall apart here. First off, R doesn't match itself when you use duplicated data. Try this code, for example. You can see R gives the same parameter estimates and deviance, but much different covariance, scale, and loglikelihood. My weighted version is unable to match pretty much anything here--but I don't really know what I should be shooting for. (Note, that I realized I can get the same covariances from R if I alter the code to use Gamma Haven't really tested this at all. But I wanted to point out that R has the same loglikelihoods and deviance, but differing scale and covariance parameters between the weighted table and the duplicated table. So if a stronger mind wants to think about this and dream up the correct tests, I would appreciate it. |
|
The df.resid in R is wrong for the interpretation as caseweights. Running your model and looking at the summaries called summ and summbig: So this is either buggy in R, or they use a different definition for the weights. Poisson and Binomial always have scale=1 (except quasi mle case). The target for us is to get the same results in repeat and in freq_weight form, because those are supposed to be the same with the interpretation as frequency weights. Are you getting the same params in both cases, identical to R? If Poisson match, and Gaussian doesn't, then the problem needs to be in the scale calculation, either it doesn't use the weights, or it doesn't use the correct df_resid. You could push your changes and we squash them before merging. (git is good for cleaning up an experimental PR.) |
|
@thequackdaddy To makesure: Do you need frequency weights for your application? i.e. each weight represents a number of observations with identical exog and endog. e.g. about different kinds of weights: |
|
( AFAIU, claims is the aggregate number of claims for all It can still serve as a test case, but AFAICS, the interpretation as frequency weights is not appropriate substantively. |
|
from R's glm documentation so these are weights for the variance and not frequency weights. If I see this correctly, then we could get this through frequency weights if we multiply the weights by nobs / weights.sum() so that total weights is nobs. Stata does this for most weights, even if we don't do it the same way in WLS. So we can still implement frequency weights internally and then adjust in some initialization to get the right interpretation. |
|
I've committed my changes. Have a look. To be clear, what I want to model is the number of insurance claims per year. (The dataset I've given you is total number of claims... I know... I was too lazy to divide). The datasets are generally 1 record per insurance record and a weight of the proportion of a year the policy was in effect. (Policies can frequently only have a portion of year as weight because of mid-term endorsements and cancellations.) So this is a frequency calculation (number of claims per year is the endog) and the proportion of a year is the weight. I had written a long dialogue about this, but then you posted this info about R. Let me read through it again and get back to you. At the least, I'd like to continue working on this out of curiosity. I'm going to be away for a few days soon. So feel free to edit this or write tests. I started writing tests with nose, but then gave up after everything I wrote failed. At the very least, I appreciate your help with this. Its made me understand software development much better. |
|
Write whatever helps to understand the case. We need to have frequency weights for many usecases and to reuse them for other weights. Large parts of other weights and interpretation is still unclear to me, they should all be the same for the parameter estimate, I think. However, differ in the interpretation for inference, as you have seen with R. Given that there is also the possibility of offset and exposure and the possibility to manipulate the variance function, it's not clear to me what different options are appropriate for different use cases. You can also commit failing tests, or put them in a script or a notebook. The latter is what I often do when I'm still in the experimental stage for new methods. For frequency weights, we could just work through the failures and get the details to work correctly. |
|
Josef, Oh my. I've been overthinking and hadn't fully grasped what you are writing. I hadn't grasped the difference between R's weight and SAS's weight until just now. Take this... https://support.sas.com/documentation/cdl/en/statug/63033/HTML/default/viewer.htm#statug_genmod_sect030.htm I feel dumb now. I think I shouldn't be calling the weights in I think I'm seeing the light... Though that could be the beer talking. |
|
Count models like Poisson and Binomial have an inherent additive structure to model the "sample size" of an observation either through total number of trials in Binomial or exposure in Poisson. If the observation is an average, then the variance is inverse proportional to n, the group size. So, the scaling (weight) and exposure depends on the units of endog. If we only have discrete explanatory variables, then we can just combine records that are identical and assign frequency weights, In additive distributions like Binomial and Poisson, those things are identical, except that we have to watch out how we count the number of observations, i.e. rescale weights, nobs and df_resid in a way that is appropriate to the data. IIRC, the SPSS documentation starts out with two weights and just multiplies them together. Related aside: WLS regression model uses weights in the inverse variance interpretation. In terms of unit tests GLM Gaussian with variance weights should be the same as WLS, except for possible small sample corrections. |
|
I went ahead and wrote what I think some appropriate tests would be. Could you look them over to make sure they make sense and you agree? Right now, I'm only testing the frequency weighted small dataset vs. the duplicated one. There's lots of fails, as I expect. If these tests make sense, I'll see if I can get these to equal. Thanks. |
|
Tests look good. I prefer now assert_allclose to assert_almost_equal because it allows better control over the tolerance with atol and rtol which is an advantage if the values vary widely. A tip: I often rename test temporarily so that nose doesn't run them, e.g. Another "how I work": |
|
Ok statistics question. I'm struggling a little with calculating the scale parameter but I think I have a solution. I want to make sure its appropriate. The default scale parameter is the Chi-Squared Statistic (Pearson) divided by the degrees of freedom of the residual. In python: I think the solution is really to take a weighted average of the scale. In The Practioner's Gude (its a common actuarial reference on GLM's) page 19 defines the scale parameter as the following: I'm thinking of implementing that as... So when Thoughts? |
|
looks fine, AFAICS. In WLS we use You could start in your way, and later we can check which intermediate results we want to store for reuse. for example I thought of using |
|
Ok, we're beginning to cook with gas here here. Poisson, Gamma, Gaussian, and Inverse Gaussian are looking great. Able to match params, covariance, loglikelihoods. Looks really promising. But we have a few problems.
if isinstance(self.link, L.Power) and self.link.power == 1:
nobs2 = np.sum(freq_weights, axis=0) / 2.
SSR = np.sum((endog-self.fitted(mu)) ** 2, axis=0)
llf = -np.log(SSR) * nobs2
llf -= (1+np.log(np.pi/nobs2))*nobs2
return llf
else:
return -0.5 * np.sum(freq_weights * ((endog - mu) ** 2 / scale +
np.log(scale / freq_weights) +
np.log(2 * np.pi)))
So tons of progress today! I will be away for the next few days. So, don't expect much progress from me then. Thanks. |
|
Based on the network graph https://github.com/statsmodels/statsmodels/network: Instead of the last merge, you could have just force pushed on this remote branch. (Or, to be safe, push it to a new branch and open a new PR.) Aside: It looks like, based on the commit message, you reverted the previous commit that merged into master. That's not needed because in interactive rebase we can skip commits by just deleting the from the rebase pop up text file. Also by squashing the PR I meant squashing mostly the first few commits. In general I prefer for statsmodels to keep most of the commits separate because most of the time they provide additional information about the changes, discussion and design. Since this branch still has the original commits, it just takes another interactive rebase to remove the last two commits, I think. I will try it out later today. (Right now I have too many checkouts with open work in progress branches.) Aside: I don't remember some of the git commands (syntax and details) because for much of the standard work I just use git gui. |
|
Sounds good. There's only 4 files that have changed, so making a new PR with these changes is easy enough for me. I'll let you try to handle. Again, my apologies. |
|
apropos git: see my recent comment here #2749 (comment) |
|
I rebased locally and trying things out now. I just realized that this is using rdatasets in the unit tests. Running nosetest on a test case takes very long, no idea why. The time it prints is only 0.009s for TestWtdGlmPoisson. |
|
An observation on convergence, see also #2803: I don't know where the differences come from, the optimization should be the same, except for floating point issues. The starting values, first params in history, differ a bit. First deviance differs by a large amount, but "repeated" is smaller. I'm looking at the HC0 case, but that does not differ in the optimization part. |
|
|
|
some timing on the Poisson example, on my computer: loading rdataset is 25s big exog shape is (23359, 10) |
|
Now that you mention it, I was thinking that the A question... there is a variable I don't fully understand how the optimizer is supposed to work, so perhaps there's a deeper bug in there I don't understand. |
|
looks like a good catch. That could then be a reason that newton shows number of iterations equal to 1 if it's already optimized, but then I don't know where the time is spent with |
|
to summ up a bit what I looked at
I haven't tried out yet the code after fixing |
|
switching to maxiter=_max_start_irls with newton leaves the time it takes unchanged at 25 seconds, but now res2.mle_retvals shows 3 iterations. |
|
another comparison correction: maybe fweights and exposure take the same time. The computation time is too small with irls and fluctuates for simple timing with time.time(). |
|
freq_weights are stored as pandas Series, it should get an asarray to have numpy arrays I'm still trying to figure out the robust covariances, and I don't understand exposure anymore. |
|
Gee whiz, Josef. Didn't realize how much bug-checking you were going to be doing on this. I'm impressed. I hope my PR's haven't made you lose any sleep. Godspeed. Let me know if you want me to handle. However, I think you might be working on a different code base and my git skills are awful. I will await your orders. |
|
Because I'm working on top of your branch after rebase, I will push my branch to a new PR most likely later today. Then there will still be work left. I have more work here because there are now a lot of extra things available for GLM. Some we can postpone, but I have to figure it out sooner or later anyway. freq_weights in GLM is the start to add it to other models, and this way you did all the model specific work. |
|
This is now part of #2835. |
Again, I'm a newbie at this, and I haven't documented this much... So I appreciate your forbearance as you work with me.
So a few notes:
statsmodels.base.tests.test_shrink_pickle.TestRemoveDataPickleGLM.test_remove_data_pickletest. I don't understand this test, so I'm not sure what to look for. If you could help me look into that, I'd appreciate it.You can compare the results from R with my results for Gaussian, Gamma, and Poisson using the code below:
R:
Python Code: