You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
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.
The Pearson residual for Poisson/QuasiBinomial
User-specified weights
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.
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.
quick answer, contribution would be welcome and I'm able to hold some hands.
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.
I'm not sure what this refers to. We have pearson residuals, and scale. Maybe we need standardization, or it follows from 1.
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).
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).
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:
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:
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:
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.
@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.
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.
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)
@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.
@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.
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.
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.
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.)
Activity
kshedden commentedon Feb 8, 2016
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.
josef-pkt commentedon Feb 8, 2016
quick answer, contribution would be welcome and I'm able to hold some hands.
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 thatscale(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.I'm not sure what this refers to. We have pearson residuals, and scale. Maybe we need standardization, or it follows from 1.
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).
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)
josef-pkt commentedon Feb 8, 2016
IRLS should mainly require to multiply the WLS weights by the user provided case weights.
josef-pkt commentedon Feb 8, 2016
as reference: similar issue #2753
that was my interpretation (as not an R user) of what is missing in GLM.
thequackdaddy commentedon Feb 9, 2016
@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:
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:
kshedden commentedon Feb 9, 2016
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:
thequackdaddy commentedon Feb 9, 2016
Thanks. PR #2805 created.
josef-pkt commentedon Feb 9, 2016
I'll look into it soon
about
statsmodels.base.tests.test_shrink_pickle.TestRemoveDataPickleGLM.test_remove_data_pickleWe 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_weightsor similar to distinguish them from other weights that are also for the data, e.g. precision/variance/outliers, ...josef-pkt commentedon Feb 9, 2016
@kshedden I would rather have different
weightkeywords 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.thequackdaddy commentedon Feb 10, 2016
@kshedden @josef-pkt Thanks for the comments. What's the verdict on keywords vs. switch? I would say go with
freq_weightsfor consistency's sake.kshedden commentedon Feb 10, 2016
Go with Josef's call on this.
On Tue, Feb 9, 2016 at 9:04 PM, thequackdaddy [email protected]
wrote:
thequackdaddy commentedon Feb 12, 2016
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.
josef-pkt commentedon Feb 12, 2016
It's available, but it's not yet fully integrated into a
cov_typeoption. 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 forcov_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)
josef-pkt commentedon Feb 12, 2016
@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
eclecticreadings, but I think it would be a good area for statsmodels to expand into.thequackdaddy commentedon Feb 17, 2016
@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.
josef-pkt commentedon Feb 17, 2016
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.
thequackdaddy commentedon Feb 17, 2016
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.
josef-pkt commentedon Feb 17, 2016
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.
newtonuses X'X in the Hessian,bfgswould 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
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_regularizedis 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.)
[-]GLM feature wishlist[/-][+]SUMM: GLM feature wishlist[/+]