Skip to content

ENH: Add linear restrictions to RecursiveLS - #4133

Merged
ChadFulton merged 28 commits into
statsmodels:masterfrom
ChadFulton:recursivels-restrictions
Jun 13, 2018
Merged

ChadFulton merged 28 commits into
statsmodels:masterfrom
ChadFulton:recursivels-restrictions

Conversation

@ChadFulton

Copy link
Copy Markdown
Member

Allow linear restrictions on the (recursively estimated) least squares parameter estimates.

Needs unit tests.

@coveralls

coveralls commented Nov 22, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.2%) to 83.481% when pulling 160accf on ChadFulton:recursivels-restrictions into d8cb151 on statsmodels:master.

@codecov-io

codecov-io commented Nov 22, 2017 •

Copy link
Copy Markdown

Codecov Report

Merging #4133 into master will increase coverage by 0.18%.
The diff coverage is 94.7%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #4133      +/-   ##
==========================================
+ Coverage   80.74%   80.93%   +0.18%     
==========================================
  Files         573      577       +4     
  Lines       87893    88696     +803     
  Branches     9147     9889     +742     
==========================================
+ Hits        70970    71782     +812     
+ Misses      14678    14651      -27     
- Partials     2245     2263      +18
Impacted Files Coverage Δ
statsmodels/tsa/statespace/kalman_filter.py 87.63% <ø> (-0.07%) ⬇️
statsmodels/regression/tests/test_recursive_ls.py 99.09% <100%> (+0.63%) ⬆️
statsmodels/regression/recursive_ls.py 94.4% <89.13%> (-2.46%) ⬇️
statsmodels/base/tests/test_generic_methods.py 96.43% <0%> (ø) ⬆️
statsmodels/sandbox/distributions/mv_normal.py 38.97% <0%> (ø) ⬆️
statsmodels/sandbox/bspline.py 0% <0%> (ø) ⬆️
statsmodels/sandbox/stats/multicomp.py 40.25% <0%> (ø) ⬆️
statsmodels/stats/tests/test_diagnostic.py 91.77% <0%> (ø) ⬆️
statsmodels/sandbox/distributions/gof_new.py 0% <0%> (ø) ⬆️
... and 26 more

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 d8cb151...160accf. Read the comment docs.

@ChadFulton
ChadFulton force-pushed the recursivels-restrictions branch from a5f75e3 to 92f77f8 Compare June 3, 2018 23:59
@ChadFulton

Copy link
Copy Markdown
Member Author

A couple of notes:

  • In 8302be4 I change the reported log-likelihood to be that compatible with the least squares approach (computed from the recursive residuals) rather than that from the prediction error decomposition of the Kalman filter. Even with exact diffuse initialization, they are not the same.

  • If there are constraints on the parameters, the covariance matrix for the full set of parameters will be singular and the notes part will complain about the condition number. Is there anything we usually do for this kind of situation where this is expected?

@ChadFulton

Copy link
Copy Markdown
Member Author

Other than those notes, if this comes back green, it is ready to merge.

@josef-pkt

Copy link
Copy Markdown
Member

I will look at it briefly tomorrow (i.e. today)

I am using singular cov_params for the fit_constrained and similar results.
It works fine as far as I have seen it so far. but I opened a few issues to think more about what we should do in these cases.
One annoying thing about singular cov_params are runtime warnings, but my guess is that we don't want to silence all of them except in unit tests.

Comment thread statsmodels/regression/recursive_ls.py Outdated
return numer / denom

@cache_readonly
def llf_obs(self):

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.

maybe better llf_recursive, IIUC
those are sequential loglike_obs values, and not the loglike evaluated at the final params, is it?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Ah, this is a good idea, thank you.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

If I do this, I guess I should leave llf as the Kalman filter output rather than the one computed from the recursive residuals, since it might be confusing to have np.sum(res.llf_obs) != res.llf?

Comment thread statsmodels/regression/recursive_ls.py Outdated

@cache_readonly
def llf(self):
return np.sum(self.llf_obs)

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.

Does this have a standard MLE interpretation?
e.g. would be use this for comparing models, or for aic, bic

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yes, this one (computed from the recursive residuals) is the same as the OLS profile log-likelihood function (i.e after concentrating out the scale), the same as you would get from sm.OLS.loglike with scale=None.

@josef-pkt

Copy link
Copy Markdown
Member

The constraints look fine to me.

I never looked at the meaning of other results statistics like llf if they are defined via recursive residuals. So I don't have much of an idea what's appropriate there.

@josef-pkt

Copy link
Copy Markdown
Member

