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 and be an observation. Define , and . Rows of sum to one and go from previous state to next:
Each emission is independent of the others given its state, and the latent future depends on the past through the current state. is specified: it need not be the stationary distribution. Distinguish three questions: filtering uses data through , 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 , the previous state provides no additional information about 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.
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 :
The sum eliminates the previous state and the emission is outside because it depends on the current state. The likelihood is . To calculate it stably, normalize each step with and store :
Here and . If , 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 and the emission then weights the states.
For example, with and probabilities of emitting 0 equal to 0.8 and 0.3, the first observation 0 produces and . The filter is , not . For the transition and second emission of the exercise, the joint message becomes and the two-symbol evidence is 0.24. The second scaling constant is ; 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 starts at and moves backward:
The backward message summarizes how compatible future data are with each current state. In the scaled implementation each step is divided by ; then is obtained by normalizing the product . Smoothed transition probabilities are
Summing over rows and columns gives and . 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 comes from multiplying four pieces: past weight through , transition , emission at and future weight after . Normalizing all pairs turns those weights into a joint distribution of two adjacent states. If , also : inference preserves model constraints. A high marginal at today and another high marginal at tomorrow do not imply that pair 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 equal to the best joint log weight of a prefix ending in :
Store the index attaining each maximum. After choosing the best final state, follow backpointers. Time complexity is and pointers require space; deterministic tie rules can be defined. A zero transition is represented as , not an invented small probability.
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.
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
with explicit handling of all terms. Scaling and log-sum-exp are two ways to retain the same mathematical likelihood; they do not eliminate model misspecification.
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 ; if every predecessor of a state is impossible, its message remains . 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 . Sample and then, for each ,
Data after are independent of given ; 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 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 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 : 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.
"""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,yWe check a short sequence by enumerating paths. FFBS frequency is random; the tolerance covers Monte Carlo variation for this seed and sample count.
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 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 for A, C, G and T. The island starts from 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.
"""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)
npm run lab and open the connection link.Exercises
Step 1 of 3. Which variable from the immediate past is summed over?
import numpy as np
def viterbi_log(log_pi,log_A,log_B):
return Noneimport numpy as np
def ffbs_draws(f,A,n,seed):
return None