Skip to content

FAQ-D: recreating a model, keywords #1732

Open

Description

@josef-pkt

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

  1. josef-pkt commented on Jun 12, 2021

    @josef-pkt
    MemberAuthor

    good description (reading it again when I need it)

    currently file search finds 59 matches for _get_init_kwds across all parts of statsmodels. So, this seems to work fine.
    bug: GenericLikelihood mixin bootstrap method does not use this #5169

  2. josef-pkt commented on Jul 11, 2021

    @josef-pkt
    MemberAuthor

    possible bugs with having missing_idx, formula and design_info in _init_keys
    #7569 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions