Skip to content

SUMM: GLM feature wishlist #2804

Open
Open

Description

@thequackdaddy

Hello,

So long story short, I'm an actuary looking to do some GLM modeling in python. I have some experience with R, but am open to new things. I've been watching this project for a bit but have been too lazy/impatient to get some features implemented.

So here's a list of features in the GLM that I'm considering putting some PR's together for. I appreciate any advice you can give about statsmodels philosophy before I write too much and its all rejected. I don't want to waste your time with my PR's, so the more advice the better.

  1. QuasiPoisson. This is a TODO in the GLM family module. I don't think its that hard. My experimenting seems to show that literally copying Poisson is most of the work.
  2. The Pearson residual for Poisson/QuasiBinomial
  3. User-specified weights
  4. Tweedie

I'd appreciate your input before I start this. Note, I'm an actuary, not a programmer, so I'd need some handholding on some things.

Thanks.

Activity

  1. kshedden commented on Feb 8, 2016

    @kshedden
    Contributor

    I've been planning to add weights to the gradient optimization side of GLM. It's fairly easy there because the likelihood, score, and Hessian are all linear combinations of their per-observation analogues. So it's just a matter of including a case weight in those calculations.

    I'm less clear about how weights go into IRLS, but it may just be a matter of using another level of weighting somewhere. I don't know the details of IRLS.

    Also, GEE extends GLM, and GEE has weights. Those weights are currently constrained to be constant within groups, but I want to relax that requirement, just never got around to it. At this point, when I need weights I use GEE with single-case groups.

  2. josef-pkt commented on Feb 8, 2016

    @josef-pkt
    Member

    quick answer, contribution would be welcome and I'm able to hold some hands.

    1. We don't have overdispersed, but we have fit(cov_type='HC0') which is robust to more general heteroscedasticity, variance problems than a standard GLM dispersion factor.
      GLM and all models in linear exponential family, like Logit and Poisson, work very well for Quasi-MLE already. I have lots of examples, also for continuous data in [0,1] for Binomial or continuous nonnegative for Poisson. I'm not planning that we need separate Quasi-XXX families as R.

      Nevertheless, we don't have support for fit(cov_type='quasi') itself. I don't know yet what 'quasi' or dispersed should be called. The necessary work is mainly for cov_params and for quasi likelihood ratio test or deviance ANOVA with dispersion (when needed). The main problem is to check that scale (not equal to 1) is correctly handled, for example for Poisson. Related, I have extra function for over dispersion and dispersion tests but they are not yet included.

    2. I'm not sure what this refers to. We have pearson residuals, and scale. Maybe we need standardization, or it follows from 1.

    3. very high on my wishlist. Is work, but shouldn't be difficult. (frequency/case weights have an obvious interpretation, generic weights are a bit unclear in how extra results should be handled).

    4. Tweedie would be welcome. I looked at it last year and it didn't look so easy (how to compute it and how to come up with a robust way to truncate the infinite sum). It wasn't high enough on my priority to actually try out anything (based on reading SAS or SPSS documentation, IIRC).

    (edit: reformatted to make markup work)

  3. josef-pkt commented on Feb 8, 2016

    @josef-pkt
    Member

    IRLS should mainly require to multiply the WLS weights by the user provided case weights.

  4. josef-pkt commented on Feb 8, 2016

    @josef-pkt
    Member

    as reference: similar issue #2753
    that was my interpretation (as not an R user) of what is missing in GLM.

  5. thequackdaddy commented on Feb 9, 2016

    @thequackdaddy
    MemberAuthor

    @josef-pkt Thanks for your background and history on this.

    I went ahead and tried to tackle my third item first as I see it as the most pressing problem. So I built something that adds weights to the models.

    My first attempt to do this is here:

    https://github.com/thequackdaddy/statsmodels/tree/glm_weights/statsmodels

    I haven't made this an official pull request. If you think that is the best route to go, let me know.

    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:

    • I pass all the genmod tests other than the perfect separation test. The perfect separation test essentially gives perfect separation, but it it fits. I changed the perfect separation test to something really, really obvious and passed the test that way.
    • As far as I can tell, I am only failing statsmodels.base.tests.test_shrink_pickle.TestRemoveDataPickleGLM.test_remove_data_pickle test. 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:

    library(MASS)
    data(Insurance)
    
    Insurance$Group <- factor(Insurance$Group, ordered = FALSE)
    Insurance$Age <- factor(Insurance$Age, ordered = FALSE)
    Insurance$Group <- relevel(Insurance$Group, "1-1.5l")
    Insurance$Age <- relevel(Insurance$Age, "25-29")
    model <- glm('Claims ~ 1 + C(District)  + Group + Age', 
                 data=Insurance, 
                 family=poisson(), 
                 weights = unlist(Insurance['Holders']))
    summary(model)
    model <- glm('Claims ~ 1 + C(District)  + Group + Age', 
                 data=Insurance, 
                 family=gaussian(), 
                 weights = unlist(Insurance['Holders']))
    summary(model)
    Insurance$Claims[Insurance$Claims ==0 ] <- 0.001
    model <- glm('Claims ~ 1 + C(District)  + Group + Age', 
                 data=Insurance, 
                 family=Gamma, 
                 weights = unlist(Insurance['Holders']))
    summary(model)
    

    Python Code:

    import pandas as pd
    from patsy import dmatrices
    import statsmodels.api as sm
    import numpy as np
    
    data_link = 'https://vincentarelbundock.github.io/Rdatasets/csv/MASS/Insurance.csv'
    data = pd.read_csv(data_link, index_col=0)
    y, x = dmatrices('Claims ~ 1 + C(District) + Group + Age', data)
    sm.GLM(endog=y, exog=x, family=sm.families.Poisson(), data_weights=data['Holders']).fit().summary()
    sm.GLM(endog=y, exog=x, family=sm.families.Gaussian(), data_weights=data['Holders']).fit().summary()
    y[y == 0] = 0.001
    sm.GLM(endog=y, exog=x, family=sm.families.Gamma(), data_weights=data['Holders']).fit().summary()
    
  6. kshedden commented on Feb 9, 2016

    @kshedden
    Contributor

    Looks promising to me... I would go ahead and make the PR. Then we can
    preserve the comments and see the test results.

    Next step would be to add some unit tests that check the results with
    non-unit weights.

    I'm not sure, but perhaps we want the interface to be something like
    "weights=1., wgt_type='data', ..." to add more weight types in the future
    (like stata does).

    It would be worth checking for performance regressions when weights=1. In
    some cases, it might be better to short-circuit the multiplication rather
    than multiplying a big matrix by 1 to no effect.

    On Tue, Feb 9, 2016 at 6:39 PM, thequackdaddy [email protected]
    wrote:

    @josef-pkt https://github.com/josef-pkt Thanks for your background and
    history on this.

    I went ahead and tried to tackle #3
    #3 first as I see it as
    the most pressing problem. So I built something that adds weights to the
    models.

    My first attempt to do this is here:

    https://github.com/thequackdaddy/statsmodels/tree/glm_weights/statsmodels

    I haven't made this an official pull request. If you think that is the
    best route to go, let me know.

    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:

    • I pass all the genmod tests other than the perfect separation test.
      The perfect separation test essentially gives perfect separation, but it it
      fits. I changed the perfect separation test to something really, really
      obvious and passed the test that way.
    • As far as I can tell, I am only failing
      statsmodels.base.tests.test_shrink_pickle.TestRemoveDataPickleGLM.test_remove_data_pickle
      test. 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-Code below:
    library(MASS)
    data(Insurance)

    Insurance$Group <- factor(Insurance$Group, ordered = FALSE)
    Insurance$Age <- factor(Insurance$Age, ordered = FALSE)
    Insurance$Group <- relevel(Insurance$Group, "1-1.5l")
    Insurance$Age <- relevel(Insurance$Age, "25-29")
    model <- glm('Claims ~ 1 + C(District) + Group + Age',
    data=Insurance,
    family=poisson(),
    weights = unlist(Insurance['Holders']))
    summary(model)
    model <- glm('Claims ~ 1 + C(District) + Group + Age',
    data=Insurance,
    family=gaussian(),
    weights = unlist(Insurance['Holders']))
    summary(model)
    Insurance$Claims[Insurance$Claims ==0 ] <- 0.001
    model <- glm('Claims ~ 1 + C(District) + Group + Age',
    data=Insurance,
    family=Gamma,
    weights = unlist(Insurance['Holders']))
    summary(model)

    Python Code:
    import pandas as pd
    from patsy import dmatrices
    import statsmodels.api as sm
    import numpy as np

    data_link = 'https://vincentarelbundock.github.io/Rdatasets/csv/MASS/Insurance.csv'
    data = pd.read_csv(data_link, index_col=0)
    y, x = dmatrices('Claims ~ 1 + C(District) + Group + Age', data)
    sm.GLM(endog=y, exog=x, family=sm.families.Poisson(), data_weights=data['Holders']).fit().summary()
    sm.GLM(endog=y, exog=x, family=sm.families.Gaussian(), data_weights=data['Holders']).fit().summary()
    y[y == 0] = 0.001
    sm.GLM(endog=y, exog=x, family=sm.families.Gamma(), data_weights=data['Holders']).fit().summary()

    —
    Reply to this email directly or view it on GitHub
    #2804 (comment)
    .

  7. thequackdaddy commented on Feb 9, 2016

    @thequackdaddy
    MemberAuthor

    Thanks. PR #2805 created.

  8. josef-pkt commented on Feb 9, 2016

    @josef-pkt
    Member

    I'll look into it soon

    about statsmodels.base.tests.test_shrink_pickle.TestRemoveDataPickleGLM.test_remove_data_pickle
    We have a method remove_data (IIRC) that removes all full sized nobs arrays. The use case is if we want to pickle the results and models instances to be used for prediction, where we don't need the underlying data anymore.
    There are some internal kwd dictionaries that contain the names of attributes that can be removed. any new nobs arrays need to be added there, e.g. user defined weights.

    self._data_attr.extend(['weights', 'pinv_wexog', 'mu', 'data_weights',

    I need to check the details, I don't remember exactly what the attributes are named.

    I prefer freq_weights or similar to distinguish them from other weights that are also for the data, e.g. precision/variance/outliers, ...

  9. josef-pkt commented on Feb 9, 2016

    @josef-pkt
    Member

    @kshedden I would rather have different weight keywords than a switch, because the weights are not necessarily exclusive, and it's simpler to provide one keyword than have to add a second one for the switch in interpretation.

  10. thequackdaddy commented on Feb 10, 2016

    @thequackdaddy
    MemberAuthor

    @kshedden @josef-pkt Thanks for the comments. What's the verdict on keywords vs. switch? I would say go with freq_weights for consistency's sake.

  11. kshedden commented on Feb 10, 2016

    @kshedden
    Contributor

    Go with Josef's call on this.

    On Tue, Feb 9, 2016 at 9:04 PM, thequackdaddy [email protected]
    wrote:

    @kshedden https://github.com/kshedden @josef-pkt
    https://github.com/josef-pkt Thanks for the comments. What's the
    verdict on keywords vs. switch? I would say go with freq_weights for
    consistency's sake.

    —
    Reply to this email directly or view it on GitHub
    #2804 (comment)
    .

  12. thequackdaddy commented on Feb 12, 2016

    @thequackdaddy
    MemberAuthor

    Also, I meant to say thanks for Josef's answers for 1 and 2. That functionality is sufficient, I just didn't realize it.

    In general, when modeling a frequency with poisson, we'd use Pearson to calculate the scale parameter. That's available.

    For modeling other things (average loss per insured), we've used deviance to calculate the scale.

    I seem to recall that having a dataset with few non-zeroes and a ton of zeroes (which are common in frequencies) is problematic with deviance. This reminds me, I should add a test case for deviance scale as part of #2805.

    In any event, my wishlist items 1 and 2 are redundant with this functionality.

  13. josef-pkt commented on Feb 12, 2016

    @josef-pkt
    Member

    In general, when modeling a frequency with poisson, we'd use Pearson to calculate the scale parameter. That's available.

    It's available, but it's not yet fully integrated into a cov_type option. Which means the user has to do some work to use it, instead of getting the full results with just specifying cov_type, as is currently available for cov_type='HC0'

    From a few examples that I looked at, I think that HC0 is close to dispersion for the standard errors in large samples (if there is only overdispersion and not other forms of heteroscedasticity). In small samples dispersed Quasi-MLE should be less noisy than HC standard errors because it imposes more assumptions.
    (at some time in the future the better HC like HC3 will become available for GLM, when I figure that out. HC=heteroscedasticity consistent)

  14. josef-pkt commented on Feb 12, 2016

    @josef-pkt
    Member

    @thequackdaddy Given that you are an actuary, and in case you want to do more things in Python

    I was looking at loglinear models, life tables, survival with discrete time periods and similar a few months ago (partially more related to epidemiology than actuarial work). I think a lot can be done on top of GLM or similar models, but we might not cover all use cases, and it would be very useful to have higher level, use case specific tools and interface.

    I don't have a real overview for these applications and I did only eclectic readings, but I think it would be a good area for statsmodels to expand into.

  15. thequackdaddy commented on Feb 17, 2016

    @thequackdaddy
    MemberAuthor

    @josef-pkt I'm not familiar with loglinear models other than what I've briefly read on the internet. My practice is in property and casualty insurance--primarily auto accidents.

    My wishlist now has changed slightly. Next up to bat (after we're done with weights) is Tweedie. Loglinear models aren't something I've seen any actuarial literature on. We tend to be moving towards regularized regression (which I think there is some support in statsmodels for, I just haven't played with it.) as a way of model selection.

    As far as making things high level, I was planning on taking a look at patsy in the not too different future. We typically have lots of variables, and make lots of potential models. Patsy runs a little slower than some super expensive proprietary software. I believe the reason is primarily that patsy doesn't do parallelization. I was planning on looking at that too... but definately after Tweedie.

  16. josef-pkt commented on Feb 17, 2016

    @josef-pkt
    Member

    Tweedie sounds good, it was already requested before. I'm fine with reviewing and helping out when you work on Tweedie.

    Some more application questions:
    What's your data size? Does it fit reasonably well in memory?
    Do you have many categorical variables?

    BTW: glmnet for L1/L2 penalized estimation is supposed to be merged soon.

    One of the problems with using formulas with R or patsy is that it does a lot of repeated conversions if you run many models with small variations. But if there are many categorical variables and interactions, then going without formulas is not very easy.

  17. thequackdaddy commented on Feb 17, 2016

    @thequackdaddy
    MemberAuthor

    Data size: The sky and patience is the limit. Using IRLS, I've squeezed about 2-3 million records and about 50 columns of data into memory and fit a GLM. I think it took around 20-30 minutes to fit. That was a few months ago. The model I think had about 25 parameters. I'm using anaconda 3, on windows. Its an 8 core 1.8 ghz Xeon processor with 32 gb of RAM. I can get more horsepower if needed, but I think there's lower hanging fruit before I go bother IT. For example, I haven't experimented with the scipy optimizers you've added on my production model. My production machine only has statsmodels 0.6.1... so I haven't played with this yet.

    We typically have a mix of categorical and continuous variables. I think that the "perfect" model would have around 80 parameters in it, including interactions. I used to have access to some crazy expensive software that could fit 80 parameters and 5 million records in a few minutes. But I'm thinking most of the features of the $100k software can be built cheaply by me or with a minimum of effort. I'm guessing statsmodels will be slightly slower, but overall I'm pleased with it.

  18. josef-pkt commented on Feb 17, 2016

    @josef-pkt
    Member

    20 minutes sounds very long to me. Do you have the MKL version of the linear algebra libraries?
    I never tried anything large because I only have 16 GB RAM and those are largely occupied already.
    MKL is using multiple processors on my Windows desktop, so I wouldn't expect that there would be much gain in explicitly splitting the job on several processors in the case of larger in memory problems.
    50 to 100 explanatory variables should be easily handled by the current code or batching over observations.
    Profiling would help to understand where the time is spent.
    IRLS hasn't changed much since 0.6.1, so I think master wouldn't be much different.

    Another possibility (I don't know without profiling): It could be that SVD that is used in IRLS by default is more expensive than working directly with the moment matrices X'X given that the number of observation is a bit large and X'X would be a relatively small square matrix. In that case adding another IRLS method would help. newton uses X'X in the Hessian, bfgs would use an approximation to it. Working with X'X is numerically less stable than SVD in near singular cases.

    To add to the wishlist:

    I looked into

    • support for sparse arrays which is useful if there are a large number of categorical factors (or group fixed effects)
    • BigGLM: out of memory storage with batching by observations where columns fit in memory.

    Those two are for better memory usage, and I have draft code for those (not yet for GLM).
    frequency weights are also in this category, when we only have a much smaller number of unique observations than total observations.

    On the penalization side:
    glmnet fit_regularized is penalizing each column of the exog separately and uses coordinate descend which could be implemented in low memory form but might not be very fast.
    We don't have any block coordinate descend yet, block-Lasso, block-L1L2 penalization is in some cases more appropriate when we want to either keep or drop categorical variables, i.e. groups of columns instead of individual columns.

    Another general issue: If the optimization needs many iterations to converge, then spending more time on finding better starting values is worthwhile. For example with large datasets we can estimate first on subsamples. (I don't know yet how subsampling works if we need to watch out that we get all combination of categorical variables so we have full rank exog in the subsample.)

  19. changed the title [-]GLM feature wishlist[/-] [+]SUMM: GLM feature wishlist[/+] on Oct 4, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions