Module contents
Lesson 11 of 27Core 100 min

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

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 s=1,…,Ss=1,\ldots,S, let γt(s)(i)\gamma_t^{(s)}(i) denote the posterior of state ii and ξt(s)(i,j)\xi_t^{(s)}(i,j) the posterior of transition i→ji\to j. With categorical emissions and no prior, the updates are

πinuevo=1S∑sγ1(s)(i),Aijnuevo=∑s∑t=1Ts−1ξt(s)(i,j)∑s∑t=1Ts−1γt(s)(i),\pi_i^{\rm nuevo}=\frac1S\sum_s\gamma_1^{(s)}(i),\qquad A_{ij}^{\rm nuevo}= \frac{\sum_s\sum_{t=1}^{T_s-1}\xi_t^{(s)}(i,j)} {\sum_s\sum_{t=1}^{T_s-1}\gamma_t^{(s)}(i)}, Biknuevo=∑s∑t=1Tsγt(s)(i) 1[yt(s)=k]∑s∑t=1Tsγt(s)(i).B_{ik}^{\rm nuevo}= \frac{\sum_s\sum_{t=1}^{T_s}\gamma_t^{(s)}(i)\,\mathbf1[y_t^{(s)}=k]} {\sum_s\sum_{t=1}^{T_s}\gamma_t^{(s)}(i)}.

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 π\pi averages over SS starts.

To derive the update, take the part of the complete log likelihood depending on transitions: ∑s,tlog⁡Aztzt+1\sum_{s,t}\log A_{z_tz_{t+1}}. Conditional on observations and previous parameters, its expectation is ∑ijNijlog⁡Aij\sum_{ij}N_{ij}\log A_{ij} with Nij=∑s,tξt(s)(i,j)N_{ij}=\sum_{s,t}\xi_t^{(s)}(i,j). 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.

InteractiveBaum-Welch iteration by iteration
Transitions: source row, destination column
0.381
0.619
0.708
0.292
Emissions: state row, columns 0 and 1
0.469
0.531
0.344
0.656

Twelve synthetic sequences of 40 symbols, generated with seed 17. The M-step uses expected counts without pseudocounts; renaming states does not change the observed model. Local search can end at different points.

iteration 0
Initialization seed1
Log likelihood-361.341
Increase from start0.000
Follow parameters and log likelihood for a fixed synthetic sample.

The E-step uses previous parameters to obtain γ\gamma and ξ\xi; 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:

μinuevo=∑s,tγt(s)(i)yt(s)∑s,tγt(s)(i),(σi2)nuevo=∑s,tγt(s)(i)(yt(s)−μinuevo)2∑s,tγt(s)(i).\mu_i^{\rm nuevo}=\frac{\sum_{s,t}\gamma_t^{(s)}(i)y_t^{(s)}}{\sum_{s,t}\gamma_t^{(s)}(i)},\qquad (\sigma_i^2)^{\rm nuevo}= \frac{\sum_{s,t}\gamma_t^{(s)}(i)(y_t^{(s)}-\mu_i^{\rm nuevo})^2} {\sum_{s,t}\gamma_t^{(s)}(i)}.

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 αk−1\alpha_k-1 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 ii with self-transition probability a=Aiia=A_{ii}, duration DD counts the first step and has

p(D=d)=(1−a)ad−1,d=1,2,…,E[D]=11−a.p(D=d)=(1-a)a^{d-1},\quad d=1,2,\ldots,\qquad \mathbb E[D]=\frac1{1-a}.

The probability of leaving on the next step, conditional on remaining inside, is always 1−a1-a. 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.

InteractiveGeometric and explicit durations
  • Observed waiting times
  • Geometric
  • Shifted negative binomial

272 measured waits between Old Faithful geyser eruptions, the R faithful dataset; they are not observed hidden states. Bins [0,5), …, [120,125), with the later tail omitted. The shifted negative binomial fits mean and variance, but does not capture all features of the bimodal distribution.

0.986
Actual mean (min)70.90
Geometric mean (min)71.4
L1 error in displayed bins: geometric1.267
L1 error in displayed bins: negative binomial0.614
Compare actual waiting times with two discrete families; the negative binomial is fitted by moments.

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 D=1+XD=1+X 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 X=D−1X=D-1 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 p(x,y)p(\vb x,\vb y): states or labels generate observations via emissions. A linear-chain CRF directly models the conditional distribution of labels y\vb y given observations x\vb x:

pθ(y∣x)=exp⁡{∑tθ⊤ϕ(yt−1,yt,x,t)}Zθ(x),Zθ(x)=∑y′exp⁡{∑tθ⊤ϕ(yt−1′,yt′,x,t)}.p_\theta(\vb y\given\vb x)= \frac{\exp\{\sum_t\theta\T\boldsymbol\phi(y_{t-1},y_t,\vb x,t)\}} {Z_\theta(\vb x)},\qquad Z_\theta(\vb x)=\sum_{\vb y'}\exp\{\sum_t\theta\T\boldsymbol\phi(y'_{t-1},y'_t,\vb x,t)\}.

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.

InteractiveOverlapping features for labeling
WordLuciaviveenAstoria
TruthOtherOtherOtherPlace
CRFOtherOtherOtherPlace
HMMOtherOtherOtherPlace

Binary labels, 80 synthetic Spanish training sentences and 40 test sentences with separate name and place vocabularies. All eight CRFs were trained with L-BFGS and regularization 0.2; the supervised HMM uses words and an unknown category. Token accuracy is for this sample, not a universal ranking.

CRF accuracy on 40 test sentences87.9 %
HMM accuracy on the same sentences90.4 %
Place weight: capital / suffix / previous0.37 · 0.22 · 0.48
Enable features of a trained CRF and compare its labels with a supervised HMM.

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:

∇θlog⁡pθ(y∣x)=∑tϕ(yt−1,yt,x,t)−Eθ ⁣[∑tϕ(Yt−1,Yt,x,t)∣x].\nabla_\theta\log p_\theta(\vb y\given\vb x) =\sum_t\boldsymbol\phi(y_{t-1},y_t,\vb x,t) -\mathbb E_\theta\!\left[\sum_t\boldsymbol\phi(Y_{t-1},Y_t,\vb x,t)\mid\vb x\right].

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 λθ\lambda\theta 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 0.00010.0001 and 0.00250.0025; these are synthetic values, not market prices. Parameters are estimated from three initializations. Labels may permute.

[ ]Gaussian Baum-Welch from scratchBrowser
"""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,states
[ ]Generate series and prepare restartsBrowser
pi_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
[ ]Restart 1Browser
fit0=restart(0)
[ ]Restart 2Browser
fit1=restart(1)
[ ]Restart 3Browser
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.

[ ]Linear-chain CRF from scratchBrowser
"""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/total
[ ]Verify the gradientBrowser
train=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
[ ]Train and evaluateBrowser
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

ProofM-step for transitions
Prove: Derive the update of row Aᵢ under the constraint that it sums to one.
0
Let Nᵢⱼ be the sum of ξₜ(i,j) over times and sequences.

Step 1 of 3. Which part of the objective depends on row i?

Numeric
In an HMM, what is the mean duration in steps of a state whose self-transition is 0.95?
Quiz
Which normalization difference avoids the classical MEMM label-bias mechanism in a CRF?
CodeBaum-Welch with scaling
Implement baum_step(sequences,pi,A,B): one EM step for independent categorical sequences. Return (pi_new,A_new,B_new). Initial matrices are positive with normalized rows; each sequence contains at least two symbols.
import numpy as np
def baum_step(sequences,pi,A,B):
  return None,None,None
Shift+Enter to run
CodeConditional gradient
Implement grad_crf(theta,X,y): two labels, X of shape (T,2), four emission weights theta[:4] as a (2,2) matrix and four transition weights theta[4:] as (2,2). Return the gradient of log p(y|X), without regularization.
import numpy as np
def grad_crf(theta,X,y):
  return None
Shift+Enter to run
Key idea
Baum-Welch fits a joint distribution with hidden states; a CRF globally normalizes the conditional distribution and learns from observed and expected counts.

References