Module contents
Lesson 10 of 27Core 110 min

Hidden Markov models: filtering, smoothing and decoding

The hidden Markov model is a foundational sequential latent-variable model and the discrete case of a state-space model. We derive forward filtering and likelihood, forward-backward smoothing, Viterbi decoding and backward sampling from the graph structure, all with numerical stability.

After this lesson you can

  • Derive the forward and backward recursions from HMM independences.
  • Implement filtering, smoothing and likelihood with scaling or in log space.
  • Implement Viterbi and explain when it differs from marginal decoding.
  • Sample complete posterior trajectories with forward filtering backward sampling.
  • Relate forward-backward and Viterbi to sum-product and max-product on a chain.

Before you start

A chain we do not observe

A casino alternates between a fair and a loaded die, but we only see the rolls. Consecutive observations inform us about a persistent hidden sequence. A hidden Markov model or HMM uses a chain of latent states and an emission distribution per state. The same structure abstracts biological sequences, speech labels or financial regimes, provided its assumptions are appropriate.

Let zt∈{1,…,K}z_t\in\{1,\ldots,K\} and yty_t be an observation. Define πi=p(z1=i)\pi_i=p(z_1=i), Aij=p(zt=j∣zt−1=i)A_{ij}=p(z_t=j\given z_{t-1}=i) and bj(y)=p(yt=y∣zt=j)b_j(y)=p(y_t=y\given z_t=j). Rows of AA sum to one and go from previous state to next:

p(z,y)=πz1bz1(y1)∏t=2TAzt−1ztbzt(yt).p(\vb z,\vb y)=\pi_{z_1}b_{z_1}(y_1) \prod_{t=2}^{T}A_{z_{t-1}z_t}b_{z_t}(y_t).

Each emission is independent of the others given its state, and the latent future depends on the past through the current state. π\pi is specified: it need not be the stationary distribution. Distinguish three questions: filtering uses data through tt, smoothing uses the whole sequence, and decoding chooses a path under a particular loss.

In a dynamic network an arrow runs from each state to the next and another from each state to its emission. Knowing ztz_t, the previous state provides no additional information about zt+1z_{t+1} under this model. The assumption can be too restrictive: a regime whose duration depends on elapsed time requires expanding the state or changing the model. Likewise, an emission that depends on previous observations must explicitly incorporate that dependence. HMM efficiency comes from these independences, not from every real sequence satisfying them.

InteractiveThe dishonest casino
  • Filtering P(loaded)
  • Smoothing P(loaded)
  • Viterbi 0/1
  • True state 0/1

100 synthetic rolls: fair is uniform; loaded has probability 0.5 for six and 0.1 for each other face. The generating chain uses 0.05 and 0.10 as switch probabilities. Lines connect discrete times; smoothing also uses future rolls.

0.05
0.10
Seed7
Log likelihood-165.04
Time with truly loaded die43
Compare filtering, smoothing and Viterbi with the states that generated the synthetic rolls.

The fair die emits six equally likely faces; the loaded die gives six with probability 0.5 and every other face with 0.1. The generating chain switches from fair to loaded with 0.05 and in the opposite direction with 0.10. Controls change the model used for inference, not the true states. Smoothing can locate a change earlier because it sees future observations; it does not guarantee better classification in each realization. The casino idea comes from the example by Durbin and colleagues, but these rolls are simulated here. The figure uses its reproducible JavaScript generator and the lab uses NumPy: equal seeds do not imply equal sequences.

Filtering and calculating evidence

The forward algorithm propagates the message αt(j)=p(y1:t,zt=j)\alpha_t(j)=p(y_{1:t},z_t=j):

α1(j)=πjbj(y1),αt(j)=bj(yt)∑iαt−1(i)Aij.\alpha_1(j)=\pi_j b_j(y_1),\qquad \alpha_t(j)=b_j(y_t)\sum_i\alpha_{t-1}(i)A_{ij}.

The sum eliminates the previous state and the emission is outside because it depends on the current state. The likelihood is ∑jαT(j)\sum_j\alpha_T(j). To calculate it stably, normalize each step with ctc_t and store ft(j)=p(zt=j∣y1:t)f_t(j)=p(z_t=j\given y_{1:t}):

