Module contents
Lesson 13 of 27Advanced 100 min

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

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.

InteractiveFilter and smoother across a gap
  • Synthetic trajectory
  • Measurements before gap
  • Measurements after gap
  • Filter ±1.96σ
  • Smoother ±1.96σ

Synthetic random walk with q=0.1, r=0.5 and seed 19; steps 26 through 45 are hidden. Measurement lines connect points within each segment. Bands are Gaussian marginals conditional on known parameters; the smoother also uses later observations.

Filtered variance at gap center1.179
Smoothed variance at center0.614
Compare both bands on a synthetic trajectory with missing observations.

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 mtf,Ptf\vb m_t^f,\mat P_t^f be the filtered state and mt+1−,Pt+1−\vb m_{t+1}^-,\mat P_{t+1}^- the prediction. If dynamics are xt+1=Axt+wt\vb x_{t+1}=\mat A\vb x_t+\vb w_t, the smoothing gain is

Jt=PtfA⊤(Pt+1−)−1.\mat J_t=\mat P_t^f\mat A\T(\mat P_{t+1}^-)^{-1}.

It is calculated by solving a system, not forming the inverse. Condition the joint Gaussian of xt\vb x_t and xt+1\vb x_{t+1} on data through tt, then average over the smoothed marginal at t+1t+1:

mts=mtf+Jt(mt+1s−mt+1−),Pts=Ptf+Jt(Pt+1s−Pt+1−)Jt⊤.\vb m_t^s=\vb m_t^f+\mat J_t(\vb m_{t+1}^s-\vb m_{t+1}^-),\qquad \mat P_t^s=\mat P_t^f+\mat J_t(\mat P_{t+1}^s-\mat P_{t+1}^-)\mat J_t\T.

The pass starts with mTs=mTf\vb m_T^s=\vb m_T^f and PTs=PTf\mat P_T^s=\mat P_T^f. 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 mtf+Jt(xt+1−mt+1−)\vb m_t^f+\mat J_t(\vb x_{t+1}-\vb m_{t+1}^-) and covariance Ptf−JtPt+1−Jt⊤\mat P_t^f-\mat J_t\mat P_{t+1}^-\mat J_t\T. The future after t+1t+1 is independent of xt\vb x_t once xt+1\vb x_{t+1} is known. By total expectation we replace the next state with its smoothed mean; by total variance we add variation of that conditional mean, JtPt+1sJt⊤\mat J_t\mat P_{t+1}^s\mat J_t\T. Combining both terms gives the covariance equation above.

To learn dynamics we also need cross-covariance between consecutive states, with this orientation:

Cts=Cov⁡(xt,xt+1∣y1:T)=JtPt+1s.\mat C_t^s=\operatorname{Cov}(\vb x_t,\vb x_{t+1}\given\vb y_{1:T}) =\mat J_t\mat P_{t+1}^s.

The complete moment is E[xtxt+1⊤∣y]=Cts+mts(mt+1s)⊤\mathbb E[\vb x_t\vb x_{t+1}\T\given y]=\mat C_t^s+\vb m_t^s(\vb m_{t+1}^s)\T. 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 tt is the initial endpoint plus tt increments of variance qq. Conditioning also on the final endpoint subtracts the part explained by the sum of all ten increments. The remaining variance is q t(10−t)/10q\,t(10-t)/10: 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 log⁡q\log q and log⁡r\log r and exponentiate them. If also fitting a scalar autoregressive coefficient constrained to (−1,1)(-1,1), we can use a=tanh⁡ua=\tanh u. The constraint expresses a modeling decision, not a property of all possible dynamics.

InteractiveLikelihood surface for q and r
log qlog r−51−22

Deeper blue indicates greater log likelihood; the grid has 25×25 cells.

  • Observed Nile
  • Smoothed level

Annual Nile flow at Aswan, 1871 to 1970, statsmodels nile dataset divided by 100. Initial prior N(10,100) on this scale; q and r are variances on the transformed scale.

-1.60
0.00
q0.202
r1.000
Log likelihood-182.374
Select a point to recalculate the smoothed level of the Nile series.

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 101010^{10} m³ per annual observation. The fixed initial prior is N(10,100)\Normal(10,100) 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 e=y−m−e=y-m^- and S=P−+rS=P^-+r, the contribution of a parameter θ\theta to the gradient is

−12[(1/S−e2/S2)∂S∂θ+2eS∂e∂θ].-\tfrac12\left[ (1/S-e^2/S^2)\frac{\partial S}{\partial\theta} +\frac{2e}{S}\frac{\partial e}{\partial\theta}\right].

Derivatives of m−m^- and P−P^- 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

S00=∑t=0T−2E[xtxt⊤∣y],S10=∑t=0T−2E[xt+1xt⊤∣y],S11=∑t=0T−2E[xt+1xt+1⊤∣y].\mat S_{00}=\sum_{t=0}^{T-2}\mathbb E[\vb x_t\vb x_t\T\mid\vb y],\quad \mat S_{10}=\sum_{t=0}^{T-2}\mathbb E[\vb x_{t+1}\vb x_t\T\mid\vb y],\quad \mat S_{11}=\sum_{t=0}^{T-2}\mathbb E[\vb x_{t+1}\vb x_{t+1}\T\mid\vb y].

The unconstrained M-step, with complete observations and H\mat H known in this example, is

