You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
BUG/ENH: add warning for unknown kwargs in model.__init__ #7741
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.)
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.
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.
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.
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".
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.
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.
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
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.
Activity
josef-pkt commentedon Sep 21, 2021
I think the GLM case is still possible for 0.13. It would be just a noisy warning if we miss valid cases.
josef-pkt commentedon Sep 22, 2021
whitelist for model init kwargs might require work
for example
Model.from_formulahasmissing_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
josef-pkt commentedon Sep 22, 2021
trying it out in GLM
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.
josef-pkt commentedon Sep 23, 2021
scale and method shouldn't be there
test_glm uses method and scale in
__init__instead of infit.I guess they don't do anything.
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_keysto check for allowed keywords does not work because super call inGEE.__init__happens before_init_keysare set as attributes. I guess we can change that order.josef-pkt commentedon Sep 23, 2021
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.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.
ENH: warn if unknown kwargs in GLM.__init__ see statsmodels#7741
ENH: warn if unknown kwargs in GLM.__init__ see statsmodels#7741
ENH: warn if unknown kwargs in GLM.__init__ see statsmodels#7741
ENH: warn if unknown kwargs in GLM.__init__ see statsmodels#7741
josef-pkt commentedon Sep 24, 2021
An alternative implementation would be to have
kwargs_allowed = kwargs_generic + hidden subclass kwargs like n_trials
keys_allowed = self._init_keys + kwargs_allowedwhich can be checked in a
baseclass.That would check that all keywords are either in the
_init_keysor the kwargs list.It would force subclasse to specify
_init_keysbefore any super call or calls to a_check_kwargsmethod.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".
josef-pkt commentedon Sep 24, 2021
Unsupported base kwargs
In my current version I have in base.Model
The main problem is that
missingmight 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
missingsupport)(.dropna() for users is much easier than doing it inside statsmodels.)
Making a mistake in warning about
missingsupport is less serious. Eithermissing="drop"works or it will raise at some point with shape mismatch. I don't think it can silently do the wrong thing.josef-pkt commentedon Sep 24, 2021
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 BinaryModeltype(self) is BinaryModelwill not be correcttwo possibilities
type(self) in [Logit, Probit]explicit list of subclasses with the same__init__keywordsisinstance(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.init
GeneralizedPoisson, 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 classesCountModels 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.
josef-pkt commentedon Sep 25, 2021
MixedLM has it's own check of kwargs, can be replaced by generic check_kwargs
Not urgent, change for 0.14
josef-pkt commentedon Sep 25, 2021
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.
missingis 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
josef-pkt commentedon Jun 8, 2022
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.josef-pkt commentedon Dec 1, 2022
#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_kwargsin modulebashtage commentedon Jul 30, 2026
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.