Skip to content

Multivariate Kalman Filter - #1698

Merged
josef-pkt merged 173 commits into
statsmodels:masterfrom
ChadFulton:kalman
Feb 12, 2015
Merged

josef-pkt merged 173 commits into
statsmodels:masterfrom
ChadFulton:kalman

Conversation

@ChadFulton

Copy link
Copy Markdown
Member

Here's a simple branch with the code added into statsmodels.tsa.statespace. A couple of thoughts

  • At least in the dev process, I thought it might be nicer to keep it in its own module, rather than putting it with the kalmanf. I don't know what makes the most sense in the long run.
  • I have unit tests that rely on the statespace model, but I'm rewriting them so the KF pull request can be done on its own without other dependencies, especially since the statespace model is likely to change.

Edit: Original line comments.

L72

Question: do we want to keep the single-precision version (and the complex single precision, below)? I don't really see a use case, and it appears from preliminary tests that the results tend to overflow. Maybe I'll post a unit test to demonstrate and we can go from there.

L332

Question: there are a bunch of ways to initialize the KF, depending on the theory underlying the data. This one is only valid for stationary processes. Probably best to move out to the Python wrapper?

L444
Question: I think we'll want to add the ability to specify whether or not to check for convergence and alter the tolerance.

L414

This inversion is using an LU decomposition, but I think in this case I can rely on f to be positive definite since it's the covariance matrix of the forecast error, in which case I could use the much faster Cholesky decomposition approach. This is something I'm looking into, but if you happen to know one way or the other, that would be great too.

Related to this is the idea that you should "never take inverses", and I guess I need to look into replacing this with a linear solver routine if possible, in the updating stage below.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage remained the same when pulling 540bf11 on ChadFulton:kalman into 0b689a2 on statsmodels:master.

@jseabold

Copy link
Copy Markdown
Member

I don't know why these comments aren't showing up in my inbox. @josef-pkt Did you see them in yours? As to the questions:

Keep the single-precision code, but don't advertise it and comment out any tests. We are still everywhere double-precision (np.float64 and np.complex128 on platforms), but I'd like to eventually, one day handle this. It'd be nice to have some of the issues of what to look forward to already demonstrated. You don't necessarily need to test it and maybe we'll put a big, honking warning on there.

@jseabold

Copy link
Copy Markdown
Member

For the initialization. I hard-coded the non-stationary diffuse prior for ARIMA, but it should be an option. See, for example, what stata does (search for diffuse, p0, etc.)

http://www.stata.com/help.cgi?arima

@jseabold

Copy link
Copy Markdown
Member

For convergence, do you mean to the steady state? I don't give the user any control here. I hard-coded the check for 1. Haven't run into any problems with this yet...

https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/kalmanf/kalman_loglike.pyx#L104

@jseabold

Copy link
Copy Markdown
Member

For the inverse, there is likely some solver for symmetric/hermitian systems in lapack. Maybe there's something already exposed by scipy. I'm honestly not sure. Might want to have a look and use this, but I could live with it being a TODO if it's going to be a huge time sink. How big are the 'typical' multivariate problems? The number of operations saved might be (fairly) trivial, but if they can get 'big' then it might be worth it.

For the univariate case, I punted and just divided.

@josef-pkt

Copy link
Copy Markdown
Member

We don't get notification of comments that are directly to a commit, instead of to the PR.

I looked at the comments yesterday by "accident".

The cython code looks pretty close to C from my quick look, not that I understand much.

What I would prefer is that we have basic unit tests for this and merge as soon as possible. TravisCI is green for all python versions, but I would like to get more widespread testing for this, so we don't get low level problems in the last minute.
I wouldn't advertise it, and we can change it any time, but we would get nightly Windows binaries and Debian and Ubuntu testing for it.

@jseabold

Copy link
Copy Markdown
Member

Ah, I didn't notice they're commit comments. Oops.

Unit tests should be the next priority. It might also help work on the Python API if you don't have it decided yet. Something like dse, dlm, or KFAS in R [1]. Gretl also supports this AFAIK. These should give some guidance and tests for correctness.

That way we'll be sure everything is correct and there are no hidden segfaults, etc. across platforms/versions.

[1] http://www.jstatsoft.org/v41/i04/paper

@rgommers

Copy link
Copy Markdown
Member

Maybe that's a repo setting? For scipy I do get notifications for comments on commits.

@jseabold

Copy link
Copy Markdown
Member

I see that it's supposed to if you're "watching" the repo, but I don't see them anywhere in my inbox. Maybe I need to be watching the fork?

@rgommers

Copy link
Copy Markdown
Member

I think some templating is needed in the Cython code. It's four times the same, only different types/typecodes. Maybe using Tempita (which ships with Cython)?

@rgommers

Copy link
Copy Markdown
Member

And do you have a benchmark? Imho the speedup should be large, because the code will be very hard to maintain.

@jseabold

Copy link
Copy Markdown
Member

@jseabold

Copy link
Copy Markdown
Member

Re: speed-up. We don't yet have a multivariate kalman filter (or state space models), but I guess it would be nice to have an idea of the speed-up vs. some other package in Python assuming they exist, if even just for advertisement. There are some KF projects for fixed parameters AFAIK, but nothing that requires optimization.

I've tried to use in-line comments to point to what the blas calls do (e.g., pointing to Durbin and Koopman or something). This might be a nice addition to this PR when you switch to templating.

Re: the code complexity, it's mainly just a generalization of our already existing Kalman filter code. I'm not that worried about this. I.e., it's the point of the whole project. It's prohibitively computationally intensive to do this in Python. It's the reason I wrote our (special-cased) univariate kalman filter years ago. Waiting a few minutes for Kalman filter loops inside an optimizer vs. instantaneous results in R, Matlab, gretl, etc. is a no go. Unfortunately, you just can't write an optimizer around a pure Python KF and have any hope of anyone using it.

@rgommers

Copy link
Copy Markdown
Member

Yeah, all pure Python will be bad. But there's a middle ground between pure Python and all raw BLAS calls. For example, I don't think it will matter for performance if everything above the for-loop is done with scipy.linalg calls instead of direct BLAS calls.

@jseabold

Copy link
Copy Markdown
Member

Ah, sure. Though those can still be called many times for numerical gradient evaluations, for example. It looks like there are at the least code comments with the pure Python/math in most cases (hopefully all), which will greatly help any future maintenance.

It will also be nice/necessary to collect all of the filtering equations with the same notation in some documentation so this math is even less opaque.

@rgommers

Copy link
Copy Markdown
Member

One other thing: the _cpointer business. I don't see it changing any time soon, but this relies on a private attribute generated by f2py. Looks like this is the best method for packages that depend on scipy to portably call BLAS/LAPACK from Cython code, without having to worry about hairy build system issues. So what we could do is document this method in Scipy, and add a few tests to ensure we don't break this in the future. @pv does that make sense?

@ChadFulton

Copy link
Copy Markdown
Member Author

Single Precision / Templating

  • I will leave the single-precision versions in for now
  • I will maybe put failing overflow (or whatever the problem is) unit tests on the back-burner because I don't even really understand what the problem is yet.
  • Templating is definitely the way to go if possible. I hadn't heard of Tempita, but I will definitely look into it. I've already been annoyed many times having to update everything four times. (@jseabold - let me know if you'd like this as a part of GSoC and, if so, when)

@jseabold

Copy link
Copy Markdown
Member

Yeah, you can update this PR with templating I think. Should be fairly trivial and not too time consuming. It looks similar to string.Template.

I'd work on the unit tests first since templates will be mostly a cosmetic change.

@rgommers Do you know any examples of .pyx.in files in scipy or elsewhere? The documentation here looks sparse (as far as Cython(ize)+Tempita).

@ChadFulton

Copy link
Copy Markdown
Member Author

Timing for ARIMA estimation

The timing versus the old Statsmodels Kalman filter (which did not use BLAS / LAPACK calls) can be found in this notebook. The timing difference was 1 minute 31 seconds down to 7.6 seconds.

My feeling is that this particular Kalman Filter may not be useful for estimating ARIMA models, which is a special case of a univariate measurement equation so that many things can be simplified. I strongly suspect that the current Statsmodels Kalman filter (overhauled in the last few months by @jseabold) will always beat this Multivariate generalization in timings. I haven't timed them yet, but based on something @jseabold said earlier, his is faster.

There are two ways (that I know of) to go for the ARIMA models:

  1. keep the special case that we have now
  2. there is actually another special case of the multivariate Kalman filter in the case that the measurements are independent. In this case (and ARIMA models fall into this case) the multivariate filter reduces to a univariate filter.

The first is probably what we'll keep for now, and the second would probably be better in the long run.

Edit: By the way, the Cython KF versus a strictly pure python implementation is 2 orders of magnitude faster if I remember correctly.

@ChadFulton

Copy link
Copy Markdown
Member Author

Maintenance

These are good points. It is pretty much just a series of Fortran calls, which I guess almost begs the question why not just do it in Fortran and us f2py. But I suppose that would be even harder to maintain?

You are right that some of the calls can be replaced with Python calls; pruning these is a good project. One problem was that I do not know how to profile the Cython code so I don't know what I can prune; I assume I will need a C profiler of some sort; @rgommers do you have a suggestion for this? Actually, this was my first major Cython project, done last fall, so I will likely be able to improve it over the summer.

I agree with @jseabold that better commenting is a good idea. Ideally, I think that we would have a Python version of the multivariate Kalman filter and put the corresponding lines over the top (this is what I have done already, but it is out of date and most of the python lines don't work or refer to old variables, etc.).

I had standardized the variable names on a (great) applied book (Kim and Nelson, 1999) but I think that maybe it would be better to do it on the Durbin and Koopman book, which is a much more comprehensive reference. I had also briefly considered using descriptive names (e.g. forecast, forecast_error, forecast_error_cov), and I will revisit this thought. I feel like there are some variables for which I can't think of a good descriptive name.

@ChadFulton

Copy link
Copy Markdown
Member Author

Initializations

I guess I will move the initialization out of the Cython for now. It's a tricky issue for me because while I understand that there are lots of specific issues with initialization that are problem-specific, I don't have a handle on all of them. I was thinking that:

  1. For now, I'll just leave the stationary initialization as the default and allow people to override it (so as to punt on the problem!).
  2. I would like to make the framework such that we can add new special-case initializations as people have time. I guess that's not too hard (as you mention, like Stata does).

However, it might be something that we want to put back into Cython later because for a large system, that Kronecker product and inverse can take forever.

@jseabold

Copy link
Copy Markdown
Member

On Wed, May 28, 2014 at 1:44 PM, ChadFulton [email protected]:

Maintenance

These are good points. It is pretty much just a series of Fortran calls,
which I guess almost begs the question why not just do it in Fortran and us
f2py. But I suppose that would be even harder to maintain?

We got the C pointers from f2py via scipy already. This is the way to go.

You are right that some of the calls can be replaced with Python calls;
pruning these is a good project. One problem was that I do not know how to
profile the Cython code so I don't know what I can prune; I assume I will
need a C profiler of some sort; @rgommers https://github.com/rgommersdo you have a suggestion for this? Actually, this was my first major Cython
project, done last fall, so I will likely be able to improve it over the
summer.

I wouldn't worry too too much about this, honestly, but feel free, if it's
something you'd like to learn. I'd be interested to see what you come up
with. From what I've seen on cython-user, etc. many people just rely on
intuition here. E.g., acquiring a buffer is slower than grabbing a pointer
to an existing array.

I agree with @jseabold https://github.com/jseabold that better
commenting is a good idea. Ideally, I think that we would have a Python
version of the multivariate Kalman filter and put the corresponding lines
over the top (this is what I have done already, but it is out of date and
most of the python lines don't work or refer to old variables, etc.).

My preference would be to just update the comment lines with correct Python
rather than to remove code that works for (fractionally) slower but more
expressive Python code.

I had standardized the variable names on a (great) applied book (Kim and
Nelson, 1999) but I think that maybe it would be better to do it on the
Durbin and Koopman book, which is a much more comprehensive reference. I
had also briefly considered using descriptive names (e.g. forecast,
forecast_error, forecast_error_cov), and I will revisit this thought. I
feel like there are some variables for which I can't think of a good
descriptive name.

Josef, will in all likelihood opt for more useful names, but my usual style
(and what I did in my kalman filter code) is to describe what you're doing
and then just follow the notation of some reference, because as you say
there aren't always easy, simple names to be had. E.g.,

 # Update the Kalman Gain
 # K = T.dot( ...

Or whatever. We can make a Rosetta stone of notation as part of the
documentation, if necessary. Clear docs and examples are going to be
paramount here rather than notational choice. Cf. gretl and the R packages.

@jseabold

Copy link
Copy Markdown
Member

On Wed, May 28, 2014 at 1:53 PM, ChadFulton [email protected]:

Initializations

I guess I will move the initialization out of the Cython for now. It's a
tricky issue for me because while I understand that there are lots of
specific issues with initialization that are problem-specific, I don't have
a handle on all of them. I was thinking that:

  1. For now, I'll just leave the stationary initialization as the
    default and allow people to override it (so as to punt on the problem!).

I would say go ahead and fix it. Allow people to put in there own p0 and
whatever else, as in stata, but also accept 'stationary' which is what you
already have and 'diffuse,' which is what I have. If you don't have your
head around 'diffuse' yet, then just stick a TODO in. Durbin and Koopman
have a good explanation, though I don't recall if it's ARIMA specific.

  1. I would like to make the framework such that we can add new
    special-case initializations as people have time. I guess that's not too
    hard (as you mention, like Stata does).

However, it might be something that we want to put back into Cython later
because for a large system, that Kronecker product and inverse can take
forever.

This is a reason to just leave it in Cython, but accept an array from
Python. If p0 is not None, then grab the pointer to p0, check
conformability, etc. and carry on.

Reply to this email directly or view it on GitHubhttps://github.com//pull/1698#issuecomment-44441994
.

@ChadFulton

Copy link
Copy Markdown
Member Author

Inversions / Linear Solver

It won't really take any time to implement the positive definite versions (they're dpotrf and dpotri if you're interested). I've done this a bunch (a lot of Bayesian problems require inverting a variance / covariance matrix at each iteration and this can help a lot).

The part I'm not sure about is the properties of the matrix that's being inverted. As I said, it's the variance / covariance of the forecast error so it should be positive definite, but I'm a little concerned because I think that it would be possible to break it given (crazy) user input.

However, I guess that dpotrf will not break the code if it is not positive definite, but it will return an info code letting me know that it didn't work, and in that case I can drop back to dgetrf.

So I think I will put this on the to-do list, but maybe not high priority (as you mention, the main use cases for this right now have small measurement vector sizes, so this will be a small matrix). And I add a specific check for a univariate measurement in which case I also just divide.

@josef-pkt

Copy link
Copy Markdown
Member

Josef, will in all likelihood opt for more useful names

I pretty much don't care what you do in the cython code. Just for computational parts I also find it often easier to use shortcut names, usually defined as local alias.

However, I'm currently on the "language crusade" for all public parts (dir(model) dir(results)) and for all internal calculations that are not pure math, and where intuition or basic knowledge of the algorithm can substitute for "running to the library and finding the reference from which the notation was taken" or, slightly less worse, having to read a glossary each time before looking at a piece of code.
(Just to point again at VAR, which has one capital letter names for matrices that are spread over 3 or 4 classes. Read one method of a class, and it takes half an hour to track down where this one letter matrix was defined. (exaggerated, searching source code works quite well, and it only takes 5 minutes :))

@ChadFulton

Copy link
Copy Markdown
Member Author

By the way, one use for a large-scale multivariate Kalman Filter is dynamic factor models which seem to me are becoming / will become quite popular in macro.

@ChadFulton

Copy link
Copy Markdown
Member Author

I am going to apply some patches over the top of the above commits in order to pull in the history of the various files. Unfortunately even if I cherry pick the above commits afterwards, they'll have different hashes and I'll lose the inline comments. So I've moved the line comments to the first comment on the PR.

@ChadFulton

Copy link
Copy Markdown
Member Author

Thanks for the tips on profiling - I'll take a look.

(I'd like to get some idea of the profiling, I guess, if it doesn't become a time sink).

@jseabold

Copy link
Copy Markdown
Member

On Wed, May 28, 2014 at 9:17 PM, ChadFulton [email protected]:

I am going to apply some patches over the top of the above commits in
order to pull in the history of the various files. Unfortunately even if I
cherry pick the above commits afterwards, they'll have different hashes and
I'll lose the inline comments. So I've moved the line comments to the first
comment on the PR.

I'm not sure what you have in mind here, but you can just force push to
this branch. The inline comments will stay it just points to an "outdated"
diff. Unless you think it's really important I wouldn't worry about it. We
usually don't.

@ChadFulton

Copy link
Copy Markdown
Member Author

About the other unit tests that have lower agreement with the reference:

Do you have a rough idea what might be causing the difference?:
numerical precision
different definition and different algorithm
optimization problems

The MLE parameter estimates often differ slightly due to different algorithm finding slightly different maximum (often it is statespace that finds the better maximum)

The standard errors are another matter, however, and I think that it is not doing a good job calculating the information matrix via the Hessian (e.g. the Local linear trend model has it non-negative definite). I don't know why this is, however. If anyone has thoughts on how I can pursue this, I would be interested. It's possible it could be due to numerical precision issues somewhere.

@ChadFulton

Copy link
Copy Markdown
Member Author

If possible I would like to merge this tomorrow, and do further changes with new PRs.

That sounds good, I have rebased and pushed the last commits to fix the major outstanding issues (assuming that Travis passes), so I will open a new branch and new PR and you can review / merge as you like.

@ChadFulton

Copy link
Copy Markdown
Member Author

Also, documentation should build just fine (I think - it seems like there's always a little voodoo in getting Sphinx to run correctly). I have added a page with documentation of the statespace model as well as links to the autodoc for the important classes, etc., and the four notebooks have properly been added to the notebooks page.

@josef-pkt

Copy link
Copy Markdown
Member

you pushed the rebase on this PR branch, now we have 173 commits without context to which comment a commit responds to.

@josef-pkt

Copy link
Copy Markdown
Member

@ChadFulton
in general: if you need to use an attached attribute several or many times, then it's often convenient to assign it to a local name at the beginning of a method, i.e.
model = self.model
and then just use model instead of self.model each time.

@josef-pkt

Copy link
Copy Markdown
Member

SUMmary issue for follow ups #2252

@josef-pkt

Copy link
Copy Markdown
Member

you or we can add any todos or open question to #2252 so we have a list in one place.

@josef-pkt

Copy link
Copy Markdown
Member

All test pass on my Windows 32 python (with the compiled extensions from a few weeks ago)

I think it's time to merge

@ChadFulton Currently this PR (branch kalman) and the new PR #2250 (branch statespace) are identical, both look correctly rebased.
If you have a backup branch with the code just before the rebase, and assuming you didn't make any commits after the rebase, then you could try to push the no-rebase branch back here. I don't know if it will work to restore the github comment-commit links.
If not, then I'll merge this PR, because then the new #2250 PR is just a redundant copy.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.64%) to 83.88% when pulling 4dd63a7 on ChadFulton:kalman into e8cd0f4 on statsmodels:master.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.64%) to 83.88% when pulling 4dd63a7 on ChadFulton:kalman into e8cd0f4 on statsmodels:master.

@ChadFulton

Copy link
Copy Markdown
Member Author

If you have a backup branch with the code just before the rebase, and assuming you didn't make any commits after the rebase, then you could try to push the no-rebase branch back here. I don't know if it will work to restore the github comment-commit links.
If not, then I'll merge this PR, because then the new #2250 PR is just a redundant copy.

Ah now I see what you wanted to achieve with the new branch. I can do another rebase to set the commit date to be the same as the author date and give that a try if you like.

@josef-pkt

Copy link
Copy Markdown
Member

I have no idea how github links and orders commits and comments, If I merge #2250, then we could give it a try, if you no quickly how to do it.
But if it looks too messy and difficult, and you don't have a backup branch, then I wouldn't bother.

other question: Is there a unit test with a longer time series? I was going over some of the Stata examples (notebook and Stata manual), and with around 100 observations small differences in the calculations can be large in relative terms. I expect that longer time series should be better able to distinguish numerical noise from possible bugs or really different definitions/algorithms.
Also for bse (and consequentially for pvalues and confidence intervals) cov_params_default differs quite a bit from cov_params_delta, and might differ in a similar range from Stata's OPG.

@josef-pkt

Copy link
Copy Markdown
Member

I'm going to merge #2250 so we don't have to check this now.

BTW results wrapper should be feasible to do for 0.7

@josef-pkt
josef-pkt merged commit 1479460 into statsmodels:master Feb 12, 2015
@ChadFulton

Copy link
Copy Markdown
Member Author

other question: Is there a unit test with a longer time series? I was going over some of the Stata examples (notebook and Stata manual), and with around 100 observations small differences in the calculations can be large in relative terms. I expect that longer time series should be better able to distinguish numerical noise from possible bugs or really different definitions/algorithms.

Using a 700+ length time series, I get the following:

Stata SARIMAX
ar.L1 .0374327 0.03702307
ar.L2 .0379874 0.03762686
ar.L3 .0376676 0.03732947
sigma2 .0006718 0.00068415

So pretty close, but still only to 3 decimals (or 4 for sigma). Here, cov_params_default and cov_params_delta are quite close (4 or 5 decimals).

Also for bse (and consequentially for pvalues and confidence intervals) cov_params_default differs quite a bit from cov_params_delta, and might differ in a similar range from Stata's OPG.

I had thought that cov_params_default would be the better choice, since the delta method is an approximation technique that can be quite bad at times.

However, in the Local Linear Trend model, cov_params_delta returns values where cov_params_default does not; and the cov_params_delta are close (3 or 4 decimals) to Stata's OIM standard errors (using their ucm model).

One possibility may be that since in that model one of the estimated parameters is very close to zero (it is 1.079e-11) the transformation (which forces all parameters to be positive) is necessary because the perturbation used in the Hessian calculation may make the parameter be negative. Although if that was happening, then I would have thought the Hessian would have NaNs.

@josef-pkt

Copy link
Copy Markdown
Member

Given the long recursive calculation and the numerical optimization, I don't think we have to worry about a 1% or so difference in the parameter estimates.
There might be differences in the numerical derivative calculations, the optimization algorithm and the generic kalman filter might have more numerical noise than a specialized algorithm.

There is room for improvement, if Stata's numbers are more accurate, but it still means that your implementation is essentially correct.

@ChadFulton
ChadFulton deleted the kalman branch January 16, 2016 08:47
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.

6 participants