Skip to content

BUG/ENH: add warning for unknown kwargs in model.__init__ #7741

Closed

Description

@josef-pkt

update fragility when adding new keywords
One strong reason to add kwarg check is that users might run different versions of statsmodels. If we add a new keyword, then it will work on the new version of statsmodels, but silently ignore it when running the same code with an older version.


Just came up on the mailing list

using GLM(... weights=myweights) is not doing anything.
kwarg is just swallowed without warning

I think we can check for the keywords that base models support liike missing, ...

Raising an exception is to strict because it's too fragile, e.g. automatic exog_xxx handling

if kwargs is None:
    self.check_kwargs(kwargs)

only works on leaf models to avoid problems with subclassing.

My guess is that it's pretty safe adding it to GLM. discrete is messier because of the larger class hierarchy (and we don't have offset in all those models yet.)

a bit related: I would rather drop the "subset" keyword. I guess there are no unit tests for the case with extra arrays in __init__.
(I never even used it.)

Activity

  1. added this to the 0.13 milestone on Sep 21, 2021
  2. josef-pkt commented on Sep 21, 2021

    @josef-pkt
    MemberAuthor

    I think the GLM case is still possible for 0.13. It would be just a noisy warning if we miss valid cases.

  3. josef-pkt commented on Sep 22, 2021

    @josef-pkt
    MemberAuthor

    whitelist for model init kwargs might require work

    for example Model.from_formula has

            kwargs.update({'missing_idx': missing_idx,
                           'missing': missing,
                           'formula': formula,  # attach formula for unpckling
                           'design_info': design_info})
            mod = cls(endog, exog, *args, **kwargs)
    

    missing_idx, formula and design_info are internally use kwargs

    from_formula has explicit keyword, subset, drop_cols, that are not put in kwargs for model init, AFAICS

  4. josef-pkt commented on Sep 22, 2021

    @josef-pkt
    MemberAuthor

    trying it out in GLM

            kwargs_allowed = ["missing", 'missing_idx', 'formula', 'design_info',
                              'n_trials', "hasconst", "scale", "method"]
            kwargs_invalid = [i for i in kwargs if i not in kwargs_allowed]
            if kwargs_invalid:
                warnings.warn(UserWarning("unknown kwargs" +
                                          repr(kwargs_invalid)))
    

    This works for the genmod/tests except test_gee_glm.py, wee below.

    I haven't checked why there are "scale", "method" in the call to GLM.__init__.

    I guess the test_gee_glm.py warnings are because GEE keywords or kwargs are used in GLM kwargs.

    statsmodels/genmod/tests/test_gee_glm.py: 4 warnings
      ...\statsmodels\statsmod
    els\genmod\generalized_linear_model.py:296: UserWarning: unknown kwargs['groups'
    , 'time', 'weights', 'dep_data']
        warnings.warn(UserWarning("unknown kwargs" +
    
    statsmodels/genmod/tests/test_gee.py::test_quasipoisson[False]
    statsmodels/genmod/tests/test_gee.py::test_quasipoisson[True]
      ...\statsmodels\statsmod
    els\genmod\generalized_linear_model.py:296: UserWarning: unknown kwargs['groups'
    , 'time', 'weights', 'dep_data', 'cov_type']
        warnings.warn(UserWarning("unknown kwargs" +
    
  5. josef-pkt commented on Sep 23, 2021

    @josef-pkt
    MemberAuthor

    scale and method shouldn't be there

    test_glm uses method and scale in __init__ instead of in fit.
    I guess they don't do anything.

    class TestWtdGlmGammaNewton(CheckWtdDuplicationMixin):
        @classmethod
        def setup_class(cls):
            '''
            Tests Gamma family with log link.
            '''
            super(TestWtdGlmGammaNewton, cls).setup_class()
            family_link = sm.families.Gamma(sm.families.links.log())
            cls.res1 = GLM(cls.endog, cls.exog,
                            freq_weights=cls.weight,
                            family=family_link,
                            method='newton').fit()
            cls.res2 = GLM(cls.endog_big, cls.exog_big,
                            family=family_link,
                            method='newton').fit()
    
    
    class TestWtdGlmGammaScale_X2(CheckWtdDuplicationMixin):
        @classmethod
        def setup_class(cls):
            '''
            Tests Gamma family with log link.
            '''
            super(TestWtdGlmGammaScale_X2, cls).setup_class()
            family_link = sm.families.Gamma(sm.families.links.log())
            cls.res1 = GLM(cls.endog, cls.exog,
                            freq_weights=cls.weight,
                            family=family_link,
                            scale='X2').fit()
    

    The GEE items are "real"

    GEE subclasses GLM and hands GEE keywords to super, which will go through main processing in Model or LikelihoodModel.
    Using self._init_keys to check for allowed keywords does not work because super call in GEE.__init__ happens before _init_keys are set as attributes. I guess we can change that order.

  6. josef-pkt commented on Sep 23, 2021

    @josef-pkt
    MemberAuthor

    general problem with subclasses that can add their own keywords as kwargs. Those are not invalid in the subclass.

    change in condition: only raise if we have an instance of the current class.

    If I change it to the following in GLM.__init__, then all genmod/tests pass without warning on kwargs.

            if kwargs_invalid and type(self) == GLM:
                warnings.warn(UserWarning("unknown kwargs" +
                                          repr(kwargs_invalid)))
    

    gam/tests also pass with this, GLMGam is another subclass of GLM.
    It also passes without the type check, so it doesn't send anything extra through super.

  7. josef-pkt commented on Sep 24, 2021

    @josef-pkt
    MemberAuthor

    An alternative implementation would be to have
    kwargs_allowed = kwargs_generic + hidden subclass kwargs like n_trials

    keys_allowed = self._init_keys + kwargs_allowed
    which can be checked in a base class.

    That would check that all keywords are either in the _init_keys or the kwargs list.
    It would force subclasse to specify _init_keys before any super call or calls to a _check_kwargs method.

    Aside:
    We don't have formula information in _init_keys.
    Our usecase was not rebuilding a full model but building an auxiliary model that matches the main model in the relevant arrays but without "meta-information".

  8. josef-pkt commented on Sep 24, 2021

    @josef-pkt
    MemberAuthor

    Unsupported base kwargs

    In my current version I have in base.Model

    kwargs_allowed = [
            "missing", 'missing_idx', 'formula', 'design_info', "hasconst",
            ]
    

    The main problem is that missing might not work correctly in all models.
    At least we don't have comprehensive unit tests.

    Main problem is with extra arrays or multipart models which might not all go through the joint missing handling.
    It's also possibly disallowed with categorical endog.
    GLMGAM takes a penalized spline instance as extra keyword where user controls the original x used for spline basis construction.

    This requires to go through all models that don't have unit tests with missing values.
    Then, we could disallow "missing" as a valid kwarg. (or fix the missing missing support)

    (.dropna() for users is much easier than doing it inside statsmodels.)

    Making a mistake in warning about missing support is less serious. Either missing="drop" works or it will raise at some point with shape mismatch. I don't think it can silently do the wrong thing.

  9. josef-pkt commented on Sep 24, 2021

    @josef-pkt
    MemberAuthor

    Another problem: model subclasses that don't define __init__

    example: discrete
    Logit and Probit, and also MultinomialModel, don't have __init__
    They use __init__ inherited from BinaryModel

    type(self) is BinaryModel will not be correct

    two possibilities

    • type(self) in [Logit, Probit] explicit list of subclasses with the same __init__ keywords
    • isinstance(self, BinaryModel) which is redundant given that the __init__ is in BinaryModel. All subclasses are checked in the same way.

    If we do unconditional check, then it applies to all submodels, and we have duplicate checks if several __init__ are on the hierarchy branch (starting at current).

    That's only ok for current BinaryModel, may not be when we add additional binary models, e.g. BetaBinomial.

    It is already the case with CountModel.
    Poisson uses CountModel.initGeneralizedPoisson, NegativeBinomial and NegativBinomial all have their owninit` with additional keywords.

    However, none of those add anything to kwargs of CountModel.__init__, so check in CountModel using isinstance would work.

    But the messy part
    ZeroInflatedPoisson subclasses GenericZeroInflated subclasses CountModel
    all define __init__ and partially hand of keywords to super classes

    CountModels is really in an intermediate position in class hierarchy, not close to all leafs

    another complication: circular imports
    count_model module takes discrete_model modul as "base", i.e. imports and inherits form there.
    isinstance(GenericZeroInflated) in CountModel would require reverse import from subclasses to main classes.
    We have avoided this in most cases so far. (although discrete has several special cases with, e.g. issubclass(self.class, MultinomialModel) from within one module.

    aside:
    GenericZeroInflated does not hand off exog_infl to super, internally it delegates to two model instances.
    There is no check for joint missing handling across submodels.

  10. josef-pkt commented on Sep 25, 2021

    @josef-pkt
    MemberAuthor

    MixedLM has it's own check of kwargs, can be replaced by generic check_kwargs
    Not urgent, change for 0.14

  11. josef-pkt commented on Sep 25, 2021

    @josef-pkt
    MemberAuthor

    GEE: I can add check_kwargs call

    NominalGEE and OrdinalGEE don't send kwargs to super().__init__.
    I'm not sure what kwargs are actually supported.
    missing is explicit keyword and sent to super.
    It looks like missing_idx is not supported (I don't know if missing_idx is relevant in this classes.)
    It looks like formula in kwarg will also be not supported

  12. josef-pkt commented on Jun 8, 2022

    @josef-pkt
    MemberAuthor

    I did not add the init kwarg check, check_kwargs, to RLM, AFAICS

    https://stackoverflow.com/questions/72551503/summary-from-statsmodels-after-rlm-model-not-matching-the-norm-that-was-used

    Also keyword name "M" is not informative and has nonstandard capitalization.

  13. josef-pkt commented on Dec 1, 2022

    @josef-pkt
    MemberAuthor

    #7751 has added kwarg checking for most models outside tsa

    I guess some special models will still be missing. Conditional, Mice, ...
    Also, I guess count models in truncated, no check_kwargs in module

  14. bashtage commented on Jul 30, 2026

    @bashtage
    Member

    Fixed by PR #7751 (and follow-ups), which added generic _check_kwargs/_kwargs_allowed machinery in statsmodels/base/model.py, now wired into GLM, GEE, discrete count models, OLS/WLS, quantile regression, RLM, and BetaModel. Closing as fixed.

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

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions