Skip to content

ENH: GLM Tweedie Family - #2872

Merged
josef-pkt merged 15 commits into
statsmodels:masterfrom
thequackdaddy:tweedie
Apr 28, 2016
Merged

josef-pkt merged 15 commits into
statsmodels:masterfrom
thequackdaddy:tweedie

Conversation

@thequackdaddy

Copy link
Copy Markdown
Member

Hello,

This will (eventually) resolve #2858 and part of #2804 .

This adds Tweedie to the family of distributions.

A few shortcomings...

  • I don't have Stata so none of my checks are from Stata. (Also, I'm not sure where the ansocombe residuals came from. Perhaps this is a stata thing too?)
  • As the deviance function doesn't like it when endog=0 or the shape parameter is 1 or 2, I've set endog to have a min of 0.1 and used WolframAlpha to derive the deviance function for the special case shape parameters (1 and 2).
  • All the residuals seem to match except working residuals when var_power = 1 and link_power = 0 (i.e., the log link)
  • I don't really know how to write the loglikihood function for this. Its in the Glenn Myers PowerPoint and some papers, but haven't cracked it yet.
  • The documentation is (of course) incomplete. As I get a get a better handle for how this will work, I'll start writing it.

So let's get rockin.


Updated 3/28/2016

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.01%) to 85.367% when pulling 79d28f6 on thequackdaddy:tweedie into eed4ae5 on statsmodels:master.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.003%) to 85.381% when pulling 5fb2ca4 on thequackdaddy:tweedie into eed4ae5 on statsmodels:master.

@thequackdaddy

Copy link
Copy Markdown
Member Author

Getting closer... not there yet. Working residual isn't working for 1 of my test cases, don't have anscombe.

I skimmed through the Tweedie LLF R function and was quite confused exactly how that function worked. Gonna take a look at it again. I'd like to have loglikelihoods, but deviance is better than nuthin'.

@josef-pkt

Copy link
Copy Markdown
Member

@thequackdaddy We are not allowed to translate GPL licensed code! GPL is incompatible for use in a BSD licensed package.

@thequackdaddy

Copy link
Copy Markdown
Member Author

@josef-pkt Yes, I realized that after the fact. That copied code was removed. Instead, I used the deviance function and calculated the limit of the function as p-> 1 and p-> 2. The answer appears to be the same. Also, I think its slightly shorter, so that's nice.

Apologies for the confusion.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.03%) to 85.411% when pulling 45787ca on thequackdaddy:tweedie into eed4ae5 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member

This looks already very good based on the passing tests.

Note, if loglike is too difficult to implement right now, then we should raise an exception in the _fit_gradient.
Most tests on fit can just be done with the deviance which looks available.

I doubt I have time to read it carefully today. I only briefly browsed the code yesterday.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.03%) to 85.411% when pulling 45787ca on thequackdaddy:tweedie into eed4ae5 on statsmodels:master.

@thequackdaddy

Copy link
Copy Markdown
Member Author

@josef-pkt Great. Any thoughts on anscombe residuals? I'll confess I don't use them much so I have little idea how to interpret them. I generally use pearson/deviance.

