You know the feeling being on call getting paged in the middle of the night and the first glance at the alert title tells you all you need to know. The alert is a notorious false positive. So you acknowledge it and grumble to yourself while trying to fall back to sleep. Something about can’t we just use an anomaly detection tool that automatically adapts to these spikes? Okay, maybe not using those words per se but roughly that sentiment. In this post we will look into some underlying machinery behind said anomaly detection tools. Specifically, we’ll dive deep into State Space Models - a classical technique for modelling (among other systems) time series.

The notion of a time series is already familiar. A time series is just a graph of points we’re looking at, where the x-axis is some notion of time. The graph might be a stock price, disk usage, traffic for a live service, or anything really. A bit more formally, a time series is a sequence of points (also called observations), indexed by time. We will assume that the interval between successive points is of the same width (e.g. every hour, day, 30s etc).

Daily traffic observations for a fictitious live service.

As an example, the figure shows a time series in all its glory. We’re looking at a graph - the domain of which isn’t super important. What’s important is our intuition and ability to capture anomalies (when something is ‘off’ with the graph, e.g. if stocks are unusually low, or traffic is looking too spiky). Now, this graph specifically, traffic looks … normal?

Random processes

Not in the ctrl+alt+del sense. A random (or stochastic) process extends the concept of a random variable in a somewhat similar manner as the time series extends the concept of a single data point. A random process is a random variable (or set of random variables) that is tracked over time. Again, we have time indices, and at each index/point, the object, being a random variable, can take on any of its possible values. This makes it possible to use a random process as a tool to describe the state of a system that evolves over time. And since the objects being tracked are random variables, we are able to extend familiar statistics as our language when describing the system. Take the figure for example, one could think of a conceptual graph template where y-axis plots random variables, and any concrete graph like in the figure is an instantiation/realization of the template (one where each variable has been assigned a concrete value).

As an illustration, say we’re observing the state of a system using two dimensions (components): temperaturetemperature and speedspeed. At any given point in time tt, the system is in a definite/actual state α=(temperature,speed)\alpha = (temperature, speed). Say we get presented with data (observation) suggesting that at time tnt_n, the system was in state α=(25∘C,96km/h)\alpha = (25^\circ\text{C}, 96\text{km/h}). Putting on our skeptic hat, we can begin to ask questions about how well we can trust this data point. The temperature state component of the system can take on any value and it happened to be 25∘C25^\circ\text{C}, how likely is this outcome? Ignoring the likelihood of 25∘C25^\circ\text{C} temperature, how certain are we that the 25∘C25^\circ\text{C} is close to the actual value when the data was observed - maybe the instruments or other environmental conditions introduced noise during the measurement taking process such that what was supposed to read 40∘C40^\circ\text{C} became 25∘C25^\circ\text{C}? Also, is there any point in analysing 25∘C25^\circ\text{C} and 96km/h96\text{km/h} both together or is it enough to look at them in isolation (i.e. does looking at the value of one component potentially make us trust the value of the other component)? If tnt_n was early on in the lifecycle of the system, does 25∘C25^\circ\text{C} become more likely or less likely to show up, or does it not matter what time of the day it is? And so on. The first question relates to single variable probability, we consider things like the mean and any other interesting moments of the variable’s distribution. The second question considers noise (or disturbances) in our observations or analysis or the system. We will see that noise not only captures the intuitive measurement inaccuracies, but also uncertainty when we make assumptions about the system. The third question gets into multivariate probability and we can ask questions about independence or correlation between the state components. For example, if state is describing the temperature of a car engine, and the speed of the same car, then maybe (25∘C,96km/h)(25^\circ\text{C}, 96\text{km/h}) sounds like a sketchy measurement. On the other hand, if the state is describing the temperature in my oven and speed describes the movement of a diving bird, then it might be safe to assume that both components are independent of each other. The last question extends the previous question to the time variable. It asks whether statistical properties of the system state change with time, or are effectively constant. The latter behavior describes a stationary process - the joint distribution over the state components does not change over time.

At this point it might be clear that our primary goal with the introduction of random processes is to model the system under observation. And as with all modelling, we want as close a representation to the system as is feasible. For anomaly detection, we want one good enough to allow us to predict (forecast) future states of the system.

State Space Models

A state space model (SSM) provides a framework to describe a system’s evolution (moving from one state to the next) over time. As alluded to, by simply looking at the observations, we are unable to get a good enough picture of the system’s behavior. A state space model takes the perspective of treating the observations primarily as symptoms of the underlying unobserved state of the system. This is a similar perspective as with hidden Markov models (HMM) (which are a specific type of SSM). Observations are assumed to depend on the unobserved internal state of the system and are independent of each other given this hidden state. The internal state of the system changes over time and they obey the Markov property (each state depends only on the immediately preceding state, never future or other historical states). Unsurprisingly, another assumption is that the observations are noisy. the figure illustrates the dependency graph in an SSM/HMM setting. The goal is to learn the hidden layer given the observed layer.

hoibdsdeernvedαy₁₁αy₂₂αy₃₃···αyₙₙ

Conditional dependency graph of an SSM network.

SSM Components

Level and Season components.

By eyeballing a graph/series, we might be able to guess some of its properties. SSM calls these properties components. Take a typical sine wave as in the figure, it’s not a constant function so that’s at least an interesting take-off point. But we might notice that although its value is changing over time, it seems to have a ‘center’ at y=0y=0 – a baseline value around which the function takes on its values. This is called the level component. Another glaring property of the graph is the oscillation - a sine wave has the property that sin⁡(t)=sin⁡(2π+t)\sin(t) = \sin(2\pi + t). A repeating pattern in the graph is called the seasonal component. Whenever data comes in a cadence like daily, weekly, hourly etc, it’s not uncommon that there is a recurring pattern that shows up within a cycle (i.e. day, week, hour).

Observations following a sine wave about the t-axis

Noise and Trend components

Noise

The observations in the figure look all nice and clean - that makes it easy to detect that the underlying state mechanism is being driven by a sinusoid. However, as we hinted at during the random processes discussion, the observations we get in practice usually contain various forms of noise. the figure shows the same function as the figure but with a component ε\varepsilon that introduces noise to each point before observation. Now, we might have to squint a little but if we repeat the eyeball exercise, we might still be able to guess that we’re looking at a sine wave.

Observations following y=sin⁡(t)+εy = \sin(t) + \varepsilon.

The noise component in an SSM is very important. It models our uncertainty about aspects of the overall process. For example if we assume that the underlying state mechanism is deterministic in nature (like in our sine examples), then we might only introduce an observation noise component modelling our uncertainty about the measurement process (i.e. we assume that any noise in the observations are solely due to inaccuracies introduced while taking the measurements).

Let’s look a bit closer at the y=sin⁡(t)+εy = \sin(t) + \varepsilon equation of this example. This is an example of an observation equation in an SSM. The right hand side has two parts. Some function f(t)f(t) of the state at time tt, which in our example happened to be f(t)=sin⁡(t)f(t) = \sin(t) – it models the unadulterated observation value. Then an added value ε\varepsilon modelling the noise being added to the observation. If we assume that ε=0\varepsilon = 0, then we have no observation noise, and our system becomes equivalent to the figure. Otherwise, we assume that noise values ε\varepsilon are drawn from some distribution. As usual, for computation/tractability reasons, Gaussian distributions are a popular choice in practical settings. Specifically, we assume Gaussian white noise, where the distribution has zero mean and samples are independently drawn. So, ε∼N(0, σε2)\varepsilon \sim \mathcal{N}(0,\, \sigma_\varepsilon^2) with σε2>0\sigma_\varepsilon^2 > 0.

In addition to observation noise, we can also have state noise. Most interesting systems aren’t built solely from deterministic functions like sin⁡(t)\sin(t), rather stochastic behavior governs the state of the system. And in a similar manner to observation noise, we will later encounter state noise that captures our uncertainty around the other components of the system state.

Trend

Another thing our eyeball test can tell us about a graph is how the graph is trending. Basically whether it’s drifting up or down over time. This can be explained by some kind of a slope (trend) component acting on the system state over time – e.g. if some portion of the graph is trending upwards, then the function representing that component of the system currently has a positive slope, and conversely, a negative slope if trending downwards.

the figure shows the same sine wave as the figure with an upward trend via the introduction of a trend component 0.15t0.15t. For illustration, the trend component is included in the figure. This is a deterministic function but as we will see later, same as any other component, trend can include a stochastic/noise component if we would like to model uncertainty in that area of the system. An interesting note is the dynamic between the trend and the level components – intuitively with a trend component acting on the system during a time period, we might not expect observations during that period to exhibit a constant level.

Observations following y=sin⁡(t)+0.15t+εy = \sin(t) + 0.15t + \varepsilon.

If we did not notice earlier, with our better trained eyes, we might now look back at the figure and guess that there is a trend component in there somewhere.

State Space Representation

We’ve discussed that the approach to state space modelling involves decomposing a time series into the level, trend, noise and seasonal components. The representation of this decomposition uses difference equations to relate inputs to the system and its output over time.

Local Level Model

We start with the representation of the local level model, which materializes the earlier discussion of the level component.

yt=μt+εt,εt∼N(0,σε2)(1) y_t = \mu_t + \varepsilon_t, \quad \varepsilon_t \sim \mathcal{N}(0, \sigma_\varepsilon^2) \tag{1}
μt+1=μt+ξt,ξt∼N(0,σξ2)(2) \mu_{t+1} = \mu_t + \xi_t, \quad \xi_t \sim \mathcal{N}(0, \sigma_\xi^2) \tag{2}

(1) models the observation equation. As discussed, this model assumes observations/measurements are noisy, hence the observation noise component εt\varepsilon_t. The state consists solely of a level component μt\mu_t (a stochastic one if σξ2\sigma_\xi^2 is non-zero). The state equation describes how the system evolves over time. (2) says that at any given time tt, the next state of the system μt+1\mu_{t+1} is simply the current state μt\mu_t plus a noise value ξt\xi_t. The latter is the state noise component enforcing the stochastic nature of the system’s state evolution. As with the observation noise, state noises are assumed to be independent Gaussian white noise.

Effectively, the assumption is that the underlying state of the system is an accumulation of noise. But note that unlike the observation noise, it is better to think of state noise more like unpredictability/uncertainty, rather than distortion/unwanted information.

Local Linear Trend Model

The local linear trend model builds on the local level model by introducing a trend/slope component νt\nu_t to the state. To see why this addition introduces a slope, assume that σζ2\sigma_\zeta^2 is zero (deterministic component), then νt+1=νt\nu_{t+1} = \nu_t. So the value never changes from its initial ν1\nu_1. Then for each time increment, we add a constant ν1\nu_1 to the dependent variable, giving us the familiar definition of a slope. As with the state components we’ve encountered so far, a non-zero variance σζ2\sigma_\zeta^2 gives us the stochastic variant of the component.

yt=μt+εt,εt∼N(0,σε2)μt+1=μt+νt+ξt,ξt∼N(0,σξ2)νt+1=νt+ζt,ζt∼N(0,σζ2)(3) \begin{aligned} y_t &= \mu_t + \varepsilon_t, && \varepsilon_t \sim \mathcal{N}(0, \sigma_\varepsilon^2) \\ \mu_{t+1} &= \mu_t + \nu_t + \xi_t, && \xi_t \sim \mathcal{N}(0, \sigma_\xi^2) \\ \nu_{t+1} &= \nu_t + \zeta_t, && \zeta_t \sim \mathcal{N}(0, \sigma_\zeta^2) \end{aligned} \tag{3}

Local Linear Trend with Seasonal Model

The local linear trend with seasonal model extends the local linear trend model with a seasonal component γt\gamma_t. As discussed earlier, the seasonal component captures repeating patterns in the series. There are various techniques for defining the seasonal component. One could use trig functions, leading to trigonometric seasonal model variants. Another technique which we will use in this post is what is known as the dummy seasonal. For a defined periodicity ss, the dummy seasonal component can capture recurring patterns for ss seasons within the cycle. For example a time series with monthly observations may have a yearly recurring pattern, we could imagine an underlying dynamic such that January observations are drawn from a different distribution than that of February, which in turn is drawn from a different distribution than March and so on. A seasonal period of s=12s=12 is able to capture the distinct properties of each month of the year (i.e. effectively s−1s-1 degrees of freedom).

(4) shows the local linear trend with dummy seasonal model. Unlike other components which introduce one state variable, the seasonal component introduces s−1s-1 new state variables γt,…,γt−s+2\gamma_{t}, \dots, \gamma_{t-s+2}.

yt=μt+γt+εt,εt∼N(0,σε2)μt+1=μt+νt+ξt,ξt∼N(0,σξ2)νt+1=νt+ζt,ζt∼N(0,σζ2)γt+1=−∑j=1s−1γt+1−j+ωt,ωt∼N(0,σω2)(4) \begin{aligned} y_t &= \mu_t + \gamma_t + \varepsilon_t, && \varepsilon_t \sim \mathcal{N}(0, \sigma_\varepsilon^2) \\ \mu_{t+1} &= \mu_t + \nu_t + \xi_t, && \xi_t \sim \mathcal{N}(0, \sigma_\xi^2) \\ \nu_{t+1} &= \nu_t + \zeta_t, && \zeta_t \sim \mathcal{N}(0, \sigma_\zeta^2) \\ \gamma_{t+1} &= -\sum_{j=1}^{s-1} \gamma_{t+1-j} + \omega_t, && \omega_t \sim \mathcal{N}(0, \sigma_\omega^2) \end{aligned} \tag{4}

In the dummy seasonal model definition, all seasonal effects within the cycle sum up to zero. Or in the stochastic case, a noise ωt\omega_t.

∑j=0s−1γt+1−j=ωt,ωt∼N(0,σω2)(5) \sum_{j=0}^{s-1} \gamma_{t+1-j} = \omega_t, \quad \omega_t \sim \mathcal{N}(0, \sigma_\omega^2) \tag{5}

(5) is equivalent to the new γt+1\gamma_{t+1} equation in (4). Note that by this definition, the other seasonal variables γt+1−j\gamma_{t+1-j}, 1≤j≤s−11 \le j \le s-1, are simply shifted one step forward during the next time step. That is, γt+1,j=γt,j−1\gamma_{t+1,j} = \gamma_{t,j-1} for 2≤j≤s−12 \le j \le s-1, where γt,j=γt+1−j\gamma_{t,j} = \gamma_{t+1-j} denotes the jjth seasonal variable at time tt.

Worth mentioning is that although we have introduced the seasonal component as an addition to the local linear trend model, this is not a requirement. Components can be tweaked individually to form the desired model. For example a seasonal component can be added directly to a local level model if we do not intend to capture trends in the time series. Also, each component can be independently chosen to be deterministic or stochastic, dictated by the presence of the associated noise term in the equation. As an example, (6) shows a local level seasonal model with stochastic level and deterministic seasonal components.

yt=μt+γt+εt,εt∼N(0,σε2)μt+1=μt+ξt,ξt∼N(0,σξ2)γt+1=−∑j=1s−1γt+1−j(6) \begin{aligned} y_t &= \mu_t + \gamma_t + \varepsilon_t, && \varepsilon_t \sim \mathcal{N}(0, \sigma_\varepsilon^2) \\ \mu_{t+1} &= \mu_t + \xi_t, && \xi_t \sim \mathcal{N}(0, \sigma_\xi^2) \\ \gamma_{t+1} &= -\sum_{j=1}^{s-1} \gamma_{t+1-j} \end{aligned} \tag{6}

Matrix Representation

All the models we’ve discussed so far can be represented in a uniform manner using matrix algebra. This will be useful going forward as we get into the computation aspects and start kicking the tires on the models. (7) shows the general format (we still assume Gaussian white noise components).

yt=Ztαt+εt,εt∼N(0,Ht)αt+1=Ttαt+Rtηt,ηt∼N(0,Qt)(7) \begin{aligned} y_t &= Z_t\alpha_t + \varepsilon_t, && \varepsilon_t \sim \mathcal{N}(0, H_t) \\ \alpha_{t+1} &= T_t\alpha_t + R_t\eta_t, && \eta_t \sim \mathcal{N}(0, Q_t) \end{aligned} \tag{7}

All the general format does is take the equations of a given model, and map the corresponding matrices and vectors to fit them, such that the equations in both the matrix and scalar representations are equivalent.

The yty_t equation remains the observation equation, and the αt+1\alpha_{t+1} equation becomes a concise representation of the combined state equation(s).

Say our given model defines mm state variables. αt∈Rm×1\alpha_t \in \Reals^{m \times 1} is the state vector – it contains the state variables defined by the model. Zt∈R1×mZ_t \in \Reals^{1 \times m} is the observation vector – it maps the state vector (state variables) to match the model’s observation equation. Tt∈Rm×mT_t \in \Reals^{m \times m} is the transition matrix – each row matches a state equation described by the model, one per state variable. It is called the transition matrix since it takes the system from one point in time tt to the next point t+1t+1. Say that rr out of the mm state equations include a state noise component. Then, ηt∈Rr×1\eta_t \in \Reals^{r \times 1} is a random vector containing the state noise components. Rt∈Rm×rR_t \in \Reals^{m \times r} is the selection matrix – it maps each state noise component to its corresponding equation. Qt∈Rr×rQ_t \in \Reals^{r \times r} is the covariance matrix of ηt\eta_t.

Let’s illustrate this with a concrete example. Using the local linear trend with seasonal model described in (4), with seasonal period s=4s=4.

αt=[μtνtγtγt−1γt−2],Zt=[10100],Tt=[110000100000−1−1−10010000010],ηt=[ξtζtωt],Rt=[100010001000000],Qt=[σξ2000σζ2000σω2],Ht=σε2(8) \begin{aligned} \alpha_t &= \begin{bmatrix} \mu_t \\ \nu_t \\ \gamma_t \\ \gamma_{t-1} \\ \gamma_{t-2} \end{bmatrix}, & Z_t &= \begin{bmatrix} 1 & 0 & 1 & 0 & 0 \end{bmatrix}, & T_t &= \begin{bmatrix} 1 & 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 & 0 \\ 0 & 0 & -1 & -1 & -1 \\ 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 & 0 \end{bmatrix}, \\[1ex] \eta_t &= \begin{bmatrix} \xi_t \\ \zeta_t \\ \omega_t \end{bmatrix}, & R_t &= \begin{bmatrix} 1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1 \\ 0 & 0 & 0 \\ 0 & 0 & 0 \end{bmatrix}, & Q_t &= \begin{bmatrix} \sigma_\xi^2 & 0 & 0 \\ 0 & \sigma_\zeta^2 & 0 \\ 0 & 0 & \sigma_\omega^2 \end{bmatrix}, \quad H_t = \sigma_\varepsilon^2 \end{aligned} \tag{8}

While this might look like a lot at first glance, note that filling them in (7) describes the same equations in (4). The seasonal variables e.g. γt−1\gamma_{t-1} are explicitly spelled out. ηt\eta_t combines the scalar random noises into a joint distribution, and RtR_t simply matches its shape. For example, note that the first row of the expression Ttαt+RtηtT_t\alpha_t + R_t\eta_t is indeed μt+νt+ξt\mu_t + \nu_t + \xi_t, which matches the right hand side of μt+1=μt+νt+ξt\mu_{t+1} = \mu_t + \nu_t + \xi_t in (4).

A very convenient aspect to the matrix representation is that it lets us decouple the implementation from the model’s representation. Changes to the model or replacing one model with another, simply involve changes to these matrices, e.g. adding more rows, zeroing out some columns etc. The algorithm that processes the observations stays the same.

Kalman Filter

Our bet has been that each observation is a function of one or more state components that make up the internal state of the system. We don’t actually know the true state components of the system, but we can guess/infer it. Just as we eyeballed graphs earlier to get a sense for what components are at play for a given system – we can use an algorithm that uses past observation values to infer the state components (and as a result be able to predict future observation values). The Kalman filter is one such algorithm when working with Gaussian components. In this section we will derive the algorithm.

So far we’ve ended up with a mathematical representation of the system (time series) such as the one in (8). This representation requires two sets of inputs:

  1. Initial state: The recursive representation lets us compute the next state αt+1\alpha_{t+1} from the current state αt\alpha_t. So, we need an initial state to start from α1\alpha_1.
  2. Parameters: We need knowledge of the distributions that describe the noise components. Specifically we need to know the parameters that describe QtQ_t and HtH_t. Since we assume mutually independent white noise components, this is equivalent to knowledge of the variances of the individual distributions, so σξ2\sigma_\xi^2, σζ2\sigma_\zeta^2, σω2\sigma_\omega^2 and σε2\sigma_\varepsilon^2.

The Kalman filter algorithm performs two actions at each time step. At a given time step tt, it uses whatever estimated state αt\alpha_t it has of the system to predict the observation yty_t for that time step using our state representation of the system. This step is called the prediction step and the associated state αt\alpha_t is called the predicted state. Note that at this point we do not yet know the true observation value yty_t (otherwise we would not need to predict it) so the estimated state is derived from past observations, i.e. y1,y2,…,yt−1y_1, y_2, \dots, y_{t-1}. Let YtY_t denote the set of points up to time tt, that is Yt={y1,y2,…,yt}Y_t = \{y_1, y_2, \dots, y_t\}. Then the predicted state is the estimated state given Yt−1Y_{t-1}, i.e. αt=αt∣t−1=αt∣Yt−1\alpha_t = \alpha_{t \mid t-1} = \alpha_t \mid Y_{t-1}. After the true observation value yty_t is known, the algorithm uses this new knowledge to tune its estimated state. For example if its prediction of yty_t was way off from the true value, and it was already uncertain about that prediction, then it can choose to aggressively tune its state towards alignment with the observed value so that future predictions better match future observations. On the other end, if its prediction was pretty close or spot on, then it might not need to make too many changes to its estimated state. This step is called the update step. The algorithm creates a new filtered state αt∣t=αt∣Yt\alpha_{t \mid t} = \alpha_t \mid Y_t, which takes the place of the predicted state in the next time step. Hence, the filter learns about the system by continuously performing these two steps feeding into each other as we go from one time step to the next, correcting its knowledge about the system over time.

State distributions

Let the distribution of an estimated predicted state at time tt be αt∼N(at,Pt)\alpha_t \sim \mathcal{N}(a_t, P_t). Given past observations Yt−1Y_{t-1} and the predicted state at=E(αt∣Yt−1)a_t = E(\alpha_t \mid Y_{t-1}), the goal is to compute the distributions of the filtered state αt∣t∼N(at∣t,Pt∣t)\alpha_{t \mid t} \sim \mathcal{N}(a_{t \mid t}, P_{t \mid t}) and the next predicted state αt+1∼N(at+1,Pt+1)\alpha_{t+1} \sim \mathcal{N}(a_{t+1}, P_{t+1}). For completeness, we have Pt=Var(αt∣Yt−1)P_{t} = Var(\alpha_{t} \mid Y_{t-1}), Pt∣t=Var(αt∣t∣Yt)P_{t \mid t} = Var(\alpha_{t \mid t} \mid Y_t) and Pt+1=Var(αt+1∣Yt)P_{t+1} = Var(\alpha_{t+1} \mid Y_t) – these variances capture our uncertainty about the associated estimated state (how much the estimation can actually deviate from the true state of the system). So basically we need to calculate at∣t,at+1,Pt∣ta_{t \mid t}, a_{t+1}, P_{t \mid t} and Pt+1P_{t+1} based off ata_t and PtP_t.

Prediction error

The prediction error vtv_t, as the name implies, quantifies how wrong our prediction of yty_t was, after we’ve observed its true value. Recall from (7) that our observations take the form yt=Ztαt+εty_t = Z_t\alpha_t + \varepsilon_t. Let y^t\hat{y}_t be our prediction of yty_t given past observations Yt−1Y_{t-1}. So, our prediction y^t\hat{y}_t takes the form of the expected value E(yt∣Yt−1)E(y_t \mid Y_{t-1}). Replacing yty_t with our model representation, we have y^t=E(yt∣Yt−1)=E(Ztαt+εt∣Yt−1)\hat{y}_t = E(y_t \mid Y_{t-1}) = E(Z_t\alpha_t + \varepsilon_t \mid Y_{t-1}). The prediction error is simply defined as the deviation from the true value:

vt=yt−y^t=yt−E(Ztαt+εt∣Yt−1)=yt−E(Ztαt∣Yt−1)−E(εt∣Yt−1)=yt−Ztat(9) \begin{aligned} v_t &= y_t - \hat{y}_t \\ &= y_t - E(Z_t\alpha_t + \varepsilon_t \mid Y_{t-1}) \\ &= y_t - E(Z_t\alpha_t \mid Y_{t-1}) - E(\varepsilon_t \mid Y_{t-1}) \\ &= y_t - Z_ta_t \end{aligned} \tag{9}

Where we have used linearity of expectations, Gaussian white noise assumption E(εt)=0E(\varepsilon_t) = 0 and the definition that E(αt∣Yt−1)=atE(\alpha_t \mid Y_{t-1}) = a_t.

As for the expected prediction error E(vt)E(v_t), we have:

E(vt)=E(vt∣Yt−1)=E(yt−Ztat∣Yt−1)=E(Ztαt+εt−Ztat∣Yt−1)=ZtE(αt∣Yt−1)−Ztat=Ztat−Ztat=0(10) \begin{aligned} E(v_t) &= E(v_t \mid Y_{t-1}) \\ &= E(y_t - Z_ta_t \mid Y_{t-1}) \\ &= E(Z_t\alpha_t + \varepsilon_t - Z_ta_t \mid Y_{t-1}) \\ &= Z_tE(\alpha_t \mid Y_{t-1}) - Z_ta_t \\ &= Z_ta_t - Z_ta_t \\ &= 0 \end{aligned} \tag{10}

Next, the variance of the prediction error FtF_t:

Ft=Var(vt∣Yt−1)=Var(Ztαt+εt−Ztat∣Yt−1)=ZtVar(αt−at∣Yt−1)Zt⊤+Var(εt∣Yt−1)=ZtVar(αt∣Yt−1)Zt⊤+Ht=ZtPtZt⊤+Ht(11) \begin{aligned} F_t &= Var(v_t \mid Y_{t-1}) \\ &= Var(Z_t\alpha_t + \varepsilon_t - Z_ta_t \mid Y_{t-1}) \\ &= Z_tVar(\alpha_t - a_t \mid Y_{t-1})Z_t^{\top} + Var(\varepsilon_t \mid Y_{t-1}) \\ &= Z_tVar(\alpha_t \mid Y_{t-1})Z_t^{\top} + H_t \\ &= Z_tP_tZ_t^{\top} + H_t \end{aligned} \tag{11}

Where we have used the fact that εt\varepsilon_t and αt\alpha_t are uncorrelated. An interesting note is that FtF_t, the variance of the prediction error, is effectively the combined uncertainty of the estimated state and the observation noise (if we take Zt=1Z_t = 1): Ft=Pt+HtF_t = P_t + H_t.

Deriving the predicted and filtered states

Something worth highlighting here is that if we know both the prediction error vtv_t and past observations Yt−1Y_{t-1}, then by definition of vtv_t, we also know YtY_t (the observations including yty_t). This implies that the distribution p(αt∣Yt)=N(at∣t,Pt∣t)p(\alpha_t \mid Y_t) = \mathcal{N}(a_{t \mid t}, P_{t\mid t}) is equivalent to the conditional distribution p(αt∣Yt−1,vt)p(\alpha_t \mid Y_{t-1}, v_t). As a result, we have:

at∣t=E(αt∣Yt)=E(αt∣Yt−1,vt)at+1=E(αt+1∣Yt)=E(αt+1∣Yt−1,vt)(12) \begin{aligned} a_{t \mid t} &= E(\alpha_t \mid Y_t) = E(\alpha_t \mid Y_{t-1},v_t) \\ a_{t+1} &= E(\alpha_{t+1} \mid Y_t) = E(\alpha_{t+1} \mid Y_{t-1},v_t) \end{aligned} \tag{12}

We can actually derive a form for the conditional distribution p(αt∣Yt−1,vt)p(\alpha_t \mid Y_{t-1}, v_t). Since αt\alpha_t and vtv_t are jointly Gaussian distributed, we can use the conditional Gaussian Distribution Theorem which partitions a random vector into two disjoint subsets z=[xy]z = \begin{bmatrix} x \\ y \end{bmatrix} such that

[xy]∼N([μxμy],[ΣxxΣxyΣyxΣyy])(13) \begin{aligned} \begin{bmatrix} x \\ y \end{bmatrix} &\sim \mathcal{N}\left( \begin{bmatrix} \mu_x \\ \mu_y \end{bmatrix}, \begin{bmatrix} \Sigma_{xx} & \Sigma_{xy} \\ \Sigma_{yx} & \Sigma_{yy} \end{bmatrix} \right) \end{aligned} \tag{13}

and the conditional distribution of xx given yy is also Gaussian with mean and variance:

E(x∣y)=μx+ΣxyΣyy−1(y−μy)Var(x∣y)=Σxx−ΣxyΣyy−1Σyx(14) \begin{aligned} E(x \mid y) &= \mu_x + \Sigma_{xy}\Sigma_{yy}^{-1}(y - \mu_y) \\ Var(x \mid y) &= \Sigma_{xx} - \Sigma_{xy}\Sigma_{yy}^{-1}\Sigma_{yx} \end{aligned} \tag{14}
Update step

If we plug in αt\alpha_t and vtv_t for xx and yy respectively in (14), we get the following mean and variance of the conditional distribution:

at∣t=E(αt∣Yt−1,vt)=E(αt∣Yt−1)+Cov(αt,vt)Var(vt∣Yt−1)−1(vt−E(vt∣Yt−1))=E(αt∣Yt−1)+Cov(αt,vt)Var(vt∣Yt−1)−1vtPt∣t=Var(αt∣Yt−1,vt)=Var(αt∣Yt−1)−Cov(αt,vt)Var(vt∣Yt−1)−1Cov(αt,vt)⊤(15) \begin{aligned} a_{t \mid t} &= E(\alpha_t \mid Y_{t-1}, v_t) \\ &= E(\alpha_t \mid Y_{t-1}) + Cov(\alpha_t, v_t)Var(v_t \mid Y_{t-1})^{-1}(v_t - E(v_t \mid Y_{t-1})) \\ &= E(\alpha_t \mid Y_{t-1}) + Cov(\alpha_t, v_t)Var(v_t \mid Y_{t-1})^{-1}v_t \\ P_{t \mid t} &= Var(\alpha_t \mid Y_{t-1}, v_t) \\ &= Var(\alpha_t \mid Y_{t-1}) - Cov(\alpha_t, v_t)Var(v_t \mid Y_{t-1})^{-1}Cov(\alpha_t, v_t)^{\top} \end{aligned} \tag{15}

Where we have used the fact from (10) that E(vt∣Yt−1)=0E(v_t \mid Y_{t-1}) = 0.

We can also resolve the covariance of the joint distribution given Yt−1Y_{t-1}:

Cov(αt,vt)=E(αtvt⊤∣Yt−1)=E(αt(Ztαt+εt−Ztat)⊤∣Yt−1)=E(αt(αt⊤Zt⊤+εt−at⊤Zt⊤)∣Yt−1)=E(αt(αt⊤−at⊤)Zt⊤∣Yt−1)=E(αtαt⊤−αtat⊤∣Yt−1)Zt⊤=PtZt⊤(16) \begin{aligned} Cov(\alpha_t, v_t) &= E(\alpha_tv_t^{\top} \mid Y_{t-1}) \\ &= E(\alpha_t(Z_t\alpha_t + \varepsilon_t - Z_ta_t)^{\top} \mid Y_{t-1}) \\ &= E(\alpha_t(\alpha_t^{\top}Z_t^{\top} + \varepsilon_t - a_t^{\top}Z_t^{\top}) \mid Y_{t-1}) \\ &= E(\alpha_t(\alpha_t^{\top} - a_t^{\top})Z_t^{\top} \mid Y_{t-1}) \\ &= E(\alpha_t\alpha_t^{\top} - \alpha_ta_t^{\top} \mid Y_{t-1})Z_t^{\top} \\ &= P_tZ_t^{\top} \end{aligned} \tag{16}

Where we have recognized the variance PtP_t from the definition of variance Var(X)=E[XX⊤]−E[X]E[X]⊤Var(X) = E[XX^{\top}] - E[X]E[X]^{\top}.

With the covariance resolved, and (11), we can simplify (15) to get the aforementioned update step of the Kalman filter. The step where we update our estimated state with knowledge of the actual observed value for a time step.

at∣t=at+PtZt⊤Ft−1vtPt∣t=Pt−PtZt⊤Ft−1ZtPt(17) \boxed{ \begin{aligned} a_{t \mid t} &= a_t + P_tZ_t^{\top}F_t^{-1}v_t \\ P_{t \mid t} &= P_t - P_tZ_t^{\top}F_t^{-1}Z_tP_t \end{aligned} } \tag{17}
Prediction step

In the prediction step, we’re estimating (at,Pt)(a_t, P_t) based on past observations Yt−1Y_{t-1}. Or equivalently, estimating (at+1,Pt+1)(a_{t+1}, P_{t+1}) based on past observations Yt{Y_t}. So we develop similar recursive expressions for at+1a_{t+1} and Pt+1P_{t+1}.

at+1=E(αt+1∣Yt)=E(Ttαt+Rtηt∣Yt)=TtE(αt∣Yt)Pt+1=Var(αt+1∣Yt)=Var(Ttαt+Rtηt∣Yt)=TtVar(αt∣Yt)Tt⊤+Var(Rtηt∣Yt)=TtVar(αt∣Yt)Tt⊤+RtQtRt⊤(18) \begin{aligned} a_{t+1} &= E(\alpha_{t+1} \mid Y_t) \\ &= E(T_t\alpha_t + R_t\eta_t \mid Y_t) \\ &= T_tE(\alpha_t \mid Y_t) \\ P_{t+1} &= Var(\alpha_{t+1} \mid Y_t) \\ &= Var(T_t\alpha_t + R_t\eta_t \mid Y_t) \\ &= T_tVar(\alpha_t \mid Y_t)T_t^{\top} + Var(R_t\eta_t \mid Y_t) \\ &= T_tVar(\alpha_t \mid Y_t)T_t^{\top} + R_tQ_tR_t^{\top} \end{aligned} \tag{18}

where we have used the fact that E(ηt)=0E(\eta_t) = 0 (white noise), and that αt\alpha_t and ηt\eta_t are uncorrelated.

By definition, at∣t=E(αt∣Yt)a_{t \mid t} = E(\alpha_t \mid Y_t) and Pt∣t=Var(αt∣Yt)P_{t \mid t} = Var(\alpha_t \mid Y_t), so (18), together with (17) can be simplified to:

at+1=TtE(αt∣Yt)=Ttat∣t=Tt(at+PtZt⊤Ft−1vt)=Ttat+KtvtPt+1=TtVar(αt∣Yt)Tt⊤+RtQtRt⊤=Tt(Pt−PtZt⊤Ft−1ZtPt)Tt⊤+RtQtRt⊤=TtPt(Tt⊤−Zt⊤Ft−1ZtPtTt⊤)+RtQtRt⊤=TtPt(Tt⊤−[TtPtZt⊤Ft−1Zt]⊤)+RtQtRt⊤=TtPt(Tt−KtZt)⊤+RtQtRt⊤(19) \begin{aligned} a_{t+1} &= T_tE(\alpha_t \mid Y_t) \\ &= T_ta_{t \mid t} \\ &= T_t(a_t + P_tZ_t^{\top}F_t^{-1}v_t) \\ &= T_ta_t + K_tv_t \\ P_{t+1} &= T_tVar(\alpha_t \mid Y_t)T_t^{\top} + R_tQ_tR_t^{\top} \\ &= T_t(P_t - P_tZ_t^{\top}F_t^{-1}Z_tP_t)T_t^{\top} + R_tQ_tR_t^{\top} \\ &= T_tP_t (T_t^{\top} - Z_t^{\top}F_t^{-1}Z_tP_tT_t^{\top}) + R_tQ_tR_t^{\top} \\ &= T_tP_t (T_t^{\top} - [T_tP_tZ_t^{\top}F_t^{-1}Z_t]^{\top}) + R_tQ_tR_t^{\top} \\ &= T_tP_t (T_t - K_tZ_t)^{\top} + R_tQ_tR_t^{\top} \end{aligned} \tag{19}

where we have made the variable substitution Kt=TtPtZt⊤Ft−1K_t = T_tP_tZ_t^{\top}F_t^{-1}. In summary, this gives us the prediction step of the Kalman filter.

at+1=Ttat+KtvtPt+1=TtPt(Tt−KtZt)⊤+RtQtRt⊤(20) \boxed{ \begin{aligned} a_{t+1} &= T_ta_t + K_tv_t \\ P_{t+1} &= T_tP_t (T_t - K_tZ_t)^{\top} + R_tQ_tR_t^{\top} \end{aligned} } \tag{20}
Kalman Gain

The expression Kt=TtPtZt⊤Ft−1K_t = T_tP_tZ_t^{\top}F_t^{-1} is called the Kalman gain and gives an insight into how the Kalman filter works, as we discussed earlier. Then note how it’s used in our state prediction at+1=Ttat+Ktvta_{t+1} = T_ta_t + K_tv_t. We’re essentially fine tuning our state at+1a_{t+1} by taking the current state ata_t, and adding a fraction KtK_t of our prediction error vtv_t – learning from any mistakes made in our observation prediction. Note the form of the Kalman gain as essentially the fraction Pt/FtP_t/F_t (taking Tt=Zt=1T_t = Z_t = 1). This is a ratio of two uncertainties. PtP_t captures how uncertain we are about the current estimated state (i.e. having only seen past observations Yt−1Y_{t-1}, by definition of PtP_t). FtF_t if we recall from (11) is a combination of the same uncertainty plus observation noise.

Kt=PtFt=PtPt+Ht(21) \begin{aligned} K_t = \frac{P_t}{F_t} = \frac{P_t}{P_t + H_t} \end{aligned} \tag{21}

For example if we notice that there is a lot of noise in the observed values (i.e. HtH_t is very large so that FtF_t is much larger compared to PtP_t), then the ratio tends to zero and we adjust our state ever so slightly, if at all, since we won’t trust the noisy observation compared to our current estimation. On the other extreme, if observation noise is low, then the fraction tends to 1 and we adjust our state according to our prediction error since we trust the observation more than we do our current estimation.

the figure illustrates this process as the filter sees new observations. The dotted lines are the prediction errors yt−aty_t - a_t. The shaded red portion of it is the fraction Kt(yt−at)K_t(y_t - a_t) of the error the filter incorporates into (arrow) the next prediction at+1a_{t+1}. Notice that early on KtK_t is close to 1 since the filter is relatively unsure about its predictions. Then over time the filter grows confident in its predictions.

Kalman filter steps: prediction errors and the corrections applied to the state Kalman filter steps: prediction errors and the corrections applied to the state

Kalman filter on a series. Illustrating prediction errors and state corrections

Time Series Anomaly Detection

The Kalman filter recursions give us not only predictions of the next value but also how confident we are in the prediction. The latter component is of importance when looking for anomalies in the system. Because as long as we trust our filter’s prediction and its confidence in its prediction, we can classify observed values that deviate too far from the filter’s prediction as anomalies. the figure shows the result of running a Kalman filter implementation of local linear trend with seasonal model in (8) (with seasonal s=7s=7) over the traffic time series in the figure.

The Kalman filter predictions on the traffic observations. We catch the anomalous spike in the series.

The code for this filter can be found here. The filter has a hardcoded initial state a1=0a_1 = 0, and initial variance P1=106P_1=10^6, the seemingly arbitrarily large variance is important since it tells the filter to not trust the initial state and instead lean more on the observations when fine tuning the state in subsequent time periods. As a result, initially we can see that the predictions are quite off and the variance of the prediction is unreasonably large to match. Shortly after seeing enough true observations the filter gets more confident in its estimated state and predictions and the variances/bounds shrink to match (the bounds are simply computed as a number of standard deviations from the filter’s prediction). The other still-unknowns are the HtH_t and QtQ_t components, which have been hardcoded in the filter to fit this particular traffic dataset. In the following sections, we will see how to estimate these components from the dataset instead.

Diffuse Kalman Filter Initialization

When we mobilized our Kalman Filter implementation, we made some simplifying assumptions by assigning an arbitrarily large initial state variance P1P_1 (although a large value of 10610^6 sounds like a wide enough net to cast, signalling that the filter is very unsure of its initial state, it is an arbitrary assumption and makes the implementation prone to computational issues like round-off errors) and noise distributions tailored to the dataset. Of course this is not practical since in a lot of realistic applications, we may not be familiar with the intended dataset to get a reasonable approximation of these values. So, the question of initializing the filter remains open.

In this section we look at the exact initial Kalman filter technique presented in Durbin and Koopman, extending the Kalman Filter with a diffuse (unknown variance) initial state.

The idea with the diffuse initialization approach is that we still want to express that our initial state has effectively infinite variance without actually specifying a variance of infinity (since that won’t let us do anything useful). Hence we express our intent by taking limits - instead of a hardcoded variance, we introduce a variable κ\kappa and let it tend to infinity.

To do this, instead of having a single variance PtP_t, the variance is split into two components Pt=Pt(κ)=κP∞,t+P∗,tP_t = P_t(\kappa) = \kappa P_{\infin, t} + P_{\ast,t}. P∞,tP_{\infin,t} is called the diffuse component and is initialized to indicate the unknown initial state components. P∗,tP_{\ast, t} is called the finite component and initialized to the state variances of any known state components. Taking the local linear trend model as an example, with initial state α1=[μ1,ν1]⊤\alpha_1 = [\mu_1, \nu_1 ]^{\top} where μ1\mu_1 is unknown and ν1\nu_1 is roughly known. Our initial state and covariance matrices could be:

a1=[0,42]⊤,P∞,1=[1000],P∗,1=[000σν12](22) \begin{aligned} a_1 = [0, 42]^{\top}, \quad P_{\infin,1} = \begin{bmatrix} 1 & 0 \\ 0 & 0\end{bmatrix}, \quad P_{\ast,1} = \begin{bmatrix} 0 & 0 \\ 0 & \sigma_{\nu_1}^2 \end{bmatrix} \end{aligned} \tag{22}

Then as the filter processes observations and becomes confident in its estimates, the diffuse component eventually becomes zero. During the diffuse phase (the time periods tt where P∞,t≠0P_{\infin,t} \ne 0), the filter updates both covariance matrices as part of its update step. After enough observations and P∞,t=0P_{\infin,t} = 0, then the filter drops the diffuse component and becomes a regular Kalman filter. We now derive the update equations for the diffuse Kalman filter - this essentially involves deriving corresponding state update equations as we did in the ordinary Kalman filter.

Diffuse prediction error

As a result of the covariance split, the prediction error variance becomes Ft(κ)=ZtPt(κ)Zt⊤+HtF_t(\kappa) = Z_tP_t(\kappa)Z_t^{\top} + H_t, since it is a function of PtP_t. The diffusion thus extends to the prediction error variance:

Ft(κ)=κF∞,t+F∗,tF∞,t=ZtP∞,tZt⊤F∗,t=ZtP∗,tZt⊤+Ht(23) \begin{aligned} F_t(\kappa) &= \kappa F_{\infin,t} + F_{\ast,t} \\ F_{\infin,t} &= Z_tP_{\infin,t}Z_t^{\top} \\ F_{\ast,t} &= Z_tP_{\ast,t}Z_t^{\top} + H_t \end{aligned} \tag{23}

Also, we can expand Ft−1=Ft(κ)−1F_t^{-1} = F_t(\kappa)^{-1} as a power series in variable κ−1\kappa^{-1}:

Ft(κ)−1=(κF∞,t+F∗,t)−1=κ−1F∞,t−1−κ−2F∞,t−1F∗,tF∞,t−1+…(24) \begin{aligned} F_t(\kappa)^{-1} &= (\kappa F_{\infin,t} + F_{\ast,t})^{-1} \\ &= \kappa^{-1} F_{\infin,t}^{-1} - \kappa^{-2} F_{\infin,t}^{-1}F_{\ast,t}F_{\infin,t}^{-1} + \dots \end{aligned} \tag{24}
Diffuse Kalman gain

The Kalman gain in the diffuse setting becomes the same expression but taking into account the separated covariance components:

Kt(κ)=TtPtZt⊤Ft−1=Tt(κP∞,t+P∗,t)Zt⊤(κ−1F∞,t−1−κ−2F∞,t−1F∗,tF∞,t−1+… )=TtP∞,tZt⊤F∞,t+κ−1(TtP∗,tZt⊤F∞,t−TtP∞,tZt⊤F∗,tF∞,t2)+O(κ−2)(25) \begin{aligned} K_t(\kappa) &= T_tP_tZ_t^{\top}F_t^{-1} \\ &= T_t(\kappa P_{\infin,t} + P_{\ast,t})Z_t^{\top}(\kappa^{-1} F_{\infin,t}^{-1} - \kappa^{-2} F_{\infin,t}^{-1}F_{\ast,t}F_{\infin,t}^{-1} + \dots) \\ &= \frac{T_tP_{\infin,t}Z_t^{\top}}{F_{\infin,t}} + \kappa^{-1}\left(\frac{T_tP_{\ast,t}Z_t^{\top}}{F_{\infin,t}} - \frac{T_tP_{\infin,t}Z_t^{\top}F_{\ast,t}}{F_{\infin,t}^2}\right) + \mathcal{O}(\kappa^{-2}) \end{aligned} \tag{25}

(25) expands the expression which makes it possible to see the exact, limiting Kalman gain:

lim⁡κ→∞Kt(κ)=TtP∞,tZt⊤F∞,t(26) \begin{aligned} \lim_{\kappa \to \infty} K_t(\kappa) = \frac{T_tP_{\infin,t}Z_t^{\top}}{F_{\infin,t}} \end{aligned} \tag{26}

Diffuse Kalman equations

Given our limiting Kalman gain (26), we can apply it to our familiar Kalman update step equations (17) and prediction step equations (20) to get their diffuse equivalents: The diffuse update step (27) and diffuse prediction step (28).

at∣t=at+P∞,tZt⊤F∞,t−1vtP∞,t∣t=P∞,t−P∞,tZt⊤ZtP∞,tF∞,tP∗,t∣t=P∗,t−P∞,tZt⊤ZtP∗,t+P∗,tZt⊤ZtP∞,tF∞,t+P∞,tZt⊤F∗,tZtP∞,tF∞,t2(27) \boxed{ \begin{aligned} a_{t \mid t} &= a_t + P_{\infin,t}Z_t^{\top}F_{\infin,t}^{-1}v_t \\ P_{\infin,t \mid t} &= P_{\infin,t} - \frac{P_{\infin,t}Z_t^{\top}Z_tP_{\infin,t}}{F_{\infin,t}} \\ P_{\ast,t \mid t} &= P_{\ast,t} - \frac{P_{\infin,t}Z_t^{\top}Z_tP_{\ast,t} + P_{\ast,t}Z_t^{\top}Z_tP_{\infin,t}}{F_{\infin,t}} + \frac{P_{\infin,t}Z_t^{\top}F_{\ast,t}Z_tP_{\infin,t}}{F_{\infin,t}^2} \end{aligned} } \tag{27}
at+1=Ttat∣tP∞,t+1=TtP∞,t∣tTt⊤P∗,t+1=TtP∗,t∣tTt⊤+RtQtRt⊤(28) \boxed{ \begin{aligned} a_{t+1} &= T_ta_{t \mid t} \\ P_{\infin,t+1} &= T_tP_{\infin,t \mid t}T_t^{\top} \\ P_{\ast,t+1} &= T_tP_{\ast,t \mid t}T_t^{\top} + R_tQ_tR_t^{\top} \end{aligned} } \tag{28}

Worth highlighting at this point since it came with a bit of arduous analysis – what we have ended up with are essentially the same step equations for the filter but we no longer have to specify a concrete value for κ\kappa for the initial covariance P1P_1. All we have to specify is the diagonal indicator matrix P∞,1P_{\infin,1} for the unknown variances. Once the diffuse phase is over (P∞,t=0P_{\infin,t} = 0) the filter automatically switches to only the regular Kalman filter step equations using the finite covariance components – i.e. Pt=P∗,tP_t = P_{\ast,t} and Ft=F∗,tF_t = F_{\ast,t}.

Parameter estimation

The second issue to address in our Kalman Filter implementation is the hardcoded noise distribution parameters, specifically the variances HtH_t and QtQ_t. This can be addressed in practice using maximum likelihood estimation (MLE) of the parameters. The idea is as usual with MLE that we use past observations to estimate the parameters that make the observations most probable.

Likelihood evaluation

Say we’re given our initial state α1∼N(a1,P1)\alpha_1 \sim \mathcal{N}(a_1, P_1). (29) shows the log likelihood function.

log⁡L(Yn)=∑t=1nlog⁡p(yt∣Yt−1)(29) \begin{aligned} \log L(Y_n) &= \sum_{t=1}^n \log p(y_t \mid Y_{t-1}) \end{aligned} \tag{29}

Concretely, using earlier derived substitutions, we have:

p(yt∣Yt−1)=N(E(yt∣Yt−1),Var(yt∣Yt−1))=N(E(Ztαt+εt∣Yt−1),Var(Ztαt+εt∣Yt−1))=N(Ztat,Ft)(30) \begin{aligned} p(y_t \mid Y_{t-1}) &= \mathcal{N}(E(y_t \mid Y_{t-1}), Var(y_t \mid Y_{t-1})) \\ &= \mathcal{N}(E(Z_t\alpha_t + \varepsilon_t \mid Y_{t-1}), Var(Z_t\alpha_t + \varepsilon_t \mid Y_{t-1})) \\ &= \mathcal{N}(Z_ta_t, F_t) \end{aligned} \tag{30}

which gives the log-likelihood:

log⁡L(Yn)=−12∑t=1n(log⁡2π+log⁡Ft+vt2Ft)(31) \begin{aligned} \log L(Y_n) &= -\frac{1}{2}\sum_{t=1}^n (\log 2\pi + \log F_t + \frac{v_t^2}{F_t}) \end{aligned} \tag{31}

Let FtF_t and vtv_t be functions of our θ\theta, the set of parameters needed for QtQ_t and HtH_t. That is, θ=[σε2σξ2…]\theta = \begin{bmatrix} \sigma_\varepsilon^2 & \sigma_\xi^2 & \dots \end{bmatrix}. Our maximum likelihood estimate θ^\hat{\theta} becomes the minimizer of the negative log likelihood:

θ^=arg min⁡θ  −log⁡L(Yn)=arg min⁡θ12∑t=1n(log⁡Ft(θ)+vt(θ)2Ft(θ))(32) \begin{aligned} \hat{\theta} &= \operatorname*{arg\,min}_\theta \; -\log L(Y_n) \\ &= \operatorname*{arg\,min}_\theta \frac{1}{2}\sum_{t=1}^n \left(\log F_t(\theta) + \frac{v_t(\theta)^2}{F_t(\theta)}\right) \end{aligned} \tag{32}

As a result, we can train on past observations to get the most probable estimates for our parameters and feed that into the Kalman filter steps as usual. This estimation can be done e.g. once upfront if we have a dedicated set of training data, or continuously at specific points in time as we see new observations (in an online setting without historical data).

Diffuse log likelihood

In the diffuse initialization scenario, the log likelihood diverges if we let κ→∞\kappa \to \infty, which isn’t good. This limitation leads to the diffuse log-likelihood Ld(Yn)L_d(Y_n), where dd denotes the last time step of the diffuse phase (t≤dt \le d, F∞,t≠0F_{\infin,t} \ne 0). During the diffuse phase, the summation term in the likelihood contains only the diffuse variance log⁡F∞,t\log F_{\infin,t}, whereas the finite phase uses the finite components log⁡F∗,t+vt2/F∗,t\log F_{\ast,t} + v_t^2/F_{\ast,t}.

log⁡Ld(Yn)=−n2log⁡2π−12∑t=1dwt−12∑t=d+1n(log⁡Ft+vt2Ft)wt={log⁡F∞,tif F∞,t≠0log⁡F∗,t+vt2F∗,tif F∞,t=0(33) \begin{aligned} \log L_d(Y_n) &= -\frac{n}{2}\log 2\pi - \frac{1}{2}\sum_{t=1}^{d} w_t - \frac{1}{2}\sum_{t=d+1}^{n}\left(\log F_t + \frac{v_t^2}{F_t}\right) \\ w_t &= \begin{cases} \log F_{\infin,t} & \text{if } F_{\infin,t} \ne 0 \\ \log F_{\ast,t} + \dfrac{v_t^2}{F_{\ast,t}} & \text{if } F_{\infin,t} = 0 \end{cases} \end{aligned} \tag{33}

Code implementation of the diffuse Kalman filter with likelihood estimation of its parameters can be found here.