Skip to content
Closed
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
36 changes: 14 additions & 22 deletions statsmodels/genmod/families/family.py
Original file line number Diff line number Diff line change
Expand Up @@ -457,10 +457,11 @@ def resid_dev(self, endog, mu, scale=1.):

Notes
--------
`resid_dev` = (`endog` - `mu`)/sqrt(variance(`mu`))
`resid_dev` = (`endog` - `mu`) / sqrt(variance(`mu`) * `scale`)
"""

return (endog - mu) / np.sqrt(self.variance(mu))/scale
return (endog - mu) / np.sqrt(self.variance(mu) * scale)


def deviance(self, endog, mu, scale=1.):
"""
Expand All @@ -482,9 +483,10 @@ def deviance(self, endog, mu, scale=1.):

Notes
--------
`deviance` = sum((endog-mu)**2)
`deviance` = sum((endog-mu)**2 / variance(mu)) / scale
"""
return np.sum((endog-mu)**2)/scale
return np.sum((endog - mu)**2 / self.variance(mu)) / scale


def loglike(self, endog, mu, scale=1.):
"""
Expand All @@ -507,27 +509,17 @@ def loglike(self, endog, mu, scale=1.):

Notes
-----
If the link is the identity link function then the
loglikelihood function is the same as the classical OLS model.
llf = -(nobs/2)*(log(SSR) + (1 + log(2*pi/nobs)))
where SSR = sum((endog-link^(-1)(mu))**2)

If the links is not the identity link then the loglikelihood
function is defined as
The loglikelihood function is defined as
llf = sum((`endog`*`mu`-`mu`**2/2)/`scale` - `endog`**2/(2*`scale`) - \
(1/2.)*log(2*pi*`scale`))
"""
if isinstance(self.link, L.Power) and self.link.power == 1:
# This is just the loglikelihood for classical OLS
nobs2 = endog.shape[0]/2.
SSR = ss(endog-self.fitted(mu))
llf = -np.log(SSR) * nobs2
llf -= (1+np.log(np.pi/nobs2))*nobs2
return llf
else:
# Return the loglikelihood for Gaussian GLM
return np.sum((endog * mu - mu**2/2)/scale - endog**2/(2 * scale)
- .5*np.log(2 * np.pi * scale))

va = scale * self.variance(mu)

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 scale should be the same as self.variance(mu) already in the common, regular use case, but we should be able to fix scale independently of variance(mu)

I'm not sure yet

sresid = (endog - mu)**2 / va
llf = -np.sum(np.log(2 * np.pi * va)) / 2
llf -= np.sum(sresid) / 2
return llf


def resid_anscombe(self, endog, mu):
"""
Expand Down
73 changes: 47 additions & 26 deletions statsmodels/genmod/generalized_linear_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -536,7 +536,16 @@ def _update_history(self, tmp_result, mu, history):
history['deviance'].append(self.family.deviance(self.endog, mu))
return history

def estimate_scale(self, mu):

def _estimate_x2_scale(self, mu):
"""
chi^2 estimate of the scale parameter.
"""
resid = self.endog - mu
return (np.power(resid, 2) / self.family.variance(mu)).sum() / self.df_resid


def estimate_scale(self, mu, scaletype=None):
"""
Estimates the dispersion/scale.

Expand All @@ -545,46 +554,54 @@ def estimate_scale(self, mu):
Parameters
----------
mu : array
mu is the mean response estimate
`mu` is the mean response estimate
scaletype : string or float, optional
`scaletype` can be 'X2', 'dev', 'mle', or a float The
default value is None, which uses the model `scaletype`
attribute which is set when calling `fit`.

Returns
-------
Estimate of scale

Notes
-----
The default scale for Binomial and Poisson families is 1. The default
for the other families is Pearson's Chi-Square estimate.
Estimate of the scale parameter

See also
--------
statsmodels.glm.fit for more information
"""
if not self.scaletype:
if scaletype is None:
scaletype = self.scaletype

if not scaletype:
if isinstance(self.family, (families.Binomial, families.Poisson)):
return 1.
else:
resid = self.endog - mu
return ((np.power(resid, 2) / self.family.variance(mu)).sum()
/ self.df_resid)

if isinstance(self.scaletype, float):
return np.array(self.scaletype)

if isinstance(self.scaletype, str):
if self.scaletype.lower() == 'x2':
resid = self.endog - mu
return ((np.power(resid, 2) / self.family.variance(mu)).sum()
/ self.df_resid)
elif self.scaletype.lower() == 'dev':
return self.family.deviance(self.endog, mu)/self.df_resid
return self._estimate_x2_scale(mu)

if isinstance(scaletype, float):
return np.array(scaletype)

if isinstance(scaletype, str):
if scaletype.lower() == 'x2':
return self._estimate_x2_scale(mu)
elif scaletype.lower() == 'dev':
return self.family.deviance(self.endog, mu) / self.df_resid
elif scaletype.lower() == 'mle':
if isinstance(self.family, families.Gaussian):
resid = self.endog - mu
return np.mean(resid**2)
elif isinstance(self.family, (families.Binomial, families.Poisson)):
return 1.
else:
# TODO: this may not be the MLE but it produces
# llf results that match R/Stata.
return self._estimate_x2_scale(mu)
else:
raise ValueError("Scale %s with type %s not understood" %
(self.scaletype, type(self.scaletype)))
(scaletype, type(scaletype)))

else:
raise ValueError("Scale %s with type %s not understood" %
(self.scaletype, type(self.scaletype)))
(scaletype, type(scaletype)))

def predict(self, params, exog=None, exposure=None, offset=None,
linear=False):
Expand Down Expand Up @@ -1098,7 +1115,11 @@ def llnull(self):
@cache_readonly
def llf(self):
_modelfamily = self.family
val = _modelfamily.loglike(self._endog, self.mu, scale=self.scale)
scale = self.scale
# Always use MLE scale estimate for the log likelihood function.
if self.model.scaletype != 'mle':
scale = self.model.estimate_scale(self.mu, scaletype='mle')
val = _modelfamily.loglike(self._endog, self.mu, scale=scale)
return val

@cache_readonly
Expand Down