# Kernel-based Time-varying Regression - Part I¶

To address many of the time-series modeling problems at Uber, for example:

1. time-varying regression coefficients

2. complex seasonality pattern

This work proposes a kernel-based regression (KTR). The full details of model structure with an example application in marketing data science are found in Ng, Wang and Dai (2021). The core of KTR is that latent variables along with their own time-point location to approximate the coefficient curves varied over time. The core of KTR is the use of latent variables to define a smooth time varying representation of model coefficients. These smooth representations are Kernel Smooths. The KTR approach sharply reduces the number of parameters compared to typical dynamic linear models such as Harvey (1989) and Durbin and Koopman (2002). The reduced number of parameters improves computation speed; this allows for KTR tp practically handle larger numbers of regressors and detect small variance as explained in Ng (2021).

To topics covered here in Part I, are 1. KTR model structure 2. syntax to initialize, fit and predict a model 3. fit a model with complex seasonality 4. visualization of prediction and decomposed components

[1]:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

import orbit
from orbit.models import KTR
from orbit.diagnostics.plot import plot_predicted_data, plot_predicted_components

%matplotlib inline
pd.set_option('display.float_format', lambda x: '%.5f' % x)

[2]:

print(orbit.__version__)

1.1.0dev


## Model Structure¶

This section gives the mathematical structure of the KTR model. In short, it considers a time-series ($$y_t$$) as the linear combination of three parts which are the local-trend ($$l_t$$), seasonality ($$s_t$$), and regression ($$r_t$$) terms. Mathematically,

$y_t = l_t + s_t + r_t +\epsilon_t, ~ t = 1,\cdots, T,$

where the $$\epsilon_t$$ comprise a stationary random error process.

In KTR, the distinction between the local-trend, seasonality, and regressors while useful is semi-arbitrary and the time-series can also be considered as

$y_t = X_t^T\beta_t + \epsilon_t, ~ t = 1,\cdots, T,$

where $$\beta_t$$ is a $$P$$-dimensional vector of coefficients that vary over time (i.e., $$\beta_i$$ is almost certainly different from $$\beta_j$$ for $$i \neq j$$) and $$X_t$$ $$P$$-dimensional covariate vector (i.e., the $$t$$th row of $$X$$, the design matrix).

To reduce the total number of parameters in the model (potentially $$P \times t$$) the $$\beta_t$$ are parameterized with a weighted sum of $$J$$ local latent variables ($$b_1,..b_j,..b_J$$). That is

$B = K b^T$

where - coefficient matrix $$B$$ has size $$t \times P$$ with rows equal to the $$\beta_t$$. - knot matrix $$b$$ with size $$P\times J$$; each entry is a latent variable $$b_{p, j}$$. The $$b_j$$ can be viewed as the “knots” from the perspective of spline regression and $$j$$ is a time index such that $$t_j \in [1, \cdots, T]$$. - kernel matrix $$K$$ with size $$T\times J$$ where the $$i$$th row and $$j$$th element can be viewed as the normalized weight $$k(t_j, t) / \sum_{j=1}^{J} k(t_j, t)$$

For the level/trend,

$l_t = \beta_{t, \text{lev}}$

It can also be viewed as a dynamic intercept (where the regressor is a vector of ones).

For the seasonality,

$B_{\text{seas}} = K_{\text{seas}}b^T_{\text{seas}}$
$s_t = X_{t, \text{seas}}\beta_{t, \text{seas}}$

We use Fourier series to handle the seasonality; i.e., sin waves with varying periods are used for the columns of $$X_{ \text{seas}}$$.

The details for the additional regressors are given in Part II, as they are not used in this tutorial. Note this includes different choices of kernel function (which determines the kernel matrix $$K$$) and prior for matrix $$b$$.

## Data¶

To illustrate the usage of KTR, consider the daily series of electricity demand in Turkey from the 2000 - 2008.

[4]:

# from 2000-01-01 to 2008-12-31
date_col = 'date'
response_col = 'electricity'
df[response_col] = np.log(df[response_col])
print(df.shape)

(3288, 2)

[4]:

date electricity
0 2000-01-01 9.43760
1 2000-01-02 9.50130
2 2000-01-03 9.63565
3 2000-01-04 9.65392
4 2000-01-05 9.66089
[5]:

print(f'starts with {df[date_col].min()}\nends with {df[date_col].max()}\nshape: {df.shape}')

starts with 2000-01-01 00:00:00
ends with 2008-12-31 00:00:00
shape: (3288, 2)


### Train / Test Split¶

Split the data into a training set and test set for model validation.

[6]:

test_size=365
train_df=df[:-test_size]
test_df=df[-test_size:]


## A Quick Start on KTR¶

Here the Similar to other model types in Orbit, KTR follows sklearn model API style. First an instance of the Orbit class KTR is created. Second fit and predict methods are called for that instance. Note that unlike version <=1.0.15, the fitting API arg are within the function; thus, KTR is called directly.

[7]:

ktr = KTR(
response_col=response_col,
date_col=date_col,
seed=2021,
estimator='pyro-svi',
# bootstrap sampling to capture uncertainties
n_bootstrap_draws=1e4,
)

[8]:

ktr.fit(train_df)

INFO:root:Guessed max_plate_nesting = 1


We can take a look how the level is fitted with the data.

[9]:

predicted_df = ktr.predict(df=df)

[9]:

date prediction_5 prediction prediction_95
0 2000-01-01 9.30920 9.48209 9.65127
1 2000-01-02 9.36616 9.51101 9.65256
2 2000-01-03 9.40889 9.54252 9.67646
3 2000-01-04 9.41010 9.54308 9.67602
4 2000-01-05 9.40828 9.54299 9.67674
[10]:

_ = plot_predicted_data(training_actual_df=train_df, predicted_df=predicted_df,
date_col=date_col, actual_col=response_col,
test_actual_df=test_df, markersize=20, lw=.5)


It can also be helpful to see the trend knot locations and levels. This is done with the plot_lev_knots function.

[17]:

_ = ktr.plot_lev_knots()


## Fitting with Complex Seasonality¶

The previous model fit is not satisfactory as there is clear seasonality in the electrical demand time-series that is not accounted for. In this modelling example the electrical demand data is fit with a dual seasonality for weekly and yearly patterns. Since the data is daily, the seasonality periods are 7 and 365.25. These are added into the KTR object as a list through the seasonality arg. Otherwise the process is the same as the previous example.

[11]:

ktr_with_seas = KTR(
response_col=response_col,
date_col=date_col,
seed=2021,
seasonality=[7, 365.25],
estimator='pyro-svi',
n_bootstrap_draws=1e4,
)

[12]:

ktr_with_seas.fit(train_df)

INFO:root:Guessed max_plate_nesting = 1

[13]:

predicted_df = ktr_with_seas.predict(df=df, decompose=True)

[14]:

predicted_df.head(5)

[14]:

date prediction_5 prediction prediction_95 trend_5 trend trend_95 regression_5 regression regression_95 seasonality_7_5 seasonality_7 seasonality_7_95 seasonality_365.25_5 seasonality_365.25 seasonality_365.25_95
0 2000-01-01 9.34836 9.46007 9.56814 9.32158 9.43329 9.54137 0.00000 0.00000 0.00000 -0.02782 -0.02782 -0.02782 0.05460 0.05460 0.05460
1 2000-01-02 9.39211 9.48144 9.56852 9.41231 9.50164 9.58872 0.00000 0.00000 0.00000 -0.07570 -0.07570 -0.07570 0.05549 0.05549 0.05549
2 2000-01-03 9.53228 9.61243 9.69305 9.49238 9.57254 9.65316 0.00000 0.00000 0.00000 -0.01645 -0.01645 -0.01645 0.05635 0.05635 0.05635
3 2000-01-04 9.58806 9.66820 9.74872 9.49247 9.57261 9.65313 0.00000 0.00000 0.00000 0.03842 0.03842 0.03842 0.05717 0.05717 0.05717
4 2000-01-05 9.57141 9.65268 9.73346 9.49177 9.57304 9.65381 0.00000 0.00000 0.00000 0.02170 0.02170 0.02170 0.05795 0.05795 0.05795

Tips: there is an additional arg seasonality_fs_order to control the number of orders we want to approximate the seasonality. In general, they cannot violate the condition that 2 * seasonality_fs_order < seasonality since each order represents adding a pair of sine and cosine regressors.

## More Diagnostic and Visualization¶

Here are a few more diagnostic and visualization. The fit is decomposed into components, the local trend and both periods of seasonality.

[15]:

_ = plot_predicted_data(training_actual_df=train_df, predicted_df=predicted_df,
date_col=date_col, actual_col=response_col,
test_actual_df=test_df, markersize=10, lw=.5)

[16]:

_ = plot_predicted_components(predicted_df=predicted_df, date_col=date_col, plot_components=['trend', 'seasonality_7', 'seasonality_365.25'])


## References¶

1. Ng, Wang and Dai (2021) Bayesian Time Varying Coefficient Model with Applications to Marketing Mix Modeling, arXiv preprint arXiv:2106.03322

2. Hastie, Trevor and Tibshirani, Robert. (1990), Generalized Additive Models, New York: Chapman and Hall.

3. Wood, S. N. (2006), Generalized Additive Models: an introduction with R, Boca Raton: Chapman & Hall/CRC

4. Harvey, C. A. (1989). Forecasting, Structural Time Series and the Kalman Filter, Cambridge University Press.

5. Durbin, J., Koopman, S. J.. (2001). Time Series Analysis by State Space Methods, Oxford Statistical Science Series