Speech HMMs: duration, continuous density and hidden alignment
语音识别中的 HMM
Infer and enumerate a left-to-right Gaussian HMM with explicit exit probabilities, posterior flow and bounded EM updates.
hmm-speechHow long can the middle of a sound last?
Divide a hypothetical pronunciation unit into beginning, middle and end states. Slow speech can spend more frames in the middle; fast speech moves right sooner. A speech HMM explains this temporal stretching through hidden states: acoustic features are observed, while states and segment boundaries must be inferred.
This differs from a discrete-emission part-of-speech example. Acoustic features are usually continuous; states obey a temporal topology and must eventually finish. Kaldi’s three-state Bakis example has three emitting states and a nonemitting final state, with each emitting state allowing a self-loop or a forward transition. Emitting states and termination
We build a bounded model of one pronunciation unit and calculate total likelihood, the best path, frame posteriors and an EM update. The program uses six synthetic scalar features, without actual phoneme labels, a pronunciation lexicon or a continuous-speech benchmark.
Define density, transitions and termination together
There are emitting states numbered , and scalar observations . State stays with probability . A nonfinal state moves forward with probability ; the last emitting state instead leaves to the nonemitting endpoint. The initial state is fixed at 0. An accepted path must visit the last emitting state and exit.
Each state uses one Gaussian emission density with mean and positive variance :
Variance 0.01 gives peak density about 3.989. A density exceeding one is valid: its integral gives probability. Real acoustic models may use multivariate features, Gaussian mixtures, tied states or neural outputs, with different training and calibration conditions. Rabiner’s tutorial introduces discrete models before a dedicated treatment of continuous densities and mixtures. Continuous observations
Let contain transitions between emitting states and the final-exit probability; only the last state’s exit is nonzero. A row of plus sums to one. A state path has joint density and marginal likelihood:
Do not omit the exit or add an extra emission at termination. A fixed-length HMM without explicit stopping can use a different ending convention; the likelihoods cannot be interchanged. Meaning of exit probabilities
Forward value includes the current emission; backward value includes only future emissions and exit. Their recurrences are:
Then . Viterbi replaces the forward sum with a maximum and retains predecessors, seeking one best path. Forward inference retains contributions from every legal segmentation. The code uses log-sum-exp to avoid underflow from multiplying many small densities. Rabiner’s path-sum and forward derivations explain this distinction. Summation versus the best path
Conditioned on the whole observation sequence, state occupancy and adjacent-transition posterior are:
Each frame’s sums to one across states. Summing over outgoing or incoming edges recovers the corresponding neighboring frame posterior. These are conditional probabilities even though emission densities can exceed one. Weighted enumeration of complete paths checks the identities independently.
EM first computes posteriors under old parameters, then treats them as soft assignments. With and , updates are:
The extra one in the last denominator is the final exit occurring in every accepted path. We then constrain variance to and stay probability to . This is bounded parameter optimization, not unconstrained maximum likelihood. Constraints can prevent tiny-variance degeneracy; they cannot make a short training segment a reliable acoustic model. Rabiner’s continuous-emission section provides the soft-occupancy reestimation context. Continuous-density reestimation
A self-loop also imposes a duration model. Remaining in state for frames and then leaving has probability:
For , mean duration is 2.5 frames. This memoryless geometric distribution does not allow arbitrary duration shapes. If duration structure matters, consider an explicit-duration model rather than merely adding state names. Geometric duration
Keep every segmentation available for checking
The complete Python/NumPy program supports at most four states and 12 frames, with at least as many frames as states. Observations and means are bounded by ±20. Density inputs are synthetic scalars, not MFCCs extracted from recordings. enumerate_paths partitions frames into positive integer state durations, excluding illegal backward moves and skipped states.
"""Left-to-right Gaussian HMM with an explicit final exit and EM statistics.
One scalar feature per frame, one Gaussian per state; no acoustic corpus or
lexicon. Continuous densities are not class posterior probabilities.
"""
import itertools,json,math
import numpy as np
def logsum(values):
a=np.asarray(values,float);m=float(np.max(a))
return m+float(np.log(np.exp(a-m).sum())) if np.isfinite(m) else -np.inf
def model(means,variances,stay):
if any(np.iscomplexobj(x) for x in (means,variances,stay)):raise ValueError('Real parameters required')
mu=np.asarray(means,float);var=np.asarray(variances,float);p=np.asarray(stay,float)
if mu.ndim!=1 or not 1<=len(mu)<=4 or var.shape!=mu.shape or p.shape!=mu.shape or not all(np.isfinite(x).all() for x in (mu,var,p)) or (abs(mu)>20).any() or (var<1e-4).any() or (var>100).any() or (p<.05).any() or (p>.95).any():raise ValueError('Use 1–4 states, bounded means/variances and stay probabilities .05–.95')
S=len(mu);q=np.zeros((S,S));np.fill_diagonal(q,p)
for s in range(S-1):q[s,s+1]=1-p[s]
exit=np.zeros(S);exit[-1]=1-p[-1]
return dict(means=mu,variances=var,stay=p,transition=q,exit=exit)
def infer(values,parameters):
if np.iscomplexobj(values):raise ValueError('Real observations required')
x=np.asarray(values,float);p=model(parameters['means'],parameters['variances'],parameters['stay']);S=len(p['means'])
if x.ndim!=1 or not S<=len(x)<=12 or not np.isfinite(x).all() or (abs(x)>20).any():raise ValueError('Use enough bounded scalar frames to visit every state, at most12')
T=len(x);em=-.5*(np.log(2*np.pi*p['variances'])[None,:]+(x[:,None]-p['means'])**2/p['variances']);q=p['transition'];lq=np.full_like(q,-np.inf);np.log(q,out=lq,where=q>0)
a=np.full((T,S),-np.inf);a[0,0]=em[0,0];v=a.copy();parent=np.zeros((T,S),int)
for t in range(1,T):
for s in range(S):
a[t,s]=em[t,s]+logsum(a[t-1]+lq[:,s]);scores=v[t-1]+lq[:,s];parent[t,s]=int(np.argmax(scores));v[t,s]=scores[parent[t,s]]+em[t,s]
end=np.full(S,-np.inf);end[-1]=math.log(p['exit'][-1]);z=logsum(a[-1]+end);b=np.full_like(a,-np.inf);b[-1]=end
for t in range(T-2,-1,-1):
for s in range(S):b[t,s]=logsum(lq[s]+em[t+1]+b[t+1])
gamma=np.exp(a+b-z);xi=np.array([np.exp(a[t,:,None]+lq+em[t+1,None,:]+b[t+1,None,:]-z) for t in range(T-1)]).reshape(T-1,S,S)
path=[S-1]
for t in range(T-1,0,-1):path.append(int(parent[t,path[-1]]))
return dict(log_likelihood=float(z),viterbi_log_joint=float(v[-1,-1]+end[-1]),path=path[::-1],posterior=gamma.tolist(),transition_posterior=xi.tolist(),emission_density=np.exp(em).tolist())
def enumerate_paths(values,parameters):
# Nondecreasing paths are determined by positive state durations.
p=model(parameters['means'],parameters['variances'],parameters['stay']);x=np.asarray(values,float);infer(x,p);T=len(x);S=len(p['means']);rows=[]
for cuts in itertools.combinations(range(1,T),S-1):
lengths=np.diff([0,*cuts,T]);states=np.repeat(np.arange(S),lengths);weight=math.log(p['exit'][-1])
for t,s in enumerate(states):
weight+=-.5*(math.log(2*np.pi*p['variances'][s])+(x[t]-p['means'][s])**2/p['variances'][s])
if t:weight+=math.log(p['transition'][states[t-1],s])
rows.append(dict(states=states.tolist(),log_joint=float(weight)))
return dict(paths=rows,log_likelihood=logsum([r['log_joint'] for r in rows]))
def em_step(values,parameters):
x=np.asarray(values,float);p=model(parameters['means'],parameters['variances'],parameters['stay']);r=infer(x,p);gamma=np.array(r['posterior']);xi=np.array(r['transition_posterior']);mass=gamma.sum(axis=0)
if (mass<1e-10).any():raise ValueError('Insufficient occupancy for a stable update')
means=(gamma*x[:,None]).sum(axis=0)/mass;variances=np.clip((gamma*(x[:,None]-means)**2).sum(axis=0)/mass,1e-4,100)
counts=xi.sum(axis=0);self_counts=np.diag(counts);depart=counts.sum(axis=1);depart[-1]+=1 # final exit occurs once in every accepted path
stay=np.clip(self_counts/depart,.05,.95);updated=model(means,variances,stay)
return updated,dict(before=r['log_likelihood'],after=infer(x,updated)['log_likelihood'])
def demo():
x=[-.2,.1,1.,1.2,2.1,1.9];p=model([0,1,2],[.3,.3,.3],[.55,.6,.65]);r=infer(x,p);ex=enumerate_paths(x,p);trained=p;history=[r['log_likelihood']]
for _ in range(4):trained,step=em_step(x,trained);history.append(step['after'])
duration=np.arange(1,7);stay=.6;mass=(stay**(duration-1))*(1-stay)
return dict(observations=x,means=p['means'].tolist(),variances=p['variances'].tolist(),stay=p['stay'].tolist(),inference=r,enumeration=ex,training_log_likelihood=history,trained_means=trained['means'].tolist(),trained_variances=trained['variances'].tolist(),duration=dict(stay=stay,lengths=duration.tolist(),probabilities=mass.tolist(),mean=1/(1-stay),tail_after_six=stay**6),density_peak=float(1/math.sqrt(2*np.pi*.01)))
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
The six observations [−0.2, 0.1, 1, 1.2, 2.1, 1.9], state means [0, 1, 2], variances 0.3 and stay probabilities [0.55, 0.6, 0.65] admit ten legal segmentations. Total log likelihood is approximately −5.6090145623. Viterbi selects [0, 0, 1, 1, 2, 2], with log joint density approximately −6.3891122128. The best path is below the total because other segmentations contribute too.
Four EM updates raise log likelihood to approximately 0.3320660592. Positive log density does not imply probability above one or test-set improvement. Multiplying features and means by 2 and variances by 4 leaves state posteriors unchanged while reducing log density by . Raw likelihood cannot be compared across feature units directly.
Although topology is sparse, the code loops over every state pair. Time and stored transition-posteriors use . Dedicated self/next-edge code could exploit sparsity, but that optimization is not implemented here. Enumeration has paths, each inspecting frames, and is only a small-scale check.
One pronunciation unit is not a recognizer
A real recognizer must connect acoustic states to pronunciation units, lexicons and language constraints, while handling speakers, noise, silence, context and search pruning. We allow only one state order, without competing word models; six numbers do not directly yield real words.
The HMM factorizes emissions across frames given a state path. Neighboring acoustic frames are often correlated, so this is a modeling choice rather than proof that real sound is independent. One Gaussian may inadequately model complex acoustics, and EM may stop at a local solution. Compare models on isolated speaker/recording test data instead of reporting only rising training likelihood.
Check the model through paths and units
-
Understanding. Does emission density 3.989 invalidate the model? Can a per-frame state posterior exceed one?
Answer: Continuous density can exceed one; integrating gives probability. A state posterior is a discrete conditional probability between zero and one, summing to one at each frame. They are different quantities.
-
Calculation. A one-state model has stay probability 0.6, mean 0 and variance 1. What is the joint density of emitting two zeros and exiting?
Answer: Each Gaussian density is , multiplied by one 0.6 stay and one 0.4 exit: . Omitting exit scores a different model.
-
Boundary. Can three mandatory emitting states explain two frames? What mean duration corresponds to stay probability 0.6?
Answer: No: at least three frames are needed. Geometric mean duration is frames, not a requirement to remain exactly 2.5 frames on every visit.
-
Transfer. Feature units double and training log likelihood falls. Does recognition necessarily worsen?
Answer: No. Transforming means and variances consistently can preserve posteriors while density changes by a log term. Standardize features and measurement conditions before judging task performance.
The topology and inference conventions are explicit
Rabiner’s 1989 duration, forward-inference and continuous-density sections provide mathematical context. Kaldi’s pinned topology documentation explains three emitting states and a nonemitting endpoint. We combine those ideas in a specified bounded single-Gaussian model, without copying Kaldi code or replicating the paper’s application systems. Enumeration, EM and unit-transformation results apply to this synthetic example.
Make a prediction, then check
Why can a Gaussian emission density exceed one while the HMM remains valid?
Learning objectives
- Specify emitting states and final exit.
- Distinguish continuous density from posterior probability.
- Compare forward sums, Viterbi paths and state posteriors.
- Derive bounded EM and geometric duration assumptions.
Prerequisites & connections
Explore related knowledge →References
- A Tutorial on Hidden Markov Models and Selected Applications in Speech Recognition
Lawrence R. Rabiner · 1989 - Kaldi: HMM topology and transition modeling at commite02e35f0
Kaldi contributors
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-13 · Single AI author checked explicit final exit in a continuous single-Gaussian left-to-right HMM, forward/backward and Viterbi conventions, enumerated ten paths, posterior flow, bounded EM, geometric duration and change of feature units against scoped Rabiner1989 pages259/262/267 and pinned Kaldi topology documentation. Six paired equations and four explained exercises. Synthetic scalar acoustics, not Kaldi compatibility, GMM training or word recognition.
- Checked continuous density above1, explicit-exit two-frame hand calculation, ten-path marginal/posterior agreement, EM increases, unit-transform likelihood shift and geometric mean2.5.
- Four computed SVGs bind exact bilingual MDX. The five-topic group passed eleven numeric/encoding checks and 30 isolated language/width cases with four fallback fonts; ten actual screenshots inspected by the AI author. Literal-prose AST checked before freezing. Full article browser acceptance is separate; no human peer review.
- After rendered review, inserted missing spaces before English reference citations. Verified an exact whitespace-only transformation, unchanged formulas/program and preserved frozen article/test payloads; see editorial/corrections/011h-citation-spacing.
Source locations checked:
- A Tutorial on Hidden Markov Models and Selected Applications in Speech Recognition · Read and visually inspected physical pages3/6/11, printed259/262/267: duration, forward path sum and continuous densities/reestimation. The first Columbia copy lacked extracted text; this university copy supports scoped reading. No speech benchmark replication.
- Kaldi: HMM topology and transition modeling at commite02e35f0 · Read topology introduction, three emitting states plus nonemitting final state, self/next edges and final probability interpretation. Snapshot2025-09-22; this single-Gaussian example is original and does not run Kaldi.
Related topics