u1(j)=πjbj(y1),ut(j)=bj(yt)∑ift−1(i)Aij,ct=∑jut(j),ft(j)=ut(j)/ct.u_1(j)=\pi_j b_j(y_1),\quad u_t(j)=b_j(y_t)\sum_i f_{t-1}(i)A_{ij},\quad c_t=\sum_j u_t(j),\quad f_t(j)=u_t(j)/c_t.

Here ct=p(yt∣y1:t−1)c_t=p(y_t\given y_{1:t-1}) and log⁡p(y1:T)=∑tlog⁡ct\log p(y_{1:T})=\sum_t\log c_t. If ct=0c_t=0, the data are impossible under the model and there is no normalized posterior; do not silently replace it with a uniform distribution. Each prediction mixes previous probabilities with AA and the emission then weights the states.

For example, with π=(0.6,0.4)\pi=(0.6,0.4) and probabilities of emitting 0 equal to 0.8 and 0.3, the first observation 0 produces α1=(0.48,0.12)\alpha_1=(0.48,0.12) and c1=0.6c_1=0.6. The filter is (0.8,0.2)(0.8,0.2), not (0.48,0.12)(0.48,0.12). For the transition and second emission of the exercise, the joint message becomes (0.072,0.168)(0.072,0.168) and the two-symbol evidence is 0.24. The second scaling constant is 0.24/0.6=0.40.24/0.6=0.4; multiplying both constants recovers the evidence. This distinguishes the unnormalized joint message from the normalized filter.

Smoothing with the future

In forward-backward, the unscaled message βt(i)=p(yt+1:T∣zt=i)\beta_t(i)=p(y_{t+1:T}\given z_t=i) starts at βT(i)=1\beta_T(i)=1 and moves backward:

βt(i)=∑jAijbj(yt+1)βt+1(j),γt(i)=αt(i)βt(i)p(y1:T).\beta_t(i)=\sum_j A_{ij}b_j(y_{t+1})\beta_{t+1}(j),\qquad \gamma_t(i)=\frac{\alpha_t(i)\beta_t(i)}{p(y_{1:T})}.

The backward message summarizes how compatible future data are with each current state. In the scaled implementation each step is divided by ct+1c_{t+1}; then γt\gamma_t is obtained by normalizing the product ftβtf_t\beta_t. Smoothed transition probabilities are

ξt(i,j)∝ft(i)Aijbj(yt+1)βt+1(j),∑ijξt(i,j)=1.\xi_t(i,j)\propto f_t(i)A_{ij}b_j(y_{t+1})\beta_{t+1}(j), \quad \sum_{ij}\xi_t(i,j)=1.

Summing ξt\xi_t over rows and columns gives γt\gamma_t and γt+1\gamma_{t+1}. These help count expected transitions, for example when training the model later. Filtering and smoothing do not change the data: they answer questions with different information available. In real time you cannot use future data that have not arrived.

The formula for ξt\xi_t comes from multiplying four pieces: past weight through tt, transition i→ji\to j, emission at t+1t+1 and future weight after t+1t+1. Normalizing all pairs turns those weights into a joint distribution of two adjacent states. If Aij=0A_{ij}=0, also ξt(i,j)=0\xi_t(i,j)=0: inference preserves model constraints. A high marginal at ii today and another high marginal at jj tomorrow do not imply that pair (i,j)(i,j) has high probability, because these are different distributions and must be combined with their dependence.

The most probable path

The Viterbi recursion replaces the sum with a maximum. In log space, with δt(j)\delta_t(j) equal to the best joint log weight of a prefix ending in jj:

δ1(j)=log⁡πj+log⁡bj(y1),δt(j)=log⁡bj(yt)+max⁡i[δt−1(i)+log⁡Aij].\delta_1(j)=\log\pi_j+\log b_j(y_1),\quad \delta_t(j)=\log b_j(y_t)+ \max_i[\delta_{t-1}(i)+\log A_{ij}].

Store the index attaining each maximum. After choosing the best final state, follow backpointers. Time complexity is O(TK2)O(TK^2) and pointers require O(TK)O(TK) space; deterministic tie rules can be defined. A zero transition is represented as −∞-\infty, not an invented small probability.

InteractiveThe Viterbi trellis
t1
die 1
t2
die 6
t3
die 6
t4
die 6
t5
die 2
t6
die 6

Each cell is the best joint log probability ending in that state; it is not a marginal. The initial observation uses prior and emission. Backtracking follows pointers from the best final state.

cell 1 of 12
Observations1 · 6 · 6 · 6 · 2 · 6
Selected cellt=1, state fair
Fair / loaded contributionsprior and emission
Winning predecessorstart
Advance cell by cell and select a cell to compare its predecessors.

Each cell contains a prefix score, not a posterior marginal probability. The last step colors the path recovered through the pointers. The six symbols in the figure are 1, 6, 6, 6, 2, 6; model and prior are those of the casino.

InteractiveMarginals versus a path
  • State 1
  • State 2
  • State 3

Synthetic three-state HMM and seven binary observations (0, 1, 1, 1, 0, 1, 1). The parameter replaces the direct transition in both directions and renormalizes other entries in those rows. Lines connect discrete times.

0.00
Marginal maxima3 · 3 · 1 · 1 · 1 · 1 · 1
Viterbi path1 · 1 · 1 · 1 · 1 · 1 · 1
Joint log probability of marginal path−∞
Marginal path validno
With forbidden transitions, marginal maxima can form an impossible sequence.

In the reproducible example, with direct transitions 1 to 3 and 3 to 1 forbidden, marginal maxima are 3, 3, 1, 1, 1, 1, 1, whereas Viterbi chooses a valid path. Those maxima are selected separately: they need not correspond to the same probable trajectory. Under loss equal to the number of incorrect labels, the Bayesian optimum chooses each marginal maximum. Under zero loss if the whole sequence is correct and one otherwise, the optimum is the joint Viterbi MAP. Changing the loss changes the appropriate decision.

The first rule follows from linearity of expectation: expected errors are the sum over time of the probability of error at each position. Minimizing each term requires choosing the state with the largest marginal at that position. For whole-sequence loss, by contrast, error is avoided only when every label matches, and minimizing risk amounts to maximizing joint path probability. Neither rule replaces the other without specifying the relevant cost.

Scaling or working in log space

Numerical stability matters even when each step is correct. The product of many positive probabilities eventually falls below the smallest representable float and rounds to zero. Once lost, it cannot be recovered by taking logarithms. Another solution is to calculate in log space using

log⁡∑ieai=m+log⁡∑ieai−m,m=max⁡iai,\log\sum_i e^{a_i}=m+\log\sum_i e^{a_i-m},\qquad m=\max_i a_i,

with explicit handling of all −∞-\infty terms. Scaling and log-sum-exp are two ways to retain the same mathematical likelihood; they do not eliminate model misspecification.

InteractiveWhen probability becomes zero
  • Scaled
  • Naive, before zero

The six faces repeat deterministically. The naive implementation multiplies ordinary probabilities; the scaled one accumulates logarithms of normalization constants. Numerical zero does not mean the sequence has mathematical probability zero.

500
First naive zero409
Scaled log likelihood-912.03
Log-space log likelihood-912.03
Final naive probability0
Compare the naive product with the scaled recursion and log-space version.

The figure’s sequence repeats the six faces. Naive calculation eventually reaches zero in finite arithmetic, while the scaled logarithm remains finite. Near underflow, digits can also be lost before the first zero. Compare the displayed scaled and logarithmic values, not the exponential of an extremely negative log likelihood.

In log space, the sum over predecessors is calculated with log-sum-exp, whereas Viterbi uses a maximum. These are different operations: replacing one with the other changes the quantity calculated. Forbidden transitions use log⁡0=−∞\log 0=-\infty; if every predecessor of a state is impossible, its message remains −∞-\infty. Tied paths can be resolved in several ways without changing the optimal score, so a library comparison should also check the score when ties exist.

Sampling a posterior path

Forward filtering backward sampling (FFBS) first calculates ftf_t. Sample zT∼fTz_T\sim f_T and then, for each t<Tt<T,

p(zt=i∣zt+1=j,y1:T)∝ft(i)Aij.p(z_t=i\given z_{t+1}=j,y_{1:T}) \propto f_t(i)A_{ij}.

Data after tt are independent of ztz_t given zt+1z_{t+1}; their influence is already incorporated into the chosen next state. Each sample respects allowed transitions and represents a complete joint path. Sampling each state from γt\gamma_t independently destroys temporal dependence and can generate impossible paths.

The factor chain in m14-l05 explains the three recursions: forward-backward applies sum-product, Viterbi applies max-product with backtracking, and FFBS uses sum-product messages to sample. In a continuous state-space model the same questions persist, although integrals and message representations change.

To check FFBS, looking at one path is not enough. Generate many trajectories, compare per-time frequencies with γt\gamma_t and also check forbidden transitions. Frequencies vary by Monte Carlo and exact equality is not expected. Enumerating all trajectories is an excellent reference for a small sequence, but costs KTK^T: dynamic messages share subproblems and make longer sequences feasible.

Lab: HMM from scratch

The implementation takes categorical matrices with state rows and symbol columns, and transitions from previous-state rows to next-state columns. It rejects impossible observations in normalized routines. For very long sequences memory can be reduced if only the likelihood is needed, without storing all messages.

[ ]Filtering, smoothing, Viterbi and FFBSBrowser
"""Inferencia exacta en HMM categóricos; A[i,j] pasa de i a j."""
import numpy as np
from scipy.special import logsumexp


def forward(pi,A,B,y):
    pi=np.asarray(pi,float);A=np.asarray(A,float);B=np.asarray(B,float)
    y=np.asarray(y,int);T=len(y);K=len(pi)
    if T==0:raise ValueError('La secuencia debe tener al menos una observación')
    f=np.empty((T,K));c=np.empty(T)
    raw=pi*B[:,y[0]];c[0]=raw.sum()
    if c[0]<=0:raise ValueError('Observaciones imposibles')
    f[0]=raw/c[0]
    for t in range(1,T):
        raw=(f[t-1]@A)*B[:,y[t]];c[t]=raw.sum()
        if c[t]<=0:raise ValueError('Observaciones imposibles')
        f[t]=raw/c[t]
    return f,c,float(np.log(c).sum())


def smooth(pi,A,B,y):
    f,c,ll=forward(pi,A,B,y)
    A=np.asarray(A,float);B=np.asarray(B,float);y=np.asarray(y,int)
    T,K=f.shape;b=np.ones((T,K))
    for t in range(T-2,-1,-1):
        b[t]=A@(B[:,y[t+1]]*b[t+1])/c[t+1]
    gamma=f*b;gamma/=gamma.sum(axis=1,keepdims=True)
    xi=np.empty((T-1,K,K))
    for t in range(T-1):
        xi[t]=f[t,:,None]*A*(B[:,y[t+1]]*b[t+1])[None,:]
        xi[t]/=xi[t].sum()
    return f,gamma,xi,ll


def forward_log(pi,A,B,y):
    y=np.asarray(y,int)
    if len(y)==0:raise ValueError('La secuencia debe tener al menos una observación')
    with np.errstate(divide='ignore'):
        lp=np.log(pi);la=np.log(A);lb=np.log(B)
    v=lp+lb[:,y[0]]
    for obs in y[1:]:v=lb[:,obs]+logsumexp(v[:,None]+la,axis=0)
    return float(logsumexp(v))


def viterbi(pi,A,B,y):
    y=np.asarray(y,int)
    if len(y)==0:raise ValueError('La secuencia debe tener al menos una observación')
    with np.errstate(divide='ignore'):
        lp=np.log(pi);la=np.log(A);lb=np.log(B)
    T=len(y);K=len(pi);d=lp+lb[:,y[0]];back=np.zeros((T,K),dtype=int)
    for t in range(1,T):
        scores=d[:,None]+la
        back[t]=np.argmax(scores,axis=0)
        d=np.max(scores,axis=0)+lb[:,y[t]]
    if not np.isfinite(d.max()):raise ValueError('Observaciones imposibles')
    path=np.empty(T,dtype=int);path[-1]=np.argmax(d)
    for t in range(T-2,-1,-1):path[t]=back[t+1,path[t+1]]
    return path,float(d[path[-1]])


