Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 95 additions & 0 deletions statsmodels/genmod/_tweedie_compound_poisson.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
"""
Private experimental module for miscellaneous Tweedie functions.

References
----------

Dunn, Peter K. and Smyth, Gordon K. 2001. Tweedie family densities: methods of
evaluation. In Proceedings of the 16th International Workshop on
Statistical Modelling, Odense, Denmark, 2–6 July.

Jørgensen, B., Demétrio, C.G.B., Kristensen, E., Banta, G.T., Petersen, H.C.,
Delefosse, M.: Bias-corrected Pearson estimating functions for Taylor’s
power law applied to benthic macrofauna data. Stat. Probab. Lett. 81,
749–758 (2011)

Smyth G.K. and Jørgensen B. 2002. Fitting Tweedie's compound Poisson model to
insurance claims data: dispersion modelling. ASTIN Bulletin 32: 143–157
"""
import numpy as np
from scipy._lib._util import _lazywhere as lazywhere
from scipy.special import gammaln


def _theta(mu, p):
return np.where(p == 1, np.log(mu), mu ** (1 - p) / (1 - p))


def _alpha(p):
return (2 - p) / (1 - p)


def _logWj(y, j, p, phi):
alpha = _alpha(p)
logz = (-alpha * np.log(y) + alpha * np.log(p - 1) - (1 - alpha) *
np.log(phi) - np.log(2 - p))
return (j * logz - gammaln(1 + j) - gammaln(-alpha * j))


def kappa(mu, p):
return mu ** (2 - p) / (2 - p)


@np.vectorize
def _sumw(y, j_l, j_u, logWmax, p, phi):
j = np.arange(j_l, j_u + 1)
sumw = np.sum(np.exp(_logWj(y, j, p, phi) - logWmax))
return sumw


def logW(y, p, phi):
alpha = _alpha(p)
jmax = y ** (2 - p) / ((2 - p) * phi)
logWmax = np.array((1 - alpha) * jmax)
tol = logWmax - 37 # Machine accuracy for 64 bit.
j = np.ceil(jmax)
while (_logWj(y, np.ceil(j), p, phi) > tol).any():
j = np.where(_logWj(y, j, p, phi) > tol, j + 1, j)
j_u = j
j = np.floor(jmax)
j = np.where(j > 1, j, 1)
while (_logWj(y, j, p, phi) > tol).any() and (j > 1).any():
j = np.where(_logWj(y, j, p, phi) > tol, j - 1, 1)
j_l = j
sumw = _sumw(y, j_l, j_u, logWmax, p, phi)
return logWmax + np.log(sumw)


def density_at_zero(y, mu, p, phi):
return np.exp(-(mu ** (2 - p)) / (phi * (2 - p)))


def density_otherwise(y, mu, p, phi):
theta = _theta(mu, p)
logd = logW(y, p, phi) - np.log(y) + (1 / phi * (y * theta - kappa(mu, p)))
return np.exp(logd)


def series_density(y, mu, p, phi):
density = lazywhere(np.array(y) > 0,
(y, mu, p, phi),
f=density_otherwise,
f2=density_at_zero)
return density


if __name__ == '__main__':
from scipy import stats
n = stats.poisson.rvs(.1, size=10000000)
y = stats.gamma.rvs(.1, scale=30000, size=10000000)
y = n * y
mu = stats.gamma.rvs(10, scale=30, size=10000000)
import time
t = time.time()
l = series_density(y=y, mu=mu, p=1.5, phi=20)
print('That took {} seconds'.format(time.time() - t))
2 changes: 1 addition & 1 deletion statsmodels/genmod/families/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@
#from statsmodels.family.family import Gaussian, Family, Poisson, Gamma, \
# InverseGaussian, Binomial, NegativeBinomial
from .family import Gaussian, Family, Poisson, Gamma, \
InverseGaussian, Binomial, NegativeBinomial
InverseGaussian, Binomial, NegativeBinomial, Tweedie
271 changes: 270 additions & 1 deletion statsmodels/genmod/families/family.py
Original file line number Diff line number Diff line change
Expand Up @@ -1356,7 +1356,6 @@ def resid_dev(self, endog, mu, scale=1.):
return np.sign(endog - mu) * np.sqrt(tmp) / scale

def loglike(self, endog, mu, freq_weights=1., scale=1.):
# TODO: Check weights
r"""
The log-likelihood function in terms of the fitted mean response.

Expand Down Expand Up @@ -1432,3 +1431,273 @@ def resid_anscombe(self, endog, mu):
return ((hyp2f1(-self.alpha * endog) - hyp2f1(-self.alpha * mu) +
1.5 * ( endog**(2 / 3.) - mu**(2 / 3.))) /
(mu + self.alpha * mu**2)**(1 / 6.))


class Tweedie(Family):
"""
Tweedie family.

Parameters
----------
link : a link instance, optional
The default link for the Tweedie family is the log link when the
link_power is 0. Otherwise, the power link is default.
Available links are log and Power.
var_power : float, optional
The variance power.
link_power : float, optional

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.

shouldn't link_power be part of the link instance, instead of family?

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.

Ohh... you stumbled across something I noticed a while back, but never bothered to ask. I was copying from the other classes. I think it should really say link : a link class, optional. link is actually instantiated in the __init__ function.

Reading through statsmodels docs and examples we've always told people to say something like sm.GLM(endog=y, exog=x, family=sm.families.Gamma(link=sm.families.links.Log))

Is that the best approach? Personally, I agree with you it seems more natural to pass an instance of a class, not the class itself.

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 didn't compare this yet with the other classes.
We have some other issues open with the limitations of the current implementation.
I'll check this.

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.

Sounds good. You might also want to look at this line of code. I think we really might want if link is L.NegativeBinomial: I don't think that this works as currently written. (Mind you, I don't use Negative Binomial, so I'm not 100% sure here.)

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.

After an initial browsing through the families and link code:
Your tweedie implementation here follows the same pattern, except that there are no parameterized links yet.
I think this was refactored a long time ago to use only classes instead of instances for links.

I really prefer that we use link=link.Power(link_power) in the signature but that needs refactoring of the valid link check

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.

Ok. I will proceed with this, then. Perhaps the refactoring can be in a new PR. Hate to break something at this point.

The link power.

Attributes
----------
Tweedie.link : a link instance
The link function of the Tweedie instance
Tweedie.variance : varfunc instance
`variance` is an instance of statsmodels.family.varfuncs.Power
Tweedie.link_power : float
The power of the link function, or 0 if its a log link.
Tweedie.var_power : float
The power of the variance function.

See also
--------
statsmodels.genmod.families.family.Family
:ref:`links`

Notes
-----
Logliklihood function not implemented because of the complexity of
calculating an infinite series of summations. The variance power can be
estimated using the `estimate_tweedie_power` function that is part of the
`GLM` class.
"""
links = [L.log, L.Power]
variance = V.Power
safe_links = [L.log, L.Power]

def __init__(self, link=None, var_power=1., link_power=0):
self.var_power = var_power
self.link_power = link_power
self.variance = V.Power(power=var_power * 1.)
if link_power != 0 and not ((link is L.Power) or (link is None)):
msg = 'link_power of {} not supported specified link'
msg = msg.format(link_power)
raise ValueError(msg)
if (link_power == 0) and ((link is None) or (link is L.Log)):
self.link = L.log()
elif link_power != 0:
self.link = L.Power(power=link_power * 1.)
else:
self.link = link()

def _clean(self, x):
"""
Helper function to trim the data so that is in (0,inf)

Notes
-----
The need for this function was discovered through usage and its
possible that other families might need a check for validity of the
domain.
"""
return np.clip(x, 0, np.inf)

def deviance(self, endog, mu, freq_weights=1., scale=1.):
r"""
Returns the value of the deviance function.

Parameters
-----------
endog : array-like
Endogenous response variable
mu : array-like
Fitted mean response variable
freq_weights : array-like
1d array of frequency weights. The default is 1.
scale : float, optional
An optional scale argument. The default is 1.

Returns
-------
deviance : float
Deviance function as defined below

Notes
-----
When :math:`p = 1`,

.. math::

resid\_dev_i = \mu

when :math:`endog = 0` and

.. math::

resid\_dev_i = endog * \log(endog / \mu) + (\mu - endog)

otherwise.

When :math:`p = 2`,

.. math::

resid\_dev_i = (endog - \mu) / \mu - \log(endog / \mu)

For all other p,

.. math::

resid\_dev_i = endog ^{2 - p} / ((1 - p) * (2 - p)) -
endog * \mu ^{1 - p} / (1 - p) + \mu ^{2 - p} /
(2 - p)

Once :math:`resid\_dev_i` is calculated, then calculate deviance as

.. math::

D = \sum{2 * freq\_weights * resid\_dev_i}
"""
p = self.var_power
if p == 1:
dev = np.where(endog == 0,
mu,
endog * np.log(endog / mu) + (mu - endog))
elif p == 2:
endog1 = np.clip(endog, FLOAT_EPS, np.inf)
dev = ((endog - mu) / mu) - np.log(endog1 / mu)
else:
dev = (endog ** (2 - p) / ((1 - p) * (2 - p)) -
endog * mu ** (1-p) / (1 - p) + mu ** (2 - p) / (2 - p))
return np.sum(2 * freq_weights * dev)

def resid_dev(self, endog, mu, scale=1.):
r"""
Tweedie Deviance Residual

Parameters
----------
endog : array-like
`endog` is the response variable
mu : array-like
`mu` is the fitted value of the model
scale : float, optional
An optional argument to divide the residuals by scale. The default
is 1.

Returns
--------
resid_dev : array
The array of deviance residuals

Notes
-----
When :math:`p = 1`,

.. math::

resid\_dev_i = \mu

when :math:`endog = 0` and

.. math::

resid\_dev_i = endog * \log(endog / \mu) + (\mu - endog)

otherwise.

When :math:`p = 2`,

.. math::

resid\_dev_i = (endog - \mu) / \mu - \log(endog / \mu)

For all other p,

.. math::

resid\_dev_i = endog ^{2 - p} / ((1 - p) * (2 - p)) -
endog * \mu ^{1 - p} / (1 - p) + \mu ^{2 - p} /
(2 - p)
"""
p = self.var_power
if p == 1:
dev = np.where(endog == 0,
mu,
endog * np.log(endog / mu) + (mu - endog))
elif p == 2:
endog1 = np.clip(endog, FLOAT_EPS, np.inf)
dev = ((endog - mu) / mu) - np.log(endog1 / mu)
else:
dev = (endog ** (2 - p) / ((1 - p) * (2 - p)) -
endog * mu ** (1-p) / (1 - p) + mu ** (2 - p) / (2 - p))
return np.sign(endog - mu) * np.sqrt(2 * dev)

def loglike(self, endog, mu, freq_weights=1., scale=1.):
r"""
The log-likelihood function in terms of the fitted mean response.

Parameters
----------
endog : array-like
Endogenous response variable
mu : array-like
The fitted mean response values
freq_weights : array-like
1d array of frequency weights. The default is 1.
scale : float
The scale parameter. The default is 1.

Returns
-------
llf : float
The value of the loglikelihood function evaluated at
(endog,mu,freq_weights,scale) as defined below.

Notes
-----
This is not implemented because of the complexity of calculating an
infinite series of sums.
"""
return np.nan

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
-----
When :math:`p = 3`, then

.. math::

resid\_anscombe_i = (\log(endog) - \log(\mu)) / \sqrt{mu}

Otherwise,

.. math::

c = (3 - p) / 3

.. math::

resid\_anscombe_i = (1 / c) * (endog ^ c - \mu ^ c) / \mu ^{p / 6}
"""
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.))
Loading