Filters and smoothers¶
sequential_analysis.procedures.state_space
¶
Linear state-space filters.
KalmanFilter is the exact filter of the linear Gaussian model
z_t = F z_{t-1} + B u_t + w_t, w_t ~ N(0, Q) (state, n entries)
y_t = H z_t + v_t, v_t ~ N(0, R) (observation, m entries)
with z_0 ~ N(m0, P0): after each observation the state is N(mean, covariance),
the exact conditional distribution of z_t given y_1..y_t, and
log_likelihood is log p(y_1..y_t). The covariance is updated in Joseph
form, (I - K H) P (I - K H)' + K R K', which keeps it symmetric and positive
semi-definite in floating point. Local linear trends, autoregressions,
constant-velocity tracking and regression with drifting coefficients are
all special cases; constructors for the first two are provided.
RobustKalmanFilter replaces the Gaussian observation noise by a
multivariate Student t with df degrees of freedom and scale R -- a
Gaussian whose precision is scaled by a Gamma(df/2, df/2) weight lambda.
The exact filter is then intractable; the variational Bayes update of
Piche, Sarkka and Hartikainen (2012) alternates a Kalman update with
noise covariance R / lambda and
lambda = (df + m) / (df + E[(y - H z)' R^-1 (y - H z)]),
the expectation under the current state posterior, until lambda settles. An observation far from its prediction gets a small weight and moves the state little: outliers are discounted instead of dragging the filter. As df grows the filter becomes the Kalman filter.
Cost per step (PERFORMANCE.md): constant, O(n^3) in the state dimension; 0.1 ms for two states, 0.16 ms for four, in Python (numpy is slower at these sizes); the robust filter iterates the update, about 1 ms.
KalmanFilter
¶
Bases: Procedure
Exact filter of a linear Gaussian state-space model; see the module docstring.
Matrices are given as nested sequences (a number for 1x1). With one
observed quantity the input is a number, otherwise a list of m numbers;
the same holds for the control input u (declared when control is given).
local_linear_trend(level_noise, slope_noise, observation_noise, **kwargs)
classmethod
¶
Level and slope: level_t = level_{t-1} + slope_{t-1} + noise, slope a random walk, y = level + noise.
autoregressive(coefficients, process_noise, observation_noise, **kwargs)
classmethod
¶
AR(p) observed with noise: z_t = sum_i phi_i z_{t-i} + w_t, y_t = z_t + v_t (companion form).
RobustKalmanFilter
¶
Bases: KalmanFilter
Linear state-space filter with Student-t observation noise (variational Bayes); see the module docstring.
df sets how heavy the tails are: 3 to 5 for data with occasional gross
outliers. weight in the output is lambda: near 1 for an ordinary
observation, small for one the filter treats as an outlier. The
posterior is an approximation, so no likelihood is reported.
sequential_analysis.procedures.hmm
¶
Filtering in a hidden Markov model: which regime is the process in now?
A hidden state z_t in {0, ..., K-1} moves by a Markov chain,
P(z_t = k | z_{t-1} = j) = A[j][k], starting from P(z_1 = k) = initial[k];
the observation y_t depends only on z_t. The forward algorithm gives the
exact filtering distribution
P(z_t = k | y_1..y_t) proportional to e_k(y_t) sum_j P(z_{t-1} = j | y_1..y_{t-1}) A[j][k],
and the normalising constants multiply to the likelihood p(y_1..y_t). The emission densities are combined in logarithms, so observations far in the tails do not underflow.
Emission models: CategoricalEmission (a symbol 0..M-1), GaussianEmission
(a mean and standard deviation per state), PoissonEmission (a rate per
state), MultivariateGaussianEmission (a mean vector and covariance matrix
per state, for a vector observation), StudentTEmission (a location, scale
and degrees of freedom per state: Gaussian-like, robust to outliers).
emission_from_spec rebuilds any of them from its spec(). Typical
uses: regime detection (calm/volatile), a machine's hidden condition, a
patient's disease stage.
Cost per step (PERFORMANCE.md): O(K^2) for K states, 6 µs for three; a constant state.
CategoricalEmission
¶
y in {0, ..., M-1} with P(y = s | z = k) = probabilities[k][s].
GaussianEmission
¶
PoissonEmission
¶
MultivariateGaussianEmission
¶
y | z = k ~ N_d(means[k], covariances[k]), for a vector observation y of length d.
Each covariance must be symmetric (exactly) and positive definite; its Cholesky factor L (L L' = covariance) is computed once, and
log e_k(y) = -|L^-1 (y - mean)|^2 / 2 - sum_i log L_ii - d log(2 pi) / 2,
by forward substitution, every sum left to right. With d = 1 this is GaussianEmission with sd = sqrt(variance).
statistics(k, y)
¶
g(y) = (y_1, ..., y_d, then y_i y_j for i <= j, row by row: y_1 y_1, y_1 y_2, ..., y_1 y_d, y_2 y_2, ...).
from_statistics(totals, min_scale=1e-06)
¶
Maximum-likelihood means and covariances; empty states keep theirs.
The covariance is the weighted sum of squares about the mean over
the weight, plus min_scale^2 on the diagonal (a ridge: every
variance at least min_scale^2, and a covariance of collinear data
positive definite). A state whose updated covariance is still not
positive definite (by the test of the constructor) keeps its old
parameters too.
StudentTEmission
¶
y | z = k ~ means[k] + scales[k] T(df[k]): location-scale Student t, robust to outliers.
log e_k(y) = log Gamma((df+1)/2) - log Gamma(df/2) - log(df pi)/2 - log scale
- (df+1)/2 log1p(z^2 / df), z = (y - mean) / scale,
with the ratio of Gamma functions evaluated without cancellation for
large df, and log1p(z^2/df) as 2 (log|y - mean| - log scale - log(df)/2)
when z^2/df exceeds 1e300, so any finite outlier has a finite
log-density. As df grows the
density tends to GaussianEmission(means, scales). df is one number
for every state or one per state; it is held fixed by from_statistics
(not estimated).
weight(k, y)
¶
E[precision | y, z = k] = (df + 1) / (df + z^2), the weight of y in the M-step (0 for a far outlier).
statistics(k, y)
¶
g_k(y) = (u, u y, u y^2) with u = weight(k, y), at the current parameters of state k (the ECM E-step).
y | z = k is N(mean, scale^2 / tau) with tau ~ Gamma(df/2, rate df/2);
u = E[tau | y]. Given u, the complete-data likelihood is Gaussian
with weights u, which from_statistics maximises.
from_statistics(totals, min_scale=1e-06)
¶
The ECM M-step with df fixed (Liu & Rubin 1995; McLachlan & Peel 2000, section 7.5).
totals[k] = (w, S_u, S_uy, S_uy2), w the sum of the posterior
weights of state k and S_* the posterior-weighted sums of
statistics(k, y):
mean = S_uy / S_u, scale^2 = (S_uy2 - 2 mean S_uy + mean^2 S_u) / w,
the scale at least min_scale. With the u of the current
parameters this is an exact EM step for (mean, scale): the
likelihood never decreases. Empty states (or states whose
observations all have weight u = 0) keep their parameters.
HiddenMarkovFilter
¶
emission_from_spec(spec)
¶
The emission model whose spec() is spec (mirrors emissionFromSpec of the TypeScript executor).
sequential_analysis.procedures.online_hmm
¶
A hidden Markov model that learns its parameters on the stream: online EM (Cappé 2011).
HiddenMarkovFilter needs the transition matrix and the emission
parameters; fit_hmm estimates them from a recorded series. OnlineHMM
filters and estimates at once, one observation at a time, in constant
memory -- for a process that cannot be recorded first, or whose
parameters drift slowly.
It keeps, besides the filter phi_t(k) = P(z_t = k | y_1..y_t), the expected complete-data sufficient statistics conditionally on the current state,
rho_t(k) = E[ (1/t-weighted) sum_s s(z_{s-1}, z_s, y_s) | z_t = k, y_1..y_t ],
for the transitions (counts of j -> l) and the emissions (the
statistics emission.statistics of each state), updated by the backward
kernel r_t(j | k) = phi_{t-1}(j) A[j][k] / sum_j' phi_{t-1}(j') A[j'][k]:
rho_t(k) = gamma_t s(., k, y_t) + (1 - gamma_t) sum_j rho_{t-1}(j) r_t(j | k),
with step sizes gamma_t = t^-kappa (1/2 < kappa <= 1). The statistics
S_t = sum_k rho_t(k) phi_t(k) approximate the normalised expected
statistics of the batch E-step, and after burn_in observations the
parameters are their maximiser (the M-step of fit_hmm):
A[j][l] = S(j, l) / sum_l S(j, l), the emissions emission.from_statistics.
Before that the starting model is used. Cappé (2011) shows that the
estimates converge to a stationary point of the limiting likelihood under
regularity conditions; the tests check that they approach the batch
maximum-likelihood estimates (fit_hmm) and the true parameters on long
simulated series.
The starting model fixes the number of states, the emission family and the labels: like any EM, online EM finds the maximum nearest to where it starts, and states keep their labels only if they start apart.
Outputs: the filtered probabilities and most likely state, the current transition matrix and emission parameters, and the prequential log-likelihood sum_t log p(y_t | y_1..y_{t-1}), each term under the parameters of the step before -- a fair score of the learner.
Parameters (average, default True): the M-step is applied to the
statistics averaged since the burn-in (Polyak-Ruppert averaging), which
removes most of the noise of the step sizes. On series of 15 000 from a
two-state Gaussian HMM, the standard deviation over seeds of an estimated
transition probability was 0.019 for the last iterate with kappa = 0.6,
and 0.005 with averaging -- that of the batch maximum-likelihood
estimate.
Cost per step (PERFORMANCE.md): O(K^4 + K^2 m) for K states and m emission statistics, 56 µs for three Gaussian states (CPython); the state holds K + K^3 + K^2 (m + 1) numbers and as many averages, 1.7 kB of JSON for three states, constant in time.
sequential_analysis.procedures.particle_filter
¶
Particle filter for any state-space model you can simulate and evaluate.
A model says how the hidden state starts (initial, the distribution of
z_0), how it moves (transition, a draw of z_t given z_{t-1}) and how
likely an observation is (log_likelihood, log p(y_t | z_t)). Nothing
needs to be linear or Gaussian: stochastic volatility, heavy-tailed noise,
counts with a latent rate, saturation and thresholds.
ParticleFilter is the bootstrap filter (Gordon, Salmond and Smith 1993)
with adaptive systematic resampling: N particles are moved by the model,
weighted by the likelihood of y_t, and resampled when the effective sample
size N_eff = 1 / sum W_i^2 falls below resample_threshold N. Weighted
averages estimate posterior expectations given y_1..y_t, with error of
order 1/sqrt(N); and the product of the averaged likelihoods,
p_hat(y_1..t) = prod_s sum_i W_{s-1,i} p(y_s | z_s,i),
is an unbiased estimate of the likelihood p(y_1..y_t) (Del Moral 2004). All randomness comes from the run's statistical random state, so a run is reproducible and resumes bit for bit from a checkpoint.
Models provided: LinearGaussianModel (scalar, the Kalman filter's model: use it to check a filter), StochasticVolatilityModel, and StudentTLocalLevel (a random walk observed with heavy-tailed noise). Write your own by subclassing StateSpaceModel.
Cost per step (PERFORMANCE.md): O(N); 20 000 particles take 2.7 ms with numpy and 35 ms in Python; the checkpoint holds every particle and its weight, about 40 bytes each.
StateSpaceModel
¶
Bases: ABC
What ParticleFilter needs from a model. States are floats (dimension 1) or tuples of floats.
initial(rng)
abstractmethod
¶
A draw of z_0.
transition(state, rng)
abstractmethod
¶
A draw of z_t given z_{t-1} = state.
log_likelihood(state, y)
abstractmethod
¶
log p(y_t | z_t = state).
initial_many(rng, count)
¶
count draws of z_0 as a numpy array; rng is a backend.VectorRandom.
transition_many(states, rng)
¶
One draw of z_t for each z_{t-1} in the numpy array states.
log_likelihood_many(states, y)
¶
log p(y | z) for each z in the numpy array states.
LinearGaussianModel
¶
StochasticVolatilityModel
¶
Bases: StateSpaceModel
Log-variance h_t = mu + phi (h_{t-1} - mu) + sigma eta_t; return y_t = exp(h_t / 2) eps_t.
h_0 is drawn from the stationary distribution N(mu, sigma^2 / (1 - phi^2)).
StudentTLocalLevel
¶
Bases: StateSpaceModel
z_t = z_{t-1} + N(0, q), y_t = z_t + scale * t_df, z_0 ~ N(m0, p0): a level observed with outliers.
sequential_analysis.procedures.kalman
¶
Kalman filter for the local-level model, optionally with a known control input.
z_t = z_{t-1} + u_t + w_t, w_t ~ N(0, q)
y_t = z_t + v_t, v_t ~ N(0, r)
With control=True the applied action u_t is a declared logical input.
This is how feedback enters the statistical boundary: an action that
changes the observation process is itself observed.
sequential_analysis.procedures.particle
¶
Bootstrap particle filter for the local-level model: a randomized procedure.
All randomness is drawn from the statistical random state R_t that the run
passes into step. The initial particle cloud is drawn in the first step,
so initial_state stays deterministic.
sequential_analysis.procedures.ema
¶
Exponential moving average: a stateful transformation, so also a procedure.
sequential_analysis.procedures.two_sample
¶
Running difference of two independent sample means.
A two-input procedure that does not need its inputs paired: every step may carry an observation for either sample, or for both.
sequential_analysis.smoothing
¶
Smoothing: the hidden state at every time, given all the observations.
A filter answers "where is the state now, given what has been seen so far?" -- the question of a run that acts while data arrive. Looking back over a finished series (a recorded run, a day of sensor data), the better question is "where was the state at time t, given everything, including what came after t?". These functions answer it for a stretch of inputs, offline; they reuse the filter's own model and step, so a smoothing pass over the inputs of a run agrees with that run's filtering outputs.
kalman_smoother -- Rauch-Tung-Striebel: the exact conditional distribution N(m_{t|T}, P_{t|T}) of z_t given y_1..y_T in a linear Gaussian model, from a forward Kalman pass and the backward recursion
G_t = P_{t|t} F' P_{t+1|t}^-1
m_{t|T} = m_{t|t} + G_t (m_{t+1|T} - m_{t+1|t})
P_{t|T} = P_{t|t} + G_t (P_{t+1|T} - P_{t+1|t}) G_t'.
With a RobustKalmanFilter the same recursion runs on its variational
posteriors: an approximation, as the filter is.
forward_backward -- P(z_t = k | y_1..y_T) in a hidden Markov model, from the scaled forward and backward recursions. viterbi -- the single most probable path of hidden states and its log joint probability log p(z_1..z_T, y_1..y_T).
Cost (PERFORMANCE.md): linear in T; per time point O(n^3) for the Kalman smoother (0.17 ms for two states) and O(K^2) for the HMM (17 µs for forward-backward, 3 µs for Viterbi, three states). Memory is linear in T: the forward pass is kept for the backward one.
kalman_smoother(filter, inputs)
¶
Rauch-Tung-Striebel smoothing of inputs (the statistical inputs, as given to the filter's step).
forward_backward(hmm, inputs)
¶
Smoothed state probabilities of a hidden Markov model over inputs.
viterbi(hmm, inputs)
¶
The most probable sequence of hidden states (ties go to the smaller state index).
sequential_analysis.hmm_fit
¶
Fitting a hidden Markov model to a recorded series: the Baum-Welch (EM) algorithm.
HiddenMarkovFilter needs the model: the initial distribution, the
transition matrix and the emission parameters. When they are not known,
fit_hmm estimates them by maximum likelihood from a series observed
before (Baum, Petrie, Soules and Weiss 1970; Rabiner 1989). Each
iteration runs the scaled forward-backward recursions of
sequential_analysis.smoothing, accumulates the expected transitions
and the posterior-weighted sufficient statistics of the emissions
(emission.statistics), and maximises (emission.from_statistics).
The log-likelihood never decreases from one iteration to the next (the
EM property; checked in the tests), but EM finds a local maximum: give
restarts to try further starting points drawn from the data, and the
fit with the highest likelihood is returned.
The likelihood does not change when the states are relabelled ("label
switching"): a run keeps the labels of its starting model, and the best
of several random restarts is relabelled to match start as closely as
possible.
The result is a HiddenMarkovFilter, ready to filter new data as they
arrive (or OnlineHMM to keep learning on the stream). Checked against
hmmlearn: one EM step from the same starting point agrees to 1e-10
(Gaussian, Poisson and categorical emissions).
Cost: O(T K^2) per iteration for T observations and K states, in Python; a few seconds for T = 10 000 and K = 3 per hundred iterations.
e_step(model, ys)
¶
Expected complete-data sufficient statistics of a series under a model (scaled forward-backward).
fit_hmm(inputs, start, *, iterations=500, tolerance=1e-09, min_scale=1e-06, restarts=0, seed=0, fit_initial=True, fit_transition=True)
¶
Maximum-likelihood HMM parameters for a recorded series, by EM from start (and restarts random starts).
start gives the number of states, the emission family and the
starting parameters; its input name selects the field of the
records. EM stops when the log-likelihood rises by less than
tolerance in an iteration, or after iterations. min_scale
bounds standard deviations, scales and rates from below, and is the
ridge on covariances (a state that collapses onto one value otherwise
drives the likelihood to infinity). With restarts, further runs start from random soft
assignments of the observations to the states (seeded by seed), and
the best run is returned with its states sorted by their first
emission parameter; fit_initial / fit_transition False keep those
parameters as given.