def ffbs(pi,A,B,y,n_samples=1,seed=0):
    """Trayectorias de p(z_1:T | y_1:T), no sorteos marginales independientes."""
    f,_,_=forward(pi,A,B,y);A=np.asarray(A,float)
    rng=np.random.default_rng(seed);T,K=f.shape
    paths=np.empty((n_samples,T),dtype=int)
    paths[:,-1]=rng.choice(K,size=n_samples,p=f[-1])
    for t in range(T-2,-1,-1):
        p=f[t,:,None]*A[:,paths[:,t+1]];p/=p.sum(axis=0,keepdims=True)
        cumulative=np.cumsum(p,axis=0);cumulative[-1]=1.
        paths[:,t]=np.sum(cumulative<rng.random(n_samples)[None,:],axis=0)
    return paths


def simulate(pi,A,B,T,seed=0):
    rng=np.random.default_rng(seed);K=len(pi)
    states=np.empty(T,dtype=int);y=np.empty(T,dtype=int)
    states[0]=rng.choice(K,p=pi);y[0]=rng.choice(B.shape[1],p=B[states[0]])
    for t in range(1,T):
        states[t]=rng.choice(K,p=A[states[t-1]])
        y[t]=rng.choice(B.shape[1],p=B[states[t]])
    return states,y

We check a short sequence by enumerating 242^4 paths. FFBS frequency is random; the tolerance covers Monte Carlo variation for this seed and sample count.

[ ]Compare with enumerationBrowser
import itertools
pi=np.array([.6,.4]);A=np.array([[.7,.3],[.2,.8]])
B=np.array([[.8,.2],[.3,.7]]);y=np.array([0,1,0,1])
paths=np.array(list(itertools.product(range(2),repeat=len(y))))
weights=np.array([pi[z[0]]*B[z[0],y[0]]*np.prod(
    [A[z[t-1],z[t]]*B[z[t],y[t]] for t in range(1,len(y))]) for z in paths])
f,g,xi,ll=smooth(pi,A,B,y);weights/=weights.sum()
ref=np.array([[(weights*(paths[:,t]==k)).sum() for k in range(2)]
              for t in range(len(y))])
refxi=np.array([[[(weights*((paths[:,t]==i)&(paths[:,t+1]==j))).sum()
                   for j in range(2)] for i in range(2)] for t in range(len(y)-1)])
v,score=viterbi(pi,A,B,y);draws=ffbs(pi,A,B,y,20000,seed=9)
freq=np.array([[(draws[:,t]==k).mean() for k in range(2)] for t in range(len(y))])
print('log evidencia escalada y log:',ll,forward_log(pi,A,B,y))
print('errores gamma/xi:',np.max(abs(g-ref)),np.max(abs(xi-refxi)))
print('Viterbi / enumeración:',v,paths[np.argmax(weights)])
print('error máximo FFBS:',np.max(abs(freq-g)))
assert np.allclose(g,ref) and np.allclose(xi,refxi)
assert np.array_equal(v,paths[np.argmax(weights)]) and np.max(abs(freq-g))<.02

Now generate a casino and a sequence of non-overlapping base pairs. The latter is a synthetic model explicitly enriching CG in the “island” state; it is not detection in a real genome or a complete biological CpG island model. Metrics compare classification with the known state of that simulation.

[ ]Casino and synthetic CpG pairsBrowser
"""Casino y detector sintético de pares CpG; ejecutar tras hmm.py."""
pi=np.array([.5,.5])
A=np.array([[.95,.05],[.10,.90]])
B=np.array([[1/6]*6,[.1,.1,.1,.1,.1,.5]])
z,y=simulate(pi,A,B,200,seed=7)
f,g,xi,ll=smooth(pi,A,B,y)
path,score=viterbi(pi,A,B,y)
print('Casino: log evidencia, accuracy filtrado/suavizado/Viterbi',
      ll,np.mean((f[:,1]>.5)==z),np.mean((g[:,1]>.5)==z),np.mean(path==z))

# Cada observación es un par NO solapado: 0..15 codifica (primera,segunda)
# con A,C,G,T en ese orden. CG tiene índice 1*4+2 = 6.
base_bg=np.array([.3,.2,.2,.3]);base_island=np.array([.15,.35,.35,.15])
bg=np.outer(base_bg,base_bg).ravel()
island=np.outer(base_island,base_island).ravel();island[6]*=3;island/=island.sum()
pairB=np.vstack([bg,island]);pairA=np.array([[.98,.02],[.05,.95]])
true,observed=simulate(pi,pairA,pairB,600,seed=29)
_,post,_,pair_ll=smooth(pi,pairA,pairB,observed)
chosen=(post[:,1]>.5).astype(int)
tp=np.sum((chosen==1)&(true==1));fp=np.sum((chosen==1)&(true==0));fn=np.sum((chosen==0)&(true==1))
print('CpG sintético: P(CG) fondo/isla',pairB[:,6])
print('600 pares, log evidencia y acierto',pair_ll,np.mean(chosen==true))
print('VP, FP, FN; precisión y sensibilidad',tp,fp,fn,tp/(tp+fp),tp/(tp+fn))

The run with seeds 7 and 29 gives filtering/smoothing/Viterbi accuracies of 0.82/0.88/0.855 in the casino. For 600 synthetic pairs it gives 211 true positives, 13 false positives and 14 false negatives. These are results for those models and realizations, not general performance rates. Parameters are known in this lab; estimating them from data is another task.

In the base example, each non-overlapping pair is one of 16 categories generated conditional on the state. Background uses base frequencies (0.3,0.2,0.2,0.3)(0.3,0.2,0.2,0.3) for A, C, G and T. The island starts from (0.15,0.35,0.35,0.15)(0.15,0.35,0.35,0.15) and multiplies the weight of the CG pair by three before normalization. Resulting CG probabilities are 0.04 and approximately 0.295. This deliberate construction makes the signal checkable, but omits dependence between overlapping pairs, real genomic composition and biological annotation criteria.

The following local comparison uses hmmlearn and the same parameters and observations, without calling its fitting routine. Install the library in a compatible local environment to run it.

[ ]Compare with hmmlearnLocal GPU
"""Inferencia exacta en HMM categóricos; A[i,j] pasa de i a j."""
import numpy as np
from scipy.special import logsumexp


def forward(pi,A,B,y):
    pi=np.asarray(pi,float);A=np.asarray(A,float);B=np.asarray(B,float)
    y=np.asarray(y,int);T=len(y);K=len(pi)
    if T==0:raise ValueError('La secuencia debe tener al menos una observación')
    f=np.empty((T,K));c=np.empty(T)
    raw=pi*B[:,y[0]];c[0]=raw.sum()
    if c[0]<=0:raise ValueError('Observaciones imposibles')
    f[0]=raw/c[0]
    for t in range(1,T):
        raw=(f[t-1]@A)*B[:,y[t]];c[t]=raw.sum()
        if c[t]<=0:raise ValueError('Observaciones imposibles')
        f[t]=raw/c[t]
    return f,c,float(np.log(c).sum())


def smooth(pi,A,B,y):
    f,c,ll=forward(pi,A,B,y)
    A=np.asarray(A,float);B=np.asarray(B,float);y=np.asarray(y,int)
    T,K=f.shape;b=np.ones((T,K))
    for t in range(T-2,-1,-1):
        b[t]=A@(B[:,y[t+1]]*b[t+1])/c[t+1]
    gamma=f*b;gamma/=gamma.sum(axis=1,keepdims=True)
    xi=np.empty((T-1,K,K))
    for t in range(T-1):
        xi[t]=f[t,:,None]*A*(B[:,y[t+1]]*b[t+1])[None,:]
        xi[t]/=xi[t].sum()
    return f,gamma,xi,ll


def forward_log(pi,A,B,y):
    y=np.asarray(y,int)
    if len(y)==0:raise ValueError('La secuencia debe tener al menos una observación')
    with np.errstate(divide='ignore'):
        lp=np.log(pi);la=np.log(A);lb=np.log(B)
    v=lp+lb[:,y[0]]
    for obs in y[1:]:v=lb[:,obs]+logsumexp(v[:,None]+la,axis=0)
    return float(logsumexp(v))


def viterbi(pi,A,B,y):
    y=np.asarray(y,int)
    if len(y)==0:raise ValueError('La secuencia debe tener al menos una observación')
    with np.errstate(divide='ignore'):
        lp=np.log(pi);la=np.log(A);lb=np.log(B)
    T=len(y);K=len(pi);d=lp+lb[:,y[0]];back=np.zeros((T,K),dtype=int)
    for t in range(1,T):
        scores=d[:,None]+la
        back[t]=np.argmax(scores,axis=0)
        d=np.max(scores,axis=0)+lb[:,y[t]]
    if not np.isfinite(d.max()):raise ValueError('Observaciones imposibles')
    path=np.empty(T,dtype=int);path[-1]=np.argmax(d)
    for t in range(T-2,-1,-1):path[t]=back[t+1,path[t+1]]
    return path,float(d[path[-1]])


