# 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
%matplotlib inline
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

%matplotlib inline
%config InlineBackend.figure_format = 'svg'

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

## 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()
```

    Length of time series: 114



    

    


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     28.36    109.33     13.75    -96.50    151.29   2764.20      1.00
           init_s[0]     85.84    107.71     64.52    -56.27    244.16   6350.01      1.00
           init_s[1]    -21.37     70.38    -24.60   -129.36     87.29   6476.32      1.00
           init_s[2]     28.23     90.63     17.46   -109.90    168.82   8034.11      1.00
           init_s[3]    121.38    122.49    104.45    -64.41    307.98   7790.89      1.00
           init_s[4]    444.27    253.88    399.75     73.69    803.14   5425.01      1.00
           init_s[5]   1154.30    454.67   1082.10    474.81   1824.41   3323.04      1.00
           init_s[6]   1967.76    654.71   1875.68    991.57   3009.48   2508.97      1.00
           init_s[7]   3630.69   1091.43   3494.95   1942.17   5359.23   2163.04      1.00
           init_s[8]   2576.56    824.18   2465.40   1242.32   3765.52   2489.59      1.00
           init_s[9]    949.52    448.44    874.35    278.49   1578.72   4154.86      1.00
          init_s[10]     46.84    104.77     31.36   -108.52    196.83   7045.99      1.00
          init_s[11]      0.33     51.73     -1.63    -79.91     74.23   4677.82      1.00
          init_s[12]    -11.41     64.67    -12.58   -112.08     87.99   7045.24      1.00
          init_s[13]     67.82    102.62     48.88    -86.77    213.66   6894.05      1.00
          init_s[14]    331.29    254.64    279.65     -7.07    691.20   4911.24      1.00
          init_s[15]    958.97    379.11    897.11    397.58   1539.02   3593.74      1.00
          init_s[16]   1244.99    464.41   1173.42    533.33   1937.89   3028.85      1.00
          init_s[17]   1364.60    566.63   1272.27    558.66   2181.34   3294.02      1.00
          init_s[18]    610.28    306.88    558.86    172.22   1058.01   5260.91      1.00
          init_s[19]     18.12     90.42      6.50   -121.15    152.73   8773.39      1.00
          init_s[20]    -32.80     66.02    -27.80   -145.89     62.12   8010.78      1.00
          init_s[21]    -15.37     45.50     -5.29    -90.90     42.32   2738.95      1.00
          init_s[22]     -1.57     43.03     -1.71    -69.91     56.39   6246.31      1.00
          init_s[23]     38.93     84.02     25.28    -81.79    162.50   5054.23      1.00
          init_s[24]    525.13    345.44    460.70     28.97   1003.73   4487.02      1.00
          init_s[25]    925.65    452.41    844.26    269.00   1590.84   4032.84      1.00
          init_s[26]   1771.16    688.46   1662.04    747.30   2778.02   2825.21      1.00
          init_s[27]   1261.14    468.97   1192.82    557.60   1956.55   3286.92      1.00
          init_s[28]    213.69    167.78    184.25    -26.37    468.84   7015.20      1.00
          init_s[29]     -9.17     83.42    -16.21   -141.71    110.95   7638.58      1.00
          init_s[30]     -3.25     92.60    -13.25   -133.14    130.68   2646.61      1.00
          init_s[31]    -35.44     73.29    -36.46   -152.75     71.10   9199.11      1.00
          init_s[32]     -8.71     84.19    -15.67   -139.61    119.35   8349.57      1.00
          init_s[33]    112.58    135.37     91.05    -85.43    305.19   6781.17      1.00
          init_s[34]    508.20    292.01    456.43     96.94    931.00   4929.59      1.00
          init_s[35]   1056.10    444.59    978.63    394.94   1709.24   3681.42      1.00
          init_s[36]   1836.45    656.15   1739.05    837.30   2791.87   2702.09      1.00
          init_s[37]   1437.90    560.63   1346.29    606.47   2253.71   2980.41      1.00
            level_sm      0.00      0.00      0.00      0.00      0.00  15989.43      1.00
                  nu     12.26      4.77     12.59      5.42     19.98  10716.04      1.00
        offset_sigma     32.67     30.96     23.77      0.01     73.17  10475.04      1.00
          pow_season      0.09      0.04      0.09      0.02      0.15   1450.96      1.00
      pow_trend_beta      0.25      0.17      0.23      0.00      0.49   5022.31      1.00
                powx      0.62      0.13      0.62      0.41      0.85   4524.98      1.00
                s_sm      0.08      0.09      0.05      0.00      0.19  11552.92      1.00
               sigma      9.79     10.35      6.73      0.39     21.01   5790.93      1.00
    
    


## 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.66, rmse: 1242.18



```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

7ef80b65ccd0e179f50d28a66ecdac8cc41b0b47
ipynb
Jupyter Notebook
notebooks/source/time_series_forecasting.ipynb
alexalemi/numpyro
9a690c7f60dee13ff9ea88ce107400349c77ce77
MIT
notebooks/source/time_series_forecasting.ipynb
alexalemi/numpyro
9a690c7f60dee13ff9ea88ce107400349c77ce77
MIT
notebooks/source/time_series_forecasting.ipynb
alexalemi/numpyro
9a690c7f60dee13ff9ea88ce107400349c77ce77
MIT
Qwen/Qwen-72B
1. YES
2. YES