Let me know if you can figure out the formula. Also, if you could get them from stata (or R if that's possible), I'd appreciate it.

@josef-pkt

Copy link
Copy Markdown
Member

anscombe residuals are family specific formulas (where I never looked at the details)
I was reading SAS or SPSS documentation in the past, but don't remember if they have anscombe formulas.
Given that deviance worked well, I assume anscombe should also have a reasonable expression.
But it's not a strictly necessary feature. (Main usage, AFAIK, is for outlier diagnostic) Compared to the other residuals (Pearson, deviance) it also corrects for skewness.

@josef-pkt

Copy link
Copy Markdown
Member

no luck on anscombe residuals in a bit of search
SPSS genlin has a good technical documentation, but I didn't see anscombe residuals (they have all the other ones)
SAS stats also doesn't seem to have anscombe, SAS insight has anscombe but no Tweedie, AFAICS
Stata doesn't have Tweedie.

@thequackdaddy

Copy link
Copy Markdown
Member Author

@josef-pkt This may belong is a separate issue, but I couldn't find anything.

Question about "working residuals", as far as I can tell, this appears to be an "r-specific" thing. I can't find any literature talking about this concept. The best I can find is here which suggests they are simply the residuals from the last IRLS fit.

R appears to define them as residuals <- (y - mu)/mu.eta(eta). mu.eta is the derivative of mu with repect to to eta. For log, mu = exp(eta) -> dmu / deta = exp(eta).

However, we define working residuals as and basically the inverse. Specifically, I think we do (endog - mu) / sm.family.link.deriv(mu). Here, our denominator is the derivative of eta with respect to mu, which means eta = ln(mu) -> deta / dmu = 1 / mu.

The point of all this is that I remain unable to match R's working residuals, although I think that's just more of a result of the way R does the residuals vs. the way we do them. With that said, the working residuals appears to have been used many times before in testing. I suppose that the working residuals are identical when you have the identity link function, but under any any function, my guess is they'd be different.

Alternatively, it could just be there's no clear definition of the concept. With that said, intuitively, (y -mu)/mu.eta makes intuitive sense to me. (the response residual divided by the slope of mu at eta is basically the sensitivity of the residual with respect to eta.) On the other hand, (endog - mu) / self.family link.deriv(mu) is a mystery to me. That's trying to find a relationship between the response residual and eta, but it doesn't seem to be accounting for a link function.

So anyways, I'm confused by this.

@josef-pkt

Copy link
Copy Markdown
Member

I never looked at working residuals.
When in doubt I usually check the unit tests to see what they compare against, and comments Skipper added when he wrote the tests.
http://www.stata.com/manuals14/rglmpostestimation.pdf page 6
The glm_test_resids.py file says all residuals were obtained with Stata.

However, I would interpret the Stata manual as (endog - mu) * self.family link.deriv(mu)

@thequackdaddy

Copy link
Copy Markdown
Member Author

@josef-pkt Ok after looking at this more...

1.) I remain fairly confident that the way we are doing it now is incorrect. (Perhaps stata had a bug in their old version of their code and its now more apparent?)
2.) Working residuals has another problem i think. We are applying the _n_trials and _freq_weight twice. First, we apply them when calculating resid_response and then again when calculating resid_working. I'm assuming our tests just didn't notice that.

With 2) in mind, I seem to recall that you began leaning (towards the end of my commits for freq_weights) to not have weights applied to the residuals. I didn't really care then, but now see that was probably a bad idea on my part at the time. If its alright with you, I'd like to remove weights from residuals before I proceed further with Tweedie. Further note: should I remove both freq_weights and n_trials or only freq_weights?

Our algorithm does not match Stata's documentation nor the R documentation. Perhaps Stata had a bug which is now fixed? I can't test as I don't have it. I can match R's working residuals perfectly if I just multiply instead of divide.

@josef-pkt

Copy link
Copy Markdown
Member

I have Stata, but need to clean out previous work before I can run it on an example for this.
The Stata manual wasn't publicly accessible when Skipper wrote this, and didn't have Stata or the documentation back then.

Yes, I think it's better to leave the weights out of the residuals (remove them again).
For binomial n-trials it would be best to have the status before the GLM weights, then it wouldn't be a backwards incompatible change. (My guess is that counts, i.e. multiplied by n trials would make more sense.)

@josef-pkt

Copy link
Copy Markdown
Member

I get different working residuals than those in the test suite after running the cpunish poisson glm example in Stata. Also, those working residuals in the test suite are much larger than any of the other residual.

@jseabold Do you remember why the working residuals might be wrong?

I don't find any changelog or bug reports for Stata, so I cannot check what it looked like before Stata 12

@josef-pkt

Copy link
Copy Markdown
Member

I think I have anscombe residuals.
An easy explanation is in "Modern Actuarial Risk Theory - Using R" page 305 equ (11.19) and following.
Generalizing this to variance function in the form V=mu**p, it should be

c = (3 - p) / 3
resid_anscombe = c * (y**c - mu**c) / mu**(p / 6)

which should specialize to Poisson with p=1 and gamma for p=2, gaussian for p=1
inverse gaussian has p=3 and they have log(y) instead of yc and muc, i.e.
resid_anscombe = (log(y) - log(c)) / mu**2

(I didn't try to check the limit as p -> 3 in the derivation.)

@thequackdaddy

Copy link
Copy Markdown
Member Author

@josef-pkt

Going back to Anscombe...

do you mean this?

    def resid_anscombe(self, endog, mu):
        """
        The Anscombe residuals for the Tweedie family

        Parameters
        ----------
        endog : array-like
            Endogenous response variable
        mu : array-like
            Fitted mean response variable

        Returns
        -------
        resid_anscombe : array
            The Anscombe residuals as defined below.

        Notes
        -----
        Not yet...
        """
        c = (3 - self.link_power) / 3
        if self.link_power == 3:
            return (np.log(endog) - np.log(c)) / mu ** 2
        else:
            return c * (endog ** c - mu ** c) / mu ** (self.link_power / 6)

I don't understand resid_anscombe = (log(y) - log(c)) / mu**2 when p == 3 (inverse gaussian). c in that case is 0, so np.log(c) = np.nan.

@thequackdaddy

Copy link
Copy Markdown
Member Author

Ignore this last comment... In mixing var and link power...

@josef-pkt

Copy link
Copy Markdown
Member

No, I think this has to be the variance power.
the link doesn't show up it's hidden behind the mu, and this is supposed to work for any valid links.

@josef-pkt

Copy link
Copy Markdown
Member

I think I have a type there, if c=3, the expression should have mu not c
resid_anscombe = (log(y) - log(mu)) / mu**2

i.e. residuals of log transformed endog and fittedvalues.
I can check the reference again.
It's also supposed to be hardcoded in the inverse gaussian family.

@josef-pkt

Copy link
Copy Markdown
Member

yes, InverseGaussian family class has anscombe
np.log(endog / mu) / np.sqrt(mu)

BTW: np.log(0) is -inf

There are problems if endog=0, but inverse gaussian is continuous with support endog > 0, AFAIK
which I think is true for all Tweedie with power p >= 2

@thequackdaddy

Copy link
Copy Markdown
Member Author

@josef-pkt

Back to anscombe...

Is there another typo in this? For inverse gaussian, I think we want sqrt(mu) in the denominator. For the other cases, I think we want to multiply by (1 / c), not by c. So something like this...

        if self.var_power == 3:
            return (np.log(endog) - np.log(mu)) / np.sqrt(mu)
        else:
            c = (3 - self.var_power) / 3
            return (1 / c) * (endog ** c - mu ** c) / mu ** (self.var_power / 6)

This should become...
p == 0 (Gaussian) endog - mu
p == 1 (Poisson) (3 / 2) * (endog ** (2 / 3) - mu ** (2 / 3)) / mu ** (1 / 6)
p == 2 (Gamma) 3 * (endog ** (1 / 3) - mu ** (1 / 3)) / mu ** (1 / 3)
p == 3 (Inverse Gaussian) np.log(endog / mu) / np.sqrt(mu)


Edit - Messed up link_power vs. var_power again.

@josef-pkt

Copy link
Copy Markdown
Member

What you have now looks correct.
The cases are the same as in the book.
(I don't know where my notes with the derivation are.)
That's why I like unit tests, I'm too prone to small calculation mistakes and typos. (Fortunately small calculation mistake often produce widely incorrect numbers that are easy to detect, e.g. reversing a sign.)

@thequackdaddy

Copy link
Copy Markdown
Member Author

I'm totally with you on unit tests... I've found them extremely helpful. That's actually how I found this.

We should be able to validate that Tweedie's residuals match for p == 0, 1, 2, and 3. I guess we'll have to assume that the other values would match as well cause I don't have a source for any other p. (Specifically, I can't get anscombe residuals from R. I did find This package called "surveillance" which advertises anscombe residuals, but they appear to be poisson-specific and then they are standardized (for reasons I don't understand).

Thanks.

@josef-pkt

Copy link
Copy Markdown
Member

I think if anscombe residuals agree with the special cases, then there is no mistake left in the formula, and it's sufficient for testing (only p=3 is a special case, all others use the same formula).

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.05%) to 85.408% when pulling 4cf9f05 on thequackdaddy:tweedie into 81be990 on statsmodels:master.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.05%) to 85.415% when pulling 6cfcdf8 on thequackdaddy:tweedie into 81be990 on statsmodels:master.

@thequackdaddy

Copy link
Copy Markdown
Member Author

Ok I'm inching towards the finish line here... I added the fair test, and we're all green.

As a side note, I tried to also compare the results of estimate_tweedie_power with R tweedie's tweedie.profile. Our Pearson estimate is getting a 1.763 on the Fair data vs. 1.52449 in R.

model = sm.GLM(endog=data.endog, exog=data.exog[['rate_marriage', 'age', 'yrs_married']], family=sm.families.Tweedie(var_power=1.5, link_power=0))
res = model.fit()
model.estimate_tweedie_power(res.mu)

1.763

model2 <- tweedie.profile(affairs ~ rate_marriage + age + yrs_married - 1, data=data, link.power=0, p.vec=seq(1.1, 1.9, .1),
                         do.plot = TRUE)
model2$p.max

1.52449

@josef-pkt

Copy link
Copy Markdown
Member

sounds good,
about the difference to R profile:
Do you know if they use the full profile likelihood or an approximation like the extended quasi-likelihood?
It's not clear which would be more accurate in general. Estimate with profile likelihood can be biased, and assumes correctly specified distribution.
Our mean parameter estimates will be robust to deviations from the tweedie variance function, if we use the pearson estimate this way.

in general: I will look at the latest changes, but also think that we should merge this soon. Further enhancements can be done in future PRs.
Given that you have already the function for the compound poisson tweedie series approximation to the the likelihood, I think we should include the code so it's available for future enhancements.
I though that a private (leading underscore) module _tweedie_compound_poisson.py in genmod would be an appropriate location.
And since I just went looking again for some references, I'd like to get the parameter transformation between tweedie and compound poisson. This would also allow us to simulate a tweedie dataset, and we could do a brief MonteCarlo to check how good the variance parameter estimates are.
Those things could also go in there.

Aside:
Alternatives to directly using tweedie would include modeling the compound poisson directly, and also extend it to the case when we observe two endog, number of claims and total claim size at the same time. Many of those kind of models would be just combining existing models, instead of adding a new family as in this PR.

@thequackdaddy

Copy link
Copy Markdown
Member Author

R's tweedie.profile appears to use the infinite series of sums. Its awfully slow. For the fair dataset, it took maybe 5 minutes to run. So that's not going to be scalable to the millions. The way it appears to work is that it fits a GLM for each of the selected p's in p.vec then it calculates the loglikelihood. It then plots the fitted log-likelihoods (x-axis is p, y-axis is loglikelihood), fits to a spline, and finds the p which maximizes the spline... so its quite involved.

I will commit add the gist of the calculation that I provided you as the function you requested. I played with this a little more, but haven't looked at it in a few weeks... and have forgotten much of how it works. It was quite slow (obviously) but there's probably optimizations that are possible with some patience. I won't be adding any tests for the code as I don't really have anything great to check against.

If you want to add the parameter transformation so we can do some MC sampling, I think it sounds like that's going to be in a future PR for this or do you want included in this PR?

After you are happy with this, I'm happy to squash.

Thanks so much Josef.

@josef-pkt

Copy link
Copy Markdown
Member

I think this is a good place to stop and merge, after you added the helper function.

The deviance looks good now, I didn't look at the other things again.
13 commits is not too much, but I'll check if we should do some squashing.

As followup, it would be good to have a notebook that explains a bit the new family, maybe with both test cases (just copied over). AFAIK, we don't have the changelog ready right now, but we will need one or a few paragraph announcing it.

As further followup, we can also check to see if we have all possible results, given that we don't have loglike. Somewhere we need to check or mention that tweedie can only be estimated by irls and not with the scipy optimizers. (It would be possible to minimize deviance, but the class hierarchy is not set up for maximizing anything else than loglike.)

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.05%) to 85.415% when pulling 82fb598 on thequackdaddy:tweedie into 81be990 on statsmodels:master.