aside: a lag selection test failed now at least for the second time in master. AFAIR it's one of the failures that Matthew reported for 0.9.
(unrelated to this PR)

@ChadFulton

Copy link
Copy Markdown
Member Author

I never looked at the meaning of other results statistics like llf if they are defined via recursive residuals. So I don't have much of an idea what's appropriate there.

I think that in the case of recursive least squares, either the Kalman filter loglikelihood or the OLS loglikelihood should be "valid" MLE likelihoods, even if they're not computing exactly the same object.

@josef-pkt

Copy link
Copy Markdown
Member

llf and llf_obs should be consistent, i.e. sum up.
but it depends on the MLE interpretation, which I'm still not sure about.
AFAICS, you could take any consistent definition across llf, llf_obs, llf_recursive, llf_recursive_obs

@josef-pkt

Copy link
Copy Markdown
Member

We don't actually have llf_obs in any other model explicitly
but we have `results.llf = model.loglike(res.params) = sum(model.loglike_obs(res_params) as far as that is or will be available.

@ChadFulton

Copy link
Copy Markdown
Member Author

That makes sense. I think I'll just leave llf and llf_obs as usual for a state space model, and then additionally define the llf_recursive and llf_recursive_obs as you suggest.

@ChadFulton

Copy link
Copy Markdown
Member Author

Basically the recent commits fix some numerical issues, make some definitions more consistent, provide some more specific documentation about what is being computed (e.g. in llf vs llf_recursive) and adds a more comprehensive unit test against sm.OLS for the case without restrictions on the coefficients.

Also adds a sort-of test for bse in the case with restrictions on the coefficients, but it unfortunately has very poor tolerance so it's more like documentation than a real "test".

@josef-pkt

josef-pkt commented Jun 11, 2018 •

Copy link
Copy Markdown
Member

If you want to use it for comparison or unit tests, GLM-Gaussian allows linear restriction with fit_constrained

@ChadFulton

Copy link
Copy Markdown
Member Author

If you want to use it, GLM-Gaussian allows linear restriction with fit_constrained

That's amazing, I should get out of sm.tsa.statespace more often. Thanks!

Even better, the bse from RecursiveLS match the bse from sm.GLM in the case of linear constraints.

@josef-pkt

Copy link
Copy Markdown
Member

This pull request introduces 1 alert when merging 1ebf8e6 into d8cb151 - view on LGTM.com

new alerts:

  • 1 for Mismatch between signature and use of an overridden method

Comment posted by LGTM.com

@josef-pkt

Copy link
Copy Markdown
Member

Actually now that I think about it.
If there are no lagged endog in the model, then fit_constrained through exog transformation, reparameterization and offsetting y would also work.
But it only works for exog constraints, and requires endog = y - offset (for affine constraints), so it will not work in general in tsa.

(aside: I didn't look closely yet, but I would like to have offset, i.e. and exog with a fixed coefficient = 1 in all models where we cannot simply offset the endog. But I haven't thought about what details this would involve in statespace models.)

@josef-pkt

Copy link
Copy Markdown
Member

This pull request introduces 1 alert when merging d9005f8 into d8cb151 - view on LGTM.com

new alerts:

  • 1 for Mismatch between signature and use of an overridden method

Comment posted by LGTM.com

# used in OLS. Compute new ic based on llf_alternative to compare.
# TODO: Why do I need a -1 here but not in the unconstrained case? It must
# have something to do with the fact that GLM does not report the intercept
# as a degree of freedom so we need to subtract it here, but then why don't

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.

I check this tomorrow (which is today)

@ChadFulton ChadFulton Jun 12, 2018 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Hope you didn't spend too much time on this, turns out that what I wrote there is not true, and the test passes with actual_aic = aic(llf_alternative, res.nobs_effective, res.df_model). Sorry

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Ignore what I just said. The comment in the code is correct.

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.

I didn't have much time today, so I haven't looked at it yet.

Either it's a bug in my fit_constrained code, or the constant detection in the transformed model fails, or there is an ambiguity in definition of df_model if eg. the constant is part of a constraint, or all of the above.

I don't like it that df_model doesn't include the constant, I just creates pain everywhere and anytime I look at it. :(

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.

It doesn't look like a bug in fit_constrained,

I'm adjusting both df_model and df_resid for the constraints.
Implicitly this assumes that the constraints are on the slope coefficient.

        k_constr = len(q)
        res._results.df_resid += k_constr
        res._results.df_model -= k_constr

GLM initialize always subtracts 1 independent of whether there is a constant or not, i.e. we assume there always is a constant.

self.df_model = np_matrix_rank(self.exog) - 1

so I don't see anything specific to the constrained case.

# we need to do that it the unconstrained case?
actual_aic = aic(llf_alternative, res.nobs_effective, res.df_model - 1)
assert_allclose(actual_aic, res_glm.aic)
# TODO: Why does AIC match but BIC does not match?

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.

#1733 BIC uses a different definition specific to GLM.
And because of my inertia/reluctance with breaking backwards compatibility it still hasn't been changed.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Makes sense!

@josef-pkt

Copy link
Copy Markdown
Member

This pull request introduces 3 alerts when merging 9d0920e into d8cb151 - view on LGTM.com

new alerts:

  • 2 for Module-level cyclic import
  • 1 for Mismatch between signature and use of an overridden method

Comment posted by LGTM.com

# does not report the intercept as a degree of freedom so we need to
# subtract it here, but then why don't we need to do that it the
# unconstrained case?
df_model = res.df_model - 1 if constraints is not None else res.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.

you can also directly check df_model for the example, i.e df_model == 1 in the constrained and ==2 in the unconstrained case

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Interesting. Maybe the df should be different in the RecursiveLS case with constraints; it's set here by the number of diffuse observations, which almost always turns out to be equal to the number of states with diffuse initialization, and so is same here regardless of the constraints.

Since the constraint (in this example) implies that there are is really only independent 1 state, I guess the best way to handle that would be with some kind of modification of the diffuse initialization to also enforce the constraint, but I don't know of a way to do that in the current structure.

# given `test_ols`, but this is mostly to complement the tests in
# `test_glm_constrained`)
endog = dta.infl
exog = add_constant(dta[['unemp', 'm1']])

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.

unrelated aside
Isn't 'm1' integrated with drift/trend, while infl and unemp don't have a trend/drift?
i.e. it would imply that the params for m1 is zero
e.g. use differenced m1 or m1 deviation from trend ?
???

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yes, very true. Just a sloppy test :)

@josef-pkt

Copy link
Copy Markdown
Member

This pull request introduces 3 alerts when merging f06cdca into d8cb151 - view on LGTM.com

new alerts:

  • 2 for Module-level cyclic import
  • 1 for Mismatch between signature and use of an overridden method

Comment posted by LGTM.com

@ChadFulton

Copy link
Copy Markdown
Member Author

Will merge tonight unless there are concerns or suggestions for improvements.

Comment thread statsmodels/regression/recursive_ls.py Outdated
self.df_resid = np.inf # attribute required for wald tests
# Since we are overriding params with things that aren't MLE params,
# need to adjust df's
self.df_model = self.k_diffuse_states

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.

if you know that self.k_diffuse_states does not take constraints into account (or as long as it doesn't), then you could explicitly correct it for the number of constraints, i.e. subtract k_constraints if constraints are not None.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I was considering that approach, but what I was concerned about is that the initialization still has k_diffuse_states states. So, for example, the first few log-likelihood values will still be computed as under the diffuse filter, and the recommendation for that case is that there be a df correction for those observations. Since I can't fix the diffuse initialization itself to take into account the constraints, I wasn't sure if it was appropriate to use a smaller model df.

On the other hand, it would match better what is going in on e.g. GLM, and it is the case that recursive LS should be pretty much just like the usual OLS case, including if there are linear restrictions.

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.

Assuming the effect of the (diffuse) initialization goes away as more observations are used, I would go for the later outcome, i.e. use the constraints corrected df_model and df_resid.
I don't really understand how diffuse initialization works, but maybe a comment in the Notes section of the docstring mentioning this would be enough.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Assuming the effect of the (diffuse) initialization goes away as more observations are used, I would go for the later outcome, i.e. use the constraints corrected df_model and df_resid...maybe a comment in the Notes section of the docstring mentioning this would be enough.

Sounds good to me.

I don't really understand how diffuse initialization works

Basically just algebraics of a fully diffuse Gaussian prior for at least some components of the state vector; as the filter processes more observations, eventually the conditional distribution becomes proper.

@josef-pkt

Copy link
Copy Markdown
Member

This pull request introduces 3 alerts when merging 160accf into d8cb151 - view on LGTM.com

new alerts:

  • 2 for Module-level cyclic import
  • 1 for Mismatch between signature and use of an overridden method

Comment posted by LGTM.com

@ChadFulton

Copy link
Copy Markdown
Member Author

Thanks @josef-pkt for all the useful comments!

@ChadFulton
ChadFulton merged commit 9f8d3c1 into statsmodels:master Jun 13, 2018
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.

4 participants