Skip to content

BUG/ENH: Tweedie parameterization and better handling of exposure, inclusion of 'perry' and 'taylor' methods. - #3079

Open
thequackdaddy wants to merge 5 commits into
statsmodels:mainfrom
thequackdaddy:estimate_tweedie
Open

thequackdaddy wants to merge 5 commits into
statsmodels:mainfrom
thequackdaddy:estimate_tweedie

Conversation

@thequackdaddy

Copy link
Copy Markdown
Member

Hello,

See #2915 for the cause of this.

(I just realized that you probably wanted me to name the method 'gamma-glm', but I named it 'perry'. I also made a 'taylor' which is supposed to be WLS version of the same thing. If you want me to rename, let me know.)

I'm not sure this totally works. I first used the fair dataset to see how well/poorly this works (I generated sample weights, exposures. On a scale of 1-10, I'd give that a 7 as far as how good it felt. taylor and perry were very close, but the rest was quite different.

When I ran this on my real dataset, my confidence fell to a 2. I'm getting much different estimates for p using all the different methods. So I might need to think this out more.

In [4]: model = sm.GLM(
   ...:     endog=np.array(data['PDIncurredLoss']),
   ...:     exog=bx,
   ...:     family=sm.families.Tweedie(var_power=1.639, link_power=0),
   ...:     exposure=np.array(data['PDExposure'])
   ...: )
   ...: 
   ...: res = model.fit(rtol=1e-2, tol_criterion='params', maxiter=10)
   ...: p = model.estimate_tweedie_power(res.mu)

In [5]: model.estimate_tweedie_power(res.mu, method='taylor')
Out[5]: 2.0409433864515334

In [6]: model.estimate_tweedie_power(res.mu, method='perry')
Out[6]: 1.1050768778823175

In [7]: model.estimate_tweedie_power(res.mu, method='brentq')
Out[7]: 1.6455822161384193

