Approximate leave-future-out cross-validation for time series models

Paul Bürkner, Aki Vehtari, Jonah Gabry

2019-03-13

Introduction

One of the most common goals of a time series analysis is to use the observed series to inform predictions for future observations. We will refer to this task of predicting a sequence of \(M\) future observations as \(M\)-step-ahead prediction (\(M\)-SAP). Fortunately, once we have fit a model and can sample from the posterior predictive distribution, it is straightforward to generate predictions as far into the future as we want. It is also straightforward to evaluate the \(M\)-SAP performance of a time series model by comparing the predictions to the observed sequence of \(M\) future data points once they become available.

Unfortunately, we are often in the position of having to use a model to inform decisions before we can collect the future observations required for assessing the predictive performance. If we have many competing models we may also need to first decide which of the models (or which combination of the models) we should rely on for predictions. In these situations the best we can do is to use methods for approximating the expected predictive performance of our models using only the observations of the time series we already have.

If there were no time dependence in the data or if the focus is to assess the non-time-dependent part of the model, we could use methods like leave-one-out cross-validation (LOO-CV). For a data set with \(N\) observations, we refit the model \(N\) times, each time leaving out one of the \(N\) observations and assessing how well the model predicts the left-out observation. LOO-CV is very expensive computationally in most realistic settings, but the Pareto smoothed importance sampling (PSIS, Vehtari et al, 2017ab) algorithm provided by the loo package allows for approximating exact LOO-CV with PSIS-LOO-CV. PSIS-LOO-CV requires only a single fit of the full model and comes with diagnostics for assessing the validity of the approximation.

With a time series we can do something similar to LOO-CV but, except in a few cases, it does not make sense to leave out observations one at a time because then we are allowing information from the future to influence predictions of the past (i.e., times \(t + 1, t+2, \ldots\) should not be used to predict for time \(t\)). To apply the idea of cross-validation to the \(M\)-SAP case, instead of leave-one-out cross-validation we need some form of leave-future-out cross-validation (LFO-CV). As we will demonstrate in this case study, LFO-CV does not refer to one particular prediction task but rather to various possible cross-validation approaches that all involve some form of prediction for new time series data. Like exact LOO-CV, exact LFO-CV requires refitting the model many times to different subsets of the data, which is computationally very costly for most nontrivial examples, in particular for Bayesian analyses where refitting the model means estimating a new posterior distribution rather than a point estimate.

Although PSIS-LOO-CV provides an efficient approximation to exact LOO-CV, until now there has not been an analogous approximation to exact LFO-CV that drastically reduces the computational burden while also providing informative diagnostics about the quality of the approximation. In this case study we present PSIS-LFO-CV, an algorithm that typically only requires refitting the time-series model a small number times and will make LFO-CV tractable for many more realistic applications than previously possible.

More details can be found in our paper about approximate LFO-CV (Bürkner, Gabry, & Vehtari, 2019), which is available as a preprint on arXiv (https://arxiv.org/abs/1902.06281).

\(M\)-step-ahead predictions

Assume we have a time series of observations \(y = (y_1, y_2, \ldots, y_N)\) and let \(L\) be the minimum number of observations from the series that we will require before making predictions for future data. Depending on the application and how informative the data is, it may not be possible to make reasonable predictions for \(y_{i}\) based on \((y_1, \dots, y_{i-1})\) until \(i\) is large enough so that we can learn enough about the time series to predict future observations. Setting \(L=10\), for example, means that we will only assess predictive performance starting with observation \(y_{11}\), so that we always have at least 10 previous observations to condition on.

In order to assess \(M\)-SAP performance we would like to compute the predictive densities

\[ p(y_{i+1:M} \,|\, y_{1:i}) = p(y_i, \ldots, y_{i + M - 1} \,|\, y_{1},...,y_{i-1}) \]

for each \(i \in \{L + 1, \ldots, N - M + 1\}\). The quantities \(p(y_{i+1:M} \,|\, y_{1:i})\) can be computed with the help of the posterior distribution \(p(\theta \,|\, y_{1:i})\) of the parameters \(\theta\) conditional on only the first \(i-1\) observations of the time-series:

\[ p(y_{i+1:M} \,| \, y_{1:i}) = \int p(y_{i+1:M} \,| \, y_{1:i}, \theta) \, p(\theta\,|\,y_{1:i}) \,d\theta. \]

Having obtained \(S\) draws \((\theta_{1:i}^{(1)}, \ldots, \theta_{1:i}^{(S)})\) from the posterior distribution \(p(\theta\,|\,y_{1:i})\), we can estimate \(p(y_{i+1:M} | y_{1:i})\) as

\[ p(y_{i+1:M} \,|\, y_{1:i}) \approx \frac{1}{S}\sum_{s=1}^S p(y_{i+1:M} \,|\, y_{1:i}, \theta_{1:i}^{(s)}). \]

In the following, we consider factorizable models in which the response values are conditionally independent given the parameters and the likelihood can be written in the familiar form

\[ p(y \,|\, \theta) = \prod_{i=1}^N p(y_i \,|\, \theta). \]

In this case, \(p(y_{i+1:M} \,|\, y_{1:i}, \theta)\) reduces to \[ p(y_{i+1:M} \,|\, \theta) = \prod_{j = i}^{i + M -1} p(y_j \,|\, \theta), \] due to the assumption of conditional independence between \(y_{i+1:M}\) and \(y_{1:i}\) given \(\theta\).

Non-factorizable models, which do not make this assumption, are discussed in a separate vignette Leave-one-out cross-validation for non-factorizable models.

Approximate \(M\)-SAP using importance-sampling

Unfortunately, the math above makes use of the posterior distributions from many different fits of the model to different subsets of the data. That is, to obtain the predictive density \(p(y_{i+1:M} \,|\, y_{1:i})\) requires fitting a model to only the first \(i-1\) data points, and we will need to do this for every value of \(i\) under consideration (all \(i \in \{L + 1, \ldots, N - M + 1\}\)).

To reduce the number of models that need to be fit for the purpose of obtaining each of the densities \(p(y_{i+1:M} \,|\, y_{1:i})\), we propose the following algorithm. Starting with \(i = N - M + 1\), we approximate each \(p(y_{i+1:M} \,|\, y_{1:i})\) using Pareto smoothed importance sampling (PSIS, Vehtari et al, 2017ab):

\[ p(y_{i+1:M} \,|\, y_{1:i}) \approx \frac{ \sum_{s=1}^S w_i^{(s)}\, p(y_{i+1:M} \,|\, \theta^{(s)})}{ \sum_{s=1}^S w_i^{(s)}}, \]

where \(w_i^{(s)}\) are importance weights and \(\theta^{(s)}\) are draws from the posterior distribution based on all observations. To obtain \(w_i^{(s)}\), we first compute the raw importance ratios

\[ r_i^{(s)} \propto \frac{1}{\prod_{j = i}^N p(y_j \,|\, \,\theta^{(s)})}, \]

and then stabilize them using PSIS.

We then decrease \(i\) by \(1\) (i.e., we move backwards in time) and repeat the process. At some observation \(i\), the variability of importance ratios \(r_i^{(s)}\) will become too large and importance sampling fails. We will refer to this particular value of \(i\) as \(i^\star_1\). To identify the value of \(i^\star_1\) we check for which value of \(i\) does the estimated shape parameter \(k\) of the generalized Pareto distribution first crosses a certain threshold. Only then do we refit the model using only observations before \(i^\star_1\) and then restart the process. In some cases we may only need to refit once and in other cases we will find a value \(i^\star_2\) that requires a second refitting, maybe an \(i^\star_3\) that requires a third refitting, and so on. We repeat the refitting as few times as is required (only if \(k > \text{threshold}\)) until we arrive at \(i = L+1\). Recall that \(L\) is the minimum number of observations we have deemed acceptable for making predictions (setting \(L=0\) means predictions of all observations should be computed).

For LOO, we recommend to use a threshold of \(0.7\) (Vehtari et al, 2017ab), but for LFO, the threshold should be smaller as influential observations will affect all pointwise LFO approximations until the next refit and thus much stronger than in LOO. For the present case study, we choose a threshold of \(0.6\), which also seems to be generally reasonable threshold for LFO (Bürkner et al. 2019).

Autoregressive models

Autoregressive (AR) models are some of the most commonly used time-series models. An AR(p) model —an autoregressive model of order \(p\)— can be defined as

\[ y_i = \eta_i + \sum_{k = 1}^p \varphi_k y_{i - k} + \varepsilon_i, \]

where \(\eta_i\) is the linear predictor for the \(i\)th observation, \(\phi_k\) are the autoregressive parameters and \(\varepsilon_i\) are pairwise independent errors, which are usually assumed to be normally distributed with equal variance \(\sigma^2\). The model implies a recursive formula that allows for computing the right-hand side of the above equation for observation \(i\) based on the values of the equations for previous observations.

Case Study: Annual measurements of the level of Lake Huron

To illustrate the application of PSIS-LFO-CV for estimating expected \(M\)-SAP performance, we will fit a model for 98 annual measurements of the water level (in feet) of Lake Huron from the years 1875–1972. This data set is found in the datasets R package, which is installed automatically with R.

In addition to the loo package, for this analysis we will use the brms interface to Stan to generate a Stan program and fit the model, and also the bayesplot and ggplot2 packages for plotting.

library("loo")
library("brms")
library("bayesplot")
library("ggplot2")
color_scheme_set("brightblue")
theme_set(theme_default())

CHAINS <- 4
SEED <- 1234
set.seed(SEED)

Before fitting a model, we will first put the data into a data frame and then look at the time series.

N <- length(LakeHuron)
df <- data.frame(
  y = as.numeric(LakeHuron),
  year = as.numeric(time(LakeHuron)),
  time = 1:N
)

# save plot labels to reuse them
plot_labs <- labs(
  y = "Water Level (ft)", 
  x = "Year",
  title = "Water Level in Lake Huron (1875-1972)"
) 

ggplot(df, aes(x = year, y = y)) + 
  geom_point(size = 1) +
  plot_labs

The above plot shows rather strong autocorrelation of the time-series as well as some trend towards lower levels for later points in time.

We can specify an AR(4) model for these data using the brms package as follows:

control <- list(adapt_delta = 0.95)
fit <- brm(
  y ~ 1, 
  data = df, 
  autocor = cor_ar(~time, p = 4), 
  prior = prior(normal(0, 0.5), class = "ar"),
  control = control, 
  seed = SEED, 
  chains = CHAINS
)

The model implied predictions along with the observed values can be plotted, which reveals a rather good fit to the data.

preds <- posterior_predict(fit)
preds <- cbind(
  Estimate = colMeans(preds), 
  Q5 = apply(preds, 2, quantile, probs = 0.05),
  Q95 = apply(preds, 2, quantile, probs = 0.95)
)

ggplot(cbind(df, preds), aes(x = year, y = Estimate)) +
  geom_smooth(aes(ymin = Q5, ymax = Q95), stat = "identity", size = 0.5) +
  geom_point(aes(y = y)) + 
  labs(subtitle = "Mean (blue) and 90% predictive intervals (gray) vs. observed data (black)") +
  plot_labs

To allow for reasonable predictions of future values, we will require at least \(L = 20\) historical observations (20 years) to make predictions.

L <- 20

We first perform approximate leave-one-out cross-validation (LOO-CV) for the purpose of later comparison with exact and approximate LFO-CV for the 1-SAP case.

loo_cv <- loo(log_lik(fit)[, (L + 1):N])
print(loo_cv)

Computed from 4000 by 78 log-likelihood matrix

         Estimate   SE
elpd_loo    -89.0  6.5
p_loo         4.3  0.9
looic       178.1 12.9
------
Monte Carlo SE of elpd_loo is 0.0.

All Pareto k estimates are good (k < 0.5).
See help('pareto-k-diagnostic') for details.

1-step-ahead predictions leaving out all future values

The most basic version of \(M\)-SAP is 1-SAP, in which we predict only one step ahead. In this case, \(y_{i+1:M}\) simplifies to \(y_{i}\) and the LFO-CV algorithm becomes considerably simpler than for larger values of \(M\).

Exact 1-step-ahead predictions

Before we compute approximate LFO-CV using PSIS we will first compute exact LFO-CV for the 1-SAP case so we can use it as a benchmark later. The initial step for the exact computation is to calculate the log-predictive densities by refitting the model many times:

Then we compute the exact expected log predictive density (ELPD):

      ELPD
LOO -89.04
LFO -93.65

We see that the ELPD from LFO-CV for 1-step-ahead predictions is lower than the ELPD estimate from LOO-CV, which should be expected since LOO-CV is making use of more of the time series. That is, since the LFO-CV approach only uses observations from before the left-out data point but LOO-CV uses all data points other than the left-out observation, we should expect to see the larger ELPD from LOO-CV.

Approximate 1-step-ahead predictions

For illustrative purposes, we will first compute approximate 1-SAP without any refitting, even when the Pareto \(k\) estimate is too large. This will of course be a poor approximation to exact 1-SAP, in particular if the Pareto \(k\) estimates increase rather quickly beyond the threshold up to which PSIS tends to produce stable results.

If we plot the Pareto \(k\) estimates we can see that they do start to increase quickly and that once we work backwards to about halfway through the data points we get \(k > 0.6\). This is indicated by the vertical line in the plot below, which corresponds to the point \(i^\star_1\) discussed in Section Approximate \(M\)-SAP using importance-sampling above.

Consequently, it is not surprising that the resulting approximate ELPD for 1-SAP is far away from the exact ELPD we computed above:

                        ELPD
approx LFO (no refit) -88.71
exact LFO             -93.65

Next, we compute approximate 1-SAP with refit at observations where the Pareto \(k\) estimate exceeds the threshold of \(0.6\).

The code becomes a little bit more involved to handle the refitting procedure. Note that we can compute exact 1-SAP at the refitting points, which comes with no additional computational costs since we had to refit the model anyway.

We see that the final Pareto-\(k\)-estimates are mostly well below the threshold and that we only needed to refit the model a few times:

Using threshold  0.6 , model was refit  8  times, at observations 84 61 57 55 45 38 24 21

The approximate 1-SAP ELPD is remarkably similar to the exact 1-SAP ELPD computed above, which indicates our algorithm to compute approximate 1-SAP worked well for the present data and model.

                           ELPD
approx LFO (no refits)   -88.71
approx LFO (with refits) -93.41
exact LFO                -93.65

Plotting exact against approximate predictions, we see that no approximation value deviates far from its exact counterpart, providing further evidence for the good quality of our approximation.

We can also look at the maximum difference and average difference between the approximate and exact ELPD calculations, which also indicate a ver close approximation:

          [,1]
Max diff  0.06
Mean diff 0.01

\(M\)-step-ahead predictions leaving out all future values

To illustrate the application of \(M\)-SAP for \(M > 1\), we next compute exact and approximate LFO-CV for the 4-SAP case.

Exact \(M\)-step-ahead predictions

The necessary steps are the same as for 1-SAP with the exception that the log-density values of interest are now the sums of the log predictive densities of four consecutive observations. Further, the stability of the PSIS approximation actually stays the same for all \(M\) as it only depends on the number of observations we leave out, not on the number of observations we predict.

     ELPD 
-356.2244 

Approximate \(M\)-step-ahead predictions

Computing the approximate PSIS-LFO-CV for the 4-SAP case is a little bit more involved than the approximate version for the 1-SAP case, although the underlying principles remain the same.

Again, we see that the final Pareto-\(k\)-estimates are mostly well below the threshold and that we only needed to refit the model a few times:

Using threshold  0.6 , model was refit  6  times, at observations 84 64 57 53 40 21

The approximate ELPD computed for the 4-SAP case is not as close to its exact counterpart as in the 1-SAP case.

              ELPD
Approx LFO -354.42
Exact LFO  -356.22

Plotting exact against approximate pointwise predictions confirms that, for a few specific data points, the approximate predictions underestimate the exact predictions.

Conclusion

In this case study we have shown how to do carry out exact and approximate leave-future-out cross-validation for \(M\)-step-ahead prediction tasks. For the data and model used in our example, the PSIS-LFO-CV algorithm provides reasonably stable and accurate results despite not requiring us to refit the model nearly as many times. For more details on approximate LFO-CV, we refer to Bürkner et al. (2019).


References

Bürkner P. C., Gabry J., & Vehtari A. (2019). Approximate leave-future-out cross-validation for time series models. arXiv preprint.

Vehtari A., Gelman A., & Gabry J. (2017a). Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC. Statistics and Computing, 27(5), 1413–1432. :10.1007/s11222-016-9696-4. Online. arXiv preprint arXiv:1507.04544.

Vehtari A., Gelman A., & Gabry J. (2017b). Pareto smoothed importance sampling. arXiv preprint arXiv:1507.02646.


Appendix

Appendix: Session information

R version 3.5.2 (2018-12-20)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Sierra 10.12.6

Matrix products: default
BLAS: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRblas.0.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRlapack.dylib

locale:
[1] C/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] brms_2.5.0           ggplot2_3.1.0        loo_2.1.0           
[4] bayesplot_1.6.0.9000 rstanarm_2.18.2      Rcpp_1.0.0          
[7] knitr_1.21          

loaded via a namespace (and not attached):
 [1] Brobdingnag_1.2-5    splines_3.5.2        gtools_3.8.1        
 [4] StanHeaders_2.18.1   threejs_0.3.1        shiny_1.2.0         
 [7] assertthat_0.2.0     stats4_3.5.2         yaml_2.2.0          
[10] backports_1.1.3      pillar_1.3.1         lattice_0.20-38     
[13] glue_1.3.0           digest_0.6.18        promises_1.0.1      
[16] minqa_1.2.4          colorspace_1.4-0     htmltools_0.3.6     
[19] httpuv_1.4.5.1       Matrix_1.2-15        plyr_1.8.4          
[22] dygraphs_1.1.1.6     pkgconfig_2.0.2      rstan_2.18.2        
[25] mvtnorm_1.0-10       purrr_0.3.1          xtable_1.8-3        
[28] scales_1.0.0         processx_3.3.0       later_0.8.0         
[31] lme4_1.1-21          tibble_2.0.1         DT_0.5              
[34] withr_2.1.2          shinyjs_1.0          lazyeval_0.2.1      
[37] cli_1.0.1            survival_2.43-3      magrittr_1.5        
[40] crayon_1.3.4         mime_0.6             evaluate_0.13       
[43] ps_1.3.0             nlme_3.1-137         MASS_7.3-51.1       
[46] xts_0.11-2           pkgbuild_1.0.2       colourpicker_1.0    
[49] rsconnect_0.8.13     tools_3.5.2          prettyunits_1.0.2   
[52] matrixStats_0.54.0   stringr_1.4.0        munsell_0.5.0       
[55] callr_3.1.1          compiler_3.5.2       rlang_0.3.1         
[58] nloptr_1.2.1         grid_3.5.2           ggridges_0.5.1      
[61] htmlwidgets_1.3      crosstalk_1.0.0      igraph_1.2.4        
[64] miniUI_0.1.1.1       labeling_0.3         base64enc_0.1-3     
[67] rmarkdown_1.11       boot_1.3-20          codetools_0.2-15    
[70] gtable_0.2.0         abind_1.4-5          inline_0.3.15       
[73] markdown_0.9         reshape2_1.4.3       R6_2.4.0            
[76] gridExtra_2.3        rstantools_1.5.1     zoo_1.8-4           
[79] bridgesampling_0.4-0 dplyr_0.8.0.1        shinystan_2.5.0     
[82] shinythemes_1.1.2    stringi_1.3.1        parallel_3.5.2      
[85] coda_0.19-2          tidyselect_0.2.5     xfun_0.5            

Appendix: Licenses