Comment thread statsmodels/genmod/tests/test_glm.py Outdated


class TestTweediePower15(CheckTweedie):
def __init__(self):

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.

convert all the __init__ to a classmethod setup_class
check other tests for the format

this "should" speed up the unit tests because nose runs __init__ separately for each method of the class, i.e. this currently estimates the same thing seven times.

@josef-pkt

Copy link
Copy Markdown
Member

I hadn't realized that you already rebase, looks good, and I don't think it needs any squashing.

However, this adds about a minute or a bit more to the test run on TravisCI.
I guess that using setup_class to avoid repeated fitting would speed this up a bit.

@thequackdaddy

Copy link
Copy Markdown
Member Author

Yeah I rebased because I think there was conda package update that made it so my build wouldn't work... I noticed you were fighting with it, so I rebased and viola, problem solved.

I'm now using setupClass when I can. Builds on my machine... let's see what travis thinks.

from statsmodels.datasets.cpunish import load_pandas
self.data = load_pandas()
self.exog = self.data.exog[['INCOME', 'SOUTH']]
self.endog = self.data.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.

for next time:
one possible trick is to leave these in a method in the super class and call the method directly, which works (IIRC) if the method in the superclass is also a classmethod
(could be a setupClass or a getdata method in super)
super call needs the class twice, IIRC, e.g. super(TestTweediePower2, TestTweediePower2).get_data()

("IIRC" means it works but I never remember the details and have to look them up from other examples.)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Ahhh...

I thought about a super but I couldn't get that to work (in about 2 tries)... Didn't attempt this way.

Thanks for the tip.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.06%) to 85.417% when pulling 512dccf on thequackdaddy:tweedie into 81be990 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member

all green, only a little bit faster with the latest versions, and 1 minute or so faster on the older version.

Ready to merge? From my side it looks ready.

@thequackdaddy

Copy link
Copy Markdown
Member Author

I'm happy if you are.

I'm thinking my next topic is reviewing #2915. Let me re-read some of the papers.

The full log likelihood will have to wait for another day.

@josef-pkt
josef-pkt merged commit b77e1a2 into statsmodels:master Apr 28, 2016
@josef-pkt

Copy link
Copy Markdown
Member

It's merged. Thanks @thequackdaddy

@thequackdaddy
thequackdaddy deleted the tweedie branch April 28, 2016 02:27
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.

ENH: Tweedie,GLM and compound Poisson

3 participants