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
15 changes: 15 additions & 0 deletions statsmodels/base/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,21 @@ def __init__(self, endog, exog=None, **kwargs):
self._data_attr = []
self._data_attr.extend(['exog', 'endog', 'data.exog', 'data.endog',
'data.orig_endog', 'data.orig_exog'])
# store keys for extras if we need to recreate model instance
# we don't need 'missing', maybe we need 'hasconst'
self._init_keys = list(kwargs.keys())
if hasconst is not None:
self._init_keys.append('hasconst')


def _get_init_kwds(self):
"""return dictionary with extra keys used in model.__init__
"""
kwds = dict(((key, getattr(self, key, None))
for key in self._init_keys))

return kwds


def _handle_data(self, endog, exog, missing, hasconst, **kwargs):
data = handle_data(endog, exog, missing, hasconst, **kwargs)
Expand Down
20 changes: 18 additions & 2 deletions statsmodels/discrete/discrete_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -657,6 +657,16 @@ def _check_inputs(self, offset, exposure, endog):
raise ValueError("exposure is not the same length as endog")
self.exposure = exposure


def _get_init_kwds(self):
# this is a temporary fixup because exposure has been transformed
# see #1609
kwds = super(CountModel, self)._get_init_kwds()
if 'exposure' in kwds and kwds['exposure'] is not None:
kwds['exposure'] = np.exp(kwds['exposure'])
return kwds


#TODO: are these two methods only for Poisson? or also Negative Binomial?
def predict(self, params, exog=None, exposure=None, offset=None,
linear=False):
Expand Down Expand Up @@ -1787,6 +1797,9 @@ def __init__(self, endog, exog, loglike_method='nb2', offset=None,
self._initialize()
if loglike_method in ['nb2', 'nb1']:
self.exog_names.append('alpha')
# store keys for extras if we need to recreate model instance
# we need to append keys that don't go to super
self._init_keys.append('loglike_method')

def _initialize(self):
if self.loglike_method == 'nb2':
Expand Down Expand Up @@ -2137,10 +2150,13 @@ def llr_pvalue(self):

@cache_readonly
def llnull(self):

model = self.model
kwds = model._get_init_kwds()
#TODO: what parameters to pass to fit?
null = model.__class__(model.endog, np.ones(self.nobs)).fit(disp=0)
return null.llf
mod_null = model.__class__(model.endog, np.ones(self.nobs), **kwds)

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.

Couldn't you just attach exposure and offset here without going through the init_keys business?

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.

I don't like adding ifs to a superclass that checks attributes that are only available in some subclasses.
I thought about just adding the method to the CountModels.

But I want a generic solution. Here I don't need any special code for loglike_method in NegativeBinomial except registering the keyword.
plus, we will need the same for other things see #1093 (e.g. diagnostic tests)

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.

You have the generic solution, but you don't need it. I'm not saying take out init_keys, but you don't really need it here to check for parameters that are attached as attributes already.

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.

We need it. Generically, we don't know which attributes have been attached from the model.__init__ signature.
This should also automatically catch weights in WLS, rho in GLSAR, ...
I got started with this a few days ago because I added an attribute in a Poisson subclass that broke llnul called by summary(). I fixed that in a different way, but it's going to happen all the time.

The alternative to a generic solution, requires lot's of code that handles special cases.

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.

Thinking about it a bit, it's really not all that generic. You still need to know what keys you're looking for in _init_keys.

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.

Yes that's a bug. My point is that only CountModels will have an exposure, so it should be a CountModel 'feature'. NegativeBinomial came after Poisson, so there's not the right amount of code sharing yet in CountModel.

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.

The nice point of _init_keys is that we don't care what keywords names where added.
Whether they are exposure or weights or loglike_method or fixed_params_mask or order or ..., the code is generic as long as the original argument value (after data handling (*)) has been attached to the model instance as an attribute.

(*) to get ahead: I'm thinking of this for internal usage as for the use cases in #1093 where we don't need the formula or pandas metainformation.
I haven't seen or thought about any use case that might need pandas or formula information. That' much further down the road if we need it.

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 understand the reason for _init_keys. But you've hard-coded exposure here. That's not generic. Admittedly, it's because we log it in the __init__ and store the logged version. So...either fix that as part of this PR too (and add logs whenever exposure is used / fix the hard-coded exposure or offset only) or only check for exposure in CountModel. That's my main point. My other point is that if you're going to introduce those changes in this (bug fix) PR, then go the whole nine yards and implement the _get_keys or whatever. This could've been a quick two line fix to close the bug but now I'd like to see the other issues fixed in this PR, if we're going to start the other changes.

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.

I don't want to fix log(exposure) in this PR. it's not backwards compatible and needs better design (for example merge _offset_all = np.exp(exposure) + offset to avoid the repeated sum).

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.

Why is it not backwards compatible? Nothing the user does would changed. I doubt there are people out there with pickled exposure variables, but we could add a warning.

This PR either 1) fixes the bug its for only 2) Goes all the way and solve 3-4 outstanding, related issues or 3) Solves 1.5 issues and adds a hack for checking exposure in models where we don't necessarily need to.

