Repository navigation
Multivariate Kalman Filter - #1698
Conversation
|
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. |
|
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.) |
|
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... |
|
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. |
|
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. |
|
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. |
|
Maybe that's a repo setting? For scipy I do get notifications for comments on commits. |
|
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? |
|
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)? |
|
And do you have a benchmark? Imho the speedup should be large, because the code will be very hard to maintain. |
|
That's a good idea. I've mostly punted on this too. I haven't looked much into tempita [1] or how it interacts with fused types [2]. [1] http://pythonpaste.org/tempita/ |
|
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. |
|
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. |
|
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. |
|
One other thing: the |
|
Single Precision / Templating
|
|
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). |
|
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:
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. |
|
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. |
|
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:
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. |
|
On Wed, May 28, 2014 at 1:44 PM, ChadFulton [email protected]:
Or whatever. We can make a Rosetta stone of notation as part of the |
|
On Wed, May 28, 2014 at 1:53 PM, ChadFulton [email protected]:
|
|
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. |
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 ( |
|
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. |
|
Profiling: there's apparently a way to get cProfile to work now: http://docs.cython.org/src/tutorial/profiling_tutorial.html. I haven't tried that yet though. There's also some options described at http://scikit-learn.org/stable/developers/performance.html#profiling-compiled-extensions |
|
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. |
|
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). |
|
On Wed, May 28, 2014 at 9:17 PM, ChadFulton [email protected]:
|
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. |
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. |
|
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. |
|
you pushed the rebase on this PR branch, now we have 173 commits without context to which comment a commit responds to. |
|
@ChadFulton |
|
SUMmary issue for follow ups #2252 |
|
you or we can add any todos or open question to #2252 so we have a list in one place. |
|
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 |
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. |
|
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. 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. |
|
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 |
Using a 700+ length time series, I get the following:
So pretty close, but still only to 3 decimals (or 4 for sigma). Here,
I had thought that However, in the Local Linear Trend model, One possibility may be that since in that model one of the estimated parameters is very close to zero (it is |
|
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 is room for improvement, if Stata's numbers are more accurate, but it still means that your implementation is essentially correct. |
Here's a simple branch with the code added into statsmodels.tsa.statespace. A couple of thoughts
Edit: Original line comments.
L72
L332
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