The Kalman filter
A linear Gaussian state-space model is a continuous HMM whose calculations have closed forms. We derive the Kalman filter through repeated linear Gaussian Bayes updates, implement it with numerical stability, obtain likelihood through prediction errors, and study steady state and consistency tests.
After this lesson you can
- Formulate a tracking or latent-level problem as a linear Gaussian state-space model.
- Derive prediction and update steps and the Kalman gain.
- Implement the filter with Joseph form, missing observations and innovation log likelihood.
- Calculate steady-state gain by solving the discrete Riccati equation.
- Diagnose a poorly tuned filter using normalized innovations (NIS) and their autocorrelation.
Before you start
- 14Hidden Markov modelForward algorithm (filtering)
- 04Linear-Gaussian modelPrecision matrixExponential, gamma and chi-squared distributionsMahalanobis distance
- 02Cholesky decompositionPositive definite matrix
- 09Forward and back substitutionExplicit and implicit Euler methods
- 03Linear ODE systemsMatrix exponential
Tracking an unobserved state
Noisy position, indirectly measured velocity and sensors missing at some times are sequential inference problems. A linear Gaussian state-space model is an HMM with continuous state:
The initial state is Gaussian and noise terms are independent across time, of each other and of the initial state. describes dynamics uncertainty; observation noise. Matrices can depend on time. The Kalman filter calculates the exact filtering posterior under these assumptions; a linear model does not guarantee those assumptions describe the real phenomenon well.
In constant-velocity tracking, the state can contain position and velocity. Position observation does not measure velocity directly, but successive positions inform it through the transition matrix. The state represents what we wish to estimate, not necessarily something delivered by a sensor. Choosing too small an initial covariance tells the filter it is overly confident initially and can make early measurements barely change the estimate.
The figure’s trajectory is synthetic and changes direction. The filter assumes a random walk, a deliberate simplification. With small it tends to smooth and can lag behind changes; with larger it responds more to each measurement. The band represents uncertainty conditional on the chosen model: if the model is wrong, it does not guarantee nominal coverage.
Predict and update
Suppose the previous filtered state is . Applying the dynamics gives the prior for the current time:
The innovation compares observation with prediction; its covariance and the Kalman gain are
Then and, for the exact gain, . The derivation is the conditioning rule for a joint Gaussian: and .
In the scalar case with , the gain is and the posterior mean is . For example, if and , the gain is 0.8: the new mean is closer to the measurement than to the prior. Posterior variance is 0.8. If both sources have equal variance, the gain is 0.5. These interpretations depend on scale and correlations: in multiple dimensions gain is a matrix and its individual entries are not necessarily proportions between zero and one.
The figure uses a two-dimensional position and velocity state, a straight synthetic trajectory and anisotropic acceleration noise greater along the motion. A prediction propagates uncertainty; when the measurement is missing there is no update and the ellipses coincide. With data, the update reduces covariance in positive semidefinite order, although axis orientation can change.
A scalar observation of a projection does not constrain every direction equally: its likelihood forms a strip. Prior correlation lets observation of one coordinate also correct another. In the figure innovation is one, so the arrow is exactly . If observed noise tends to zero, the measured direction can become determined, provided its predictive variance is positive; unobserved directions can retain uncertainty. If grows without bound, the gain of that measurement tends to zero.
Likelihood and stability
If is positive definite, innovations contribute the log likelihood
where is the dimension observed at that step. Each term is the conditional predictive density given history. If components are missing, select available rows of and the corresponding block of ; if the entire measurement is missing, retain the prediction and add no likelihood term. For and the quadratic term, solve systems with Cholesky instead of forming .
The evidence decomposition follows from the chain rule: . Each predictive distribution is Gaussian with mean and covariance . The log determinant penalizes a more dispersed predictive distribution, while the quadratic measures innovation size in units of its covariance. The result depends on the initial distribution and treatment of missing observations; two libraries are comparable only if they use the same conventions.
The Joseph form calculates
For the optimal gain it is algebraically equal to the simplified expression. For any gain, if and are positive semidefinite, both sums of squares are too in exact arithmetic. They are not always positive definite: with a perfect measurement and a zero covariance can remain. If both input covariances are positive definite, Joseph form is positive definite. Symmetrizing removes small numerical asymmetries but does not fix an invalid model. Square-root filters propagate factorizations and can be more robust in ill-conditioned problems.
The difference matters in finite implementations: the simplified formula subtracts matrices that may have similar magnitudes, and a gain computed with numerical error can break symmetry. Joseph explicitly preserves the theoretical structure of a sum of semidefinite terms. Floating point still rounds, so demanding applications should verify symmetry and eigenvalues or use an appropriate factorization.
Steady state and information
When the system is invariant and appropriate detectability and stabilization conditions hold, predictive covariance converges to a stabilizing Riccati solution:
This equation corresponds to the prediction-after-update cycle. The steady-state gain is obtained with that predictive covariance, not the posterior without adjusting the index. For a scalar random walk with , , and .
To obtain the scalar result, write and . Substituting and yields ; take the positive root because a variance cannot be negative. The gain is . Convergence must not be assumed in an arbitrary system with unobservable components or unstable dynamics.
In information form, if inverses exist, and . The update adds observation information:
Prediction is not generally a simple sum of precisions. Information form helps combine independent contributions, but still requires care with singularity and solving systems.
Innovation consistency
NIS is . Under a correctly specified Gaussian model and known parameters, follows a with as many degrees of freedom as observations present. If innovations are independent, their sum has the summed degrees. NEES replaces innovation with state error and posterior covariance; it requires knowing truth, available in simulation but not normally in a real system.
A large NIS indicates an observation surprising relative to predicted scale; systematically small values can indicate overestimated uncertainty. Temporal correlation of innovations gives another clue: for example, dynamics that are too rigid may leave errors of the same sign for several steps. Neither one NIS nor one autocorrelation bar identifies by itself which matrix is wrong. Before tuning parameters, check dimensions, units, timing and handling of missing data.
The example generates a random walk with , and 200 synthetic observations. The figure compares the NIS sum with quantiles and displays approximate autocorrelation bands . These are different tests: an autocorrelation band is not a chi-squared interval. One realization can fall outside by chance, and passing a test does not prove the model correct. Tuning on the same series also changes the interpretation of nominal thresholds.
The time step also matters. Under constant velocity, a continuous white-acceleration model with intensity has, per axis,
This is not the same matrix as a random acceleration constant within each interval, with . Both discretize different assumptions. In general and is obtained by integrating continuous noise covariance across the interval.
Lab: filter and missing measurements
The prior corresponds to the first observed time; thereafter predict before each update. The code accepts partially missing measurements and uses Joseph and Cholesky.
"""Filtro lineal gaussiano con Joseph, datos ausentes y log-evidencia."""
import numpy as np
from scipy.linalg import cho_factor,cho_solve
def predict(mean,cov,F,Q,u=None,B=None):
mean=np.asarray(F)@mean
if u is not None:
if B is None:raise ValueError('Falta matriz de control B')
mean=mean+np.asarray(B)@np.atleast_1d(u)
cov=np.asarray(F)@cov@np.asarray(F).T+Q
return mean,(cov+cov.T)/2
def update(mean,cov,y,H,R):
"""NaN omite componentes de observación; m0,P0 son prior del mismo instante."""
y=np.atleast_1d(np.asarray(y,float));H=np.atleast_2d(H);R=np.atleast_2d(R)
mask=np.isfinite(y)
if not mask.any():return mean,cov,0.,np.nan,np.array([])
y=y[mask];H=H[mask,:];R=R[np.ix_(mask,mask)]
innovation=y-H@mean;S=H@cov@H.T+R
factor=cho_factor(S,lower=True)
K=cho_solve(factor,H@cov).T
z=cho_solve(factor,innovation);nis=float(innovation@z)
logdet=2*np.log(np.diag(factor[0])).sum()
loglik=-.5*(len(y)*np.log(2*np.pi)+logdet+nis)
mean=mean+K@innovation
J=np.eye(len(mean))-K@H
cov=J@cov@J.T+K@R@K.T
return mean,(cov+cov.T)/2,float(loglik),nis,innovation
def filter_sequence(y,m0,P0,F,Q,H,R):
"""m0,P0 son prior en t=0; la primera predicción es para t=1."""
m=np.asarray(m0,float).copy();P=np.asarray(P0,float).copy()
means=[];covs=[];ll=0.;nis=[];innovations=[]
for t,obs in enumerate(y):
if t:m,P=predict(m,P,F,Q)
m,P,ell,n,v=update(m,P,obs,H,R)
means.append(m.copy());covs.append(P.copy());ll+=ell
nis.append(n);innovations.append(v)
return np.array(means),np.array(covs),ll,np.array(nis),innovationsrng=np.random.default_rng(21);T=80
F=np.array([[1,0,1,0],[0,1,0,1],[0,0,1,0],[0,0,0,1.]])
G=np.array([[.5,0],[0,.5],[1,0],[0,1.]])
Q=.02*G@G.T;H=np.array([[1,0,0,0],[0,1,0,0.]])
R=.64*np.eye(2);m0=np.array([0.,0.,.8,.3]);P0=np.diag([1.,1.,.5,.5])
truth=np.empty((T,4));truth[0]=rng.multivariate_normal(m0,P0)
for t in range(1,T):truth[t]=F@truth[t-1]+G@rng.normal(0,np.sqrt(.02),2)
y=truth@H.T+rng.normal(0,.8,(T,2));y[20:30]=np.nan
means,covs,ll,nis,innov=filter_sequence(y,m0,P0,F,Q,H,R)
rmse=np.sqrt(np.mean(np.sum((means[:,:2]-truth[:,:2])**2,axis=1)))
print('RMSE de posición, log evidencia:',rmse,ll)
print('traza al inicio/fin de ausencia:',np.trace(covs[20]),np.trace(covs[29]))
print('mínimo autovalor posterior:',np.linalg.eigvalsh(covs).min())
assert np.linalg.eigvalsh(covs).min()>-1e-10 and np.isnan(nis[20:30]).all()
The statsmodels comparison uses a different local-level model, not the 2D trajectory. The same prior is fixed and initial likelihood burn-in is set to zero; default diffuse initialization would answer under a different convention.
from statsmodels.tsa.statespace.structural import UnobservedComponents
rng=np.random.default_rng(31);q=.4;r=1.2;n=100
z=np.cumsum(rng.normal(0,np.sqrt(q),n))
obs=z+rng.normal(0,np.sqrt(r),n);obs[20]=np.nan
own=filter_sequence(obs[:,None],np.array([0.]),np.array([[2.]]),
np.array([[1.]]),np.array([[q]]),np.array([[1.]]),np.array([[r]]))
model=UnobservedComponents(obs,level='local level')
model.ssm.initialize_known(np.array([0.]),np.array([[2.]]))
model.loglikelihood_burn=0;model.ssm.loglikelihood_burn=0
ref=model.smooth([r,q])
print('Error máximo estados:',np.max(abs(own[0][:,0]-ref.filtered_state[0])))
print('Log evidencia propia y statsmodels:',own[2],ref.llf)
assert np.allclose(own[0][:,0],ref.filtered_state[0],rtol=0,atol=1e-6)
assert np.isclose(own[2],ref.llf,rtol=0,atol=1e-6)
The following simulation fuses an accelerometer at every step and GPS every ten. Measured acceleration is used as control and the augmented state estimates a constant bias; the two-state model omits it. Truth and bias are known only to evaluate this simulation.
"""Fusión 1D sintética: acelerómetro con sesgo y GPS cada 10 pasos."""
def gps_imu_demo(seed=42):
rng=np.random.default_rng(seed);T=180;dt=1.;t=np.arange(T)
acc=.06*np.sin(t/12);bias=.12;imu_sd=.03;gps_sd=.5
imu=acc+bias+rng.normal(0,imu_sd,T)
truth=np.zeros((T,2));gps=np.full(T,np.nan)
for k in range(1,T):
truth[k,0]=truth[k-1,0]+dt*truth[k-1,1]+.5*dt**2*acc[k-1]
truth[k,1]=truth[k-1,1]+dt*acc[k-1]
gps[::10]=truth[::10,0]+rng.normal(0,gps_sd,len(gps[::10]))
outputs=[]
for with_bias in (False,True):
if with_bias:
F=np.array([[1,dt,-.5*dt**2],[0,1,-dt],[0,0,1.]])
B=np.array([[.5*dt**2],[dt],[0.]])
H=np.array([[1.,0.,0.]])
Q=imu_sd**2*(B@B.T)+np.diag([1e-6,1e-6,1e-6])
m=np.array([0.,0.,0.]);P=np.diag([1.,1.,.25])
else:
F=np.array([[1.,dt],[0.,1.]])
B=np.array([[.5*dt**2],[dt]])
H=np.array([[1.,0.]])
Q=imu_sd**2*(B@B.T)+np.diag([1e-6,1e-6])
m=np.array([0.,0.]);P=np.diag([1.,1.])
positions=[];bias_est=[]
for k in range(T):
if k:m,P=predict(m,P,F,Q,np.array([imu[k-1]]),B)
m,P,_,_,_=update(m,P,np.array([gps[k]]),H,np.array([[gps_sd**2]]))
positions.append(m[0]);bias_est.append(m[2] if with_bias else np.nan)
outputs.append((np.array(positions),np.array(bias_est)))
rmse=[float(np.sqrt(np.mean((o[0]-truth[:,0])**2))) for o in outputs]
print('GPS/IMU: RMSE sin y con sesgo',rmse,'sesgo verdadero / final estimado',bias,outputs[1][1][-1])
return truth,gps,imu,outputs,rmse
truth_gps,gps,imu,outputs,errors=gps_imu_demo()With seed 42, position RMSE is approximately 8.43 without the bias state and 1.03 with it; final bias estimate is 0.1177 versus 0.12. These are results for this trajectory, GPS frequency, noise and prior, not a promise for real sensors.
Exercises
Step 1 of 3. What is the cross-covariance of x and y?
Step 1 of 3. What appears when expanding J P⁻ Jᵀ+K R Kᵀ?
import numpy as np
from scipy.stats import chi2
def nis_test(innovation,S,confidence=.95):
return None