RTS smoothing and learning state-space models
A filter uses the past; a smoother uses the full series. We derive the Rauch-Tung-Striebel smoother and learn linear Gaussian model parameters both by directly maximizing innovation likelihood with gradients and by EM with smoothed statistics (Shumway-Stoffer).
After this lesson you can
- Derive the RTS smoother and the smoothed cross-covariance of consecutive states.
- Implement the smoother and use it to reconstruct intervals without observations.
- Estimate Q, R and dynamics by maximum likelihood with L-BFGS using an unconstrained parameterization.
- Implement EM for the linear Gaussian model and compare its convergence with direct optimization.
- Recognize identifiability problems in state-space model estimation.
Before you start
- 14Kalman filterInnovations and prediction error decompositionLinear Gaussian state-space modelForward-backward algorithm (smoothing)EM for graphical models via expected sufficient statisticsNon-identifiability and label switching
- 12Expectation-maximization algorithmEM monotonicity and convergence
- 06Limited-memory BFGS
- 05Numerically stable maximum likelihood
- 02Matrix differentialDerivatives of the inverse and log-determinant
Reconstructing the entire trajectory
A filter estimates the current state using data available up to that time. If we later observe the whole series, future measurements also inform earlier states. The Rauch, Tung and Striebel smoother (RTS) uses this information in a linear Gaussian model through a backward pass after the Kalman filter.
In the figure’s synthetic random walk, measurements at steps 26 through 45 are missing. The filter accumulates uncertainty during the gap and updates when measurements return. The smoother also uses that later measurement and reduces uncertainty in earlier states. The typical band shape inside the gap resembles a bow tie, but depends on dynamics, noise and available data. A smoothed band cannot be used as though it had been available in real time.
The backward recursion
Let be the filtered state and the prediction. If dynamics are , the smoothing gain is
It is calculated by solving a system, not forming the inverse. Condition the joint Gaussian of and on data through , then average over the smoothed marginal at :
The pass starts with and . In a fixed model, smoothing incorporates additional evidence and its covariance does not exceed filtering covariance in semidefinite order. Predictive matrices must be invertible for the implementation shown; singular systems require appropriate handling.
The intermediate conditional has mean and covariance . The future after is independent of once is known. By total expectation we replace the next state with its smoothed mean; by total variance we add variation of that conditional mean, . Combining both terms gives the covariance equation above.
To learn dynamics we also need cross-covariance between consecutive states, with this orientation:
The complete moment is . Transposing the covariance changes state order. In a multivariate problem that distinction is not cosmetic: using the wrong orientation can break the M-step.
To understand the gap in a simple case, consider a scalar random walk with endpoints exactly known at times 0 and 10. The state at is the initial endpoint plus increments of variance . Conditioning also on the final endpoint subtracts the part explained by the sum of all ten increments. The remaining variance is : zero at the endpoints and maximal in the center. With noisy observations endpoint variances are nonzero and the exact shape changes.
Fitting likelihood
Maximum likelihood for a linear Gaussian model sums predictive innovation densities, as in m14-l12. Variances must be positive: we can optimize and and exponentiate them. If also fitting a scalar autoregressive coefficient constrained to , we can use . The constraint expresses a modeling decision, not a property of all possible dynamics.
The real series contains 100 annual Nile volumes at Aswan, from 1871 to 1970, distributed with statsmodels. We divide values by 100: the resulting unit is m³ per annual observation. The fixed initial prior is on that scale. The map is a grid of 25×25 values, not a posterior distribution. A relatively flat region indicates different combinations can have similar evidence; it does not by itself identify the cause or guarantee a unique maximum.
The innovation gradient is obtained by differentiating both state predictions and their covariances. In one dimension, if and , the contribution of a parameter to the gradient is
Derivatives of and are also propagated through updates. The lab checks the gradient by central differences and uses L-BFGS with explicit bounds. A numerical maximum can depend on the initial prior, bounds, initialization and dynamics specification.
A logarithmic parameterization prevents the optimizer from trying negative variances, but does not guarantee an interior solution. A variance very close to zero can indicate a boundary; bounds that are too narrow can impose it artificially. The numerical check gradient must perturb transformed parameters and compare the same objective. In the lab, central differences cover both local-level variances and, separately, the dynamic coefficient and two variances of the autoregressive model.
EM with smoothed moments
The state-space EM algorithm calculates smoothed means, covariances and cross-covariances in the E-step. These moments replace unknown states in the expected complete log likelihood. For free dynamics, define
The unconstrained M-step, with complete observations and known in this example, is
Matrix averages the expected squared residual of , including . The lab keeps the initial prior fixed and known. Updating partially missing observations requires appropriate handling of available components; the included matrix version requires complete data.
It helps to write the update as the average of . This contains both the product of mean differences and covariances of both states and the two cross terms. Using only a pointwise smoothed trajectory omits uncertainty. Similarly, contains the mean residual plus state uncertainty projected by .
EM does not decrease log likelihood when the E-step and M-step are exact under the same objective. It can advance slowly near an optimum. L-BFGS uses a gradient and may need fewer iterations in this example, but an iteration of each method has different cost; no universal speed rule follows. The figure’s curves come from reproducible runs with the same prior and data.
In the local-level model, the M-step averages smoothed squared differences between neighboring times and the M-step averages smoothed squared residuals at observed times. Cross-covariance enters the former even if the smoothed mean barely changes. When a series contains a gap, missing data contribute no measurement residual, but their states still contribute transitions. When comparing methods, use the same initial distribution and dataset in each evaluation.
Latent parameters are not always identifiable. For an invertible matrix , the change transforms , , and the prior too. The observed distribution stays the same. Therefore, if is also learned, comparing each entry of directly to a “true” matrix may be meaningless without fixing a basis convention. In the second lab we keep fixed and demonstrate equivalence by transforming the whole model afterward.
The basis change alters hidden coordinates, not observations. Similar matrices retain their eigenvalues but can have very different entries. Fixing reduces transformation freedom, though it does not itself ensure remaining parameters are well identified with a finite sample. To interpret a fit, inspect predictions, likelihood, diagnostics and initialization sensitivity in addition to comparing matrices.
Lab: RTS and the Nile
The following code retains predictions and filtering from the m14-l12 cycle; then it calculates the smoother, cross-covariance and learning steps. The first prior corresponds to the first datum, before updating it.
"""Filtrado, RTS y EM de un modelo lineal gaussiano."""
import numpy as np
from scipy.linalg import cho_factor,cho_solve
from scipy.optimize import minimize
def kalman_history(y,m0,P0,A,Q,H,R):
"""m0,P0 son el prior del primer instante; NaN omite medidas."""
y=np.asarray(y,float)
if y.ndim==1:y=y[:,None]
m=np.asarray(m0,float).copy();P=np.asarray(P0,float).copy()
pm=[];pP=[];fm=[];fP=[];ll=0.
for t,obs in enumerate(y):
if t:m=A@m;P=A@P@A.T+Q;P=(P+P.T)/2
pm.append(m.copy());pP.append(P.copy());mask=np.isfinite(obs)
if mask.any():
h=H[mask,:];r=R[np.ix_(mask,mask)];e=obs[mask]-h@m;S=h@P@h.T+r
factor=cho_factor(S,lower=True);K=cho_solve(factor,h@P).T
ll-=.5*(len(e)*np.log(2*np.pi)+2*np.log(np.diag(factor[0])).sum()+e@cho_solve(factor,e))
m=m+K@e;J=np.eye(len(m))-K@h;P=J@P@J.T+K@r@K.T;P=(P+P.T)/2
fm.append(m.copy());fP.append(P.copy())
return np.array(pm),np.array(pP),np.array(fm),np.array(fP),float(ll)
def rts(history,A):
pm,pP,fm,fP,_=history;T=len(fm);sm=fm.copy();sP=fP.copy()
cross=np.empty((T-1,len(fm[0]),len(fm[0])))
for t in range(T-2,-1,-1):
factor=cho_factor(pP[t+1],lower=True)
J=cho_solve(factor,A@fP[t]).T
sm[t]=fm[t]+J@(sm[t+1]-pm[t+1])
sP[t]=fP[t]+J@(sP[t+1]-pP[t+1])@J.T
sP[t]=(sP[t]+sP[t].T)/2
cross[t]=J@sP[t+1] # Cov(x_t, x_{t+1} | y_1:T)
return sm,sP,cross
def em_local(y,m0,P0,q,r,steps=80):
y=np.asarray(y,float);mask=np.isfinite(y);history=[]
for _ in range(steps+1):
h=kalman_history(y,np.array([m0]),np.array([[P0]]),np.ones((1,1)),
np.array([[q]]),np.ones((1,1)),np.array([[r]]))
history.append((q,r,h[-1]));m,P,C=rts(h,np.ones((1,1)))
if len(history)==steps+1:break
q=float(np.mean((m[1:,0]-m[:-1,0])**2+P[1:,0,0]+P[:-1,0,0]-2*C[:,0,0]))
r=float(np.mean((y[mask]-m[mask,0])**2+P[mask,0,0]))
return np.array(history)
def local_likelihood_gradient(theta,y,m0,P0):
"""Log-verosimilitud y gradiente en log q, log r."""
q,r=np.exp(theta);m=float(m0);P=float(P0);dm=np.zeros(2);dP=np.zeros(2)
ll=0.;grad=np.zeros(2)
for t,obs in enumerate(y):
if t:P+=q;dP+=np.array([q,0.])
if not np.isfinite(obs):continue
e=obs-m;S=P+r;de=-dm;dS=dP+np.array([0.,r])
ll-=.5*(np.log(2*np.pi*S)+e*e/S)
grad-=.5*((1/S-e*e/S**2)*dS+2*e/S*de)
K=P/S;dK=(dP*S-P*dS)/S**2
oldP=P;m+=K*e;dm=dm+dK*e+K*de;P=(1-K)*oldP;dP=(1-K)*dP-dK*oldP
return float(ll),grad
def fit_local(y,m0,P0,q0,r0):
trace=[]
def objective(theta):
ll,g=local_likelihood_gradient(theta,y,m0,P0)
return -ll,-g
def callback(theta):
ll,_=local_likelihood_gradient(theta,y,m0,P0)
trace.append((np.exp(theta[0]),np.exp(theta[1]),ll))
initial=np.log([q0,r0]);ll,_=local_likelihood_gradient(initial,y,m0,P0)
trace.append((q0,r0,ll))
fit=minimize(objective,initial,jac=True,method='L-BFGS-B',bounds=[(-15,12),(-15,12)],
callback=callback,options={'maxiter':200,'ftol':1e-12,'gtol':1e-8})
return fit,np.array(trace)
def ar_likelihood_gradient(theta,y,m0,P0):
"""Modelo x_t=a*x_(t-1)+ruido; a=tanh(theta[0]), q/r positivas."""
a=np.tanh(theta[0]);q,r=np.exp(theta[1:]);da=1-a*a
m=float(m0);P=float(P0);dm=np.zeros(3);dP=np.zeros(3);ll=0.;grad=np.zeros(3)
for t,obs in enumerate(y):
if t:
oldm,oldP=m,P
m=a*oldm;dm=a*dm+np.array([da*oldm,0.,0.])
P=a*a*oldP+q
dP=a*a*dP+np.array([2*a*da*oldP,q,0.])
if not np.isfinite(obs):continue
e=obs-m;S=P+r;de=-dm;dS=dP+np.array([0.,0.,r])
ll-=.5*(np.log(2*np.pi*S)+e*e/S)
grad-=.5*((1/S-e*e/S**2)*dS+2*e/S*de)
K=P/S;dK=(dP*S-P*dS)/S**2;oldP=P
m+=K*e;dm=dm+dK*e+K*de;P=(1-K)*oldP;dP=(1-K)*dP-dK*oldP
return float(ll),grad
def em_matrix(y,m0,P0,A,Q,H,R,steps=15):
"""Aprende A,Q,R con H y prior conocidos y observaciones completas."""
y=np.asarray(y,float)
if not np.isfinite(y).all():raise ValueError('Este paso M exige medidas completas')
hist=[]
for iteration in range(steps+1):
h=kalman_history(y,m0,P0,A,Q,H,R);hist.append(h[-1])
if iteration==steps:break
m,P,C=rts(h,A)
E=P+np.einsum('ti,tj->tij',m,m)
E10=C.transpose(0,2,1)+np.einsum('ti,tj->tij',m[1:],m[:-1])
S00=E[:-1].sum(axis=0);S11=E[1:].sum(axis=0);S10=E10.sum(axis=0)
A=np.linalg.solve(S00,S10.T).T
Q=(S11-A@S10.T-S10@A.T+A@S00@A.T)/(len(y)-1);Q=(Q+Q.T)/2
R=np.zeros_like(R)
for t in range(len(y)):
hm=H@m[t]
R+=np.outer(y[t]-hm,y[t]-hm)+H@P[t]@H.T
R/=len(y);R=(R+R.T)/2
return A,Q,R,np.array(hist)The following cell uses the dataset included in statsmodels, without downloading or simulating data. Fit and with the fixed prior and compare evidence and smoothed level with UnobservedComponents using the same initialization and without discarding the first term.
"""Nivel local del Nilo; ejecutar tras ssm.py."""
from statsmodels.datasets import nile
from statsmodels.tsa.statespace.structural import UnobservedComponents
y=nile.load_pandas().data['volume'].to_numpy()/100
m0=10.;P0=100.;q0=.2;r0=1.
fit,path=fit_local(y,m0,P0,q0,r0)
print('L-BFGS éxito:',fit.success,'q,r:',np.exp(fit.x),'log evidencia:',-fit.fun,
'iteraciones:',len(path)-1,'gradiente:',fit.jac)
ref=UnobservedComponents(y,level='local level')
ref.ssm.initialize_known(np.array([m0]),np.array([[P0]]))
ref.loglikelihood_burn=0;ref.ssm.loglikelihood_burn=0
res=ref.smooth([np.exp(fit.x[1]),np.exp(fit.x[0])])
h=kalman_history(y,np.array([m0]),np.array([[P0]]),np.ones((1,1)),
np.array([[np.exp(fit.x[0])]]),np.ones((1,1)),np.array([[np.exp(fit.x[1])]]))
smooth_mean,smooth_cov,cross=rts(h,np.ones((1,1)))
print('Errores statsmodels log evidencia y suavizado:',
abs(res.llf-h[-1]),np.max(abs(res.smoothed_state[0]-smooth_mean[:,0])))
assert fit.success and abs(res.llf-h[-1])<1e-6Check the two derivatives with respect to and then run EM in blocks of twenty steps. Blocking keeps each execution fast and preserves state between cells.
theta=np.log([q0,r0]);ll,grad=local_likelihood_gradient(theta,y,m0,P0)
eps=1e-5;eye=np.eye(2)
fd=np.array([(local_likelihood_gradient(theta+eps*v,y,m0,P0)[0]-
local_likelihood_gradient(theta-eps*v,y,m0,P0)[0])/(2*eps) for v in eye])
print('error máximo gradiente:',np.max(abs(grad-fd)))
assert np.max(abs(grad-fd))<1e-6
q_current,r_current=q0,r0
history_em=[]
def em_block():
global q_current,r_current,history_em
h=em_local(y,m0,P0,q_current,r_current,20)
if history_em:assert abs(history_em[-1][2]-h[0,2])<1e-8
history_em.extend(h if not history_em else h[1:])
q_current,r_current=h[-1,:2]
assert np.min(np.diff(h[:,2]))>-1e-8
print('EM paso',len(history_em)-1,'q,r,log evidencia',h[-1])
em_block()em_block()em_block()em_block()In the verified run, L-BFGS obtains approximately , and log likelihood at this scale and prior. After 80 EM steps log likelihood is approximately . We do not claim the local-level model describes all of the river’s physical structure.
To also estimate dynamics, generate a synthetic autoregressive model with , , and 120 observations. Transformation constrains to . The full gradient is validated at the initial point.
rng=np.random.default_rng(7);N=120;z=np.zeros(N);z[0]=rng.normal()
for t in range(1,N):z[t]=.85*z[t-1]+rng.normal(0,np.sqrt(.1))
yar=z+rng.normal(0,np.sqrt(.3),N)
initial=np.array([np.arctanh(.5),np.log(.2),np.log(.5)])
def objective_ar(v):
ll,g=ar_likelihood_gradient(v,yar,0.,1.)
return -ll,-g
eps=1e-5;eye=np.eye(3)
fd=np.array([(objective_ar(initial+eps*v)[0]-objective_ar(initial-eps*v)[0])/(2*eps) for v in eye])
print('error máximo gradiente AR:',np.max(abs(fd-objective_ar(initial)[1])))
arfit=minimize(objective_ar,initial,jac=True,method='L-BFGS-B',options={'maxiter':150})
print('éxito, a,q,r, log evidencia:',arfit.success,np.tanh(arfit.x[0]),*np.exp(arfit.x[1:]),-arfit.fun)
assert arfit.success and np.max(abs(fd-objective_ar(initial)[1]))<1e-6
In this sample estimated is approximately 0.940, with and around 0.054 and 0.309. These are estimates from a finite realization; closeness to generating parameters is not guaranteed and likelihood can be weakly informative for separating dynamics and noise.
Lab: multivariate EM and identification
Here four states and two observations are simulated. Fit with and prior known; each block runs four EM iterations.
"""Sistema de cuatro estados y dos medidas, datos sintéticos."""
rng=np.random.default_rng(81);T=80;d=4
trueA=np.array([[.85,.05,.2,0],[0,.8,0,.25],[0,0,.7,.08],[0,0,0,.65]])
H=np.array([[1.,0,0,0],[0,1.,0,0]])
trueQ=np.diag([.04,.03,.02,.01]);trueR=np.diag([.1,.12])
m0v=np.zeros(d);P0v=np.eye(d);x=np.zeros((T,d));x[0]=rng.multivariate_normal(m0v,P0v)
for t in range(1,T):x[t]=trueA@x[t-1]+rng.multivariate_normal(np.zeros(d),trueQ)
obs=x@H.T+rng.multivariate_normal(np.zeros(2),trueR,size=T)
A4=trueA+np.array([[0,.03,-.04,0],[.02,0,0,-.04],[0,0,.05,0],[0,0,0,.04]])
Q4=.1*np.eye(d);R4=.2*np.eye(2)
history4=[]
def block4():
global A4,Q4,R4,history4
A4,Q4,R4,h=em_matrix(obs,m0v,P0v,A4,Q4,H,R4,steps=4)
if history4:assert abs(history4[-1]-h[0])<1e-8
history4.extend(h if not history4 else h[1:])
assert np.min(np.diff(h))>-1e-8
print('iteración',len(history4)-1,'log evidencia',h[-1],'mínimo incremento',np.min(np.diff(h)))block4()block4()block4()Tmat=np.array([[1.,.2,0,0],[0,1.,.1,0],[0,0,1.,.3],[0,0,0,1.]])
inv=np.linalg.inv(Tmat)
original=kalman_history(obs,m0v,P0v,A4,Q4,H,R4)[-1]
transformed=kalman_history(obs,Tmat@m0v,Tmat@P0v@Tmat.T,
Tmat@A4@inv,Tmat@Q4@Tmat.T,H@inv,R4)[-1]
print('diferencia de log evidencia tras cambio de base:',abs(original-transformed))
print('menor autovalor de Q estimada:',np.linalg.eigvalsh(Q4).min())
assert abs(original-transformed)<1e-8
The transformation of is part of the demonstration; it is not applied during fitting with fixed . In the simulation and those twelve iterations evidence rises from approximately to . The experiment illustrates an algebraic equivalence, not proof that all parameters are identifiable when is fixed.
Exercises
Step 1 of 3. What is the gain of the conditional of xₜ given xₜ₊₁?
import numpy as np
def update_Q(means,covs,cross,A):
return None