Repository navigation
Description
How can we create a new model with maybe different data that uses the same keywords in the model creation as a given model?
for motivation see #1093
usage
init_kwds = model._get_init_kwds()
mod_new = self.__class__(endog_new, exog_new, **init_kwds)
Warning _get_init_kwds returns a reference to the attributes attached to the model. If those are mutable, for example arrays like offset, exposure, weights, then changes to them will also change the underlying arrays of the given model which will cause problems or hard to find errors.
not sure if we need the copy if we want to modify the init_kwd arrays, TODO: more unit tests
import copy
init_kwds = copy.copy(self._get_init_kwds())
del init_kwds['offset']
mod_constr = self.__class__(endog, exogp_st, offset=offset, **init_kwds)
How does it work?
Each model needs to register the names of extra keyword arguments in the __init__ of the model class in _init_keys.
The base.Model registers all keywords that have been handed to it in super calls. This happens for example with weights in WLS or offset and exposure in count models and GLM.
_get_init_kwds returns a dictionary with the model attributes as values. In some cases it needs to transform or recreate the original array, for example exposure is internally stored after taking the log.
As an example, GLM has to add the family to the _init_keys: we have in GLM.__init__:
# register kwds for __init__, offset and exposure are added by super
self._init_keys.append('family')
then we have
>>> mod1._init_keys
['exposure', 'offset', 'family', 'family']
>>> mod1._get_init_kwds()
{'offset': None, 'family': <statsmodels.genmod.families.family.Binomial object at 0x052E7B30>, 'exposure': None}
Warning: This is a new feature and has been used only in a few tested cases so far.
No comprehensive test suite and not all models have registered their init_keys yet.
Activity
josef-pkt commentedon Jun 12, 2021
good description (reading it again when I need it)
currently file search finds 59 matches for
_get_init_kwdsacross all parts of statsmodels. So, this seems to work fine.bug: GenericLikelihood mixin
bootstrapmethod does not use this #5169josef-pkt commentedon Jul 11, 2021
possible bugs with having missing_idx, formula and design_info in
_init_keys#7569 (comment)