AI Wiki中文/EN

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.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

How 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.

Three continuous-emission states admit ten segmentations of six frames. Posterior probabilities, log density and geometric duration represent different quantities.
Three continuous-emission states admit ten segmentations of six frames. Posterior probabilities, log density and geometric duration represent different quantities.

Define density, transitions and termination together

There are SS emitting states numbered 0,…,S−10,\ldots,S-1, and scalar observations x0,…,xT−1x_0,\ldots,x_{T-1}. State ss stays with probability psp_s. A nonfinal state moves forward with probability 1−ps1-p_s; 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 μs\mu_s and positive variance σs2\sigma_s^2:

bs(x)=12πσs2exp⁡ ⁣[−(x−μs)22σs2].b_s(x)=\frac{1}{\sqrt{2\pi\sigma_s^2}}\exp\!\left[-\frac{(x-\mu_s)^2}{2\sigma_s^2}\right].

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 QQ contain transitions between emitting states and ese_s the final-exit probability; only the last state’s exit is nonzero. A row of QQ plus ese_s sums to one. A state path qq has joint density and marginal likelihood:

w(q,x)=1[q0=0] bq0(x0)∏t=1T−1Qqt−1,qtbqt(xt) eqT−1,Z(x)=∑qw(q,x).w(q,x)=\mathbf1[q_0=0]\,b_{q_0}(x_0)\prod_{t=1}^{T-1}Q_{q_{t-1},q_t}b_{q_t}(x_t)\,e_{q_{T-1}},\qquad Z(x)=\sum_qw(q,x).

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 At(s)A_t(s) includes the current emission; backward value Bt(s)B_t(s) includes only future emissions and exit. Their recurrences are:

At(s)=bs(xt)∑jAt−1(j)Qjs,A0(s)=1[s=0]bs(x0);Bt(s)=∑jQsjbj(xt+1)Bt+1(j),BT−1(s)=es.A_t(s)=b_s(x_t)\sum_jA_{t-1}(j)Q_{js},\quad A_0(s)=\mathbf1[s=0]b_s(x_0);\qquad B_t(s)=\sum_jQ_{sj}b_j(x_{t+1})B_{t+1}(j),\quad B_{T-1}(s)=e_s.

Then Z=∑sAT−1(s)esZ=\sum_sA_{T-1}(s)e_s. 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 γ\gamma and adjacent-transition posterior ξ\xi are:

γt(s)=At(s)Bt(s)Z,ξt(s,j)=At(s)Qsjbj(xt+1)Bt+1(j)Z.\gamma_t(s)=\frac{A_t(s)B_t(s)}Z,\qquad \xi_t(s,j)=\frac{A_t(s)Q_{sj}b_j(x_{t+1})B_{t+1}(j)}Z.

Each frame’s γ\gamma sums to one across states. Summing ξ\xi 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 Gs=∑tγt(s)G_s=\sum_t\gamma_t(s) and Nsj=∑t=0T−2ξt(s,j)N_{sj}=\sum_{t=0}^{T-2}\xi_t(s,j), updates are:

μs′=∑tγt(s)xtGs,(σs2)′=∑tγt(s)(xt−μs′)2Gs,ps′=Nss∑jNsj+1[s=S−1].\mu'_s=\frac{\sum_t\gamma_t(s)x_t}{G_s},\qquad (\sigma_s^2)'=\frac{\sum_t\gamma_t(s)(x_t-\mu'_s)^2}{G_s},\qquad p'_s=\frac{N_{ss}}{\sum_jN_{sj}+\mathbf1[s=S-1]}.

The extra one in the last denominator is the final exit occurring in every accepted path. We then constrain variance to [10−4,100][10^{-4},100] and stay probability to [0.05,0.95][0.05,0.95]. 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 ss for dd frames and then leaving has probability:

P(Ds=d)=psd−1(1−ps),d=1,2,…,E[Ds]=11−ps.P(D_s=d)=p_s^{d-1}(1-p_s),\qquad d=1,2,\ldots,\qquad \mathbb E[D_s]=\frac1{1-p_s}.

For ps=0.6p_s=0.6, 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 Tln⁡2T\ln2. 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 O(TS2)O(TS^2). Dedicated self/next-edge code could exploit sparsity, but that optimization is not implemented here. Enumeration has (T−1S−1)\binom{T-1}{S-1} paths, each inspecting TT 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

  1. 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.

  2. 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 1/2π1/\sqrt{2\pi}, multiplied by one 0.6 stay and one 0.4 exit: 0.6×0.4/(2π)0.6\times0.4/(2\pi). Omitting exit scores a different model.

  3. 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 1/(1−0.6)=2.51/(1-0.6)=2.5 frames, not a requirement to remain exactly 2.5 frames on every visit.

  4. 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 Tln⁡2T\ln2 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?

Choose one answer

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

  1. A Tutorial on Hidden Markov Models and Selected Applications in Speech Recognition
    Lawrence R. Rabiner · 1989
  2. 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:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.