Skip to content

Avoid setting model.df_model in results.__init__ - #3735

Closed
jbrockmendel wants to merge 4 commits into
statsmodels:masterfrom
jbrockmendel:discrete_freedom
Closed

jbrockmendel wants to merge 4 commits into
statsmodels:masterfrom
jbrockmendel:discrete_freedom

Conversation

@jbrockmendel

Copy link
Copy Markdown
Contributor

Test case to check that model.df_model is not changed on call to fit_regularized

closes #3734

Test case to check that model.df_model is not changed on call to fit_regularized

closes statsmodels#3734

@josef-pkt josef-pkt left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

minor comment on unit tests
otherwise, looks good to me

data = sm.datasets.randhie.load()
model = sm.NegativeBinomial(data.endog, data.exog, loglike_method='nb2')

res1 = model.fit()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in general: If convergence is not of interest in a test, then use start_params with solution, or close to solution.
that saves some time in the test runs

res3 = model.fit()
# res3 should be identical to res1. This test is being added in a PR
# that fixes a bug in which the call to `fit_regularized` modifies
# model.df_model, leading to res3.df_model != res1.df_model

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is not supposed to be a novel :)
one line (or maybe more for essential information) should be enough, details are in the issue.
e.g. "df should not be changed by having called fit_regularized"

also you can also check the model df directly, e.g.
assert_equal(res2.model.df_model, res1.model.df_model)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A lot of authors weren't appreciated in their own eras...

also you can also check the model df directly, e.g.
assert_equal(res2.model.df_model, res1.model.df_model)

Aren't res2.model and res1.model the same object?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, you're right.
the res2.model.df_model check needs to assert the integer, or a copy of the df

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not entirely clear: does your last comment mean there is still an edit needed?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can remove the comment, but I was thinking that a direct test the model.df_model remains == 8 and similar for df_resid would be the more direct test that it is unchanged.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess so. The assertion regarding res2.df_model is needed to ensure we don't accidentally have a trivially-passing test. We could even skip the fit() calls if we really wanted. I'm inclined to keep it as is because of a very specific laziness.

@coveralls

coveralls commented Jun 2, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.009%) to 90.445% when pulling f825843 on jbrockmendel:discrete_freedom into ac25464 on statsmodels:master.

@coveralls

coveralls commented Jun 2, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.009%) to 90.445% when pulling 38adbb8 on jbrockmendel:discrete_freedom into ac25464 on statsmodels:master.

@coveralls

coveralls commented Jun 2, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.009%) to 90.445% when pulling 38adbb8 on jbrockmendel:discrete_freedom into ac25464 on statsmodels:master.

@jbrockmendel

Copy link
Copy Markdown
Contributor Author

Related: #1203

@jbrockmendel

Copy link
Copy Markdown
Contributor Author

Looks like similar incrementing of df_model and df_resid happens in generalized_linear_model and in base._constraints.fit_constrained_wrap.

The same fix here can be applied to genmod. Unfortunately that method is not getting covered when I run tests locally. Coveralls says it is covered; I'll look into the discrepancy.

The version in _constraints is called only from tests, and is a near copy/paste of the methods in discrete and genmod, so I'm guessing it is on its way out.

@josef-pkt

Copy link
Copy Markdown
Member

Are you running the full test suite?
The genmod test are a bit spread out across subfolders, depending a bit on where I added them during an extension, e.g. there are several in discrete and in base for the semi-generic functionality, e.g. cov_type tests are in several places and not always where the corresponding model is, e.g. writing one set of test for both Poisson and GLM-Poisson or OLS and GLM-Gaussian.

The version in statsmodels.base are the most generic solutions, e.g. IIRC Poisson -> GLM -> generic was the development path. The main problem for adding base._constrained fit_constrained to all models is that it needs offset, which was or is only available in GLM and discrete.CountModels. Enhancement to other models are still missing. So. base._constraints is waiting for the subclasses to catch up before taking over.
(typical development for generic features: try it out for one model, extend it to similar models, try to figure out what is required by models for this to work, make up some API along the way, and finally add the generic solution, if we manage to figure it out, to a base class.)

@jbrockmendel

Copy link
Copy Markdown
Contributor Author

Are you running the full test suite?

I must not have been. Now it is getting hit as expected.

So. base._constraints is waiting for the subclasses to catch up before taking over.

Luckily the code there doesn't alter self.model.df_foo inplace, only increments self._results.df_foo. In a perfect world I'd like to avoid even doing that much, but I'm not going to sweat this peripheral case for now.

@josef-pkt

Copy link
Copy Markdown
Member

Luckily the code there doesn't alter self.model.df_foo inplace

Luck or design? In some parts we can still see the age of the code. In the early development of statsmodels it wasn't so clear that we have to be careful about whether attributes are immutable model attributes or mutable results attributes. discrete fit_regularized hasn't been refactored since the beginning quite some time ago. (And that's another reason that a code review every 5 (?) years is useful.)

In a near perfect world, I can still argue that df_xxx are attributes of an instance and are supposed to be set in __init__ (of results).


another special/generic case
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/base/model.py#L2057
where I retrofit model.df_xxx if it doesn't exist.
This is supposed to handle the case where we only know in fit and after how many parameters we actually have. It also will have cases that it will not handle correctly, but it is difficult to figure out how many parameters we have in general nonlinear models .

@jbrockmendel

Copy link
Copy Markdown
Contributor Author

where I retrofit model.df_xxx if it doesn't exist

Yah, I stumbled on that a few minutes ago. Looks like the only place it gets hit is in tsa.arma_mle. That has the long-standing problem of having k_ar and k_ma (well actually nar and nma) not being set at __init__, so it doesn't make sense to set its df_model and df_resid attributes.

I propose we patch arma_mle so that it doesn't reach that branch, then require that model.df_model be defined before the call to fit, and get rid of the not-hasattr branches there (possibly after a release cycle in which those branches issue a DeprecationWarning or something).

In a near perfect world, I can still argue that df_xxx are attributes of an instance and are supposed to be set in init (of results).

The more I look at this, the more I think that is feasible. Moreover, the shim that will make it work may also take care of the "#create dummy results Instance, TODO: wire up properly" workaround in all three appearances of fit_constrained.

The only cases I see where results.df_model != model.df_model are either a) fit_regularized, b) fit_constrained.

The L1 case is pretty easy, let's focus on the constrained case. We can pass k_constr (and possibly res_constr) as kwargs to fit inside fit_constrained. A two line patch to LikelihoodModel.fit will pass that through to LikelihoodModelResults.__init__. Then in __init__ set results.df_model = model.df_model - kwargs.get('k_constr', 0). Similar for df_resid.

I'll try it and check that this actually works.

@josef-pkt

Copy link
Copy Markdown
Member

GenericLikelihoodModel and associated Results are allowed and supposed to have some "magic" so it works for different usecases without requiring the user writing a MLE Model as subclass to figure out and set many details.
miscmodels.TModel and TArma are examples. TModel allows the df of the t-distribution to be fixed or estimated without much extra coding effort.

I don't really like hardcoding and imposing something like k_constr in the base classes. Any assumptions and pattern that are hard coded based on current models might make future extensions more difficult
https://github.com/statsmodels/statsmodels/pull/1665/files#diff-204b0120deaf8dc3d3037809c40cc9b1L154

@jbrockmendel

Copy link
Copy Markdown
Contributor Author

I don't really like hardcoding and imposing something like k_constr in the base classes. Any assumptions and pattern that are hard coded based on current models might make future extensions more difficult

Suppose hypothetically that the suggestion 1) does work for all existing cases and 2) reflects an underlying logic that tentatively appears to apply generally. What would an appropriate place for that be?

@josef-pkt

Copy link
Copy Markdown
Member

I think a relatively simple way will be to have eventually a proper results.__init__, e.g. df_resid and df_model could be added as keyword arguments, and fit is responsible to construct them based on the fit information and keywords. (One trade-off is that df_resid is not necessarily needed, e.g. for predict, and it should be lazily evaluated if it is costly to compute, as in the case of the trace of the hat-matrix in Ridge or other penalized regression.)

A related problem with a large amount of retrofitting the results instance is
josef-pkt@d1c5783#diff-b165b4bd4e10edd0dfb485e47c562b2cR581
issue #2393

The problem is that the results classes were initially designed to be closely linked to a specific model class. Essentially, it is one class split into two to take advantage of inheritance (and to keep results attributes separate from model attributes).
As we accumulate more variation in the models and estimation methods this tight integration becomes a serious limitation, unless we keep adding new results classes for every variation. (e.g. using Mixins more heavily to combine different components.)

also related to #3738 (comment)

@jbrockmendel

Copy link
Copy Markdown
Contributor Author

Between this thread and #3738, it seems like there are two inter-related topics here:

  1. How should XYZResults be created, inherited, wrapped, and have their attributes set.

  2. How should df_model and df_resid be defined/set.

(And at the intersection of these two, the actual topic of the PR, in-place modification of model attributes outside model methods.)

On the first, I'm resigned to punting on creation/inheritance/wrapping as being not worth the effort to try to push significant design changes. A better use of time will be incrementally moving attribute setting into __init__ (or initialize in some cases) in cases where doing so leaves the logic unchanged.

On the second, in a perfect world df_model and df_resid would be functions of model attributes, data/params shapes etc in a way that was internally consistent-- i.e. a natural fit for properties. I'm giving up on the properties suggestion for now in favor of more incremental adjustments towards systematization.

As to the PR itself, I think the only outstanding question is whether the same bugfix should be applied to GenericLikelihoodModelResults. I'd venture "yes", but would settle for a "# TODO: consider changing this" note and kicking it down the road.

@josef-pkt

Copy link
Copy Markdown
Member

GenericLikelihoodModelResults

        if hasattr(model, 'df_resid'):
            self.df_resid = model.df_resid
        else:
            self.df_resid = self.endog.shape[0] - self.df_model
            # retrofitting the model, used in t_test TODO: check design
            self.model.df_resid = self.df_resid

This does not modify an existing model.df_resid, so it should be fine.
However, this will or would not be necessary if the methods in results don't access results.model.df_resid directly anymore. I don't know if all models/results classes have now df_resid as a results attribute or property.

I had forgotten that this discussion is in a PR, given the simultaneous discussion in issues.
The changes in this PR are good and just a non-controversial bug fix.

Any more general changes will need to check and make sure that df_resid, df_model have enough test coverage across models. df_resid is not used in the basic results with asymptotic normal assumption, i.e. when use_t=False, So the basic unit tests for a model will or might not always cover it.

t_test enforces that df_resid is defined, but doesn't use it's value if use_t=False.

@jbrockmendel

Copy link
Copy Markdown
Contributor Author

This does not modify an existing model.df_resid, so it should be fine.

You're right, but it is modifying the model object. Changing what attributes the model has may not cause the same types of problems as re-setting them, but it definitely makes development more difficult. Having to track down and/or guess what attributes exist is sub-optimal.

However, this will or would not be necessary if the methods in results don't access results.model.df_resid directly anymore. I don't know if all models/results classes have now df_resid as a results attribute or property.

In the tests, the only model that reaches that code is tsa.arma_mle. In some ways arma_mle would not be out of place in miscmodels. It doesn't need df_model or df_resid internally.

Any more general changes will need to check and make sure that df_resid, df_model have enough test coverage across models. df_resid is not used in the basic results with asymptotic normal assumption, i.e. when use_t=False, So the basic unit tests for a model will or might not always cover it.

Let's wrap this up and move this part of the discussion to the next PR/Issue.

@josef-pkt

Copy link
Copy Markdown
Member

just a quick check, hitting a line of code in the tests doesn't mean that the attribute is necessary.

base t_test uses
df_resid = getattr(self, 'df_resid_inference', self.df_resid)

I don't find any search result for self.model.df in base.model except for the setting of the df in the model instance.
This would indicate that model.df_resid is not accessed in the base models and therefore shouldn't be needed in GenericLikelihoodModels. (sandwich_covariance for cov_type also doesn't use any model.df_xxx.)
So, we are already pretty far in using only the results.df, and the model.df are only needed for setting the results.df.

@jbrockmendel

Copy link
Copy Markdown
Contributor Author

@josef-pkt I think we've reached an agreement on the actual content of this PR. Some of the discussion above is on related topics and can be moved to an Issue.

I'll rebase and de-conflict once you give the go-ahead.

@coveralls

coveralls commented Sep 24, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.008%) to 81.552% when pulling eaeeb9a on jbrockmendel:discrete_freedom into 687d807 on statsmodels:master.

@codecov-io

Copy link
Copy Markdown

Codecov Report

Merging #3735 into master will increase coverage by <.01%.
The diff coverage is 100%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #3735      +/-   ##
==========================================
+ Coverage   78.97%   78.98%   +<.01%     
==========================================
  Files         541      541              
  Lines       80818    80822       +4     
  Branches     9185     9185              
==========================================
+ Hits        63829    63840      +11     
+ Misses      14915    14909       -6     
+ Partials     2074     2073       -1
Impacted Files Coverage Δ
statsmodels/discrete/discrete_model.py 87.95% <100%> (+0.28%) ⬆️
statsmodels/discrete/tests/test_discrete.py 98.34% <100%> (+0.01%) ⬆️
statsmodels/base/l1_slsqp.py 90.16% <0%> (+3.27%) ⬆️

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 687d807...eaeeb9a. Read the comment docs.

@josef-pkt

Copy link
Copy Markdown
Member

looks good,

needs rebase to remove "Merge branch 'master' ..."
I think we can do a full squash in rebase.
merge is on my todo list for tomorrow

josef-pkt added a commit that referenced this pull request Sep 28, 2017
BUG/REF Avoid changing model.df_model by results closes #3734, closes #3735
@jbrockmendel

Copy link
Copy Markdown
Contributor Author

Excellent! Really psyched to see this one go through

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.

BUG: mutable model.df_model in discrete_model

4 participants