(This is not a problem of simply adding a method to a given class)
What I Want to Achieve
Using Maximum Likelihood Estimation (Generic models)
of statsmodels
, I implemented an MLE estimator, and want to add a user-made method, which uses exog
and params
, to a class of fitted result (not an instance), e.g., using classmetod()
. But an error occurs because those variables are not available. How can I achieve my goal?
Let me explain what I have done so far, using an example from here.
(I had a look at this for adding a method to an existing class.)
Example
import numpy as np
from scipy import stats
import statsmodels.api as sm
from statsmodels.base.model import GenericLikelihoodModel,GenericLikelihoodModelResults
data = sm.datasets.spector.load_pandas()
endog = data.endog
exog = sm.add_constant(data.exog)
class MyProbit(GenericLikelihoodModel):
def loglike(self, params):
exog = self.exog
endog = self.endog
q = 2 * endog - 1
return stats.norm.logcdf(q*np.dot(exog, params)).sum()
# my attemp starts ---------------
def my_method(self):
return print(self.exog, self.params, self.model)
GenericLikelihoodModelResults.my_method = classmethod(my_method)
# my attemp ends ----------------
res = MyProbit(endog, exog).fit()
res.my_method()
This generates the following error.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-29-a2d4f516bca7> in <module>
23 res = MyProbit(endog, exog).fit()
24
---> 25 res.my_method()
<ipython-input-29-a2d4f516bca7> in my_method(self)
17 # my attemp start ---------------
18 def my_method(self):
---> 19 return print(self.exog, self.params, self.model)
20 GenericLikelihoodModelResults.my_method = classmethod(my_method)
21 # my attemp ends ----------------
AttributeError: type object 'GenericLikelihoodModelResults' has no attribute 'exog'
This suggests that exog
(similarly, endog
and params
) are not available in GenericLikelihoodModelResults
. Indeed, adding the following code shows none of exog
, etc.
def my_check(self):
return dir(self)
GenericLikelihoodModelResults.my_check = classmethod(my_check)
This is despite the fact that they are available at an instance, as one can check using
res.exog
res.endog
res.params
I appreciate any constructive suggestions/comments.