In [8]: res.summary()
Out[8]: 
<class 'statsmodels.iolib.summary.Summary'>
"""
                 Generalized Linear Model Regression Results                  
==============================================================================
Dep. Variable:                      y   No. Observations:              3569086
Model:                            GLM   Df Residuals:                  3569058
Model Family:                 Tweedie   Df Model:                           27
Link Function:                    log   Scale:                   2553.65026079
Method:                          IRLS   Log-Likelihood:                    nan
Date:                Sun, 26 Jun 2016   Deviance:                   7.7973e+07
Time:                        20:20:35   Pearson chi2:                 9.11e+09
No. Iterations:                    10                                         

On the bright side, all the methods feel like converge with a guess-and-check approach. So that keeps it above a 1.

@thequackdaddy thequackdaddy changed the title BUG/ENH: Tweeide parameterization and better handling of exposure, inclusion of 'perry' and 'taylor' methods. BUG/ENH: Tweedie parameterization and better handling of exposure, inclusion of 'perry' and 'taylor' methods. Jun 27, 2016
@coveralls

coveralls commented Jun 27, 2016 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.02%) to 88.828% when pulling 804b9e4 on thequackdaddy:estimate_tweedie into 032a9ab on statsmodels:master.

# Already logged
exposure = np.exp(self.exposure)
elif exposure is None:
exposure = np.ones(len(self.endog))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think exposure = 1. should work correctly with broadcasting in the following.

@josef-pkt

josef-pkt commented Jun 27, 2016 •

Copy link
Copy Markdown
Member

If there are descriptive names available, then we try to avoid using author names.
I think perry -> glm-gamma and taylor -> ols (or ols-logs)
wls for weights is just and extension/variation on ols with user defined weights

There might be a wls version with weights/var_weights depending on mu to get something similar to glm-gamma, assuming known variance of residual**2. (maybe in future)

elif method == 'taylor':
from statsmodels.regression.linear_model import WLS

y = np.log(np.power(endog2 - mu2, 2))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

my guess is that we need to clip endog2 - mu2 to be larger than zero. Somebody will come up with a case with zero residuals. I'm not sure what's a good threshold, 1e-6?

@thequackdaddy thequackdaddy changed the title BUG/ENH: Tweedie parameterization and better handling of exposure, inclusion of 'perry' and 'taylor' methods. WIP: BUG/ENH: Tweedie parameterization and better handling of exposure, inclusion of 'perry' and 'taylor' methods. Jul 5, 2016
@coveralls

coveralls commented Jul 5, 2016 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.02%) to 88.828% when pulling b68d653 on thequackdaddy:estimate_tweedie into c5b2f2e on statsmodels:master.

@coveralls

coveralls commented Jul 5, 2016 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.02%) to 88.829% when pulling b68d653 on thequackdaddy:estimate_tweedie into c5b2f2e on statsmodels:master.

@coveralls

coveralls commented Jul 5, 2016 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.02%) to 88.829% when pulling b68d653 on thequackdaddy:estimate_tweedie into c5b2f2e on statsmodels:master.

@thequackdaddy

Copy link
Copy Markdown
Member Author

I put together a gist of what I think you mean by a monte-carlo simulation.

The implied p that I'd like to calculate is ~1.76, however, I'm getting ~1.95.

https://gist.github.com/thequackdaddy/2e4690a3eb8964b207d5122d41c7e7f4

Didn't spend a lot of time on this, so could be a problem lurking somewhere. The p-values are very, very low, so perhaps I need to make the model not as good?

@josef-pkt

Copy link
Copy Markdown
Member

@thequackdaddy I have not yet tried to catch up with this and related issues.

Is there a bug somewhere that should be fixed for statsmodels 0.8, or can this wait for 0.9?

@thequackdaddy

thequackdaddy commented Aug 11, 2016 •

Copy link
Copy Markdown
Member Author

@josef-pkt Sorry for not getting back to you earlier. I'm working on some work things and haven't had time to commit anything.

I think there is a bug if you are working with exposure. If you aren't using exposure weighting, I think it kind of works.

I'm happy to have this wait until 0.9. I wrote a Notebook, by the way, that uses the series approximation method (like the R dtweedie package). It works very well and runs reasonably quickly on my datasets. Unfortunately, that's on my work laptop. I'll try to clean it up and upload it as a gist.

So feel free to leave as-is and we'll clean up later. If you have free time to review the notebook once its ready, I'd appreciate it. I really need someone much smarter than me to buy-in before I believe what I've done myself.

On a side note, the Tweedie-family functionality that we've programmed so far works very well for my models. I'm hoping to have management approve gen1 in the next few weeks with production following a few months later. I've basically assumed a Tweedie variance power parameter of 1.6 based on the CV of the size of loss distributions. The models validate extremely well and far, far outperform our current programs, so that's exciting. The bad news (from my perspective) is that with significant performance gains, that means many customers will see large increases (and some will see decreases), so management will have some heartburn from that. That's more an implementation question than a model question, however.

My department has increased staffing and after some new people are trained I'm hoping maybe I can be more active.

@thequackdaddy

Copy link
Copy Markdown
Member Author

After experimenting with this some more, I'm really now leaning towards thinking that the BrentQ/psi method might only really work in some limited situations.

[I made this gist)[https://gist.github.com/thequackdaddy/25a32272e1219973eab308948ab89a2a] showing the two methods on a random dataset I generated. The SeriesApproximation method works extremely well--the optimum p-values from the scipy minimize function is very close to the actual p-value.

The psi_p value is all over the map.

@josef-pkt - At one point, you suggested that you were able to get the psi_p method to approxmiate very well. Do you have that code? I'm wondering if I've screwed something up. (Not unlikely).

@josef-pkt

Copy link
Copy Markdown
Member

AFAIR, using the GLM-gamma worked well.
Using brentq worked well for me only in larger samples.
In small samples (100 nobs or something like this) the psi function was not monotonic, and IIRC had several zeros/roots. (It might be related to solving the scale inside the psi function.)

(I'm trying to finish release preparation, and might not look closely very soon.)

@thequackdaddy

Copy link
Copy Markdown
Member Author

@josef-pkt As mentioned in the other thread, I think this works pretty well.

Would you have some time to work through this with me :)

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.05%) to 87.893% when pulling b56fec7 on thequackdaddy:estimate_tweedie into fc3584f on statsmodels:master.

@thequackdaddy thequackdaddy changed the title WIP: BUG/ENH: Tweedie parameterization and better handling of exposure, inclusion of 'perry' and 'taylor' methods. BUG/ENH: Tweedie parameterization and better handling of exposure, inclusion of 'perry' and 'taylor' methods. Dec 4, 2016
@thequackdaddy

Copy link
Copy Markdown
Member Author

Not really actively working on this anymore as I think its pretty much good enough for me for now.

Comparing to R's tweedie package, there's also qtweedie and ptweedie which return the quantiles and cumulative distribution (Pr(X <= x)) which would be very useful for q-q plots. I can't seem to find literature on that though. Having that would allow me to run q-q plots--which I've never done on Tweedie but I found a stackexchange explanation of. Seems do-able... good wishlist item.

@thequackdaddy

Copy link
Copy Markdown
Member Author

Since exploring with var_weights, I think its fair to say that exposure requires some incorporation of var_weights. I removed all the exposure logic... For now, I'm just getting this to pass again and fixing a merge conflict.

@coveralls

coveralls commented Dec 22, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.01%) to 82.098% when pulling c528d32 on thequackdaddy:estimate_tweedie into de9a7da on statsmodels:master.

@codecov-io

codecov-io commented Dec 22, 2017 •

Copy link
Copy Markdown

Codecov Report

Merging #3079 into master will increase coverage by 0.25%.
The diff coverage is n/a.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #3079      +/-   ##
==========================================
+ Coverage   79.48%   79.73%   +0.25%     
==========================================
  Files         558      562       +4     
  Lines       83455    84919    +1464     
  Branches     9538     9808     +270     
==========================================
+ Hits        66331    67713    +1382     
- Misses      14951    14986      +35     
- Partials     2173     2220      +47
Impacted Files Coverage Δ
statsmodels/regression/linear_model.py 91.01% <ø> (ø) ⬆️
statsmodels/sandbox/regression/treewalkerclass.py 0% <0%> (ø) ⬆️
statsmodels/iolib/summary.py 54.54% <0%> (ø) ⬆️
statsmodels/stats/libqsturng/make_tbls.py 0% <0%> (ø) ⬆️
statsmodels/tsa/statespace/mlemodel.py 85.59% <0%> (ø) ⬆️
statsmodels/regression/mixed_glm.py 93.3% <0%> (ø)
statsmodels/regression/bayes_mixed_glm.py 91.61% <0%> (ø)
statsmodels/regression/tests/test_mixed_glm.py 100% <0%> (ø)
...atsmodels/regression/tests/test_bayes_mixed_glm.py 100% <0%> (ø)
statsmodels/genmod/tests/test_glm.py 98.8% <0%> (+0.08%) ⬆️
... and 1 more

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update de9a7da...c7c3260. Read the comment docs.

@thequackdaddy

Copy link
Copy Markdown
Member Author

I sat down to work through this again and I think I hit something of a breakthrough. I re-did the method to essentially:

  • Start with a guess of the variance power
  • Estimate the scale using the pearson-chi2 technique using that power
  • Use the psi_p formula to estimate a new variance power.
    This converges very slowly, especially when the variance power is off. So I used the minimize_scalar optimizer to re-run this algorithm with the updated variance powers. Thus, you get a new scale every time. Once I did that, it actually works fairly well.

I have a gist outlining how this works below.

Still not totally ready. I will try this technique using real data (right now... the data is simulated) so perhaps that will give me a better judgement of if this is truly working.

https://gist.github.com/thequackdaddy/8830d4bac9b57ba94a31e5cd1de63b8e

@thequackdaddy

Copy link
Copy Markdown
Member Author

I should add that I need to see how accurate/inaccurate this all is if there are var_weights as that is truly important to me. I'm not entirely sure at this point. I would imagine that taylor and perry won't work either (I'm not sure how variance weights would work in that case.)

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.01%) to 82.098% when pulling c7c3260 on thequackdaddy:estimate_tweedie into de9a7da on statsmodels:master.

1 similar comment
@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.01%) to 82.098% when pulling c7c3260 on thequackdaddy:estimate_tweedie into de9a7da on statsmodels:master.

scale /= self.var_weights

def psi_p(power):
psi = ((self.endog - mu) ** 2 / (scale * mu ** power) - 1)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

var_weights always needs to go in in the same way as inverse scale (1 / scale), i.e. line 806 above
so, this looks fine to me.

model = GLM(y, x, freq_weights=weights,
family=families.Gamma(families.links.log))
res = model.fit()
scale, power = res.params

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

res.params here is in log scale, i.e. links.log
Don't you need to rescale params? Or is this implied/correctly parameterized in model?

x = np.column_stack((np.ones(len(self.endog)), np.log(mu)))
model = WLS(endog=y, exog=x, weights=weights)
res = model.fit()
scale, power = res.params

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

here there is no log-link, so I think either this or perry/glm has the wrong parameterization.
?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

correction: endog here is loged

@josef-pkt

Copy link
Copy Markdown
Member

I don't want to take the time right now to go back into the optimization problems here with the power parameter. The gist also has runtime warnings that we might be able to work around by clipping or restricting to valid ranges. (I didn't check, and don't remember running into it when I was playing with Tweedie.)

Given that this is just a helper method and won't directly affect other code, I think we can merge if you think it works better than the current version.
GLM-gamma and WLS, perry and taylor, methods look fine but I didn't try to check the math.

(Based on my earlier experiments, it might be necessary to use some global optimizer to work around multiple roots. I'm not sure about that because we don't have a loglike to rank roots/zeros.

Aside: Why does the precision of the var_power matter? Mean parameters or glm tweedie should be fine even if tweedie var power is off by a bit (?). Maybe we can use other, higher moments or quantiles or ... to better match the power parameter. E.g. like trying to find the appropriate count distribution after we have more of them.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants