Skip to content

SUMM/REF/ENH: GenericLikelihoodModel needs updating #4679

Open

Description

@josef-pkt

triggered by #4676 bootstrap breaks if exog is None.

AFAICS, GenericLikelihoodModel hasn't been updated in 5 years. It needs a general update to catch up with changes in the rest of statsmodels, some enhancements (cov_type='bootstrap') and there are several open issues.

two main updates to catch up with change in patter

  • _init_keys, and _get_init_kwds for recreating the model. This only covers keyword for model.__init__ while cloneattr can pick any attribute.

  • cov_type: AFAIR the inherited robust cov_types work, if the relevant methods like score_obs are specified in the subclass. We can extend this to allow for bootstrap and remove the "old fashionedly" or wrongly named covjac, covjhj and their bse versions from ResultsMixin.

  • bootstrap does not permute extra init arrays, e.g. if we have weights or offset.

  • bootstrap should compute cov_params and not just bse

  • bootstrap start_params: we could use the params that were estimated by fit,
    and remove any detour through cloneattr mentioned in code comments.

different type of bootstrap sampling schemes, e.g. residual bootstrap could be added as bootstrap/cov_kwds options.

other changes to bootstrap are a separate issue, e.g. bootstrap for hypothesis tests or confidence intervals based on pivotal statistic need separate methods and don't fit in the current model-results structure directly.

Some models as possible test cases or miscmodels cases are

Note, beta regression can have two exog which would need a corrected bootstrap.

about the name
Why did I use GenericLikelihoodModelResults instead of GenericLikelihoodResults?
Should we still rename it?
There is no way to make it backwards compatible during deprecation, but it will rarely be used by class name.

Activity

  1. added this to the 0.10 milestone on May 22, 2018
  2. josef-pkt commented on Sep 7, 2018

    @josef-pkt
    MemberAuthor

    related, but I haven't tried to figure out the detail:

    It looks like the cloneattr has/had a bug
    037d135
    If it never worked correctly and doesn't have any existing usecases, then we could remove it in refactoring without backwards compatibility problems.
    (if hascloneattr is always falls, then we never actually attach any of the cloneattr.)

    What's an example/test case for cloneattr?

  3. josef-pkt commented on Sep 7, 2018

    @josef-pkt
    MemberAuthor

    inconsistency in automatic setting of df_model, df_resid
    see #5143 (comment)

    I think the current behavior by defaulting to df_model = k_exog is wrong, it should be len(params) and easily overridable by users in case it differs from len(params), e.g. if constraints are imposed or prior transformation like demeaning has to be taken into account.

  4. josef-pkt commented on Sep 9, 2018

    @josef-pkt
    MemberAuthor

    summary missing cov_type
    The GenericLikelihoodModelResults.summary does not show cov_type and might need also other updating.
    using cov_type='hc0' the method should/could be M-estimator or QMLE, we don't actually require a proper, correctly specified likelihood function. (see comments in #5143

  5. josef-pkt commented on Jun 12, 2021

    @josef-pkt
    MemberAuthor

    ResultMixin still has old attributes for robust cov and bse that predate cov_type, covjac (is OPG0, covjhj (is HC0, and a misspelling of hjjh)

    those can be deleted, If those are available, then fit cov_type should also be available (require score_obs)

    Another difference to other models:
    The evaluated score_obs and hessian are cached in score_obsv and hessv.
    We don't have a general policy for caching hessian yet, it's mostly in normalized_cov_params, score_obs can be large

  6. josef-pkt commented on Jul 9, 2021

    @josef-pkt
    MemberAuthor

    class hierarchy and super

    GenericLikelihoodModelResults.__init__ does not call super and has no code for cov_type.
    the way it works is that fit calls super which returns a LikelihoodModelResults instance created in LikelihoodModel.fit.
    The LikelihoodModelResults instance is used in GenericLikelihoodModelResults.__init__ or relevant results classes. Attributes are copied directly from the LikelihoodModelResults instance with self.__dict__.update(mlefit.__dict__)

    This is based on the design of DiscreteResults class which originated this pattern. DiscreteResults.__init__ does the same, no super call and attribute copying, but it has separate cov_type handling.
    But I guess the cov_type handling there should now never apply:

            if not hasattr(self, 'cov_type'):
                # do this only if super, i.e. mlefit did not already add cov_type
                # robust covariance
    

    This might be left over from before cov_type handling was added to the base LikelihoodModelResults class

  7. josef-pkt commented on Jul 9, 2021

    @josef-pkt
    MemberAuthor

    statespace.mlemodel.MLEModel and MLEResults follow a similar pattern as DiscreteResults.
    It uses the super().fit results instance from the optimization and dispatches to appropriate Results classes with it.
    However, it has explicit attribute handling instead of the full copying self.__dict__.update(mlefit.__dict__).
    The fit method res.mlefit = mlefit attaches the super results instance instead of copying it.

    statespace.mlemodel results class inherits from tsa.base.TimeSeriesModelResults(base.LikelihoodModelResults) which has __init__ that follows the base.LikelihoodModelResults pattern (no results class in args)
    TimeSeriesModelResults.__init__ just calls the super().__init__

    statespace MLEResults.__init__ explicitly calls the super

    tsbase.TimeSeriesModelResults.__init__(self, model, params,
                                                   normalized_cov_params=None,
                                                   scale=scale)
    
  8. josef-pkt commented on Jul 9, 2021

    @josef-pkt
    MemberAuthor

    more structure

    • hessian is computed in LikelihoodModel.fit and added as normalized_cov_params to LikelihoodModelResults
      also attaches optimization results and options mle_retvals and mle_settings
    • LikelihoodModelResults.__init__ calls super attaches args and handles cov_type
    • the base class Results.__init__ attaches kwargs and calls initialize, which only attaches params, model and (if available) k_constant.

    This means basic LikelihoodModelResults only has a few attributes set in __init__

    LikelihoodModelResults.__init__ does not forward kwargs to super, so all kwargs except use_t and cov_type related are ignored.
    this might be a BUG We should be able to add attributes through init instead of retro-fitting results instances in sub classes.

  9. josef-pkt commented on Jul 9, 2021

    @josef-pkt
    MemberAuthor

    related Poisson.fit skips next super class to avoid creating a generic wrapped CountResults instance
    cntfit = super(CountModel, self).fit(...

    DiscreteModel fit just returns a base LikelihoodModelResults instance, without wrapper

    This means we also need to pay attention to which classes return plain results instances and which return wrapped instances.

    GenericZeroInflated does not avoid the CountResults wrapper and needs to use mlefit._results

            mlefit = super(GenericZeroInflated, self).fit(...)
            zipfit = self.result_class(self, mlefit._results)
            result = self.result_class_wrapper(zipfit)
    

    One possible rule could be that all classes that don't return a requested self.result_class, self.result_class_wrapper should return a results instance that is not wrapped.
    e.g. CountModel.fit should not add the wrapper

    GenericLikelihoodModel.fit does not use a wrapper
    genericmlefit = results_class(self, mlefit)

  10. josef-pkt commented on Jul 16, 2021

    @josef-pkt
    MemberAuthor

    problem with df_model, df compared to null model for beta regression
    #7584 (comment)

  11. tgbrooks commented on Sep 28, 2021

    @tgbrooks
    Contributor
    * hessian is computed in LikelihoodModel.fit and added as `normalized_cov_params` to LikelihoodModelResults
      also attaches optimization results and options mle_retvals and mle_settings
    

    Does this mean that PHRegResults will get the mle_retvals and mle_settings values? This would be helpful to me as you currently can't check for convergence.

  12. josef-pkt commented on Sep 28, 2021

    @josef-pkt
    MemberAuthor

    mle_retvals not automatically added in all cases.
    For example it was, or maybe still is, inconsistent in GLM.

    The presence of mle_retvals needs to be checked. I never looked at those details for PHRegResults.
    I think it should be automatically added in plain fit that just use the scipy optimizers.

  13. josef-pkt commented on Sep 30, 2021

    @josef-pkt
    MemberAuthor

    the GenericLikelihoodModel still uses nparams (which is also in the doc examples)
    self.nparams = len(self.exog_names)

    The results class checks for k_params
    k_params = len(mlefit.params)
    but it's used only for checking df_model, df_resid

    GenericLikelihoodModel.initialize does not take extra params into account, and doesn't cross-check this with other information.

            if self.exog is not None:
                # assume constant
                er = np.linalg.matrix_rank(self.exog)
                self.df_model = float(er - 1)
                self.df_resid = float(self.exog.shape[0] - er)
    

    we get the warning that df don't match k_params, but they are not automatically corrected.

    maybe make k_extra public, as it is used in count models for NB and GPP

    Also the above model initialize code is also wrong if we have more than 1 exog, e.g. in multipart models like BetaModel.
    I think it's now better to drop the code that initializes df_model df_resid at GenericLikelihoodModel.__init__.
    If the user doesn't specify those, then we let the results class guess and warn.

  14. josef-pkt commented on Sep 30, 2021

    @josef-pkt
    MemberAuthor

    Using the constraints with mask as in TModel, params for the optimization is reduced length

    summary is also for the optimization parameters, ie. the restricted df is not shown.
    We could add an extra line for the summary table, or add separately the information that is was estimated under constraint of fixing one parameter. "df_fixed=3"

    In contrast, fit_constrained shows the original parameters, but in that case linear constraints are allowed and the transformed parameters don't have much of an interpretation.

  15. josef-pkt commented on Oct 1, 2021

    @josef-pkt
    MemberAuthor

    We could add a flag attribute to GenericLikelihoodModel that complex step derivatives are allowed.
    Users could either provide it as __init__ arg, specify in initialize or set/change the attribute
    (discussion on twitter about possibly low precision of standard difference derivatives.)

  16. josef-pkt commented on Oct 1, 2021

    @josef-pkt
    MemberAuthor

    also a PredictMixin would be nice,
    to add fittedvalues, resid (resid_pearson ?) and whatever residual analysis is useful
    e.g. regression model with heteroscedasticity or other mean parameterized models can still have standard fittedvalues and resid.

  17. josef-pkt commented on Jan 6, 2022

    @josef-pkt
    MemberAuthor

    example for usage of GenericLikelihoodModel
    https://github.com/statcompute/py_countreg/blob/main/codes/py_countreg.py

    nloglikeobs needs long deprecation and we need to remove it from recipes and doc examples, so it won't be the advertised pattern anymore.

  18. josef-pkt commented on Sep 29, 2022

    @josef-pkt
    MemberAuthor

    bump

    deprecate old cov and related functions, e.g. covjhj
    they show up in docs of inheriting classes for example BetaModel https://www.statsmodels.org/dev/generated/statsmodels.othermod.betareg.BetaResults.html

  19. modified the milestones: 0.10, 0.15 on Sep 29, 2022
  20. josef-pkt commented on Oct 28, 2022

    @josef-pkt
    MemberAuthor

    another thought (not checked)

    I guess the Null model will not be available unless a subclass of GenericLikelihood explicitly specified it.
    Context: do we need df_model and df_null/k_null generically ? #8475

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions