NonGaussian Local Linear Trend Models¶
Introduction¶
With NonGaussian state space models, we have the same basic setup as Gaussian state space models, but now a potentially nonGaussian measurement density. That is we are interested in problems of the form:
Usually MCMC based schemes are the right way to tackle this problem. Currently PyFlux uses BBVI for speed, but the meanfield approximation means there can be some bias in the states (although the results are generally okay for prediction). In the future, PyFlux will use a more structured approximation.
The NonGaussian local linear trend model has the same form as a Gaussian local linear trend model, but with a nonGaussian measurement density.
Example¶
For fun, and since it’s topical, we’ll apply a Poisson local level model to count data on the number of goals the football team Leicester have scored since they rejoined the Premier League. Each index represents a match they have played. This is a short dataset, but it shows the principle behind the model.
import numpy as np
import pyflux as pf
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
leicester = pd.read_csv('http://www.pyflux.com/notebooks/leicester_goals_scored.csv')
leicester.columns= ["Time","Goals","Season2"]
plt.figure(figsize=(15,5))
plt.plot(leicester["Goals"])
plt.ylabel('Goals Scored')
plt.title('Leicester Goals Since Joining EPL');
plt.show()
We can fit a Poisson local linear trend model as follows:
model = pf.NLLT(data=leicester, target='Goals', family=pf.Poisson())
We can also use the higherlevel wrapper which allows us to specify the family. If you pick a Normal distribution, then the Kalman filter will be used:
model = pf.LocalTrend(data=leicester, target='Goals', family=pf.Poisson())
Next we estimate the latent variables through a BBVI estimate \(z^{BBVI}\):
x = model.fit(iterations=5000)
x.summary()
10% done : ELBO is 27837.965202
20% done : ELBO is 10667.1947315
30% done : ELBO is 5150.42573307
40% done : ELBO is 2567.54029949
50% done : ELBO is 1291.29282788
60% done : ELBO is 578.99494029
70% done : ELBO is 251.124996408
80% done : ELBO is 100.355592594
90% done : ELBO is 49.3752685727
100% done : ELBO is 13.9899801048
Final model ELBO is 46.2333499244
Poisson Local Linear Trend Model
======================================================= ================================================
Dependent Variable: Goals Method: BBVI
Start Date: 0 Unnormalized Log Posterior: 235.942
End Date: 74 AIC: 467.884097447
Number of observations: 75 BIC: 463.24912122
========================================================================================================
Latent Variable Median Mean 95% Credibility Interval
======================================== ================== ================== =========================
Sigma^2 level 0.1738 0.1739 (0.1539  0.197)
Sigma^2 trend 0.0 0.0 (0.0  0.0)
========================================================================================================
We can plot the evolution parameter with plot_z()
:
model.plot_z([0])
model.plot_z([1])
Next we will plot the insample fit using plot_fit()
:
model.plot_fit(figsize=(15,10))
Class Description¶

class
NLLT
(data, ar, integ, target, family)¶ NonGaussian Local Linear Trend Models (NLLT).
Parameter Type Description data pd.DataFrame or np.ndarray Contains the univariate time series integ int How many times to difference the data (default: 0) target string or int Which column of DataFrame/array to use. family pf.Family instance The distribution for the time series, e.g pf.Normal()
Attributes

latent_variables
¶ A pf.LatentVariables() object containing information on the model latent variables, prior settings. any fitted values, starting values, and other latent variable information. When a model is fitted, this is where the latent variables are updated/stored. Please see the documentation on Latent Variables for information on attributes within this object, as well as methods for accessing the latent variable information.
Methods

adjust_prior
(index, prior)¶ Adjusts the priors for the model latent variables. The latent variables and their indices can be viewed by printing the
latent_variables
attribute attached to the model instance.Parameter Type Description index int Index of the latent variable to change prior pf.Family instance Prior distribution, e.g. pf.Normal()
Returns: void  changes the model
latent_variables
attribute

fit
(method, **kwargs)¶ Estimates latent variables for the model. User chooses an inference option and the method returns a results object, as well as updating the model’s
latent_variables
attribute.Parameter Type Description method str Inference option: e.g. ‘MH’ or ‘MLE’ See Bayesian Inference and Classical Inference sections of the documentation for the full list of inference options. Optional parameters can be entered that are relevant to the particular mode of inference chosen.
Returns: pf.Results instance with information for the estimated latent variables

plot_fit
(**kwargs)¶ Plots the fit of the model against the data. Optional arguments include figsize, the dimensions of the figure to plot.
Returns : void  shows a matplotlib plot

plot_predict
(h, past_values, intervals, **kwargs)¶ Plots predictions of the model, along with intervals.
Parameter Type Description h int How many steps to forecast ahead past_values int How many past datapoints to plot intervals boolean Whether to plot intervals or not Optional arguments include figsize  the dimensions of the figure to plot. Please note that if you use Maximum Likelihood or Variational Inference, the intervals shown will not reflect latent variable uncertainty. Only MetropolisHastings will give you fully Bayesian prediction intervals. Bayesian intervals with variational inference are not shown because of the limitation of meanfield inference in not accounting for posterior correlations.
Returns : void  shows a matplotlib plot

plot_predict_is
(h, fit_once, fit_method, **kwargs)¶ Plots insample rolling predictions for the model. This means that the user pretends a last subsection of data is outofsample, and forecasts after each period and assesses how well they did. The user can choose whether to fit parameters once at the beginning or every time step.
Parameter Type Description h int How many previous timesteps to use fit_once boolean Whether to fit once, or every timestep fit_method str Which inference option, e.g. ‘MLE’ Optional arguments include figsize  the dimensions of the figure to plot. h is an int of how many previous steps to simulate performance on.
Returns : void  shows a matplotlib plot

plot_z
(indices, figsize)¶ Returns a plot of the latent variables and their associated uncertainty.
Parameter Type Description indices int or list Which latent variable indices to plot figsize tuple Size of the matplotlib figure Returns : void  shows a matplotlib plot

predict
(h)¶ Returns a DataFrame of model predictions.
Parameter Type Description h int How many steps to forecast ahead Please note that if you use Maximum Likelihood or Variational Inference, the intervals shown will not reflect latent variable uncertainty. Only MetropolisHastings will give you fully Bayesian prediction intervals. Bayesian intervals with variational inference are not shown because of the limitation of meanfield inference in not accounting for posterior correlations.
Returns : pd.DataFrame  the model predictions

predict_is
(h, fit_once, fit_method)¶ Returns DataFrame of insample rolling predictions for the model.
Parameter Type Description h int How many previous timesteps to use fit_once boolean Whether to fit once, or every timestep fit_method str Which inference option, e.g. ‘MLE’ Returns : pd.DataFrame  the model predictions

References¶
Harvey, A. C. (1989). Forecasting, Structural Time Series Models and the Kalman Filter. Cambridge University Press, Cambridge.
Ranganath, R., Gerrish, S., and Blei, D. M. (2014). Black box variational inference. In Artificial Intelligence and Statistics.