# Time Series Forecasting

In this tutorial, we will demonstrate how to build a model for time series forecasting in NumPyro. Specifically, we will replicate the **Seasonal, Global Trend (SGT)** model from the [Rlgt: Bayesian Exponential Smoothing Models with Trend Modifications](https://cran.r-project.org/web/packages/Rlgt/index.html) package. The time series data that we will use for this tutorial is the **lynx** dataset, which contains annual numbers of lynx trappings from 1821 to 1934 in Canada.


```python
import os

from IPython.display import set_matplotlib_formats
import matplotlib.pyplot as plt
import pandas as pd

import jax.numpy as np
from jax import lax, random, vmap
from jax.nn import softmax

import numpyro; numpyro.set_host_device_count(4)
import numpyro.distributions as dist
from numpyro.diagnostics import autocorrelation, hpdi
from numpyro import handlers
from numpyro.infer import MCMC, NUTS

if "NUMPYRO_SPHINXBUILD" in os.environ:
    set_matplotlib_formats('svg')

assert numpyro.__version__.startswith('0.2.4')
```

## Data

First, lets import and take a look at the dataset.


```python
URL = "https://raw.githubusercontent.com/vincentarelbundock/Rdatasets/master/csv/datasets/lynx.csv"
lynx = pd.read_csv(URL, index_col=0)
data = lynx["value"].values
print("Length of time series:", data.shape[0])
plt.figure(figsize=(8, 4))
plt.plot(lynx["time"], data)
plt.show()
```

The time series has a length of 114 (a data point for each year), and by looking at the plot, we can observe [seasonality](https://en.wikipedia.org/wiki/Seasonality) in this dataset, which is the recurrence of similar patterns at specific time periods. e.g. in this dataset, we observe a cyclical pattern every 10 years, but there is also a less obvious but clear spike in the number of trappings every 40 years. Let us see if we can model this effect in NumPyro.

In this tutorial, we will use the first 80 values for training and the last 34 values for testing.


```python
y_train, y_test = np.array(data[:80], dtype=np.float32), data[80:]
```

## Model

The model we are going to use is called **Seasonal, Global Trend**, which when tested on 3003 time series of the [M-3 competition](https://forecasters.org/resources/time-series-data/m3-competition/), has been known to outperform other models originally participating in the competition:

$$
\begin{align}
\text{exp_val}_{t} &= \text{level}_{t-1} + \text{coef_trend} \times \text{level}_{t-1}^{\text{pow_trend}} + \text{s}_t \times \text{level}_{t-1}^{\text{pow_season}}, \\
\sigma_{t} &= \sigma \times \text{exp_val}_{t}^{\text{powx}} + \text{offset}, \\
y_{t} &\sim \text{StudentT}(\nu, \text{exp_val}_{t}, \sigma_{t})
\end{align}
$$

, where `level` and `s` follows the following recursion rules:

$$
\begin{align}
\text{level_p} &=
\begin{cases}
y_t - \text{s}_t \times \text{level}_{t-1}^{\text{pow_season}} & \text{if } t \le \text{seasonality}, \\ 
\text{Average} \left[y(t - \text{seasonality} + 1), \ldots, y(t)\right] & \text{otherwise},
\end{cases} \\
\text{level}_{t} &= \text{level_sm} \times \text{level_p} + (1 - \text{level_sm}) \times \text{level}_{t-1}, \\
\text{s}_{t + \text{seasonality}} &= \text{s_sm} \times \frac{y_{t} - \text{level}_{t}}{\text{level}_{t-1}^{\text{pow_trend}}}
+ (1 - \text{s_sm}) \times \text{s}_{t}.
\end{align}
$$

A more detailed explanation for SGT model can be found in [this vignette](https://cran.r-project.org/web/packages/Rlgt/vignettes/GT_models.html) from the authors of the Rlgt package. Here we summarize the core ideas of this model:

+ [Student's t-distribution](https://en.wikipedia.org/wiki/Student%27s_t-distribution), which has heavier tails than normal distribution, is used for the likelihood.
+ The expected value `exp_val` consists of a trending component and a seasonal component:
  - The trend is governed by the map $x \mapsto x + ax^b$, where $x$ is `level`, $a$ is `coef_trend`, and $b$ is `pow_trend`. Note that when $b \sim 0$, the trend is linear with $a$ is the slope, and when $b \sim 1$, the trend is exponential with $a$ is the rate. So that function can cover a large family of trend.
  - When time changes, `level` and `s` are updated to new values. Coefficients `level_sm` and `s_sm` are used to make the transition smoothly.
+ When `powx` is near $0$, the error $\sigma_t$ will be nearly constant while when `powx` is near $1$, the error will be propotional to the expected value.
+ There are several varieties of SGT. In this tutorial, we use generalized seasonality and seasonal average method.

Note that `level` and `s` are updated recursively while we collect the expected value at each time step. NumPyro uses [JAX](https://github.com/google/jax) in the backend to JIT compile many critical parts of the NUTS algorithm, including the verlet integrator and the tree building process. However, doing so using Python's `for` loop in the model will result in a long compilation time for the model, so we use `jax.lax.scan` instead. A detailed explanation for using this utility can be found in [lax.scan documentation](https://jax.readthedocs.io/en/latest/_autosummary/jax.lax.scan.html#jax.lax.scan). Here we use it to collect expected values while the pair `(level, s)` plays the role of carrying state.


```python
def scan_exp_val(y, init_s, level_sm, s_sm, coef_trend, pow_trend, pow_season):
    seasonality = init_s.shape[0]

    def scan_fn(carry, t):
        level, s, moving_sum = carry
        season = s[0] * level ** pow_season
        exp_val = level + coef_trend * level ** pow_trend + season
        exp_val = np.clip(exp_val, a_min=0)

        moving_sum = moving_sum + y[t] - np.where(t >= seasonality, y[t - seasonality], 0.)
        level_p = np.where(t >= seasonality, moving_sum / seasonality, y[t] - season)
        level = level_sm * level_p + (1 - level_sm) * level
        level = np.clip(level, a_min=0)
        new_s = (s_sm * (y[t] - level) / season + (1 - s_sm)) * s[0]
        s = np.concatenate([s[1:], new_s[None]], axis=0)
        return (level, s, moving_sum), exp_val

    level_init = y[0]
    s_init = np.concatenate([init_s[1:], init_s[:1]], axis=0)
    moving_sum = level_init
    (last_level, last_s, moving_sum), exp_vals = lax.scan(
        scan_fn, (level_init, s_init, moving_sum), np.arange(1, y.shape[0]))
    return exp_vals, last_level, last_s
```

With our utility function defined above, we are ready to specify the model using *NumPyro* primitives. In NumPyro, we use the primitive `sample(name, prior)` to declare a latent random variable with a corresponding `prior`. These primitives can have custom interpretations depending on the effect handlers that are used by NumPyro inference algorithms in the backend. e.g. we can condition on specific values using the `substitute` handler, or record values at these sample sites in the execution trace using the `trace` handler. Note that these details are not important for specifying the model, or running inference, but curious readers are encouraged to read the [tutorial on effect handlers](http://pyro.ai/examples/effect_handlers.html) in Pyro.


```python
def sgt(y, seasonality):
    # heuristically, standard derivation of Cauchy prior depends on the max value of data
    cauchy_sd = np.max(y) / 150

    nu = numpyro.sample("nu", dist.Uniform(2, 20))
    powx = numpyro.sample("powx", dist.Uniform(0, 1))
    sigma = numpyro.sample("sigma", dist.HalfCauchy(cauchy_sd))
    offset_sigma = numpyro.sample("offset_sigma", dist.TruncatedCauchy(low=1e-10, loc=1e-10,
                                                                       scale=cauchy_sd))

    coef_trend = numpyro.sample("coef_trend", dist.Cauchy(0, cauchy_sd))
    pow_trend_beta = numpyro.sample("pow_trend_beta", dist.Beta(1, 1))
    # pow_trend takes values from -0.5 to 1
    pow_trend = 1.5 * pow_trend_beta - 0.5
    pow_season = numpyro.sample("pow_season", dist.Beta(1, 1))

    level_sm = numpyro.sample("level_sm", dist.Beta(1, 2))
    s_sm = numpyro.sample("s_sm", dist.Uniform(0, 1))
    init_s = numpyro.sample("init_s", dist.Cauchy(0, y[:seasonality] * 0.3))

    exp_val, last_level, last_s = scan_exp_val(
        y, init_s, level_sm, s_sm, coef_trend, pow_trend, pow_season)
    omega = sigma * exp_val ** powx + offset_sigma
    numpyro.sample("y", dist.StudentT(nu, exp_val, omega), obs=y[1:])
    # we return last `level` and last `s` for forecasting
    return last_level, last_s
```

Note that all prior parameters are retrieved from [this file](https://github.com/cbergmeir/Rlgt/blob/master/Rlgt/R/rlgtcontrol.R) in the original source.

## Inference

First, we want to choose a good value for `seasonality`. Following [the demo in Rlgt](https://github.com/cbergmeir/Rlgt/blob/master/Rlgt/demo/lynx.R), we will set `seasonality=38`. Indeed, this value can be guessed by looking at the plot of the training data, where the second order seasonality effect has a periodicity around $40$ years. Note that $38$ is also one of the highest-autocorrelation lags.


```python
print("Lag values sorted according to their autocorrelation values:\n") 
print(np.argsort(autocorrelation(y_train))[::-1])
```

    Lag values sorted according to their autocorrelation values:
    
    [ 0 67 57 38 68  1 29 58 37 56 28 10 19 39 66 78 47 77  9 79 48 76 30 18
     20 11 46 59 69 27 55 36  2  8 40 49 17 21 75 12 65 45 31 26  7 54 35 41
     50  3 22 60 70 16 44 13  6 25 74 53 42 32 23 43 51  4 15 14 34 24  5 52
     73 64 33 71 72 61 63 62]


Now, let us run $4$ MCMC chains (using the No-U-Turn Sampler algorithm) with $5000$ warmup steps and $5000$ sampling steps per each chain. The returned value will be a collection of $20000$ samples.


```python
kernel = NUTS(sgt)
mcmc = MCMC(kernel, num_warmup=5000, num_samples=5000, num_chains=4)
mcmc.run(random.PRNGKey(2), y_train, seasonality=38)
mcmc.print_summary()
samples = mcmc.get_samples()
```

    
                          mean       std    median      5.0%     95.0%     n_eff     r_hat
          coef_trend     37.41    146.47     14.58    -94.66    158.11    899.45      1.00
           init_s[0]     86.47    112.10     64.44    -71.79    238.22   3103.90      1.00
           init_s[1]    -20.09     74.78    -24.72   -133.16     89.86   3727.80      1.00
           init_s[2]     30.61     96.50     18.96   -114.20    172.59   6539.20      1.00
           init_s[3]    122.40    125.50    104.49    -65.33    307.99   5502.14      1.00
           init_s[4]    447.19    253.84    404.01     72.97    817.14   4448.29      1.00
           init_s[5]   1168.04    469.86   1089.44    480.24   1859.17   3045.90      1.00
           init_s[6]   1990.85    676.57   1888.51    939.77   2999.54   2269.65      1.00
           init_s[7]   3670.58   1116.12   3529.56   1936.24   5377.14   2239.09      1.00
           init_s[8]   2600.92    830.22   2497.08   1275.30   3830.12   2382.89      1.00
           init_s[9]    950.62    441.38    873.10    305.99   1605.88   3591.29      1.00
          init_s[10]     48.80    109.00     31.85   -107.24    204.84   5029.92      1.00
          init_s[11]     -1.05     50.78     -2.22    -84.10     68.44   6261.04      1.00
          init_s[12]    -10.22     64.41    -12.06   -119.67     84.49   5551.32      1.00
          init_s[13]     67.32    102.99     47.42    -74.20    228.30   6769.72      1.00
          init_s[14]    330.62    248.06    284.87    -20.52    672.49   6404.36      1.00
          init_s[15]    967.45    380.59    904.08    379.27   1522.60   3433.92      1.00
          init_s[16]   1257.06    484.78   1176.15    547.50   1994.05   2617.35      1.00
          init_s[17]   1381.97    569.38   1287.81    533.50   2198.29   2556.74      1.00
          init_s[18]    613.77    313.95    561.28    161.09   1064.75   3710.26      1.00
          init_s[19]     17.24     91.46      5.80   -121.23    146.82   5663.56      1.00
          init_s[20]    -31.33     66.56    -26.82   -141.77     65.53   6836.88      1.00
          init_s[21]    -15.05     47.50     -5.05    -97.72     43.51   2110.57      1.00
          init_s[22]     -2.25     45.41     -2.05    -69.50     60.48   4455.37      1.00
          init_s[23]     39.60     88.02     24.74    -83.23    169.93   5845.50      1.00
          init_s[24]    525.67    342.66    462.01     18.68    998.37   4501.69      1.00
          init_s[25]    926.82    453.26    846.58    269.68   1575.50   4160.67      1.00
          init_s[26]   1788.62    692.88   1683.25    742.71   2830.06   2661.40      1.00
          init_s[27]   1270.05    477.56   1189.62    548.85   1974.94   2725.48      1.00
          init_s[28]    213.62    172.18    183.75    -29.46    467.98   6231.66      1.00
          init_s[29]     -9.53     86.49    -17.25   -142.24    114.82   6054.94      1.00
          init_s[30]     -5.89     84.86    -13.67   -143.76    118.33   7664.38      1.00
          init_s[31]    -37.11     74.85    -37.10   -154.99     79.57   5162.96      1.00
          init_s[32]     -9.05     86.82    -16.76   -142.67    117.25   4841.36      1.00
          init_s[33]    112.13    139.36     89.61    -83.02    305.20   5633.16      1.00
          init_s[34]    510.17    296.97    459.01     77.70    915.20   4574.63      1.00
          init_s[35]   1069.24    451.47    992.84    398.07   1733.07   3594.75      1.00
          init_s[36]   1846.93    651.34   1747.20    868.30   2841.41   2858.36      1.00
          init_s[37]   1446.64    549.45   1365.04    607.13   2254.92   3286.41      1.00
            level_sm      0.00      0.00      0.00      0.00      0.00  10572.39      1.00
                  nu     12.18      4.75     12.40      5.42     20.00   8974.57      1.00
        offset_sigma     32.51     30.53     23.66      0.00     71.60   9205.88      1.00
          pow_season      0.09      0.04      0.09      0.01      0.15   1406.05      1.00
      pow_trend_beta      0.26      0.17      0.23      0.00      0.50   1427.71      1.00
                powx      0.62      0.13      0.61      0.40      0.83   5128.73      1.00
                s_sm      0.08      0.09      0.05      0.00      0.19   4123.16      1.00
               sigma      9.81      9.70      6.96      0.42     20.98   6775.15      1.00
    
    Number of divergences: 3594


## Forecasting

Given `samples` from `mcmc`, we want to do forecasting for the testing dataset `y_test`. First, we will make some utilities to do forecasting given a sample. Note that to retrieve the last `level` and last `s` value, we run the model forward by constraining the latent sites to a sample from the posterior using the `substitute` handler:

```python
...    level, s = substitute(sgt, sample)(y, seasonality)
```


```python
# Ref: https://github.com/cbergmeir/Rlgt/blob/master/Rlgt/R/forecast.rlgtfit.R
def sgt_forecast(future, sample, y, level, s):
    seasonality = s.shape[0]
    moving_sum = np.sum(y[-seasonality:])
    pow_trend = 1.5 * sample["pow_trend_beta"] - 0.5
    yfs = [0] * (seasonality + future)
    for t in range(future):
        season = s[0] * level ** sample["pow_season"]
        exp_val = level + sample["coef_trend"] * level ** pow_trend + season
        exp_val = np.clip(exp_val, a_min=0)
        omega = sample["sigma"] * exp_val ** sample["powx"] + sample["offset_sigma"]
        yf = numpyro.sample("yf[{}]".format(t), dist.StudentT(sample["nu"], exp_val, omega))
        yf = np.clip(yf, a_min=1e-30)
        yfs[t] = yf

        moving_sum = moving_sum + yf - np.where(t >= seasonality,
                                                yfs[t - seasonality], y[-seasonality + t])
        level_p = moving_sum / seasonality
        level_tmp = sample["level_sm"] * level_p + (1 - sample["level_sm"]) * level
        level = np.where(level_tmp > 1e-30, level_tmp, level)
        # s is repeated instead of being updated
        s = np.concatenate([s[1:], s[:1]], axis=0)


def forecast(future, rng_key, sample, y, seasonality):
    level, s = handlers.substitute(sgt, sample)(y, seasonality)
    forecast_model = handlers.seed(sgt_forecast, rng_key)
    forecast_trace = handlers.trace(forecast_model).get_trace(future, sample, y, level, s)
    results = [np.clip(forecast_trace["yf[{}]".format(t)]["value"], a_min=1e-30)
               for t in range(future)]
    return np.stack(results, axis=0)
```

Then, we can use [jax.vmap](https://jax.readthedocs.io/en/latest/jax.html#jax.vmap) to get prediction given a collection of samples. This allows us to vectorize the computation across the test dataset which can be dramatically faster as compared to using for-loop to collect predictions per test data point.


```python
rng_keys = random.split(random.PRNGKey(3), samples["nu"].shape[0])
forecast_marginal = vmap(lambda rng_key, sample: forecast(
    len(y_test), rng_key, sample, y_train, seasonality=38))(rng_keys, samples)
```

Finally, let's get sMAPE, root mean square error of the prediction, and visualize the result with the mean prediction and the 90% highest posterior density interval (HPDI).


```python
y_pred = np.mean(forecast_marginal, axis=0)
sMAPE = np.mean(np.abs(y_pred - y_test) / (y_pred + y_test)) * 200
msqrt = np.sqrt(np.mean((y_pred - y_test) ** 2))
print("sMAPE: {:.2f}, rmse: {:.2f}".format(sMAPE, msqrt))
```

    sMAPE: 62.63, rmse: 1242.24



```python
plt.figure(figsize=(8, 4))
plt.plot(lynx["time"], data)
t_future = lynx["time"][80:]
hpd_low, hpd_high = hpdi(forecast_marginal)
plt.plot(t_future, y_pred, lw=2)
plt.fill_between(t_future, hpd_low, hpd_high, alpha=0.3)
plt.title("Forecasting lynx dataset with SGT model (90% HPDI)")
plt.show()
```

As we can observe, the model has been able to learn both the first and second order seasonality effects, i.e. a cyclical pattern with a periodicity of around 10, as well as spikes that can be seen once every 40 or so years. Moreover, we not only have point estimates for the forecast but can also use the uncertainty estimates from the model to bound our forecasts. 

## Acknowledgements

We would like to thank Slawek Smyl for many helpful resources and suggestions. Fast inference would not have been possible without the support of JAX and the XLA teams, so we would like to thank them for providing such a great open-source platform for us to build on, and for their responsiveness in dealing with our feature requests and bug reports.

## References

[1] `Rlgt: Bayesian Exponential Smoothing Models with Trend Modifications`,<br>&nbsp;&nbsp;&nbsp;&nbsp;
Slawek Smyl, Christoph Bergmeir, Erwin Wibowo, To Wang Ng, Trustees of Columbia University

a1b1ddd72128d78f0687510fdc51a2bfc0f1f34c
ipynb
Jupyter Notebook
notebooks/source/time_series_forecasting.ipynb
ibab/numpyro
076bb2a15026734a41abf4eb39ce384ab68c297f
Apache-2.0
2020-11-30T23:51:45.000Z
2020-11-30T23:51:45.000Z
notebooks/source/time_series_forecasting.ipynb
ibab/numpyro
076bb2a15026734a41abf4eb39ce384ab68c297f
Apache-2.0
notebooks/source/time_series_forecasting.ipynb
ibab/numpyro
076bb2a15026734a41abf4eb39ce384ab68c297f
Apache-2.0
2020-11-30T23:52:33.000Z
2020-11-30T23:52:33.000Z
Qwen/Qwen-72B
1. YES
2. YES