Right now it's 3, but it'd make more sense to do 1 or 2 I think. In any case, we've talked about this PR more than it warrants.

res_null = mod_null.fit(disp=0)
return res_null.llf

@cache_readonly
def fittedvalues(self):
Expand Down
6 changes: 3 additions & 3 deletions statsmodels/discrete/tests/results/results_discrete.py
Original file line number Diff line number Diff line change
Expand Up @@ -942,9 +942,9 @@ def negativebinomial_geometric_bfgs(self):
self.df_model = 9.0
self.df_resid = 20180.0
self.llf = -43540.58000589021
self.llnull = -44199.27443567125
self.llr = 1317.3888595620811
self.llr_pvalue = 5.4288002863296022e-278
self.llnull = -44586.650971362695 # old value -44199.27443567125
self.llr = 2092.1425097129977 # old value 1317.3888595620811
self.llr_pvalue = 0 # old value 5.4288002863296022e-278
self.fittedvalues = [ 0.89348994, 0.89348994, 0.89348994,
0.89348994, 0.89348994, 0.9365745 , 0.9365745 , 0.9365745 ,
0.9365745 , 0.9365745 ]
Expand Down
4 changes: 2 additions & 2 deletions statsmodels/discrete/tests/test_discrete.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
import os
import numpy as np
from numpy.testing import (assert_, assert_raises, assert_almost_equal,
assert_equal, assert_array_equal)
assert_equal, assert_array_equal, assert_allclose)

from statsmodels.discrete.discrete_model import (Logit, Probit, MNLogit,
Poisson, NegativeBinomial)
Expand Down Expand Up @@ -53,7 +53,7 @@ def test_params(self):
assert_almost_equal(self.res1.params, self.res2.params, DECIMAL_4)

def test_conf_int(self):
assert_almost_equal(self.res1.conf_int(), self.res2.conf_int, DECIMAL_4)
assert_allclose(self.res1.conf_int(), self.res2.conf_int, rtol=8e-5)

def test_zstat(self):
assert_almost_equal(self.res1.tvalues, self.res2.z, DECIMAL_4)
Expand Down
29 changes: 29 additions & 0 deletions statsmodels/discrete/tests/test_sandwich_cov.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
exog_data = data['yr_con op_75_79'.split()]
exog = add_constant(exog_data, prepend=False)
group = np.asarray(data['ship'], int)
exposure = np.asarray(data['service'])


# TODO get the test methods from regression/tests
Expand Down Expand Up @@ -69,6 +70,13 @@ def get_robust_clu(cls):
cls.corr_fact = np.sqrt(corr_fact)


def test_oth(self):
res1 = self.res1
res2 = self.res2
assert_allclose(res1._results.llf, res2.ll, 1e-4)
assert_allclose(res1._results.llnull, res2.ll_0, 1e-4)


class TestPoissonClu(CheckCountRobustMixin):

@classmethod
Expand All @@ -79,6 +87,16 @@ def setup_class(cls):
cls.get_robust_clu()


class TestPoissonCluExposure(CheckCountRobustMixin):

@classmethod
def setup_class(cls):
cls.res2 = results_st.results_poisson_exposure_clu #nonrobust
mod = smd.Poisson(endog, exog, exposure=exposure)
cls.res1 = mod.fit(disp=False)
cls.get_robust_clu()


class TestNegbinClu(CheckCountRobustMixin):

@classmethod
Expand All @@ -89,6 +107,17 @@ def setup_class(cls):
cls.get_robust_clu()


# TODO: check what's going on with the params
class T_estNegbinCluExposure(CheckCountRobustMixin):

@classmethod
def setup_class(cls):
cls.res2 = results_st.results_negbin_exposure_clu #nonrobust
mod = smd.NegativeBinomial(endog, exog, exposure=exposure)
cls.res1 = mod.fit(disp=False)
cls.get_robust_clu()


# mod_nbe = smd.NegativeBinomial(endog, exog, exposure=data['service'])
# res_nbe = mod_nbe.fit()
# mod_nb = smd.NegativeBinomial(endog, exog)
Expand Down