def ffbs(pi,A,B,y,n_samples=1,seed=0):
    """Trayectorias de p(z_1:T | y_1:T), no sorteos marginales independientes."""
    f,_,_=forward(pi,A,B,y);A=np.asarray(A,float)
    rng=np.random.default_rng(seed);T,K=f.shape
    paths=np.empty((n_samples,T),dtype=int)
    paths[:,-1]=rng.choice(K,size=n_samples,p=f[-1])
    for t in range(T-2,-1,-1):
        p=f[t,:,None]*A[:,paths[:,t+1]];p/=p.sum(axis=0,keepdims=True)
        cumulative=np.cumsum(p,axis=0);cumulative[-1]=1.
        paths[:,t]=np.sum(cumulative<rng.random(n_samples)[None,:],axis=0)
    return paths


def simulate(pi,A,B,T,seed=0):
    rng=np.random.default_rng(seed);K=len(pi)
    states=np.empty(T,dtype=int);y=np.empty(T,dtype=int)
    states[0]=rng.choice(K,p=pi);y[0]=rng.choice(B.shape[1],p=B[states[0]])
    for t in range(1,T):
        states[t]=rng.choice(K,p=A[states[t-1]])
        y[t]=rng.choice(B.shape[1],p=B[states[t]])
    return states,y

from hmmlearn.hmm import CategoricalHMM
pi=np.array([.5,.5]);A=np.array([[.95,.05],[.1,.9]])
B=np.array([[1/6]*6,[.1,.1,.1,.1,.1,.5]])
_,y=simulate(pi,A,B,200,seed=7)
f,g,xi,ll=smooth(pi,A,B,y);path,score=viterbi(pi,A,B,y)
model=CategoricalHMM(n_components=2,n_features=6,init_params='',params='',implementation='scaling')
model.startprob_=pi;model.transmat_=A;model.emissionprob_=B
ref_ll,ref_g=model.score_samples(y[:,None])
ref_score,ref_path=model.decode(y[:,None],algorithm='viterbi')
print('errores log evidencia, posterior, puntuación:',
      abs(ll-ref_ll),np.max(abs(g-ref_g)),abs(score-ref_score))
print('caminos coinciden:',np.array_equal(path,ref_path))
assert np.isclose(ll,ref_ll) and np.allclose(g,ref_g)
assert np.isclose(score,ref_score) and np.array_equal(path,ref_path)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofForward recursion
Prove: Derive the message αₜ(j)=p(y₁:ₜ,zₜ=j).
0
Aᵢⱼ=p(zₜ=j|zₜ₋₁=i) and the emission depends only on zₜ.

Step 1 of 3. Which variable from the immediate past is summed over?

Numeric
π=(0.6,0.4), A=[[0.7,0.3],[0.2,0.8]], b₁(0)=0.8, b₂(0)=0.3, b₁(1)=0.2, b₂(1)=0.7 and observations (0,1). What is unnormalized α₂(state 2)?
Quiz
Which rules minimize expected loss for incorrect labels and an incorrect whole sequence, respectively?
CodeViterbi in log space
Implement viterbi_log(log_pi,log_A,log_B), where log_B[t,j] is the log emission for each time and state. Return the path as a length-T vector of indices. Zero probabilities arrive as −inf; the tests contain at least one possible path.
import numpy as np
def viterbi_log(log_pi,log_A,log_B):
  return None
Shift+Enter to run
CodeBackward sampling
Implement ffbs_draws(f,A,n,seed), where f[t,i] is the normalized filter. Return n integer paths of shape (n,T). Use np.random.default_rng(seed) and sample the final state from f[-1], then each previous state with weights f[t,i] A[i,z[t+1]].
import numpy as np
def ffbs_draws(f,A,n,seed):
  return None
Shift+Enter to run
Key idea
Forward filters and calculates evidence; backward incorporates the future, Viterbi optimizes a path and FFBS samples joint trajectories.

References