Skip to content

REF: GLM init invalid kwargs use ValueWarning - #7751

Merged
josef-pkt merged 7 commits into
statsmodels:mainfrom
josef-pkt:warn_kwargs_glm2
Sep 26, 2021
Merged

josef-pkt merged 7 commits into
statsmodels:mainfrom
josef-pkt:warn_kwargs_glm2

Conversation

@josef-pkt

@josef-pkt josef-pkt commented Sep 24, 2021 •

Copy link
Copy Markdown
Member

replaces UserWarning by ValueWarning in GLM kwarg check
followup to #7741

this uses now base Model helper function check_kwargs
this adds check_args to

GLM, GEE
discrete CountModel, BinaryModel
RLM
regression: OLS, WLS, GLS, QuantReg

also includes bug fix for #7755 GLS.fit_regularized

@josef-pkt

Copy link
Copy Markdown
Member Author

I changed my mind about not adding it to other models.

We will likely add new keywords to models in 0.14.
If users try example code with old versions, then it will silently be ignored.

candidate for OLS, WLS is ddof #2799
several discrete models still need to get offset (several messy, partially overlapping PRs of mine)

@josef-pkt

josef-pkt commented Sep 24, 2021 •

Copy link
Copy Markdown
Member Author

possible new pattern

subclasses still need to opt-in and call the check using

kwargs_extra = ["offset"]
if type(self) is <class_name>:
    self._check_kwargs(kwargs, kwargs_extra)

The type check ensures that the check is only done in the appropriate class, and not in super classes.
OLS->WLS, GEE->GLM

To be more precise, the name would need to be keys_kwargs_extra

@josef-pkt

josef-pkt commented Sep 24, 2021 •

Copy link
Copy Markdown
Member Author

latest commit is a trial, it is set to raise instead of warn in discrete and OLS
It's easier to check exceptions than warnings in pytest output

The tests that assert warn will also cause test failures

@josef-pkt

Copy link
Copy Markdown
Member Author

Looks like only one fail, and that is expected
TestProbitNewton.test_init_kwargs tests for warning not exception.