Anueva=S10S00−1,Qnueva=S11−AS10⊤−S10A⊤+AS00A⊤T−1.\mat A_{\rm nueva}=\mat S_{10}\mat S_{00}^{-1},\quad \mat Q_{\rm nueva}= \frac{\mat S_{11}-\mat A\mat S_{10}\T-\mat S_{10}\mat A\T +\mat A\mat S_{00}\mat A\T}{T-1}.

Matrix R\mat R averages the expected squared residual of yt−Hxt\vb y_t-\mat H\vb x_t, including HPtsH⊤\mat H\mat P_t^s\mat H\T. The lab keeps the initial prior fixed and H\mat H known. Updating partially missing observations requires appropriate handling of available components; the included matrix version requires complete data.

It helps to write the Q\mat Q update as the average of E[(xt+1−Axt)(xt+1−Axt)⊤∣y]\mathbb E[(\vb x_{t+1}-\mat A\vb x_t)(\vb x_{t+1}-\mat A\vb x_t)\T\mid\vb y]. 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, R\mat R contains the mean residual plus state uncertainty projected by H\mat H.

InteractiveEM and L-BFGS on the same problem
log qlog r−51−22
  • EM
  • L-BFGS
  • EM trajectory
  • L-BFGS trajectory

Same real Nile data and fixed prior as the preceding figure. Both curves were calculated using the lab code from q=0.2, r=1; 80 EM iterations and the L-BFGS trajectory to convergence are shown. Iteration count does not equal computation time.

iteration 0
EM: iteration / log evidence0 / -182.397
L-BFGS: iteration / log evidence0 / -182.397
EM q / r0.200 / 1.000
L-BFGS q / r0.200 / 1.000
Play the actual trajectories of both methods for the Nile local level.

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 qq M-step averages smoothed squared differences between neighboring times and the rr 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 T\mat T, the change xt′=Txt\vb x'_t=\mat T\vb x_t transforms A′=TAT−1\mat A'=\mat T\mat A\mat T^{-1}, Q′=TQT⊤\mat Q'=\mat T\mat Q\mat T\T, H′=HT−1\mat H'=\mat H\mat T^{-1} and the prior too. The observed distribution stays the same. Therefore, if H\mat H is also learned, comparing each entry of A\mat A directly to a “true” matrix may be meaningless without fixing a basis convention. In the second lab we keep H\mat H 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 H\mat H 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.

[ ]RTS, gradients and EM from scratchBrowser
"""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@[email protected]+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@[email protected]+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@[email protected]+K@[email protected];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=([email protected]@A.T+A@[email protected])/(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 qq and rr with the fixed prior and compare evidence and smoothed level with UnobservedComponents using the same initialization and without discarding the first term.

[ ]Nile: L-BFGS and comparison with statsmodelsBrowser
"""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-6

Check the two derivatives with respect to log⁡q,log⁡r\log q,\log r and then run EM in blocks of twenty steps. Blocking keeps each execution fast and preserves state between cells.

[ ]Check gradient and start EMBrowser
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])
[ ]Nile EM, block 1Browser
em_block()
[ ]Nile EM, block 2Browser
em_block()
[ ]Nile EM, block 3Browser
em_block()
[ ]Nile EM, block 4Browser
em_block()

In the verified run, L-BFGS obtains approximately q=0.1468q=0.1468, r=1.5100r=1.5100 and log likelihood −179.864-179.864 at this scale and prior. After 80 EM steps log likelihood is approximately −179.865-179.865. 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 a=0.85a=0.85, q=0.1q=0.1, r=0.3r=0.3 and 120 observations. Transformation tanh⁡\tanh constrains aa to (−1,1)(-1,1). The full gradient is validated at the initial point.

[ ]Maximum likelihood of dynamics and noiseBrowser
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 aa is approximately 0.940, with qq and rr 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 A,Q,R\mat A,\mat Q,\mat R with H\mat H and prior known; each block runs four EM iterations.

[ ]Prepare 4D systemBrowser
"""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)
[email protected]+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)))
[ ]4D EM, block 1Browser
block4()
[ ]4D EM, block 2Browser
block4()
[ ]4D EM, block 3Browser
block4()
[ ]Change the latent basisBrowser
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@[email protected],
                           Tmat@A4@inv,Tmat@[email protected],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 H\mat H is part of the demonstration; it is not applied during fitting with fixed H\mat H. In the simulation and those twelve iterations evidence rises from approximately −113.175-113.175 to −96.398-96.398. The experiment illustrates an algebraic equivalence, not proof that all parameters are identifiable when H\mat H is fixed.

Exercises

ProofRTS recursion
Prove: Obtain the smoother equations from a joint Gaussian.
0
With data through t, Cov(xₜ,xₜ₊₁)=PₜᶠAᵀ.

Step 1 of 3. What is the gain of the conditional of xₜ given xₜ₊₁?

Numeric
A random walk has q=1 and states known exactly at times 0 and 10. What is the smoothed variance of the state at time 5?
Quiz
Why can't a full-interval smoother be used for an instantaneous decision, and what alternative exists?
CodeM-step for Q
Implement update_Q(means,covs,cross,A), where means[t] and covs[t] are smoothed moments and cross[t]=Cov(x_t,x_{t+1}|y). Return the mean expected squared residual of x_{t+1}−A x_t.
import numpy as np
def update_Q(means,covs,cross,A):
  return None
Shift+Enter to run
Key idea
RTS uses future observations to smooth; EM also requires cross-moments, and likelihood must be interpreted with the model parameterization and identifiability.

References