Module contents
Lesson 12 of 27Core 110 min

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

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:

xt=Fxt−1+But+wt,yt=Hxt+vt,wt∼N(0,Q),vt∼N(0,R).\vb x_t=\mat F\vb x_{t-1}+\mat B\vb u_t+\vb w_t,\quad \vb y_t=\mat H\vb x_t+\vb v_t,\qquad \vb w_t\sim\Normal(\vb0,\mat Q),\quad \vb v_t\sim\Normal(\vb0,\mat R).

The initial state is Gaussian and noise terms are independent across time, of each other and of the initial state. Q\mat Q describes dynamics uncertainty; R\mat R 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.

Interactive1D tracking with Q and R
  • True position
  • Measurements
  • Filter ±1.96 σ

Piecewise synthetic motion with turns and measurement noise of standard deviation 0.65, seed 91. The filter assumes a random walk; the band is conditional on chosen Q and R, not a coverage guarantee if the model is wrong.

0.010
0.42
Q/R0.024
Final standard deviation0.245
Adjust assumed variances and compare position, measurements and the filter band.

The figure’s trajectory is synthetic and changes direction. The filter assumes a random walk, a deliberate simplification. With small Q/RQ/R it tends to smooth and can lag behind changes; with larger Q/RQ/R 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 N(mt−1,Pt−1)\Normal(\vb m_{t-1},\mat P_{t-1}). Applying the dynamics gives the prior for the current time:

mt−=Fmt−1+But,Pt−=FPt−1F⊤+Q.\vb m_t^-=\mat F\vb m_{t-1}+\mat B\vb u_t,\qquad \mat P_t^-=\mat F\mat P_{t-1}\mat F\T+\mat Q.

The innovation compares observation with prediction; its covariance and the Kalman gain are

et=yt−Hmt−,St=HPt−H⊤+R,Kt=Pt−H⊤St−1.\vb e_t=\vb y_t-\mat H\vb m_t^-,\quad \mat S_t=\mat H\mat P_t^-\mat H\T+\mat R,\quad \mat K_t=\mat P_t^-\mat H\T\mat S_t^{-1}.

Then mt=mt−+Ktet\vb m_t=\vb m_t^-+\mat K_t\vb e_t and, for the exact gain, Pt=(I−KtH)Pt−\mat P_t=(\mat I-\mat K_t\mat H)\mat P_t^-. The derivation is the conditioning rule for a joint Gaussian: Cov⁡(xt,yt∣y1:t−1)=Pt−H⊤\operatorname{Cov}(\vb x_t,\vb y_t\given y_{1:t-1})=\mat P_t^-\mat H\T and Cov⁡(yt∣y1:t−1)=St\operatorname{Cov}(\vb y_t\given y_{1:t-1})=\mat S_t.

In the scalar case with H=1H=1, the gain is K=P−/(P−+R)K=P^-/(P^-+R) and the posterior mean is (1−K)m−+Ky(1-K)m^-+Ky. For example, if P−=4P^-=4 and R=1R=1, 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.

InteractiveBreathing ellipses
  • prediction 95 %
  • posterior 95 %
  • true position

Synthetic straight trajectory with velocity (1, 0.4), position measurements of standard deviation 0.8 and seed 42. The filter uses greater acceleration noise along the motion; without measurement, both ellipses coincide and accumulated uncertainty grows. The frame adapts to time, but stays the same when covering or uncovering the sensor at that time.

30
Measurement availableno
Prior position trace36.114
Posterior position trace36.114
Compare prior and posterior covariance and cover the sensor for an interval.

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.

InteractiveGeometry of the gain
  • prior 95 %
  • posterior 95 %
  • measurement ±1 σ
  • correction K

Zero-mean prior with covariance [[2,0.8],[0.8,1]]. A scalar projection with value 1 is observed, so the measurement produces a strip, not a closed two-dimensional ellipse.

30
0.50
Gain K0.724 · 0.405
Innovation variance2.943
Rotate a scalar observation and observe its strip and state correction.

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 Ktet\mat K_t\vb e_t. If observed noise tends to zero, the measured direction can become determined, provided its predictive variance is positive; unobserved directions can retain uncertainty. If RR grows without bound, the gain of that measurement tends to zero.

Likelihood and stability

If St\mat S_t is positive definite, innovations contribute the log likelihood

log⁡p(y1:T)=−12∑t[ℓtlog⁡(2π)+log⁡∣St∣+et⊤St−1et],\log p(\vb y_{1:T})=-\tfrac12\sum_t [\ell_t\log(2\pi)+\log|\mat S_t|+\vb e_t\T\mat S_t^{-1}\vb e_t],

where ℓt\ell_t is the dimension observed at that step. Each term is the conditional predictive density given history. If components are missing, select available rows of H\mat H and the corresponding block of R\mat R; if the entire measurement is missing, retain the prediction and add no likelihood term. For Kt\mat K_t and the quadratic term, solve systems with Cholesky instead of forming St−1\mat S_t^{-1}.

The evidence decomposition follows from the chain rule: p(y1:T)=∏tp(yt∣y1:t−1)p(y_{1:T})=\prod_t p(y_t\given y_{1:t-1}). Each predictive distribution is Gaussian with mean Hmt−\mat H\vb m_t^- and covariance St\mat S_t. 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

Pt=(I−KtH)Pt−(I−KtH)⊤+KtRKt⊤.\mat P_t=(\mat I-\mat K_t\mat H)\mat P_t^-(\mat I-\mat K_t\mat H)\T+ \mat K_t\mat R\mat K_t\T.

For the optimal gain it is algebraically equal to the simplified expression. For any gain, if P−\mat P^- and R\mat R are positive semidefinite, both sums of squares are too in exact arithmetic. They are not always positive definite: with a perfect measurement and KH=I\mat K\mat H=\mat I 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:

P−=FP−F⊤+Q−FP−H⊤(HP−H⊤+R)−1HP−F⊤.\mat P^-=\mat F\mat P^-\mat F\T+\mat Q -\mat F\mat P^-\mat H\T (\mat H\mat P^-\mat H\T+\mat R)^{-1} \mat H\mat P^-\mat F\T.

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 q=1q=1, r=4r=4, P+=(17−1)/2P^+=(\sqrt{17}-1)/2 and K=(17−1)/8≈0.390388K=(\sqrt{17}-1)/8\approx0.390388.

To obtain the scalar result, write P−=P++qP^-=P^++q and P+=rP−/(P−+r)P^+=rP^-/(P^-+r). Substituting q=1q=1 and r=4r=4 yields (P+)2+P+−4=0(P^+)^2+P^+-4=0; take the positive root because a variance cannot be negative. The gain is P−/(P−+r)=P+/rP^-/(P^-+r)=P^+/r. Convergence must not be assumed in an arbitrary system with unobservable components or unstable dynamics.

In information form, if inverses exist, Y=(P)−1\mat Y=(\mat P)^{-1} and η=Ym\boldsymbol\eta=\mat Y\vb m. The update adds observation information:

Y+=Y−+H⊤R−1H,η+=η−+H⊤R−1y.\mat Y^+=\mat Y^-+\mat H\T\mat R^{-1}\mat H,\qquad \boldsymbol\eta^+=\boldsymbol\eta^-+\mat H\T\mat R^{-1}\vb y.

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 dt=et⊤St−1etd_t=\vb e_t\T\mat S_t^{-1}\vb e_t. Under a correctly specified Gaussian model and known parameters, dtd_t follows a χ2\chi^2 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.

InteractiveWhite innovations or not
  • ACF
  • ±1.96/√200, approximate guide
  • lower limit

One synthetic 200-step realization, seed 53. χ² limits apply to NIS, not autocorrelation. ACF bands are an approximate guide; multiple simultaneous checks may produce an excursion by chance.

-2.0
Assumed Q0.0100
NIS sum288.94
95 % χ² interval with 200 degrees162.73 to 241.06
Individual NIS outside 95 %14
Change Q and compare the normalized sequence, its autocorrelation and NIS.

The example generates a random walk with Q=0.1Q=0.1, R=1R=1 and 200 synthetic observations. The figure compares the NIS sum with χ2002\chi^2_{200} quantiles and displays approximate autocorrelation bands ±1.96/200\pm1.96/\sqrt{200}. 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 QQ 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 qcq_c has, per axis,

F=(1Δt01),Q=qc(Δt3/3Δt2/2Δt2/2Δt).\mat F=\begin{pmatrix}1&\Delta t\\0&1\end{pmatrix},\quad \mat Q=q_c\begin{pmatrix}\Delta t^3/3&\Delta t^2/2\\ \Delta t^2/2&\Delta t\end{pmatrix}.

This is not the same matrix as a random acceleration constant within each interval, Gσa2G⊤\mat G\sigma_a^2\mat G\T with G=(Δt2/2,Δt)⊤\mat G=(\Delta t^2/2,\Delta t)\T. Both discretize different assumptions. In general F=eAΔt\mat F=e^{\mat A\Delta t} and Q\mat Q is obtained by integrating continuous noise covariance across the interval.

Lab: filter and missing measurements

The prior m0,P0m_0,P_0 corresponds to the first observed time; thereafter predict before each update. The code accepts partially missing measurements and uses Joseph and Cholesky.

[ ]Kalman filter from scratchBrowser
"""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),innovations
[ ]Synthetic 2D trackingBrowser
rng=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.

[ ]Compare with statsmodelsBrowser
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.

[ ]Synthetic GPS and IMU fusionBrowser
"""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

ProofGaussian conditioning
Prove: Derive the state update from the joint Gaussian of x and y.
0
The prior is N(m⁻,P⁻), y=Hx+v and v is independent with covariance R.

Step 1 of 3. What is the cross-covariance of x and y?

ProofJoseph form
Prove: Relate Joseph to the simplified update and study positivity.
0
J=I−KH and S=HP⁻Hᵀ+R.

Step 1 of 3. What appears when expanding J P⁻ Jᵀ+K R Kᵀ?

Numeric
For a scalar random walk with Q=1 and R=4, calculate the steady-state Kalman gain.
CodeNIS test
Implement nis_test(innovation,S,confidence=.95). S is a positive-definite matrix; return (NIS, lower bound, upper bound, inside). Use chi-squared quantiles with dimension equal to the number of components and solve the system without inverting S.
import numpy as np
from scipy.stats import chi2
def nis_test(innovation,S,confidence=.95):
  return None
Shift+Enter to run
Quiz
For an informative scalar observation, what happens when R grows without bound? What does Q=0 imply?
Key idea
Kalman alternates prediction and Gaussian conditioning; innovation and its diagnostics help check whether the uncertainty model is plausible.

References