still missing check_kwargs in WLS and GLS (needs type(self) check

other models: RLM, BetaModel, OrderedModel, ....
I think it should be safe to add it to all leaf models. (models that don't have subclasses yet.)

as followup: Maintenance when adding new models, refactorings or enhancements:

When we add new subclasses or refactor current subclasses (like ZeroInflated), then the current checks might fail.
In those cases, we need to add or handle new valid keywords/kwargs.

Adding new explicit keywords to existing classes will not affect kwargs (if they are keywords in the class that does the relevant check_kwargs, e.g. offset to BinaryModel and all it's subclasses, but MNLogit will likely not get offset at the same time. )

@josef-pkt

josef-pkt commented Sep 25, 2021 •

Copy link
Copy Markdown
Member Author

when I add check_kwargs without extra kwds, I get a test failure in test_regression.test_regularized_predict which uses weights.

weights is not used in GLM.whiten, so using it is a bug and will not produce WLS results

test_regularized_predict is just a consistency check between predict and fittedvalues, no verifying numbers

update
I'm rewriting the unit test so it's correct and passes with additional asserts, but I get unexplained results with 1-dim sigma 7755

@josef-pkt

Copy link
Copy Markdown
Member Author

tests have only the one expected failure (warn versus raise)

doc build errored

Sphinx parallel build error:
RuntimeError: Non Expected exception in `/home/runner/work/statsmodels/statsmodels/docs/source/gee.rst` line 36
make: *** [Makefile:39: html] Error 2
Error: Process completed with exit code 2.

I have no idea and I didn't change GEE directly, And it didn't fail in previous runs

Time to clean up PR and merge

@josef-pkt

Copy link
Copy Markdown
Member Author

adding check_kwargs to GEE, I get test failures with incorrect kwargs
test_gee.py
test_quasipoisson(reg) looks wrong, cov_type in __init__ but cov_params is not used and checked

test_plot has ValueError: unknown kwargs ['freq_weights', 'var_weights']

a structural problem _init_keys is wrong. This affects our general pattern for _init_keys

GEE extends _init_keys from GLM

-> raise
(Pdb) model._init_keys
['offset', 'exposure', 'freq_weights', 'var_weights', 'groups', 'time', 'weights
', 'dep_data', 'family', 'update_dep', 'constraint', 'family', 'cov_struct']

@josef-pkt

Copy link
Copy Markdown
Member Author

fix until we have a better solution:
explicitly remove the super _init_keys that don't apply

in GEE.__init__

self._init_keys.extend(["update_dep", "constraint", "family",
                                "cov_struct"])
        try:
            self._init_keys.remove("freq_weights")
            self._init_keys.remove("var_weights")
        except ValueError:
            pass

@lgtm-com

lgtm-com Bot commented Sep 25, 2021

Copy link
Copy Markdown

This pull request introduces 1 alert and fixes 1 when merging 19cae58 into 4cf63aa - view on LGTM.com

new alerts:

  • 1 for Unused import

fixed alerts:

  • 1 for Module is imported more than once

@josef-pkt

josef-pkt commented Sep 25, 2021 •

Copy link
Copy Markdown
Member Author

last commit GLM raises, new cases found
statsmodels.base.tests.test_penalized.TestPenalizedGLMBinomCountOracleHC2
E ValueError: unknown kwargs ['penal', 'pen_weight']

statsmodels/base/tests/test_penalized.py
uses several subclasses of GLM and discrete models.

but why are they not excluded by type(self) is GLM:

this is getting tricky, the problem is in llnull

statsmodels/genmod/generalized_linear_model.py:1668: in null
    return GLM(endog, exog, family=self.family,

null uses kwargs = model._get_init_kwds() and then estimates the null model using GLM or WLS, not a penalized subclass.
which I guess is correct if we don't penalize a constant.

and why does it happen only with PenalizedGLMBinomCount and not with other GLM families or with discrete subclasses?

GAM should have the same problem, but there are no failing unit tests.
It looks like llnull, mull is not unit tested in gam

incomplete unit tests to fix all those cases.

Maybe ignore for now and let the check_kwargs warnings go as noise to the user.

a bit dirty as solution:
subclass llnull to temporarily drop penal in _init_keys befor calling super().null.


actually, I ran into this before

PenalizedMixin.__init__ has

        self._null_drop_keys = getattr(self, '_null_drop_keys', [])
        self._null_drop_keys.extend(['penal'])

count_model, discrete_model and betareg moduls use _null_drop_keys

base.model._LLRMixin hass null method that drops the _null_drop_keys before creating the model

        kwds = model._get_init_kwds().copy()
        for key in getattr(model, '_null_drop_keys', []):
            del kwds[key]
        # TODO: what parameters to pass to fit?
        mod_null = model.__class__(model.endog, np.ones(self.nobs), **kwds)

we need this also in GLMResults

GAM doesn't have it, so there likely are problems in llnull.

@josef-pkt

Copy link
Copy Markdown
Member Author

adding this to GLMResults.null fixes base/tests/test_penalized

        for key in getattr(model, '_null_drop_keys', []):
            del kwds[key]

AFAICS, GAM does not extend _init_keys
so we will not be able to reproduce is as penalized model.
_init_keys will be defined by the super models of GAM

@josef-pkt

Copy link
Copy Markdown
Member Author

idea: add global flag to switch between warning and exception
use exception during development, and warning for release.

@lgtm-com

lgtm-com Bot commented Sep 26, 2021

Copy link
Copy Markdown

This pull request fixes 1 alert when merging 843d01e into 4cf63aa - view on LGTM.com

fixed alerts:

  • 1 for Module is imported more than once

@josef-pkt

Copy link
Copy Markdown
Member Author

all green, two test fail because warning instead of ValueError is expected

switch back to warn and then merge

@lgtm-com

lgtm-com Bot commented Sep 26, 2021

Copy link
Copy Markdown

This pull request fixes 1 alert when merging 16f99fc into 4cf63aa - view on LGTM.com

fixed alerts:

  • 1 for Module is imported more than once

@josef-pkt
josef-pkt merged commit e741f3b into statsmodels:main Sep 26, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant