You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
@ChadFulton (I had a power outage several times today and had time to read the Bruce Hansen paper)
I also started to read his "Inference in TAR Models" in Studies in Nonlinear Dynamics and Econometrics but then got power, internet and kids back.
I think the gist is a good start. I also think you should focus on the estimation model and Results first before getting into the details of the test of SETAR with different number of regimes.
One question for which I added a paragraph in the wiki page is which result methods and statistics you can inherit. It looks like most of the inference comes from the OLSResults, including White heteroscedasticiy robust standard errors.
However, from the "Inference in TAR Models" paper it looks like that we get non-standard distribution of the parameters if we take the uncertainty about the threshold parameter into account. (But there might be different asymptotics.)
Other parts of the results might be pure time series analysis, prediction/forcasting, ... where you might be able to copy things from the current AR/ARMA models and then look into creating a common superclass if necessary.
I wouldn't worry a lot about performance early on,
for example I would use OLS whenever possible, it's fully tested and you don't have to worry about mistakes in rewriting parts of it, you need to create a new exog for each grid point so you don't really safe much in not using it. Also keeping sparse matrices in mind is ok, but I wouldn't start with them soon, since with 2 regimes you only have about 50% empty.
Also most of these parts will be easy to swap later for a more efficient implementation, if necessary.
One big item: If you need to simulate the SETAR for the bootstrap, then this will be very slow. I expect that you need an iteration loop over all time points, and that might have to go into cython. However, based on my quick reading, in several cases we don't need to simulate the full SETAR/TAR model.
Thanks for the reply and the wiki update. This is very helpful, as always! I'm glad to be getting into a bit of the guts of SM with the model class, and there's a lot to figure out.
I also started to read his "Inference in TAR Models" in Studies in Nonlinear Dynamics and Econometrics but then got power, internet and kids back.
I took a brief look at this, and had thought that the "Testing for Linearity" paper was essentially a more completed version of the "Inference in TAR Models" paper (e.g. looks at higher order SETAR models, and considers the asymptotic distribution of the test statistics a bit more).
Looking again, it looks like that's not the case. e.g. if I want to compute e.g. confidence intervals for the estimated delay and threshold parameters I'll need to use results from the "Inference ..." paper. I'll look closer.
However, from the "Inference in TAR Models" paper it looks like that we get non-standard distribution of the parameters if we take the uncertainty about the threshold parameter into account.
I need to look into this more too. My reading of other papers (including "Testing for Linearity") was that OLS on the constructed dataset would produce appropriate t stats and CIs. But it does look like Hansen is saying that the confidence regions will be different. I had attributed the difference in the OLS standard errors and those in the paper to not having applied White's correction. I'll do that first, and see if that matches Hansen (1999)'s s.e.'s.
In the 1999 paper, he seems to indicate that the only non-standard distribution is on the LR test statistic (which would normally be chi-squared, but here is not).
One big item: If you need to simulate the SETAR for the bootstrap, then this will be very slow. I expect that you need an iteration loop over all time points, and that might have to go into cython. However, based on my quick reading, in several cases we don't need to simulate the full SETAR/TAR model.
Since the bootstrapping is for the linearity testing, I'll hold off on thinking too much about this for now. But it does look like he has some tricks in the 1999 paper.
For the actual estimation conditional on the delay and threshold, it's just OLS (with maybe some non-standard critical values, but that doesn't seem like it'd impose much additional computation), so it doesn't seem to me like there'd be any real problem scaling up the high regime models.
Estimating the delay parameter is also not such a big problem computationally because of the small search space.
The computational problem is estimating the threshold parameters. Prior to Hansen's results, the approach seems to have been the researcher graphically assessing the appropriate threshold values. So one of Hansen's contributions was to allow estimating threshold values.
However, Hansen is focused on the AR and SETAR(2) models in the "Inference in TAR models" paper, and adds the SETAR(3) case in the "Testing for Linearity" case, and he provides a trick to do the grid search in the SETAR(3) case which reduces the algorithm from max_delay*threshold_grid_size**2 to (max_delay+2)*threshold_grid_size.
He references Bai and Perron (1998) for where he got the trick, so I'll have to take a look at their paper for more information on whether their trick can be applied to higher order SETARs than SETAR(3).
When we get to a SETAR(4), if the trick can't be applied, the selection algorithm will be max_delay*threshold_grid_size**2 which is on the order of 20,000 - 500,000. And of course SETAR(5) is another order of magnitude, etc.
So the question is, if a trick can't be applied to make this computationally tractable, do we even want to attempt to select the hyperparameters for a 4th or higher order model? Or should I throw a NotImplementedError or similar, letting them know that they should fall back to the graphical selection of thresholds?
Now that I've written all this, though, I'm now thinking it's not a big deal either way. I have to implement the general grid search case to do SETAR(2), and then if it's a SETAR(3) I'll drop into a special case. So whatever we decide on the higher order cases, it won't change what I'm initially doing, and we can either put in an exception or not.
page 7 of the "Inference in TAR Models", paragraph after equation (10):
greek messed up in copying
Since °O is consistent for °0 at a fast rate, it is possible to show that the first-order asymptotic approximation
to the distribution of O µ (when ° is estimated) is identical to that given in Equation (9). Thus we can act as if
°O D °0, and use O 2.°O / as an asymptotically valid confidence interval for µ. One might be skeptical that this
approach will yield good finite sample approximations in practice. In small samples, ° might not be estimated
very precisely, and this sampling error will contaminate the distribution of O µ. It appears desirable to use a
sampling approach that takes this uncertainty into account,
We have this in several cases in econometrics, some parameters are estimated at a faster than usual rate (are superconsistent). Then we can take them as fixed for the (first-order) asymptotics.
So OLS (sandwich) standard errors are fine.
However, in some cases first-order asymptotics could require a pretty large sample size to be a good approximation, and bootstrap (or higher order approaches) give better results in smaller samples.
my impression was (max_delay+2)*threshold_grid_size extends to higher dimension.
I would assume in most cases there will be at most 3 regimes SETAR(3)
Depending on the curvature (I have no idea), I would replace a full gridsearch with a directed search in larger dimensions. Make coarse grid and then refine specific regions, or try bisection or some heuristic search strategy.
maybe there are some additional tricks that the machine learning guys have since they do this a lot more.
gridsearch can work in parallel, so we can use joblib to reduce the time
BTW: given that you have the OLSResults instance, you can directly get the bse for the heteroscedasticity robust sandwiches, HC0_se, ...
The robust standard errors do match what Hansen has in his 1999 paper.
We have this in several cases in econometrics, some parameters are estimated at a faster than usual rate (are superconsistent). Then we can take them as fixed for the (first-order) asymptotics.
So OLS (sandwich) standard errors are fine.
However, in some cases first-order asymptotics could require a pretty large sample size to be a good approximation, and bootstrap (or higher order approaches) give better results in smaller samples.
Ah! That makes sense. Now that I take a look at his paper, it doesn't look like it'll be too hard to include the asymptotic-correct confidence regions he talks about to the output. I suppose it's not high on the TODO since the robust errors are a good first-order approximation, but I'll make a note about it.
my impression was (max_delay+2)*threshold_grid_size extends to higher dimension.
That would be good. I'll be implementing this next, so I'll be looking into this pretty soon.
Depending on the curvature (I have no idea), I would replace a full gridsearch with a directed search in larger dimensions. Make coarse grid and then refine specific regions, or try bisection or some heuristic search strategy.
From my reading, I wonder if directed search is not feasible, although I don't know too much about advanced solutions. Just after equation 12 in "Testing for Linearity", he writes
The maximization (11) is best solved through a grid search, noting that the argument d
is discrete and that the function f2(gamma�,d) is typically a highly erratic function of �gamma.
gridsearch can work in parallel, so we can use joblib to reduce the time
That would be great. I see that you added a parallel_func() in #111, but I don't see anything using it. Are there reasons not to use that, and instead do something manually like in the kernel density estimation?
It also looks like at that time it took a while to import joblib. Perhaps I should only use it if the grid is large enough?
That would be great. I see that you added a parallel_func() in #111, but I don't see anything using it. Are there reasons not to use that, and instead do something manually like in the kernel density estimation?
I thought it was used for simulated confidence intervals in vector_ar for SVAR, but I cannot find it by grepping. (I didn't pay close attention when SVAR got merged.)
On Windows, we need almost 10 second per job as minumum to pay off, if there are heavier imports (like scipy.stats which brings with it half of scipy). So, after adding parallel and after finding this out, I lost most of my interest in parallel computing. We have very few algorithms that take a long enough time to execute, and few tasks that can be parallelized and split into large enough jobs. Bootstrap, Monte Carlo and permutation tests are the main candidates, but we still don't have much of a systematic approach to that. Similar cross-validation is currently only used in nonparametric, and gridsearch is not used at all so far.
I want to see the highly erratic function before I give up on directed search. Even then, we might want to have a fast approximate option and a slow comprehensive search option.
Doing bootstrap on top of searching a fine grid, sounds ok for the final version of a project, but not for data exploration.
After what seems like forever beating my head against the delay and threshold selection, I finally have a working version that can match both Hansen's paper and the R tsDyn output (!!). Expect to see this tomorrow, and many more assorted SETAR pieces soon after.
Highlights (more details in Wiki, flagged as 7/25/13):
Sunspots dataset output can be replicated across Hansen's results and R package tsDyn output (this was tough! not only is Hansen's sunspots dataset subtly different than the statsmodels one, slight differences in threshold grid selection can affect the selected parameters, and tsDyn exhibits some weird behavior)
Other datasets' output (e.g. I tried GDPC1) can't be replicated in R package tsDyn output.
Performance: on a MacBook Air, 0.25-0.40ms per model selection iteration. For example:
SETAR(2) with AR order 11 and default threshold grid size (100) requires 11*100 iterations = ~270ms
SETAR(3) with AR order 11 and default threshold grid size requires 11*100 + 100 + (a bit more due to iterative improvements on threshold estimates) = ~470ms
Parallel: given this, it seems like joblib will only be worthwhile in bootstrapping?
I was not able to make directed search workable - there are large flat regions on the objective function, and I don't know how to get directed search's step size to be appropriate. It turns out the objective function is pretty darn erratic.
Re-added the graphs I had before. The one I posted originally ("Sunspot: SSR for d=3") was SSR, so we wanted to minimize it, and the 3d one I just posted as well as all the graphs in the wiki are of the objective function f_2(\gamma, d) which we want to maximize.
SSR = AR1_SSR - f_2(\gamma, d), so they're just a vertical flip with an intercept change of each other.
So, just to make sure I'm not confusing anyone, "Objective" in a graph refers to something that should be maximized, while "SSR" is something that should be minimized.
[Edit: updated the 11 graphs in the wiki to have consistent y-axis limits]
Just to keep some continuity in this thread, the SETAR model is now largely complete, although some portions don't have associated unit tests, and the bootstrapped linearity tests are quite slow.
Here's a notebook that extends the ARMA Notebook example by testing for non-linearity with the BDS test from earlier, and then compares the ARMA(3,0) with a SETAR(2;3,3). (and also uses the BDS test!)
How do you use the BDS test in the notebook? AFAICS, it's in a different branch
Quick read: the notebook looks good, but I wonder how the seasonality of the sunspots could be better captured.
Does ARMA and SETAR still work if we increase the order to 12? Or do we have then too many parameters?
(more macroeconomics would be to include an exchange rate or business cycle example.)
(for later when I have time to look at this: What are the assumptions on stationarity of the AR polynomial in the different regimes? Is stationarity imposed? I guess not because it's OLS,)
How do you use the BDS test in the notebook? AFAICS, it's in a different branch
You're right, I excluded those parts from the version I committed, but I'm going to make this a blog post so I wanted to include that test.
Quick read: the notebook looks good, but I wonder how the seasonality of the sunspots could be better captured. Does ARMA and SETAR still work if we increase the order to 12? Or do we have then too many parameters?
Yes, actually the version I've been working with mostly from Hansen uses an 11 order AR process. I used 3 here to keep continuity with the ARMA Notebook, but actually there's not much change in e.g. the forecasts, although the ARMA(11,0) is pretty good at capturing the cycles over even the longer range that I have in the notebooks (sometimes even better than the SETAR, depending on the starting point).
(more macroeconomics would be to include an exchange rate or business cycle example.)
Good idea. I'll find a good example.
(for later when I have time to look at this: What are the assumptions on stationarity of the AR polynomial in the different regimes? Is stationarity imposed? I guess not because it's OLS,)
I believe that you are correct and that stationarity is not imposed on the regimes - e.g. I think that sometimes in three regime models, the middle regime is taken to be a random walk.
Right now it's pretty bad. Since select_hyperparameters() takes about 400 ms with threshold_grid_size=100, and it's being run at least reps*2 times, a 10 rep bootstrap tables ~ 6 seconds. Obviously we need a lot more than 10, and e.g. Hansen recommends 2000, which would be something like 1200 s = 20 minutes. I ran 2000 reps to check, and it took about that long, maybe a few minutes more.
I've been trying to find a way to optimize it, but with really no success. I'm caching the objective function as much as I can to prevent re-calculation. From what I can tell, it doesn't look like the kind of thing that Cython can help, because profiling indicates that it's the underlying numpy functions that are taking the time (but of course, I've just been getting started with Cython, so what do I know...). Even so, I set up a few alternate Cython implementations of select_hyperparameters() and build_exog(), but with no speed improvements.
I've set up joblib functionality for the bootstrapping via parallel_func(), which on my MacBook Air which has 2 cores, it pretty much doubled the speed from 6s to 3s for 10 reps, and from 60s to 30s for 100 reps. Still not super though.
If you have ideas for where I can work on improving this, let me know. I've sort of run out of places that I know to look. Maybe revisit directed search, as you mentioned above?
Here's a profile (I cut it off for brevity) for select_hyperparameters() with order=2, ar_order=11, and threshold_grid_size = 100.
Obviously build_exog is a candidate for improvement, but I can't find a way to make it faster. Here's a profile for 1000 runs (so that the times show up in 3 decimals) of build_exog:
Even though I added a bunch of functionality, I haven't added any new unit tests, mostly because I'm not sure how to do so. Here are the untested areas:
Threshold confidence intervals: The paper which implemented this ultimately only gave confidence intervals for a TAR model (i.e. the threshold variable was not a lag of the endogenous variable). Everything I did for SETAR should be applicable to TAR models, and I plan to make a new branch that migrates the core functionality to a TAR class, with SETAR as a subclass that will just set the appropriate threshold variable. At this point I'll be able to test against Hansen's paper and Hansen's code.
Predictions / Forecasts: I'm not sure how to test this. Do you know where are the result sets for the e.g. ARIMA forecasts came from? I still need to set up GRETL, maybe its SETAR model has forecasting...
Order Testing: I'm also not sure how to test this, since it's bootstrapped and it takes so long to run. I can match the shapes of the bootstrap distributions in e.g. Figure 7 of Hansen, and get pretty close to the bootstrapped p-values in Table 7. I have Hansen's code, so maybe I should do e.g. overnight runs with something like 100,000 repetitions to see if the p-values converge?
Also, I need to do some basic unit tests, esp. on datatypes. I've been fixing problems with datatypes on the fly, but that leads me to suspect there are more lurking.
Predictions / Forecasts: I'm not sure how to test this. Do you know where are the result sets for the e.g. ARIMA forecasts came from? I still need to set up GRETL, maybe its SETAR model has forecasting...
From what I have seen in the test suite, Skipper got the forecast results from Stata. Some unit tests for tsa ARIMA are against GRETL (Skipper found a bug in Gretl, when the numbers didn't match.)
You might also be able to test against ARIMA for the case of 1 regime, although it uses a different estimation method. One source of errors is the indexing and timing, and maybe you can verify that against ARIMA.
If you cannot find any benchmark numbers, then you could also add regression test (and add a comment that it's only a regression test, so we know the numbers are not benchmark numbers). If you can match a published table, then it will give at least a few digits for verification.
Verifying bootstrap results in the test suite is very limited, If you set a seed, you can get "reasonable" numbers with a bootstrap replication that is not very large and is at least in the right ball park.
Also, if you expect that you are able to verify common code with another model later on, then I think more regression test are acceptable for now, and you add more verified tests when you have the more general model.
overall: I wouldn't worry too much unless there are other packages that are much faster. If there are no obvious speed improvements, then it takes time to get these results.
These are not results that we need for exploratory and interactive data analysis, and I think in some cases running the statistical during a coffee break or overnight is ok. We start to have a few cases like this.
I think the only larger time savings will come from an improved directed search.
For practical usage, choosing the number of replications in the bootstrap based on preliminary results might also be useful. For example, run 500 bootstrap samples, if the p-value is large then stop, because it doesn't really matter for hypothesis tests whether the p-value is 0.4 or 0.8. Similar, it would be nice if users could do the bootstrap in steps, run 500 samples, inspect, and then decide whether to run 1500 more samples.
Neither of these two are used yet in statsmodels.
You could open a separate issue for performance improvements, and work on the other things.
In SETAR the underlying estimation is OLS so it's still fast, for other cases even getting one estimate will be time consuming.
Also, from a user perspective, if I have a model and want to change some of the initial parameters. can I just change the attribute directly? I imagine not but haven't looked into it. Nevertheless, I can imagine a user wanting to estimate a setar with two regimes and a setar with 3 regimes and it would be easy if there were some set_num_regime methods that would allow the user to change some of the initial parameters without creating a whole new model instance.
Also, did some profiling for the setar (2,2). It seems like when build_exog is called within _grid_search_objective, there are some unnecessary calculations at the end (mostly the checks with the nobs). Are they necessary every time build_exog is called? I will email you the profile.
Just playing around with the code a bit, I can't call a fit for the same model twice:
Thanks! This was a bug from some sloppy use of self.exog. I've included it in some other fixes of annoying mistakes that I'll push in a bit.
Also, from a user perspective, if I have a model and want to change some of the initial parameters. can I just change the attribute directly?
This is something I hadn't really thought about, but it sounds good to have. So, were you thinking of something like:
mod=SETAR(2,2)
res2=mod.fit()
mod.order=3# or mod.set_order(3)res3=mod.fit()
# ...printres2.summary()
printres3.summary()
if so, I'm not sure how we could achieve that, since the results object relies on the model object. I'd suggest passing the result constructor a deep copy of the model object instead of the object itself, but I've never been too sure about how much one can count on a deep copy to not give WTFs. What do you think?
I could make a setter for the important parameters (e.g. order, ar_order, delay, thresholds, trend, min_regime_frac, max_delay, threshold_grid_size) that would re-call fit() if it had already been called. Then the fact that the results class held the model object would actually work to our benefit. Although then I think the @cache_readonly decorator would have to be removed from the properties.
that would work right now. whoops, no it wouldn't. It seems like it would be good to include a setter method for those parameters above to clear everything out when something changes. What do you think?
Or maybe you had something else in mind?
Also, did some profiling for the setar (2,2). It seems like when build_exog is called within _grid_search_objective, there are some unnecessary calculations at the end (mostly the checks with the nobs). Are they necessary every time build_exog is called? I will email you the profile.
I think these are necessary - because each time _grid_search_objective is called with a different delay and/or threshold, so the dataset has to be built again, and every time I need to make sure that there are enough observations in each regime (apparently this is required for the asymptotic theory to hold), otherwise the (delay, thresholds) combination shouldn't even be considered as a candidate in the hyperparameter search.
That's a bummer, though, that the nobs count is taking 22% of the time. Seems awfully high to sum a column of ones and zeros?
Also, from a user perspective, if I have a model and want to change some
of the initial parameters. can I just change the attribute directly?
This is something I hadn't really thought about, but it sounds good to
have. So, were you thinking of something like:
mod = SETAR(2,2)
res2 = mod.fit()
mod.order = 3 # or mod.set_order(3)
res3 = mod.fit()
IIUC, we've switched all of the models to taking these types of parameters
during model instantiation. Cf. ARIMA. It alleviates some headaches with
stale results, etc. Open to suggestions, but it seems to be the most
straightforward way.
Activity
josef-pkt commentedon Jul 11, 2013
@ChadFulton (I had a power outage several times today and had time to read the Bruce Hansen paper)
I also started to read his "Inference in TAR Models" in Studies in Nonlinear Dynamics and Econometrics but then got power, internet and kids back.
I think the gist is a good start. I also think you should focus on the estimation model and Results first before getting into the details of the test of SETAR with different number of regimes.
One question for which I added a paragraph in the wiki page is which result methods and statistics you can inherit. It looks like most of the inference comes from the OLSResults, including White heteroscedasticiy robust standard errors.
However, from the "Inference in TAR Models" paper it looks like that we get non-standard distribution of the parameters if we take the uncertainty about the threshold parameter into account. (But there might be different asymptotics.)
Other parts of the results might be pure time series analysis, prediction/forcasting, ... where you might be able to copy things from the current AR/ARMA models and then look into creating a common superclass if necessary.
I wouldn't worry a lot about performance early on,
for example I would use OLS whenever possible, it's fully tested and you don't have to worry about mistakes in rewriting parts of it, you need to create a new exog for each grid point so you don't really safe much in not using it. Also keeping sparse matrices in mind is ok, but I wouldn't start with them soon, since with 2 regimes you only have about 50% empty.
Also most of these parts will be easy to swap later for a more efficient implementation, if necessary.
One big item: If you need to simulate the SETAR for the bootstrap, then this will be very slow. I expect that you need an iteration loop over all time points, and that might have to go into cython. However, based on my quick reading, in several cases we don't need to simulate the full SETAR/TAR model.
ChadFulton commentedon Jul 11, 2013
Thanks for the reply and the wiki update. This is very helpful, as always! I'm glad to be getting into a bit of the guts of SM with the model class, and there's a lot to figure out.
I took a brief look at this, and had thought that the "Testing for Linearity" paper was essentially a more completed version of the "Inference in TAR Models" paper (e.g. looks at higher order SETAR models, and considers the asymptotic distribution of the test statistics a bit more).
Looking again, it looks like that's not the case. e.g. if I want to compute e.g. confidence intervals for the estimated delay and threshold parameters I'll need to use results from the "Inference ..." paper. I'll look closer.
I need to look into this more too. My reading of other papers (including "Testing for Linearity") was that OLS on the constructed dataset would produce appropriate t stats and CIs. But it does look like Hansen is saying that the confidence regions will be different. I had attributed the difference in the OLS standard errors and those in the paper to not having applied White's correction. I'll do that first, and see if that matches Hansen (1999)'s s.e.'s.
In the 1999 paper, he seems to indicate that the only non-standard distribution is on the LR test statistic (which would normally be chi-squared, but here is not).
Since the bootstrapping is for the linearity testing, I'll hold off on thinking too much about this for now. But it does look like he has some tricks in the 1999 paper.
ChadFulton commentedon Jul 11, 2013
Another issue, speed and special cases:
For the actual estimation conditional on the delay and threshold, it's just OLS (with maybe some non-standard critical values, but that doesn't seem like it'd impose much additional computation), so it doesn't seem to me like there'd be any real problem scaling up the high regime models.
Estimating the delay parameter is also not such a big problem computationally because of the small search space.
The computational problem is estimating the threshold parameters. Prior to Hansen's results, the approach seems to have been the researcher graphically assessing the appropriate threshold values. So one of Hansen's contributions was to allow estimating threshold values.
However, Hansen is focused on the AR and SETAR(2) models in the "Inference in TAR models" paper, and adds the SETAR(3) case in the "Testing for Linearity" case, and he provides a trick to do the grid search in the SETAR(3) case which reduces the algorithm from
max_delay*threshold_grid_size**2to(max_delay+2)*threshold_grid_size.He references Bai and Perron (1998) for where he got the trick, so I'll have to take a look at their paper for more information on whether their trick can be applied to higher order SETARs than SETAR(3).
When we get to a SETAR(4), if the trick can't be applied, the selection algorithm will be
max_delay*threshold_grid_size**2which is on the order of 20,000 - 500,000. And of course SETAR(5) is another order of magnitude, etc.So the question is, if a trick can't be applied to make this computationally tractable, do we even want to attempt to select the hyperparameters for a 4th or higher order model? Or should I throw a NotImplementedError or similar, letting them know that they should fall back to the graphical selection of thresholds?
Now that I've written all this, though, I'm now thinking it's not a big deal either way. I have to implement the general grid search case to do SETAR(2), and then if it's a SETAR(3) I'll drop into a special case. So whatever we decide on the higher order cases, it won't change what I'm initially doing, and we can either put in an exception or not.
josef-pkt commentedon Jul 11, 2013
page 7 of the "Inference in TAR Models", paragraph after equation (10):
greek messed up in copying
We have this in several cases in econometrics, some parameters are estimated at a faster than usual rate (are superconsistent). Then we can take them as fixed for the (first-order) asymptotics.
So OLS (sandwich) standard errors are fine.
However, in some cases first-order asymptotics could require a pretty large sample size to be a good approximation, and bootstrap (or higher order approaches) give better results in smaller samples.
josef-pkt commentedon Jul 11, 2013
About gridsearch:
(max_delay+2)*threshold_grid_sizeextends to higher dimension.josef-pkt commentedon Jul 11, 2013
BTW: given that you have the OLSResults instance, you can directly get the bse for the heteroscedasticity robust sandwiches,
HC0_se, ...ChadFulton commentedon Jul 12, 2013
The robust standard errors do match what Hansen has in his 1999 paper.
Ah! That makes sense. Now that I take a look at his paper, it doesn't look like it'll be too hard to include the asymptotic-correct confidence regions he talks about to the output. I suppose it's not high on the TODO since the robust errors are a good first-order approximation, but I'll make a note about it.
ChadFulton commentedon Jul 12, 2013
That would be good. I'll be implementing this next, so I'll be looking into this pretty soon.
From my reading, I wonder if directed search is not feasible, although I don't know too much about advanced solutions. Just after equation 12 in "Testing for Linearity", he writes
That would be great. I see that you added a parallel_func() in #111, but I don't see anything using it. Are there reasons not to use that, and instead do something manually like in the kernel density estimation?
It also looks like at that time it took a while to import joblib. Perhaps I should only use it if the grid is large enough?
josef-pkt commentedon Jul 12, 2013
I thought it was used for simulated confidence intervals in vector_ar for SVAR, but I cannot find it by grepping. (I didn't pay close attention when SVAR got merged.)
On Windows, we need almost 10 second per job as minumum to pay off, if there are heavier imports (like scipy.stats which brings with it half of scipy). So, after adding parallel and after finding this out, I lost most of my interest in parallel computing. We have very few algorithms that take a long enough time to execute, and few tasks that can be parallelized and split into large enough jobs. Bootstrap, Monte Carlo and permutation tests are the main candidates, but we still don't have much of a systematic approach to that. Similar cross-validation is currently only used in nonparametric, and gridsearch is not used at all so far.
josef-pkt commentedon Jul 12, 2013
I want to see the
highly erratic functionbefore I give up on directed search. Even then, we might want to have a fast approximate option and a slow comprehensive search option.Doing bootstrap on top of searching a fine grid, sounds ok for the final version of a project, but not for data exploration.
ChadFulton commentedon Jul 12, 2013
I actually did see an example in one of the sources I was looking at, somewhere! haha, I'll try and dig it up (but I take your point, nonetheless).
Initial (minimal functionality) SETAR model
ChadFulton commentedon Jul 25, 2013
After what seems like forever beating my head against the delay and threshold selection, I finally have a working version that can match both Hansen's paper and the R tsDyn output (!!). Expect to see this tomorrow, and many more assorted SETAR pieces soon after.
ChadFulton commentedon Jul 25, 2013
@j-grana6 I pushed the new SETAR model along with updated unit tests. I've also updated the wiki, and I'll post the highlights here.
ChadFulton commentedon Jul 25, 2013
Highlights (more details in Wiki, flagged as 7/25/13):
6 remaining items
ChadFulton commentedon Jul 26, 2013
Re-added the graphs I had before. The one I posted originally ("Sunspot: SSR for d=3") was SSR, so we wanted to minimize it, and the 3d one I just posted as well as all the graphs in the wiki are of the objective function f_2(\gamma, d) which we want to maximize.
SSR = AR1_SSR - f_2(\gamma, d), so they're just a vertical flip with an intercept change of each other.So, just to make sure I'm not confusing anyone, "Objective" in a graph refers to something that should be maximized, while "SSR" is something that should be minimized.
[Edit: updated the 11 graphs in the wiki to have consistent y-axis limits]
ChadFulton commentedon Aug 10, 2013
Just to keep some continuity in this thread, the SETAR model is now largely complete, although some portions don't have associated unit tests, and the bootstrapped linearity tests are quite slow.
Here's a notebook that extends the ARMA Notebook example by testing for non-linearity with the BDS test from earlier, and then compares the ARMA(3,0) with a SETAR(2;3,3). (and also uses the BDS test!)
http://nbviewer.ipython.org/6202381
josef-pkt commentedon Aug 10, 2013
How do you use the BDS test in the notebook? AFAICS, it's in a different branch
Quick read: the notebook looks good, but I wonder how the seasonality of the sunspots could be better captured.
Does ARMA and SETAR still work if we increase the order to 12? Or do we have then too many parameters?
(more macroeconomics would be to include an exchange rate or business cycle example.)
(for later when I have time to look at this: What are the assumptions on stationarity of the AR polynomial in the different regimes? Is stationarity imposed? I guess not because it's OLS,)
ChadFulton commentedon Aug 10, 2013
You're right, I excluded those parts from the version I committed, but I'm going to make this a blog post so I wanted to include that test.
Yes, actually the version I've been working with mostly from Hansen uses an 11 order AR process. I used 3 here to keep continuity with the ARMA Notebook, but actually there's not much change in e.g. the forecasts, although the ARMA(11,0) is pretty good at capturing the cycles over even the longer range that I have in the notebooks (sometimes even better than the SETAR, depending on the starting point).
Good idea. I'll find a good example.
I believe that you are correct and that stationarity is not imposed on the regimes - e.g. I think that sometimes in three regime models, the middle regime is taken to be a random walk.
ChadFulton commentedon Aug 11, 2013
Bootstrap Performance for order_test:
Right now it's pretty bad. Since
select_hyperparameters()takes about 400 ms with threshold_grid_size=100, and it's being run at least reps*2 times, a 10 rep bootstrap tables ~ 6 seconds. Obviously we need a lot more than 10, and e.g. Hansen recommends 2000, which would be something like 1200 s = 20 minutes. I ran 2000 reps to check, and it took about that long, maybe a few minutes more.I've been trying to find a way to optimize it, but with really no success. I'm caching the objective function as much as I can to prevent re-calculation. From what I can tell, it doesn't look like the kind of thing that Cython can help, because profiling indicates that it's the underlying numpy functions that are taking the time (but of course, I've just been getting started with Cython, so what do I know...). Even so, I set up a few alternate Cython implementations of
select_hyperparameters()andbuild_exog(), but with no speed improvements.I've set up joblib functionality for the bootstrapping via
parallel_func(), which on my MacBook Air which has 2 cores, it pretty much doubled the speed from 6s to 3s for 10 reps, and from 60s to 30s for 100 reps. Still not super though.If you have ideas for where I can work on improving this, let me know. I've sort of run out of places that I know to look. Maybe revisit directed search, as you mentioned above?
Here's a profile (I cut it off for brevity) for select_hyperparameters() with order=2, ar_order=11, and threshold_grid_size = 100.
Obviously build_exog is a candidate for improvement, but I can't find a way to make it faster. Here's a profile for 1000 runs (so that the times show up in 3 decimals) of build_exog:
ChadFulton commentedon Aug 11, 2013
Unit Testing:
Even though I added a bunch of functionality, I haven't added any new unit tests, mostly because I'm not sure how to do so. Here are the untested areas:
Threshold confidence intervals: The paper which implemented this ultimately only gave confidence intervals for a TAR model (i.e. the threshold variable was not a lag of the endogenous variable). Everything I did for SETAR should be applicable to TAR models, and I plan to make a new branch that migrates the core functionality to a TAR class, with SETAR as a subclass that will just set the appropriate threshold variable. At this point I'll be able to test against Hansen's paper and Hansen's code.
Predictions / Forecasts: I'm not sure how to test this. Do you know where are the result sets for the e.g. ARIMA forecasts came from? I still need to set up GRETL, maybe its SETAR model has forecasting...
Order Testing: I'm also not sure how to test this, since it's bootstrapped and it takes so long to run. I can match the shapes of the bootstrap distributions in e.g. Figure 7 of Hansen, and get pretty close to the bootstrapped p-values in Table 7. I have Hansen's code, so maybe I should do e.g. overnight runs with something like 100,000 repetitions to see if the p-values converge?
Also, I need to do some basic unit tests, esp. on datatypes. I've been fixing problems with datatypes on the fly, but that leads me to suspect there are more lurking.
josef-pkt commentedon Aug 11, 2013
From what I have seen in the test suite, Skipper got the forecast results from Stata. Some unit tests for tsa ARIMA are against GRETL (Skipper found a bug in Gretl, when the numbers didn't match.)
You might also be able to test against ARIMA for the case of 1 regime, although it uses a different estimation method. One source of errors is the indexing and timing, and maybe you can verify that against ARIMA.
If you cannot find any benchmark numbers, then you could also add regression test (and add a comment that it's only a regression test, so we know the numbers are not benchmark numbers). If you can match a published table, then it will give at least a few digits for verification.
Verifying bootstrap results in the test suite is very limited, If you set a seed, you can get "reasonable" numbers with a bootstrap replication that is not very large and is at least in the right ball park.
Also, if you expect that you are able to verify common code with another model later on, then I think more regression test are acceptable for now, and you add more verified tests when you have the more general model.
josef-pkt commentedon Aug 11, 2013
overall: I wouldn't worry too much unless there are other packages that are much faster. If there are no obvious speed improvements, then it takes time to get these results.
These are not results that we need for exploratory and interactive data analysis, and I think in some cases running the statistical during a coffee break or overnight is ok. We start to have a few cases like this.
I think the only larger time savings will come from an improved directed search.
For practical usage, choosing the number of replications in the bootstrap based on preliminary results might also be useful. For example, run 500 bootstrap samples, if the p-value is large then stop, because it doesn't really matter for hypothesis tests whether the p-value is 0.4 or 0.8. Similar, it would be nice if users could do the bootstrap in steps, run 500 samples, inspect, and then decide whether to run 1500 more samples.
Neither of these two are used yet in statsmodels.
You could open a separate issue for performance improvements, and work on the other things.
In SETAR the underlying estimation is OLS so it's still fast, for other cases even getting one estimate will be time consuming.
j-grana6 commentedon Aug 14, 2013
Just playing around with the code a bit, I can't call a fit for the same model twice:
In [38]: mod = SETAR(np.asarray(x), 2,1)
In [39]: fitted = mod.fit()
In [40]: fitted.params
Out[40]:
array([ 1.17018660e-17, 9.00000000e-01, -1.70593696e-02,
9.65828370e-01])
In [41]: mod.fit()
InvalidRegimeError Traceback (most recent call last)
in ()
----> 1 mod.fit()
/tmp/ipython-69144Pt.py in fit(self)
/tmp/ipython-69144Pt.py in build_exog(self, delay, thresholds, check_nobs)
InvalidRegimeError: Regime 1 has too few observations: threshold values may need to be adjusted
j-grana6 commentedon Aug 14, 2013
Also, from a user perspective, if I have a model and want to change some of the initial parameters. can I just change the attribute directly? I imagine not but haven't looked into it. Nevertheless, I can imagine a user wanting to estimate a setar with two regimes and a setar with 3 regimes and it would be easy if there were some set_num_regime methods that would allow the user to change some of the initial parameters without creating a whole new model instance.
j-grana6 commentedon Aug 14, 2013
Also, did some profiling for the setar (2,2). It seems like when build_exog is called within _grid_search_objective, there are some unnecessary calculations at the end (mostly the checks with the nobs). Are they necessary every time build_exog is called? I will email you the profile.
ChadFulton commentedon Aug 14, 2013
Thanks! This was a bug from some sloppy use of self.exog. I've included it in some other fixes of annoying mistakes that I'll push in a bit.
This is something I hadn't really thought about, but it sounds good to have. So, were you thinking of something like:
if so, I'm not sure how we could achieve that, since the results object relies on the model object. I'd suggest passing the result constructor a deep copy of the model object instead of the object itself, but I've never been too sure about how much one can count on a deep copy to not give WTFs. What do you think?
Or, if you meant:
I could make a setter for the important parameters (e.g. order, ar_order, delay, thresholds, trend, min_regime_frac, max_delay, threshold_grid_size) that would re-call fit() if it had already been called. Then the fact that the results class held the model object would actually work to our benefit. Although then I think the @cache_readonly decorator would have to be removed from the properties.
Or, if you just meant
that would work right now.whoops, no it wouldn't. It seems like it would be good to include a setter method for those parameters above to clear everything out when something changes. What do you think?Or maybe you had something else in mind?
I think these are necessary - because each time _grid_search_objective is called with a different delay and/or threshold, so the dataset has to be built again, and every time I need to make sure that there are enough observations in each regime (apparently this is required for the asymptotic theory to hold), otherwise the (delay, thresholds) combination shouldn't even be considered as a candidate in the hyperparameter search.
That's a bummer, though, that the nobs count is taking 22% of the time. Seems awfully high to sum a column of ones and zeros?
Thanks for the comments!
jseabold commentedon Aug 14, 2013
On Wed, Aug 14, 2013 at 4:46 PM, ChadFulton [email protected]: