What are State Space Models?
Contents
# meta-data does not work yet in VScode
# https://github.com/microsoft/vscode-jupyter/issues/1121
{
"tags": [
"hide-cell"
]
}
### Install necessary libraries
try:
import jax
except:
# For cuda version, see https://github.com/google/jax#installation
%pip install --upgrade "jax[cpu]"
import jax
try:
import distrax
except:
%pip install --upgrade distrax
import distrax
try:
import jsl
except:
%pip install git+https://github.com/probml/jsl
import jsl
try:
import rich
except:
%pip install rich
import rich
{
"tags": [
"hide-cell"
]
}
### Import standard libraries
import abc
from dataclasses import dataclass
import functools
import itertools
from typing import Any, Callable, NamedTuple, Optional, Union, Tuple
import matplotlib.pyplot as plt
import numpy as np
import jax
import jax.numpy as jnp
from jax import lax, vmap, jit, grad
from jax.scipy.special import logit
from jax.nn import softmax
from functools import partial
from jax.random import PRNGKey, split
import inspect
import inspect as py_inspect
import rich
from rich import inspect as r_inspect
from rich import print as r_print
def print_source(fname):
r_print(py_inspect.getsource(fname))
What are State Space Models?¶
A state space model or SSM is a partially observed Markov model, in which the hidden state, \(\hidden_t\), evolves over time according to a Markov process, possibly conditional on external inputs or controls \(\input_t\), and each hidden state generates some observations \(\obs_t\) at each time step. (In this book, we mostly focus on discrete time systems, although we consider the continuous-time case in XXX.) We get to see the observations, but not the hidden state. Our main goal is to infer the hidden state given the observations. However, we can also use the model to predict future observations, by first predicting future hidden states, and then predicting what observations they might generate. By using a hidden state \(\hidden_t\) to represent the past observations, \(\obs_{1:t-1}\), the model can have ``infinite’’ memory, unlike a standard Markov model.
Formally we can define an SSM as the following joint distribution:
where \(p(\hmmhid_t|\hmmhid_{t-1},\inputs_t)\) is the transition model, \(p(\hmmobs_t|\hmmhid_t, \inputs_t, \hmmobs_{t-1})\) is the observation model, and \(\inputs_{t}\) is an optional input or action. See Figure 3 for an illustration of the corresponding graphical model.
Fig. 3 Illustration of an SSM as a graphical model.¶
We often consider a simpler setting in which there are no external inputs, and the observations are conditionally independent of each other (rather than having Markovian dependencies) given the hidden state. In this case the joint simplifies to
See Figure 4 for an illustration of the corresponding graphical model. Compare (2) and (3).
Fig. 4 Illustration of a simplified SSM.¶
Inferential goals¶
Fig. 6 Illustration of the different kinds of inference in an SSM. The main kinds of inference for state-space models. The shaded region is the interval for which we have data. The arrow represents the time step at which we want to perform inference. \(t\) is the current time, \(T\) is the sequence length, \(\ell\) is the lag and \(h\) is the prediction horizon.¶
Given the sequence of observations, and a known model, one of the main tasks with SSMs to perform posterior inference, about the hidden states; this is also called state estimation. At each time step \(t\), there are multiple forms of posterior we may be interested in computing, including the following:
the filtering distribution \(p(\hmmhid_t|\hmmobs_{1:t})\)
the smoothing distribution \(p(\hmmhid_t|\hmmobs_{1:T})\) (note that this conditions on future data \(T>t\))
the fixed-lag smoothing distribution \(p(\hmmhid_{t-\ell}|\hmmobs_{1:t})\) (note that this infers \(\ell\) steps in the past given data up to the present).
We may also want to compute the predictive distribution \(h\) steps into the future:
where the hidden state predictive distribution is
See \cref{fig:dbn_inf_problems} for a summary of these distributions.
In addition to comuting posterior marginals, we may want to compute the most probable hidden sequence, i.e., the joint MAP estimate
or sample sequences from the posterior
Algorithms for all these task are discussed in the following chapters, since the details depend on the form of the SSM.
Example: inference in the casino HMM¶
We now illustrate filtering, smoothing and MAP decoding applied to the casino HMM from sec:casino.
# Call inference engine
filtered_dist, _, smoothed_dist, loglik = hmm.forward_backward(x_hist)
map_path = hmm.viterbi(x_hist)
/opt/anaconda3/lib/python3.8/site-packages/jax/_src/numpy/lax_numpy.py:5154: UserWarning: Explicitly requested dtype <class 'jax._src.numpy.lax_numpy.int64'> requested in astype is not available, and will be truncated to dtype int32. To enable more dtypes, set the jax_enable_x64 configuration option or the JAX_ENABLE_X64 shell environment variable. See https://github.com/google/jax#current-gotchas for more.
lax_internal._check_user_dtype_supported(dtype, "astype")
# Find the span of timesteps that the simulated systems turns to be in state 1
def find_dishonest_intervals(z_hist):
spans = []
x_init = 0
for t, _ in enumerate(z_hist[:-1]):
if z_hist[t + 1] == 0 and z_hist[t] == 1:
x_end = t
spans.append((x_init, x_end))
elif z_hist[t + 1] == 1 and z_hist[t] == 0:
x_init = t + 1
return spans
# Plot posterior
def plot_inference(inference_values, z_hist, ax, state=1, map_estimate=False):
n_samples = len(inference_values)
xspan = np.arange(1, n_samples + 1)
spans = find_dishonest_intervals(z_hist)
if map_estimate:
ax.step(xspan, inference_values, where="post")
else:
ax.plot(xspan, inference_values[:, state])
for span in spans:
ax.axvspan(*span, alpha=0.5, facecolor="tab:gray", edgecolor="none")
ax.set_xlim(1, n_samples)
# ax.set_ylim(0, 1)
ax.set_ylim(-0.1, 1.1)
ax.set_xlabel("Observation number")
# Filtering
fig, ax = plt.subplots()
plot_inference(filtered_dist, z_hist, ax)
ax.set_ylabel("p(loaded)")
ax.set_title("Filtered")
Text(0.5, 1.0, 'Filtered')
# Smoothing
fig, ax = plt.subplots()
plot_inference(smoothed_dist, z_hist, ax)
ax.set_ylabel("p(loaded)")
ax.set_title("Smoothed")
Text(0.5, 1.0, 'Smoothed')
# MAP estimation
fig, ax = plt.subplots()
plot_inference(map_path, z_hist, ax, map_estimate=True)
ax.set_ylabel("MAP state")
ax.set_title("Viterbi")
Text(0.5, 1.0, 'Viterbi')
# TODO: posterior samples
Example: inference in the tracking SSM¶
We now illustrate filtering, smoothing and MAP decoding applied to the 2d tracking HMM from Example: model for 2d tracking.
