Learning HMMs with Baum-Welch, and from HMMs to linear-chain CRFs
Baum-Welch is EM with forward-backward as its E-step. We implement it for multiple sequences, study local optima and non-identifiability, extend it to explicit durations in HSMMs, and contrast the generative HMM with the discriminative linear-chain CRF, which reuses these recursions to calculate its partition function and gradient.
After this lesson you can
- Derive Baum-Welch as EM with expected sufficient statistics calculated by forward-backward.
- Implement Baum-Welch with multiple sequences and discrete or Gaussian emissions.
- Explain the implicit geometric duration distribution of an HMM and when an HSMM is needed.
- Define a linear-chain CRF and calculate its conditional log likelihood and gradient with forward-backward.
- Compare generative and discriminative approaches to sequence labeling.
Before you start
- 14Forward-backward algorithm (smoothing)Viterbi algorithmScaling and log-space recursionsEM for graphical models via expected sufficient statisticsNon-identifiability and label switchingMarkov random fieldPartition functionHidden Markov model
- 12Expectation-maximization algorithmEM monotonicity and convergence
- 11Softmax (multinomial logistic) regression
- 06Limited-memory BFGS
Learning a hidden chain
In m14-l10 we calculated the state posterior with known parameters. Now we observe sequences but not their states and want to fit transitions and emissions. Baum-Welch is EM applied to an HMM: forward-backward calculates expected sufficient statistics and the M-step maximizes their expected complete log likelihood.
For independent sequences , let denote the posterior of state and the posterior of transition . With categorical emissions and no prior, the updates are
The transition denominator excludes the final state of each sequence. Do not invent a transition from one sequence’s end to the beginning of another. Each sequence contributes an initial state, so the update of averages over starts.
To derive the update, take the part of the complete log likelihood depending on transitions: . Conditional on observations and previous parameters, its expectation is with . Each row is optimized with a Lagrange multiplier to enforce a sum of one. The solution divides each expected count by the total exits from the same state. The E-step does not invent definitive labels: it distributes weight over all possible paths.
The E-step uses previous parameters to obtain and ; the M-step normalizes their counts. Under an exact M-step and valid conditions, observed log likelihood does not decrease, but this does not guarantee a global maximum. The figure uses twelve synthetic binary sequences of length 40 and changes only initialization. Exchanging state labels leaves the observed distribution unchanged: compare parameters after aligning states, not by their arbitrary number.
For univariate Gaussian emissions, counts become weighted sums:
A variance can collapse when fitting an isolated observation. The lab imposes an explicit minimum and maximizes within that constraint. If a category receives zero probability, later sequences may become impossible; a proper Dirichlet prior and smoothing can avoid zeros. An interior MAP step adds to expected counts of each row; with boundary parameters or a penalized objective, raw likelihood monotonicity must not be asserted automatically. The additive posterior-mean update is a different rule and should be identified as such.
EM’s guarantee compares objectives under specific assumptions. With exactly calculated statistics and an M-step maximizing the same objective, an iteration does not reduce observed likelihood. Numerical tolerance can introduce small rounding differences. A prior changes the objective to the posterior and an approximate M-step requires its own improvement condition. Record the relevant objective and try several initializations; an increasing curve only shows that accepted steps improved, not that no better solution exists elsewhere.
Duration and the semi-Markov model
In a standard HMM, upon entering state with self-transition probability , duration counts the first step and has
The probability of leaving on the next step, conditional on remaining inside, is always . A high self-transition increases the mean but does not create a peak at a preferred duration greater than one. A hidden semi-Markov model assigns an explicit duration distribution to each state and updates by segments. The chain between segments may exclude self-transitions to avoid redundant representations. Inference sums over possible states and durations and typically costs more than an ordinary HMM.
The 272 waiting times between eruptions of Old Faithful geyser are the real R faithful dataset, in minutes. They are observed durations, not labeled hidden states. The figure bins in five-minute intervals and omits the tail from 125 onward. The shifted negative binomial is fitted to empirical mean and variance; it improves binned error against the geometric with similar mean, but need not reproduce bimodality. In an HSMM it would be a duration choice, not proof that the geyser follows that model.
The observed mean is about 70.90 minutes and this sample’s population variance is 184.14 minutes squared. For the shifted distribution the moments of are matched to a negative binomial, yielding approximate shape 42.76 and probability 0.3796. The displayed error sums absolute differences by bin only in the displayed window: it is not a total distance over the whole support. The geometric can reach the same mean with self-transition near 0.986, but assigns considerable mass to short waits absent from this sample. Fitting the mean does not automatically fit the shape.
From generating observations to conditioning on them
An HMM models the joint distribution : states or labels generate observations via emissions. A linear-chain CRF directly models the conditional distribution of labels given observations :
Normalization is global over complete paths. A feature can look at initial capitalization, a suffix and the previous word simultaneously without specifying a generative distribution over words. An HMM can incorporate derived features if it defines a suitable emission model; the difference is that the CRF does not have to model their joint distribution. Information available at prediction must match what is used to calculate features.
Sentences and labels are synthetic. The figure’s eight models were actually trained with L-BFGS and the combinations of three features, on the corpus generated by the lab. The HMM uses word emissions with an unknown category; test names and places do not appear in training. Token accuracies are for this particular dataset. An additional feature can help or hurt on test, as the selector shows; there is no universal superiority.
The conditional log-likelihood gradient has a direct interpretation:
It is observed count minus expected count under the model. Forward-backward on potentials calculates the partition function and required marginals; Viterbi replaces sum with maximum to decode. With quadratic penalty, subtract from the log-likelihood gradient. L-BFGS minimizes the regularized negative in the lab. Regularization matters with many sparse features and few examples.
In the code, a path’s score sums the product of features and weights of its label at each position and a weight for each consecutive label pair. The forward message for the current label sums exponentiated scores of all prefixes ending there; in log space it uses log-sum-exp. The backward message supplies the suffix. Their normalized product yields label and transition marginals for calculating the gradient’s second term. The example adds no special start or end weight: adding them is a possible extension that must include its own counts.
A maximum entropy Markov model normalizes each outgoing decision locally: this normalization can favor states with few exits and produce label bias. The CRF normalizes over complete paths, avoiding that particular local restriction. This does not make it immune to misspecification, class imbalance or data bias. A generative HMM can use unlabeled data via EM; the supervised CRF shown requires labels. Predictive results depend on data, priors, features and objective.
In a local decision with one allowed exit, its conditional probability is one regardless of the weight assigned to that exit. An opportunity to compare that path with others using later evidence is thus lost. Global normalization preserves competition between complete-path scores. In a real application, future words as features are legitimate only if they will be available at decision time; for full-sentence labeling they may be, whereas in an online system they may not.
Lab: Gaussian regimes
The engine calculates forward-backward in log space and updates sequences separately. We generate four independent series of 80 returns, with zero means and variances and ; these are synthetic values, not market prices. Parameters are estimated from three initializations. Labels may permute.
"""Forward-backward logarítmico y Baum-Welch gaussiano multiserie."""
import numpy as np
from scipy.special import logsumexp
def fb(logpi,logA,logB):
T,K=logB.shape
if T==0:raise ValueError('Secuencia vacía')
a=np.empty((T,K));b=np.zeros((T,K));a[0]=logpi+logB[0]
for t in range(1,T):a[t]=logB[t]+logsumexp(a[t-1,:,None]+logA,axis=0)
ll=logsumexp(a[-1])
if not np.isfinite(ll):raise ValueError('Secuencia imposible')
for t in range(T-2,-1,-1):b[t]=logsumexp(logA+logB[t+1,None,:]+b[t+1,None,:],axis=1)
gamma=np.exp(a+b-ll)
xi=np.exp(a[:-1,:,None]+logA[None,:,:]+logB[1:,None,:]+b[1:,None,:]-ll)
return gamma,xi,float(ll)
def gaussian_emissions(y,mu,var):
y=np.asarray(y,float)
return -.5*(np.log(2*np.pi*var)[None,:]+(y[:,None]-mu[None,:])**2/var[None,:])
def baum_gaussian(sequences,pi,A,mu,var,steps=50,var_floor=1e-4,tol=1e-6):
"""Máxima verosimilitud restringida var>=var_floor; sin unir fronteras."""
pi=np.asarray(pi,float).copy();A=np.asarray(A,float).copy()
mu=np.asarray(mu,float).copy();var=np.asarray(var,float).copy()
K=len(pi);history=[]
for iteration in range(steps+1):
initial=np.zeros(K);trans=np.zeros((K,K));weight=np.zeros(K)
sx=np.zeros(K);sx2=np.zeros(K);total=0.
with np.errstate(divide='ignore'):lp=np.log(pi);la=np.log(A)
for seq in sequences:
y=np.asarray(seq,float);g,xi,ll=fb(lp,la,gaussian_emissions(y,mu,var))
total+=ll;initial+=g[0];trans+=xi.sum(axis=0)
weight+=g.sum(axis=0);sx+=(g*y[:,None]).sum(axis=0)
sx2+=(g*y[:,None]**2).sum(axis=0)
history.append(total)
if iteration==steps or (iteration>0 and total-history[-2]<tol):break
pi=initial/initial.sum()
A=trans/trans.sum(axis=1,keepdims=True)
mu=sx/weight
var=np.maximum(sx2/weight-mu**2,var_floor)
return pi,A,mu,var,np.array(history)
def simulate_gaussian(pi,A,mu,var,lengths,seed=0):
rng=np.random.default_rng(seed);K=len(pi);sequences=[];states=[]
for T in lengths:
z=np.empty(T,dtype=int);y=np.empty(T)
z[0]=rng.choice(K,p=pi);y[0]=rng.normal(mu[z[0]],np.sqrt(var[z[0]]))
for t in range(1,T):
z[t]=rng.choice(K,p=A[z[t-1]])
y[t]=rng.normal(mu[z[t]],np.sqrt(var[z[t]]))
sequences.append(y);states.append(z)
return sequences,statespi_true=np.array([.6,.4]);A_true=np.array([[.97,.03],[.08,.92]])
series,states=simulate_gaussian(pi_true,A_true,np.array([0.,0.]),
np.array([.0001,.0025]),[80]*4,33)
def restart(seed):
rng=np.random.default_rng(seed)
means=rng.normal(0,.01,2)
variances=np.exp(rng.uniform(np.log(.0001),np.log(.005),2))
result=baum_gaussian(series,np.array([.5,.5]),np.array([[.8,.2],[.2,.8]]),
means,variances,steps=40,var_floor=1e-6)
history=result[-1]
assert np.all(np.diff(history)>-1e-7)
print('semilla',seed,'iteraciones',len(history)-1,'log evidencia',history[-1],
'varianzas',result[3],'menor incremento',np.min(np.diff(history)))
return result
fit0=restart(0)fit1=restart(1)fit2=restart(2)In this run the three initializations find virtually the same value and two swap the variance order. This agreement does not guarantee an absence of local optima on other data. Log likelihood is summed by sequence and excludes artificial transitions between them.
Lab: conditional CRF
Each sentence uses two labels, “other” and “place”. The test set uses people and places different from training. The model uses intercept, initial capitalization, suffix and previous word, plus four transition weights. The objective returns the regularized mean negative and its gradient.
We check the twelve gradient coordinates by central differences over 24 sentences to keep the test fast; subsequent training still uses all 80 sentences.
"""CRF de cadena con dos etiquetas, características solapadas y L-BFGS."""
import numpy as np
from scipy.special import logsumexp
from scipy.optimize import minimize
def corpus(n,seed,heldout=False):
rng=np.random.default_rng(seed)
people=['Lucia','Daria','Pablo','Nora'] if heldout else ['Julia','Ana','Mario','Elena','Luis','Clara']
places=['Astoria','Lisboa','Berlin','Tirana'] if heldout else ['Sofia','Roma','Valencia','Lima','Paris','Praga']
data=[]
for _ in range(n):
person=str(rng.choice(people));place=str(rng.choice(places));kind=int(rng.integers(4))
if kind==0:tokens=[person,'vive','en',place];tags=[0,0,0,1]
elif kind==1:tokens=[person,'visita',place];tags=[0,0,1]
elif kind==2:tokens=['ayer',person,'viaja','a',place];tags=[0,0,0,0,1]
else:tokens=[person,'llama','a',str(rng.choice(people))];tags=[0,0,0,0]
data.append((tokens,np.array(tags,int)))
return data
def features(tokens,mask=(1,1,1)):
return np.array([[1.,mask[0]*float(w[0].isupper()),
mask[1]*float(w.lower().endswith('ia')),
mask[2]*float(i>0 and tokens[i-1].lower()=='en')]
for i,w in enumerate(tokens)])
def crf_stats(W,C,X):
T=len(X);em=X@W.T;a=np.empty((T,2));b=np.zeros((T,2));a[0]=em[0]
for t in range(1,T):a[t]=em[t]+logsumexp(a[t-1,:,None]+C,axis=0)
logZ=logsumexp(a[-1])
for t in range(T-2,-1,-1):b[t]=logsumexp(C+em[t+1,None,:]+b[t+1,None,:],axis=1)
g=np.exp(a+b-logZ)
xi=np.exp(a[:-1,:,None]+C[None,:,:]+em[1:,None,:]+b[1:,None,:]-logZ)
return logZ,g,xi,em
def crf_objective(theta,data,mask=(1,1,1),reg=.2):
W=theta[:8].reshape(2,4);C=theta[8:].reshape(2,2)
value=0.;gradW=np.zeros_like(W);gradC=np.zeros_like(C)
for tokens,tags in data:
X=features(tokens,mask);Z,g,xi,em=crf_stats(W,C,X)
value+=Z-em[np.arange(len(tags)),tags].sum()-C[tags[:-1],tags[1:]].sum()
expected=g.T@X;observed=np.zeros_like(W)
np.add.at(observed,tags,X);gradW+=expected-observed
gradC+=xi.sum(axis=0)
np.add.at(gradC,(tags[:-1],tags[1:]),-1)
value=value/len(data)+.5*reg*(theta@theta)
grad=np.r_[gradW.ravel(),gradC.ravel()]/len(data)+reg*theta
return value,grad
def fit_crf(data,mask=(1,1,1),reg=.2):
return minimize(crf_objective,np.zeros(12),args=(data,mask,reg),
jac=True,method='L-BFGS-B',options={'maxiter':200,'ftol':1e-12,'gtol':1e-8})
def decode_scores(em,transition,initial=None):
T,K=em.shape;back=np.zeros((T,K),int)
d=em[0]+(np.zeros(K) if initial is None else initial)
for t in range(1,T):
scores=d[:,None]+transition;back[t]=np.argmax(scores,axis=0)
d=em[t]+np.max(scores,axis=0)
path=np.empty(T,int);path[-1]=np.argmax(d)
for t in range(T-2,-1,-1):path[t]=back[t+1,path[t+1]]
return path
def decode_crf(theta,tokens,mask=(1,1,1)):
W=theta[:8].reshape(2,4);C=theta[8:].reshape(2,2)
return decode_scores(features(tokens,mask)@W.T,C)
def fit_supervised_hmm(data,smoothing=.25):
vocab=sorted({w for words,_ in data for w in words})
lookup={w:i for i,w in enumerate(vocab)};unknown=len(vocab)
init=np.full(2,smoothing);A=np.full((2,2),smoothing)
B=np.full((2,len(vocab)+1),smoothing)
for words,y in data:
init[y[0]]+=1
np.add.at(A,(y[:-1],y[1:]),1)
for w,k in zip(words,y):B[k,lookup[w]]+=1
init/=init.sum();A/=A.sum(axis=1,keepdims=True);B/=B.sum(axis=1,keepdims=True)
return lookup,unknown,init,A,B
def decode_hmm(model,tokens):
vocab,unknown,pi,A,B=model;idx=[vocab.get(w,unknown) for w in tokens]
return decode_scores(np.log(B[:,idx].T),np.log(A),np.log(pi))
def accuracy(data,predict):
correct=total=0
for tokens,y in data:
z=predict(tokens);correct+=np.sum(z==y);total+=len(y)
return correct/totaltrain=corpus(80,12);test=corpus(40,93,True)
theta=np.random.default_rng(3).normal(size=12)*.2
grad_data=train[:24]
value,gradient=crf_objective(theta,grad_data)
h=1e-5;eye=np.eye(len(theta))
finite=np.array([(crf_objective(theta+h*v,grad_data)[0]-
crf_objective(theta-h*v,grad_data)[0])/(2*h) for v in eye])
print('Error máximo del gradiente:',np.max(abs(gradient-finite)))
assert np.max(abs(gradient-finite))<1e-7
res=fit_crf(train,mask=(1,1,1),reg=.2)
hmm=fit_supervised_hmm(train)
print('L-BFGS terminado:',res.success,'norma máxima del gradiente:',np.max(abs(res.jac)))
print('Exactitud por token CRF:',accuracy(test,lambda x:decode_crf(res.x,x)))
print('Exactitud por token HMM:',accuracy(test,lambda x:decode_hmm(hmm,x)))
print('Pesos CRF de lugar:',res.x[4:8])
assert res.success and np.max(abs(res.jac))<1e-5
The supervised HMM counts labeled words and transitions with smoothing 0.25; an absent word uses a common unknown category. The CRF uses regularization 0.2 and features of the observed sentence. The figure’s token accuracies were obtained by repeating the fit for each mask on this same sample. Evaluating generalization of a feature-selection procedure would require an additional outer split.
Exercises
Step 1 of 3. Which part of the objective depends on row i?
import numpy as np
def baum_step(sequences,pi,A,B):
return None,None,Noneimport numpy as np
def grad_crf(theta,X,y):
return NoneReferences
- R datasets: Old Faithful Geyser Data, 272 observations. Pinned CSV copy from Rdatasets, SHA-256
5043db1e2c51c8e8fd67e0868c768ae589770cc76ad0ac0c5b7afd1fca31fc57. - Sutton and McCallum, An Introduction to Conditional Random Fields.
- Lafferty, McCallum and Pereira, Conditional Random Fields (2001).
- Baum, Petrie, Soules and Weiss, A Maximization Technique (1970).