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
Tweedie is also in the linear exponential family and is use, for example, to model claim amounts.
Tweedie is a special case of compound Poisson distribution, that has the pdf/likelihood specified as infinite sum. The base distribution is Gamma in the case of Tweedie with shape parameter constraint to the interval [1, 2](check again?)
GLM
However, to estimate the parameters in GLM with IRLS (or GMM) all we need are the mean and variance function which are simple.
So to get the parameter estimates and the Wald inference we don't need the loglike or deviance and the associated infinite sum. However, we need it to estimate the shape parameter, if we want MLE. (I don't remember: the shape parameter is related to the dispersion and can be directly calculated from it as in the Negative Binomial case without going through the likelihood function.)
compound Poisson distribution
Because Tweedie is just a special case, we can also use the generic tools for compound Poisson distribution to calculate the probabilities or loglike, e.g. use fft of the characteristic function.
(Possible problem for fft is that we need to run the fft for each observation which can be costly in large samples.)
If we can truncate the infinite sum after a few terms in the estimation, then the loglike could be a short fully vectorized loop.
References
.... from actuarial literature
I just saw this by chance but didn't read it:
Xacur, Oscar Alberto Quijano, and José Garrido. 2015. “Generalised Linear Models for Aggregate Claims: To Tweedie or Not?” European Actuarial Journal 5 (1): 181–202. doi:10.1007/s13385-015-0108-5.
@thequackdaddy What results do you need in a Tweedie GLM model?
AFAICS, we can get the parameter and cov_params estimates (conditional on the shape parameter) with a few hours of work plus time to write unit tests.
Deviance and loglikelihood will require more work.
@josef-pkt Yes, I'd need a way to estimate the shape parameter.
With that said, I've seen plenty of people that just assume that the shape is 1.5, and calculate params/cov_params from that. Its a better approach than nothing...
My knowledge of Tweedie's formulation is honestly quite limited... Most of what I've read/worked with is Poisson and Gamma... So there's some education of underlying statistics that necessary before I go off and program something. There's a few R Vignettes that have proven very helpful to me in the past.
I'm pretty sure we get an easy estimate of the shape parameter even though it won't be the full maximum likelihood estimate.
What I mainly thought about is whether you just need coefficients with cov_params and mean prediction, or whether you also need the distribution itself, or likelihood ratio tests, deviance measures and similar. The former we can get without ever constructing the full likelihood and similar truncated infinite sums.
You're instincts are right then. If we can get an easy estimate of the shape parameter, then get params/cov_params, thats about 98%.
Eventually, I'd like to use AIC (or Chi-Sq) to compare models. I presume that woudln't work for the time being. But if we can build off of this to get there, that's encouraging. I haven't actually looked at AIC yet from statsmodels, so I've not thought about it much.
Dunn is author of R package Tweedie and has several papers https://cran.r-project.org/web/packages/tweedie
Dunn, Peter K., and Gordon K. Smyth. 2005. “Series Evaluation of Tweedie Exponential Dispersion Model Densities.” Statistics and Computing 15 (4): 267–80. doi:10.1007/s11222-005-4070-y.
———. 2007. “Evaluation of Tweedie Exponential Dispersion Model Densities by Fourier Inversion.” Statistics and Computing 18 (1): 73–86. doi:10.1007/s11222-007-9039-6.
Hasan, Md Masud, and Peter K. Dunn. 2011. “Two Tweedie Distributions That Are near-Optimal for Modelling Monthly Rainfall in Australia.” International Journal of Climatology 31 (9): 1389–97. doi:10.1002/joc.2162.
So I spent some time this morning re-educating myself on some of the underlying math here. I'm honestly still a little fuzzy on some of the details but this is what I'm thinking.
For a random variable Y which follows an EDM (exponential dispersion model) family, we can write the density in one of 2 ways...
where mu = E[Y] = kappa'(theta) is the mean, and scale > 0 is the dispersion parameter, d(y, u) is the unit deviance, theta is the canonical parameter, and kappa(theta) is the cumulant function. (Dunn and Smith). The cumulants of a random variable are defined via the cumulant-generating function K(t), which is the natural logarithm of the moment-generating function. (Wikipedia).
(quasi-?)Deviance for a Tweedie function appears to be defined as:
Special cases when p=1 -> dev = mu - endog * (1 + np.log(mu / endog1))
and p = 2 -> dev = -1 + (endog / mu) + np.log(mu / endog1)
(Limit of deviance function as p -> 1 and 2, respectively.)
Dunn and Smith present 2 ways of evaluating the density.
Method 1.) Inversion of cumulant generating function. This uses Fourier inversion to invert the cgf.
Method 2, Uses series (I think via Taylor Expansion?) summing only those terms in the series that contribute significantly to the sum. This is done by treating the idnex of the indinite summation as continuous and then using Stirling's approximation. The text references Jorgensens 1997 work, which I can't find.
This table below shows which method works best under what constraints. Additionally, The chart visually illustrates the density plots.
As an alternative to these methods, Dunn and Smith also present a "saddlepoint approximation" (not sure what the saddlepoint refers to? Maybe the maximum likelihood at each p? Seems more like a ridge to me...)
Looking at this extended quasilikihood formula, I was actually thinking that programming it would be relatively straightforward. Part of me wonders if I simply calculated the extended quasi liklihood at maybe 5-10 different p's, would that be sufficient? Something like a super-simple scikit-learn gridsearch? (There is a commercial product that I worked with in the past that I'm thinking actually did something like that. The user would provide an initial p guess, and it would fit the model multiple times with different p's and stop when it found one that met some tolerance. I presume it was just that the likelihood to the left and to the right were both lower. Not sure of the details beyond that.)
The plan is to add Tweedie only for 1< p < 2, is it?
Did you see anything about local optima with respect to estimating p also. Given that maximizing with respect to p is only a one-dimensional problem, and if there are no local minima, then the scipy optimizers should work well.
I guess we need to add a specific fit method that estimates p on top of the irls estimate.
Did you see any recommendation for a moment estimator for p?
Maybe... After your comment I had another look at saddle point approximation... It appears this extended quasi likelihood is based off of the same simplification... At least the formulas look quite similar (though there's an extra 1/2 I think in the quasi... My Math could be wrong.)
For saddle point approximation Dunn and Smith essentially suggest finding some roots using chebychev polynomials and then interpolating.
They don't say anything there being a local maxima/minima... Although maybe if they suggest there's a saddle point, that should be one.
That is really making think that's what the commercial software did... It got a very precise evaluation of p relatively quickly, but then you'd have to refit the model and get new Params. After iterating between finding the best p and finding fitting the Params a few times (2-3 times maybe?) you got a pretty good fit.
saddle point approximation is just a specific form of asymptotic ( distributional) expansion.
It's used in some higher order approximation of the distribution of test statistics or estimators, but I never managed to figure it out (and the applications didn't look high priority and useful enough to try harder). AFAIK, almost everything has to be derived case by case, so it's not very useful as generic approach.
(Here, the x-axis are the p values from 1.05 to 1.95 (inclusive) stepping by 5.) This also makes me think, that given the data that I think I'll have, I'm fairly sure that I can get a p-curve to look something like that.
Not so good news:
The algorithm is a little slow, especially on lots and lots of data--and won't even run for me at 2 million observations. (locked up my laptop twice trying to run it...)
A very brief sketch of the algorithm...
First, find the maximum and minimum index (denoted j) for which the W function is within floating point accuracy of the maximum of the W. (Note that this probably should be calculated on series-by-series basis. I'm (sadly) calculating it all together.)
Calculate the values of W at each of these indices.
This becomes the a( . ) in the GLM PDF formula. The y * theta - kappa(theta) are calculated, logs are taken and then added together, yielding a density.
So the problems are quite obvious...
When you have lots of different values (only y and mu should really change), the number of indices needed to calculate grow rapidly. As I'm basically calculating the index using the minimum and maximum of all these indices, and these indices can sometimes be very wide, there's a lot of waste. (Potential improvement, calculate index for each observation, not all at once.) This process is embarassingly parallel... Perhaps parallization is in order?
There's a few piecewise functions in the algorithm. The most troubling to me is the one at the beginning which says if y == 0, then use an easy formula based off of the canonical link and if y > 0, then use the infinite sum. When I have 0's in the data, it seems that they must go through the whole infinite sum process--and the calculation is quite horrible. I'm wondering is there a better way to set this up so when y == 0, we'll not try to do anything in the infite sum logic? np.where (which is what I've been using) still calls the function with the zeros and it just is burning CPU cycles as far as I can see.
Outrageous though... is this is job for cython? I don't know cython, but it doesn't look that horrible. I understand you can also release the GIL so this embarrassingly parallel part could actually be done in parallel. I need to investigate this more, however.
about cython and speeding up:
most similar functions, that for example need to calculate an infinite sum by truncation with limiting the approximation error, are in scipy special in either Fortran or C.
However, I think before trying out cython, we should figure out what an efficient implementation for our usecase would look like, since we only need it for the specific regression case.
FFT is an alternative, but I have looked at the fft inversion of the characteristic function for compound-Poisson only for the simple distribution case, i.e. evaluate the pdf or cdf at a single parameter for many points in the support at the same time. The task is different in the regression case because we need only a single point on the pdf but for many distribution parameters. My guess is that the fft inversion won't be very efficient for this case.
To your gist, based on a very brief look, IIUC:
In similar situations in scipy stats we are vectorizing the sum to go by large chunks instead of incrementing by 1.
Full loops where we have to iterate many million times are slow in Python, but if we can vectorize it in an appropriate way and shorten the number of iterations in the loop, then a numpy based solution is often reasonably fast. I haven't checked yet how your loops are vectorized.
What are the large endog values in your actual dataset?
The endog values are claim amounts per year... so... Loss Payments / Years Policy Active.
Some policies can be really short... (only in force for a month or so). So the denominator can be real small there. Or the policy could be in force for an entire year. Maybe the largest endog would be $10 million? (In the dataset I'm looking it, its only $750k, but it could easily be higher if you have a big claim on a policy that was quickly cancelled...)
At least this time I'm planning to take notes for the 10 or 20 papers that I'm skimming right now.
Partially independent a full tweedie implementation:
Some of the older actuarial articles estimate tweedie through the compound Poisson representation, some when the number of claims (count) is also observed.
I think going through the compound Poisson representation might be a computationally a competitive way for your special case of at most a few claims per observation, i.e. compounding at most 0 to 10 claims in the compounding distribution, which is different from the large scale aggregation case with many claims per record where direct compounding gets expensive.
Ok, this time I found the right reference with full theoretical background and derivation of the bias correction for estimating the tweedie variance parameters.
It's essentially as I stated, but there is an extra weight term in the moment condition for p
Jørgensen, Bent, Clarice G. B. Demétrio, Erik Kristensen, Gary T. Banta, Hans Christian Petersen, and Matthieu Delefosse. 2011. “Bias-Corrected Pearson Estimating Functions for Taylor’s Power Law Applied to Benthic Macrofauna Data.” Statistics & Probability Letters, Statistics in Biological and Medical Sciences, 81 (7): 749–58. doi:10.1016/j.spl.2011.01.005.
I'm back. Finally. Sorry for being away for so long. Things got busy at work.
I found the paper and have read it. Full disclosure, I'm not a PhD and have never been good at reading academic papers. So a lot of this discussion is way over my head. With that said, I think I understand the gist of what we're supposed to do.. I found a copy here.
The strategy appears to be to set up a so-called chaser algorithm that iteratively solves these 2 equations.
This seems like pretty major rewrite of the _fit_irls function, so I'd prefer to not go fully down that route, but rather meet use _fit_irls to calculate Beta/params (formula 4.1), then run an algorithm to solve equation 4.2 Then use the updated values from 4.2 to re-fit _fit_irls again until converged.
(gamma?) (I think that squiggly line t-looking thing is a lower case gamma) is a variable that can represent either the shape or scale parameter in the Tweedie function. In fact, the paper treats it like a matrix so it can actually be both. The capital S with the u over it to the -1 is a "sensitivity matrix".
The S_gamma term is...
T_gamma is a little confusing for me. This is called a correction term.
Fortunately, 3 of the 4 terms are 0.
So only the term with b (the Tweedie shape parameter) appears to have a non-zero value. I think this means that the scale parameter will be similar between this estimate at the standard pearson Tweedie estimate.
I'm a little in the dark exactly what the "x_i" means here. The most clear explanation I can get from the paper is...
I think this means that I need to get the calculate the value of derivative of Tweedie's PDF function. I seem to recall that we have the derivatives of the link function ready to go, but not necessarily for Tweedie. I'm a little in the dark exactly what this means. Any ideas?
(Note: 3 years ago a lot of this was over my head in spite of a PhD in economics, with background in econometrics, but not in statistics as emphasised in statistics)
my latest issue related to this is #2889
I did some background reading of the statistics literature in the mean time.
I think we don't want to rewrite fit_irls or other fitting methods in GLM. The easiest way to get started is to have a separate estimator that alternates between the two estimation parts, and where the main result is the GLM instance for the mean estimation for given, estimated tweedie dispersion parameters.
(We do something similar in the normal linear model when we estimate a variance function depending on explanatory variables, and we don't want to use the full normal MLE.)
Because tweedie has two dispersion/variance parameters we will have to do nonlinear optimization or rootfinding for those. The direct iteration is one possibility, or we can use a scipy optimizer also in the variance/dispersion step.
Double exponential models is structurally a bit similar, where the regular GLM is combined with a second dispersion GLM which is often based on the Gamma family.
(I was reading things also with respect to other generalization of GLM that have some similarities to what we need for Tweedie.)
.
I read the paper again. I would start without the bias correction for the power parameter b in the paper.
that is all we need to do is substitute exp(lambda) from equation (3.8) into (3.9) and solve equation (3.9) setting it equal to zero.
Since it's just an equality in one parameter, a scipy rootfinder like brentq or similar might work.
This can then be used to alternate with a GLM Tweedie fit for the beta parameters (for mean function) and this pearson estimation for the variance/dispersion parameters.
Given your sample size the bias correction might not have a large effect.
Adding the bias correction and solve equation (3.12) equal to zero instead doesn't look very complicated, but it requires the J_{\beta}^{-1} matrix.
newton scoring in equ. (4.2) looks also feasible without bias correction, but including bias correction needs again more difficult terms.
I would skip trying to implement the covariance of the variance/dispersion parameters in section 5, at least initially.
They mention that the bias corrected version is equal to the GLM gamma version for the dispersion/variance submodel. This is similar to double exponential model. But I'm not sure that will work out of the box, because we need to estimate the power parameter, and there might be some extra weights involved. I haven't looked at the Perry article that they reference for this.
Godambe matrix would essentially just be cov_type="HC0" if we get a model for this, but I haven't checked yet whether that will be easy or not.
About notation: They use clustered data in the application.
AFAICS (a guess where it's better to code first, and only read the small print if there are problems) we can ignore the j index and the n_i and just take i as referring to an observation and x_i as the exogs of observation i. Then we just have the standard setup, where mu_i will be the predicted mean (fittedvalues), and (y_i - mu_i) in equ. 3.8 and 3.9 are just the residuals from the mean GLM-Tweedie results.
The p-values "feel" reasonable... but they seem a little low... I'm not that familiar with the R tweedie package, so it would be nice to see if the scale and power I get match what R has. Not really sure where to start with that, however.
I agree though, that this is easily the fastest derivation of p I've come across.
a quick check (I haven't looked at everything yet)
you have a minus instead of a times in your psi_p function (elambda - mu ** power) in denominator should be (elambda * mu ** power)
One check if the variance function captures the dispersion approximately well is to compare the parameter standard errors with the robust standard errors, i.e. add `cov_type='HC0' to fit.
Another check for roughly the size is to just estimate the logged model: OLS with log(resid**2) ~ log(mu)), IIRC, which will be biased but should still give roughly the same numbers for explambda and power.
The tweedie package should have some examples, I also saw examples in several places in actuarial slides of talks or similar.
About standard errors for the variance power parameter:
If I see and remember this correctly (?), then johansen takes the effect of estimating the mean parameter into account, and there is an asymmetry, we can ignore the estimation of the variance parameters for the mean calculation, but we can or should not ignore the fact that the mean parameters are estimated when calculating cov_params for the variance parameters.
(I need to reread johansen and knudsen when we want to calculate the bse for the variance parameters.)
In double exponential models this is not necessary, because the orthogonality, independence goes both ways.
brentq is a bit fragile, I sometimes get exceptions ValueError: f(a) and f(b) must have different signs
In other cases I'm using a backup for the case when f(a) and f(b) don't have different signs.
Also the lower bound a might have to be larger. There were some problems reported in one of the articles, but I don't remember for which estimator of the power parameter.
Sorry for asking this newbie question, I am very new to statsmodels and just found this.
Does this mean that a Tweedie GLM is possible in an upcoming version? I guess that must be v0.8 since I found nothing in the 0.7 docs.
Yes, it's available in the 0.8rc1.
but see #3079 for possible problems and enhancements for it.
(the default tweedie power parameter estimation is computationally not very robust, and the interaction with exposure has to be checked again for some of the results.)
I wanted to point out that I (think) I've managed to sort out a way to use the series evaluation method outlined in this paper:
Dunn, Peter K. and Smyth, Gordon K. 2004.
Series evaluation of Tweedie exponential dispersion model densities.
29 September 2004
I then used the minimize_scalar function from scipy.optimize to optimize the variance power for tweedie likelihood.
On my datasets, this works pretty well and I'd say its robust. All the hard math is done is numpy and so its relatively fast. You can find an optimal p in 10-20 seconds on a dataset with the following characteristics:
nobs = 5378317
p_opt = 1.487
Around 2% of the observations have endog > 0
Activity
josef-pkt commentedon Mar 16, 2016
@thequackdaddy What results do you need in a Tweedie GLM model?
AFAICS, we can get the parameter and cov_params estimates (conditional on the shape parameter) with a few hours of work plus time to write unit tests.
Deviance and loglikelihood will require more work.
thequackdaddy commentedon Mar 16, 2016
@josef-pkt Yes, I'd need a way to estimate the shape parameter.
With that said, I've seen plenty of people that just assume that the shape is 1.5, and calculate params/cov_params from that. Its a better approach than nothing...
My knowledge of Tweedie's formulation is honestly quite limited... Most of what I've read/worked with is Poisson and Gamma... So there's some education of underlying statistics that necessary before I go off and program something. There's a few R Vignettes that have proven very helpful to me in the past.
josef-pkt commentedon Mar 16, 2016
I'm pretty sure we get an easy estimate of the shape parameter even though it won't be the full maximum likelihood estimate.
What I mainly thought about is whether you just need coefficients with cov_params and mean prediction, or whether you also need the distribution itself, or likelihood ratio tests, deviance measures and similar. The former we can get without ever constructing the full likelihood and similar truncated infinite sums.
thequackdaddy commentedon Mar 16, 2016
Ahh... I see.
You're instincts are right then. If we can get an easy estimate of the shape parameter, then get params/cov_params, thats about 98%.
Eventually, I'd like to use AIC (or Chi-Sq) to compare models. I presume that woudln't work for the time being. But if we can build off of this to get there, that's encouraging. I haven't actually looked at AIC yet from statsmodels, so I've not thought about it much.
josef-pkt commentedon Mar 17, 2016
https://www.casact.org/education/annual/2009/handouts/c25-meyers.pdf slides overview with comments on calculation
http://www.leg.ufpr.br/lib/exe/fetch.php/publications:papercompanions:artigo.pdf using estimating equations
Dunn is author of R package Tweedie and has several papers
https://cran.r-project.org/web/packages/tweedie
Dunn, Peter K., and Gordon K. Smyth. 2005. “Series Evaluation of Tweedie Exponential Dispersion Model Densities.” Statistics and Computing 15 (4): 267–80. doi:10.1007/s11222-005-4070-y.
———. 2007. “Evaluation of Tweedie Exponential Dispersion Model Densities by Fourier Inversion.” Statistics and Computing 18 (1): 73–86. doi:10.1007/s11222-007-9039-6.
Hasan, Md Masud, and Peter K. Dunn. 2011. “Two Tweedie Distributions That Are near-Optimal for Modelling Monthly Rainfall in Australia.” International Journal of Climatology 31 (9): 1389–97. doi:10.1002/joc.2162.
thequackdaddy commentedon Mar 30, 2016
Note to self and others interested:
So I spent some time this morning re-educating myself on some of the underlying math here. I'm honestly still a little fuzzy on some of the details but this is what I'm thinking.
For a random variable Y which follows an EDM (exponential dispersion model) family, we can write the density in one of 2 ways...
where mu = E[Y] = kappa'(theta) is the mean, and scale > 0 is the dispersion parameter, d(y, u) is the unit deviance, theta is the canonical parameter, and kappa(theta) is the cumulant function. (Dunn and Smith). The cumulants of a random variable are defined via the cumulant-generating function K(t), which is the natural logarithm of the moment-generating function. (Wikipedia).
(quasi-?)Deviance for a Tweedie function appears to be defined as:
Special cases when p=1 -> dev = mu - endog * (1 + np.log(mu / endog1))
and p = 2 -> dev = -1 + (endog / mu) + np.log(mu / endog1)
(Limit of deviance function as p -> 1 and 2, respectively.)
Dunn and Smith present 2 ways of evaluating the density.
Method 1.) Inversion of cumulant generating function. This uses Fourier inversion to invert the cgf.
Method 2, Uses series (I think via Taylor Expansion?) summing only those terms in the series that contribute significantly to the sum. This is done by treating the idnex of the indinite summation as continuous and then using Stirling's approximation. The text references Jorgensens 1997 work, which I can't find.
This table below shows which method works best under what constraints. Additionally, The chart visually illustrates the density plots.
As an alternative to these methods, Dunn and Smith also present a "saddlepoint approximation" (not sure what the saddlepoint refers to? Maybe the maximum likelihood at each p? Seems more like a ridge to me...)
http://www.statsci.org/smyth/pubs/iwsm01a.pdf
I've also stumbled across some formulas what I think has been described as an extended-"quasi"-likilihood of the following:
https://lstat.kuleuven.be/research/seminars_events/files/3afmd/Kaas.PDF
The SAS documentation have the same formula.
It is unclear to me how SAS first maximizes the extended quasi-liklihood first, and then the the approximate likilhood.
http://www.leg.ufpr.br/lib/exe/fetch.php/publications:papercompanions:artigo.pdf
Looking at this extended quasilikihood formula, I was actually thinking that programming it would be relatively straightforward. Part of me wonders if I simply calculated the extended quasi liklihood at maybe 5-10 different p's, would that be sufficient? Something like a super-simple scikit-learn gridsearch? (There is a commercial product that I worked with in the past that I'm thinking actually did something like that. The user would provide an initial p guess, and it would fit the model multiple times with different p's and stop when it found one that met some tolerance. I presume it was just that the likelihood to the left and to the right were both lower. Not sure of the details beyond that.)
josef-pkt commentedon Mar 30, 2016
The plan is to add Tweedie only for 1< p < 2, is it?
Did you see anything about local optima with respect to estimating p also. Given that maximizing with respect to p is only a one-dimensional problem, and if there are no local minima, then the scipy optimizers should work well.
I guess we need to add a specific fit method that estimates p on top of the irls estimate.
Did you see any recommendation for a moment estimator for p?
thequackdaddy commentedon Mar 30, 2016
Maybe... After your comment I had another look at saddle point approximation... It appears this extended quasi likelihood is based off of the same simplification... At least the formulas look quite similar (though there's an extra 1/2 I think in the quasi... My Math could be wrong.)
For saddle point approximation Dunn and Smith essentially suggest finding some roots using chebychev polynomials and then interpolating.
They don't say anything there being a local maxima/minima... Although maybe if they suggest there's a saddle point, that should be one.
That is really making think that's what the commercial software did... It got a very precise evaluation of p relatively quickly, but then you'd have to refit the model and get new Params. After iterating between finding the best p and finding fitting the Params a few times (2-3 times maybe?) you got a pretty good fit.
josef-pkt commentedon Mar 30, 2016
saddle point approximation is just a specific form of asymptotic ( distributional) expansion.
It's used in some higher order approximation of the distribution of test statistics or estimators, but I never managed to figure it out (and the applications didn't look high priority and useful enough to try harder). AFAIK, almost everything has to be derived case by case, so it's not very useful as generic approach.
thequackdaddy commentedon Mar 31, 2016
So good news and not so good news...
I've put together code that calculates Tweedie densities for 1 < p < 2 using the series method. It wasn't that bad. I followed the paper here:
http://www.statsci.org/smyth/pubs/tweediepdf-series-preprint.pdf
My code is here:
https://gist.github.com/thequackdaddy/1ee4c24665e9a2b2be93790d888b4775
The speed actually seems much quicker than the R code...
Takes 0.61 seconds.
So I a little faster, I think.
I can also make some pretty charts.
(Here, the x-axis are the p values from 1.05 to 1.95 (inclusive) stepping by 5.) This also makes me think, that given the data that I think I'll have, I'm fairly sure that I can get a p-curve to look something like that.
Not so good news:
The algorithm is a little slow, especially on lots and lots of data--and won't even run for me at 2 million observations. (locked up my laptop twice trying to run it...)
A very brief sketch of the algorithm...
So the problems are quite obvious...
Outrageous though... is this is job for cython? I don't know cython, but it doesn't look that horrible. I understand you can also release the GIL so this embarrassingly parallel part could actually be done in parallel. I need to investigate this more, however.
josef-pkt commentedon Mar 31, 2016
np.whereis not good for not very cheap calculations. Use direct assignment with a mask, or use a copy of lazy_where. This got added to scipy as internal helper function for cases like this.https://github.com/scipy/scipy/blob/master/scipy/_lib/_util.py#L26
about cython and speeding up:
most similar functions, that for example need to calculate an infinite sum by truncation with limiting the approximation error, are in scipy special in either Fortran or C.
However, I think before trying out cython, we should figure out what an efficient implementation for our usecase would look like, since we only need it for the specific regression case.
FFT is an alternative, but I have looked at the fft inversion of the characteristic function for compound-Poisson only for the simple distribution case, i.e. evaluate the pdf or cdf at a single parameter for many points in the support at the same time. The task is different in the regression case because we need only a single point on the pdf but for many distribution parameters. My guess is that the fft inversion won't be very efficient for this case.
To your gist, based on a very brief look, IIUC:
In similar situations in scipy stats we are vectorizing the sum to go by large chunks instead of incrementing by 1.
Full loops where we have to iterate many million times are slow in Python, but if we can vectorize it in an appropriate way and shorten the number of iterations in the loop, then a numpy based solution is often reasonably fast. I haven't checked yet how your loops are vectorized.
What are the large endog values in your actual dataset?
thequackdaddy commentedon Mar 31, 2016
The endog values are claim amounts per year... so... Loss Payments / Years Policy Active.
Some policies can be really short... (only in force for a month or so). So the denominator can be real small there. Or the policy could be in force for an entire year. Maybe the largest endog would be $10 million? (In the dataset I'm looking it, its only $750k, but it could easily be higher if you have a big claim on a policy that was quickly cancelled...)
18 remaining items
josef-pkt commentedon Apr 2, 2016
At least this time I'm planning to take notes for the 10 or 20 papers that I'm skimming right now.
Partially independent a full tweedie implementation:
Some of the older actuarial articles estimate tweedie through the compound Poisson representation, some when the number of claims (count) is also observed.
I think going through the compound Poisson representation might be a computationally a competitive way for your special case of at most a few claims per observation, i.e. compounding at most 0 to 10 claims in the compounding distribution, which is different from the large scale aggregation case with many claims per record where direct compounding gets expensive.
josef-pkt commentedon Apr 2, 2016
Ok, this time I found the right reference with full theoretical background and derivation of the bias correction for estimating the tweedie variance parameters.
It's essentially as I stated, but there is an extra weight term in the moment condition for
pJørgensen, Bent, Clarice G. B. Demétrio, Erik Kristensen, Gary T. Banta, Hans Christian Petersen, and Matthieu Delefosse. 2011. “Bias-Corrected Pearson Estimating Functions for Taylor’s Power Law Applied to Benthic Macrofauna Data.” Statistics & Probability Letters, Statistics in Biological and Medical Sciences, 81 (7): 749–58. doi:10.1016/j.spl.2011.01.005.
search term as used by Jørgensen is "Pearson estimating functions".
I found related references initially through
http://www.leg.ufpr.br/lib/exe/fetch.php/publications:papercompanions:artigo.pdf
Bonat, Estimating function analysis for a class of Tweedie regression models
thequackdaddy commentedon Apr 11, 2016
I'm back. Finally. Sorry for being away for so long. Things got busy at work.
I found the paper and have read it. Full disclosure, I'm not a PhD and have never been good at reading academic papers. So a lot of this discussion is way over my head. With that said, I think I understand the gist of what we're supposed to do.. I found a copy here.
The strategy appears to be to set up a so-called chaser algorithm that iteratively solves these 2 equations.
This seems like pretty major rewrite of the
_fit_irlsfunction, so I'd prefer to not go fully down that route, but rather meet use_fit_irlsto calculate Beta/params (formula 4.1), then run an algorithm to solve equation 4.2 Then use the updated values from 4.2 to re-fit_fit_irlsagain until converged.(gamma?) (I think that squiggly line t-looking thing is a lower case gamma) is a variable that can represent either the shape or scale parameter in the Tweedie function. In fact, the paper treats it like a matrix so it can actually be both. The capital S with the u over it to the -1 is a "sensitivity matrix".
The S_gamma term is...
T_gamma is a little confusing for me. This is called a correction term.
Fortunately, 3 of the 4 terms are 0.
So only the term with b (the Tweedie shape parameter) appears to have a non-zero value. I think this means that the scale parameter will be similar between this estimate at the standard pearson Tweedie estimate.
I'm a little in the dark exactly what the "x_i" means here. The most clear explanation I can get from the paper is...
I think this means that I need to get the calculate the value of derivative of Tweedie's PDF function. I seem to recall that we have the derivatives of the link function ready to go, but not necessarily for Tweedie. I'm a little in the dark exactly what this means. Any ideas?
Thanks.
josef-pkt commentedon Apr 11, 2016
I will look at the details later, tonight.
(Note: 3 years ago a lot of this was over my head in spite of a PhD in economics, with background in econometrics, but not in statistics as emphasised in statistics)
my latest issue related to this is #2889
I did some background reading of the statistics literature in the mean time.
I think we don't want to rewrite fit_irls or other fitting methods in GLM. The easiest way to get started is to have a separate estimator that alternates between the two estimation parts, and where the main result is the GLM instance for the mean estimation for given, estimated tweedie dispersion parameters.
(We do something similar in the normal linear model when we estimate a variance function depending on explanatory variables, and we don't want to use the full normal MLE.)
Because tweedie has two dispersion/variance parameters we will have to do nonlinear optimization or rootfinding for those. The direct iteration is one possibility, or we can use a scipy optimizer also in the variance/dispersion step.
Double exponential models is structurally a bit similar, where the regular GLM is combined with a second dispersion GLM which is often based on the Gamma family.
(I was reading things also with respect to other generalization of GLM that have some similarities to what we need for Tweedie.)
.
josef-pkt commentedon Apr 12, 2016
I read the paper again. I would start without the bias correction for the power parameter
bin the paper.that is all we need to do is substitute exp(lambda) from equation (3.8) into (3.9) and solve equation (3.9) setting it equal to zero.
Since it's just an equality in one parameter, a scipy rootfinder like brentq or similar might work.
This can then be used to alternate with a GLM Tweedie fit for the beta parameters (for mean function) and this pearson estimation for the variance/dispersion parameters.
Given your sample size the bias correction might not have a large effect.
Adding the bias correction and solve equation (3.12) equal to zero instead doesn't look very complicated, but it requires the J_{\beta}^{-1} matrix.
newton scoring in equ. (4.2) looks also feasible without bias correction, but including bias correction needs again more difficult terms.
I would skip trying to implement the covariance of the variance/dispersion parameters in section 5, at least initially.
They mention that the bias corrected version is equal to the GLM gamma version for the dispersion/variance submodel. This is similar to double exponential model. But I'm not sure that will work out of the box, because we need to estimate the power parameter, and there might be some extra weights involved. I haven't looked at the Perry article that they reference for this.
Godambe matrix would essentially just be cov_type="HC0" if we get a model for this, but I haven't checked yet whether that will be easy or not.
About notation: They use clustered data in the application.
AFAICS (a guess where it's better to code first, and only read the small print if there are problems) we can ignore the j index and the n_i and just take
ias referring to an observation andx_ias the exogs of observationi. Then we just have the standard setup, where mu_i will be the predicted mean (fittedvalues), and (y_i - mu_i) in equ. 3.8 and 3.9 are just the residuals from the mean GLM-Tweedie results.thequackdaddy commentedon Apr 12, 2016
Ok I did this pretty simply and got this code... I'm only really deriving 3.9 and using
brentqto find the root.https://gist.github.com/thequackdaddy/e34fe095d0043cec353d60e0e0cb2b22#file-tweeide_moments-py-L24
The p-values "feel" reasonable... but they seem a little low... I'm not that familiar with the R tweedie package, so it would be nice to see if the scale and power I get match what R has. Not really sure where to start with that, however.
I agree though, that this is easily the fastest derivation of p I've come across.
josef-pkt commentedon Apr 12, 2016
a quick check (I haven't looked at everything yet)
you have a minus instead of a times in your
psi_pfunction(elambda - mu ** power)in denominator should be(elambda * mu ** power)One check if the variance function captures the dispersion approximately well is to compare the parameter standard errors with the robust standard errors, i.e. add `cov_type='HC0' to fit.
Another check for roughly the size is to just estimate the logged model: OLS with
log(resid**2) ~ log(mu)), IIRC, which will be biased but should still give roughly the same numbers for explambda and power.The tweedie package should have some examples, I also saw examples in several places in actuarial slides of talks or similar.
josef-pkt commentedon Apr 12, 2016
About standard errors for the variance power parameter:
If I see and remember this correctly (?), then johansen takes the effect of estimating the mean parameter into account, and there is an asymmetry, we can ignore the estimation of the variance parameters for the mean calculation, but we can or should not ignore the fact that the mean parameters are estimated when calculating cov_params for the variance parameters.
(I need to reread johansen and knudsen when we want to calculate the bse for the variance parameters.)
In double exponential models this is not necessary, because the orthogonality, independence goes both ways.
josef-pkt commentedon Apr 12, 2016
I added another comment about elambda calculation to the gist
thequackdaddy commentedon Apr 12, 2016
Oh geez. I misread that totally didn't I? Thanks.
I'll see if I can check vs. the robust se.
josef-pkt commentedon Apr 12, 2016
brentq is a bit fragile, I sometimes get exceptions
ValueError: f(a) and f(b) must have different signsIn other cases I'm using a backup for the case when f(a) and f(b) don't have different signs.
Also the lower bound
amight have to be larger. There were some problems reported in one of the articles, but I don't remember for which estimator of the power parameter.univ12 commentedon Oct 10, 2016
Sorry for asking this newbie question, I am very new to statsmodels and just found this.
Does this mean that a Tweedie GLM is possible in an upcoming version? I guess that must be v0.8 since I found nothing in the 0.7 docs.
josef-pkt commentedon Oct 10, 2016
Yes, it's available in the 0.8rc1.
but see #3079 for possible problems and enhancements for it.
(the default tweedie power parameter estimation is computationally not very robust, and the interaction with exposure has to be checked again for some of the results.)
thequackdaddy commentedon Nov 3, 2016
@univ12 @josef-pkt Hello,
I wanted to point out that I (think) I've managed to sort out a way to use the series evaluation method outlined in this paper:
Dunn, Peter K. and Smyth, Gordon K. 2004.
Series evaluation of Tweedie exponential dispersion model densities.
29 September 2004
I then used the
minimize_scalarfunction fromscipy.optimizeto optimize the variance power for tweedie likelihood.On my datasets, this works pretty well and I'd say its robust. All the hard math is done is numpy and so its relatively fast. You can find an optimal
pin 10-20 seconds on a dataset with the following characteristics:nobs = 5378317
p_opt = 1.487
Around 2% of the observations have
endog > 0Here's a plot of the density when endog>0:
https://github.com/thequackdaddy/statsmodels/tree/estimate_tweedie
@univ12 If you want to try it out and let me know if it works well for you, I'd appreciate it.
model.estimate_tweedie_power(res.mu, method='series_approximation', p0=1.5, bounds=(1.05, 1.95))is a simple way to invoke it.So far, the method seems pretty robust.