Algorithm Search⌘K

Algorithmcore

Viterbi training

Also called segmental k-means.

Train an HMM by alternating a Viterbi alignment of the data with re-estimation from the hard counts. It never lowers the best-path likelihood and is a fast stand-in for Baum-Welch.

Time
Θ(k T N^2) worst
Space
Θ(T N + N^2 + N M) extra
Where
M = the number of output symbols; N = the number of states; T = the total number of frames; k = the number of rounds
Properties
deterministicnot exactofflineiterative
Origin
Biing Hwang Juang, Lawrence R. Rabiner, 1990

Viterbi training estimates the parameters λ=(π,A,B)\lambda = (\pi, A, B) of a hidden Markov model from unlabeled sequences. Each round aligns every training sequence with its best state path by the Viterbi algorithm, and then sets the parameters to the relative frequencies of the counts along those paths. It is the hard-count version of the Baum-Welch algorithm, in the same way that k-means is the hard-count version of EM for a Gaussian mixture. In speech recognition the method is also called segmental k-means (Juang and Rabiner 1990).

In plain words

You have a model with a few hidden states and many recordings, but nobody told you which state made which part of each recording. Start with a rough guess of the model. Then repeat two steps. First, for each recording, find the one sequence of states that the current model likes best. Second, pretend that this guess is the truth: count how often each state starts, how often each state follows each other state, and how often each state makes each output, and turn the counts into new probabilities.

Each round makes the best sequence of states at least as likely as before, so the process stops. It can stop at a poor answer if the first guess is poor. It is faster than the method that weighs all state sequences, and it gives a clear label to every frame.

The problem

The input is a set of training sequences O1,…,ORO^1, \ldots, O^R over MM symbols, a number of states NN, and a start model λ1\lambda_1. Write log⁡\log for the natural log, with log⁡0=−∞\log 0 = -\infty. Viterbi training looks for a model with a large value of

F(λ)=∑r=1Rmax⁡Qlog⁡P(Or,Q∣λ),F(\lambda) = \sum_{r=1}^{R} \max_{Q} \log P(O^r, Q \mid \lambda),

the log joint probability of the best state path of each sequence. Compare the objective of Baum-Welch, the total log likelihood ∑rlog⁡P(Or∣λ)=∑rlog⁡∑QP(Or,Q∣λ)\sum_r \log P(O^r \mid \lambda) = \sum_r \log \sum_Q P(O^r, Q \mid \lambda), which sums over all paths. The two objectives have different maxima in general. This is the HMM parameter learning problem with the best path in place of the sum.

The code uses discrete outputs, so bj(k)b_j(k) is a table. In a GMM-HMM acoustic model the outputs are feature vectors, and the update of bjb_j fits a Gaussian mixture to the frames that the paths give to state jj. With one Gaussian per state this is again a closed form: the mean and the variance of those frames. With more components, k-means on the frames of each state splits them among the components, which is where the name segmental k-means comes from.

The algorithm

  1. VITERBI-TRAINING(O^1 .. O^R, λ, K, tol)
  2. 1F_old ← -∞
  3. 2for round ← 1 to K do
  4. 3for r ← 1 to R do Q^r, s_r ← VITERBI(λ, O^r) ▷ best path and its log joint
  5. 4F ← s_1 + ... + s_R
  6. 5if F ≤ F_old + tol then return λ
  7. 6F_old ← F
  8. 7count along Q^1 .. Q^R: n_i starts in i, n_ij steps i → j, c_jk frames in j with symbol k
  9. 8π_i ← n_i / Σ n, a_ij ← n_ij / Σ_j' n_ij', b_j(k) ← c_jk / Σ_k' c_jk' ▷ a row with no counts keeps its value
  10. 9return λ

Line L3 is a forced alignment when each sequence has a known transcript, because then the HMM of the sequence is the left-to-right chain of its transcript. The general case on this page runs the full Viterbi recursion over all NN states. The tie rule of the code is that of the Viterbi algorithm page: the smallest state index wins.

The start model matters. A common start for a left-to-right model is the uniform segmentation: cut each sequence into NN equal parts, give part jj to state jj, and estimate λ1\lambda_1 from these paths. The function uniform_segmentation_start of the code does this.

Example

Take N=2N = 2 states and the symbols x,yx, y. The single training sequence is O=(x,y,x)O = (x, y, x). The start model has π=(0.2,0.8)\pi = (0.2, 0.8), aij=0.5a_{ij} = 0.5 for all i,ji, j, b1=(0.8,0.2)b_1 = (0.8, 0.2) and b2=(0.5,0.5)b_2 = (0.5, 0.5), where bj=(bj(x),bj(y))b_j = (b_j(x), b_j(y)).

Round 1. The transitions are uniform, so the best path takes the best state at each frame: state 2 first, because π2b2(x)=0.4>π1b1(x)=0.16\pi_2 b_2(x) = 0.4 > \pi_1 b_1(x) = 0.16, then state 2 for yy (0.5>0.20.5 > 0.2), then state 1 for xx (0.8>0.50.8 > 0.5). The path Q=(2,2,1)Q = (2, 2, 1) has P(O,Q)=0.4⋅0.5⋅0.5⋅0.5⋅0.8=0.04P(O, Q) = 0.4 \cdot 0.5 \cdot 0.5 \cdot 0.5 \cdot 0.8 = 0.04. The counts are one start in state 2, the steps 2→22 \to 2 and 2→12 \to 1, the emissions x,yx, y in state 2 and xx in state 1. So π=(0,1)\pi = (0, 1), row 2 of AA becomes (0.5,0.5)(0.5, 0.5), row 1 has no counts and keeps (0.5,0.5)(0.5, 0.5), b1=(1,0)b_1 = (1, 0) and b2=(0.5,0.5)b_2 = (0.5, 0.5).

Round 2. The best path is again (2,2,1)(2, 2, 1), now with P(O,Q)=1⋅0.5⋅0.5⋅0.5⋅0.5⋅1=0.0625P(O, Q) = 1 \cdot 0.5 \cdot 0.5 \cdot 0.5 \cdot 0.5 \cdot 1 = 0.0625. The counts are the same, so the model does not change.

Round 3. The objective is again 0.06250.0625, so line L5 stops. The values of exp⁡(F)\exp(F) were 0.040.04, 0.06250.0625 and 0.06250.0625.

The total likelihood went the other way. Under the start model P(O)=0.1274P(O) = 0.1274, and under the final model P(O)=0.09375P(O) = 0.09375. Viterbi training raised the probability of the best path and lowered the probability of the data. The test test_total_likelihood_can_decrease checks these numbers.

Correctness

The proof is in proofs/correctness.md. For a fixed tuple of paths Q\mathbf{Q}, the log joint G(λ;Q)=∑rlog⁡P(Or,Qr∣λ)G(\lambda; \mathbf{Q}) = \sum_r \log P(O^r, Q^r \mid \lambda) splits into one term ∑xcxlog⁡px\sum_x c_x \log p_x for each row of π\pi, AA and BB. By Gibbs' inequality, the relative frequencies of line L8 maximize each term, so they maximize GG. This is a theorem. Then

F(λk+1)≥G(λk+1;Qk)≥G(λk;Qk)=F(λk),F(\lambda_{k+1}) \ge G(\lambda_{k+1}; \mathbf{Q}_k) \ge G(\lambda_k; \mathbf{Q}_k) = F(\lambda_k),

because FF is a maximum over paths. So FF never decreases (a theorem, in exact arithmetic). There are finitely many tuples of paths, and the proof shows that a tuple can repeat only in the last two rounds, so the algorithm stops after a finite number of rounds. It stops at a fixed point, which is a local optimum of the alternation and not in general the global maximum of FF.

Proof: Viterbi training never lowers the best-path likelihood and stopsfull

We use the notation of the page: a discrete HMM λ=(π,A,B)\lambda = (\pi, A, B) with NN states and MM symbols, and training sequences O1,…,ORO^1, \ldots, O^R. All logs are natural logs, and log⁡0=−∞\log 0 = -\infty. For a tuple of state paths Q=(Q1,…,QR)\mathbf{Q} = (Q^1, \ldots, Q^R), one path per sequence, write

G(λ;Q)=∑r=1Rlog⁡P(Or,Qr∣λ),F(λ)=∑r=1Rmax⁡Qlog⁡P(Or,Q∣λ)=max⁡QG(λ;Q).G(\lambda; \mathbf{Q}) = \sum_{r=1}^{R} \log P(O^r, Q^r \mid \lambda), \qquad F(\lambda) = \sum_{r=1}^{R} \max_{Q} \log P(O^r, Q \mid \lambda) = \max_{\mathbf{Q}} G(\lambda; \mathbf{Q}).

Round kk of the algorithm starts with the model λk\lambda_k. Lines L3 and L4 compute a tuple Qk\mathbf{Q}_k of Viterbi paths and Fk=G(λk;Qk)F_k = G(\lambda_k; \mathbf{Q}_k). The Viterbi algorithm returns a best path (see the viterbi-algorithm page), so Fk=F(λk)F_k = F(\lambda_k). If the round does not stop at line L5, lines L7 and L8 set λk+1\lambda_{k+1} to the relative frequencies of the counts along Qk\mathbf{Q}_k.

Lemma 1 (the update step). For a fixed tuple Q\mathbf{Q}, the relative frequencies of lines L7 and L8 maximize G(λ;Q)G(\lambda; \mathbf{Q}) over all models λ\lambda. A row with no counts may take any value without changing GG.

Proof. Let nin_i be the number of paths that start in ii, nijn_{ij} the number of steps i→ji \to j and cjkc_{jk} the number of frames in state jj with the symbol kk. Then

G(λ;Q)=∑inilog⁡πi+∑i∑jnijlog⁡aij+∑j∑kcjklog⁡bj(k).G(\lambda; \mathbf{Q}) = \sum_i n_i \log \pi_i + \sum_i \sum_j n_{ij} \log a_{ij} + \sum_j \sum_k c_{jk} \log b_j(k).

The rows π\pi, ai⋅a_{i\cdot} and bj⋅b_{j\cdot} appear in separate terms, and each term has the form ∑xcxlog⁡px\sum_x c_x \log p_x with counts cx≥0c_x \ge 0 and a distribution pp. If C=∑xcx>0C = \sum_x c_x > 0, Gibbs' inequality gives ∑xcxlog⁡px≤∑xcxlog⁡(cx/C)\sum_x c_x \log p_x \le \sum_x c_x \log (c_x / C), with equality at px=cx/Cp_x = c_x / C. If C=0C = 0 the term is 00 for every pp. □\square

Theorem 1 (monotone objective). F(λk+1)≥F(λk)F(\lambda_{k+1}) \ge F(\lambda_k) for every round kk that updates the model.

Proof. F(λk+1)=max⁡QG(λk+1;Q)≥G(λk+1;Qk)≥G(λk;Qk)=F(λk)F(\lambda_{k+1}) = \max_{\mathbf{Q}} G(\lambda_{k+1}; \mathbf{Q}) \ge G(\lambda_{k+1}; \mathbf{Q}_k) \ge G(\lambda_k; \mathbf{Q}_k) = F(\lambda_k). The first inequality is the definition of FF, and the second is Lemma 1. □\square

Write M(Q)=max⁡λG(λ;Q)M(\mathbf{Q}) = \max_\lambda G(\lambda; \mathbf{Q}). The proof of Theorem 1 also gives the sandwich

M(Qk)=G(λk+1;Qk)≤Fk+1=G(λk+1;Qk+1)≤M(Qk+1).(S)M(\mathbf{Q}_k) = G(\lambda_{k+1}; \mathbf{Q}_k) \le F_{k+1} = G(\lambda_{k+1}; \mathbf{Q}_{k+1}) \le M(\mathbf{Q}_{k+1}). \tag{S}

Theorem 2 (termination). In exact arithmetic with tol =0= 0, the algorithm stops after finitely many rounds. If ZZ is the number of tuples of state paths, at most Z+1Z + 1 rounds update the model.

Proof. A round b≥2b \ge 2 updates the model only if Fb>Fb−1F_b > F_{b-1}, so the values FkF_k strictly increase along the rounds that update the model. Assume that two updating rounds a<ba < b have Qa=Qb\mathbf{Q}_a = \mathbf{Q}_b. By (S), Fb≤M(Qb)=M(Qa)≤Fa+1F_b \le M(\mathbf{Q}_b) = M(\mathbf{Q}_a) \le F_{a+1}. If b>a+1b > a + 1, then Fb>Fa+1F_b > F_{a+1}, which is false. So b=a+1b = a + 1. Then λa+2\lambda_{a+2} comes from the same counts as λa+1\lambda_{a+1}. The relative frequencies are the same, and a row with no counts keeps the value of λa+1\lambda_{a+1}, so λa+2=λa+1\lambda_{a+2} = \lambda_{a+1}. Then Fa+2=Fa+1F_{a+2} = F_{a+1} and round a+2a + 2 stops at line L5. So a tuple of paths repeats at most once, in two consecutive rounds, and only just before the end. There are Z≤∏rNTrZ \le \prod_r N^{T_r} tuples, which is finite. □\square

With tol >0> 0 or with the round limit, the code stops no later. In floating point the values FkF_k are rounded, so Theorem 1 holds up to rounding errors; the tests allow 10−910^{-9}.

Proposition (the total likelihood can go down). Theorem 1 is about FF, the log likelihood of the best path. The total log likelihood ∑rlog⁡P(Or∣λ)\sum_r \log P(O^r \mid \lambda) can decrease in a round.

Proof by example. Take N=2N = 2, M=2M = 2 with the symbols x,yx, y, one sequence O=(x,y,x)O = (x, y, x), π=(0.2,0.8)\pi = (0.2, 0.8), aij=0.5a_{ij} = 0.5 for all i,ji, j, b1=(0.8,0.2)b_1 = (0.8, 0.2) and b2=(0.5,0.5)b_2 = (0.5, 0.5). With uniform transitions, the best path takes the state of largest πibi(o1)\pi_i b_i(o_1) at the first frame and of largest bi(ot)b_i(o_t) later: Q=(2,2,1)Q = (2, 2, 1), with P(O,Q)=0.8⋅0.5⋅0.5⋅0.5⋅0.5⋅0.8=0.04P(O, Q) = 0.8 \cdot 0.5 \cdot 0.5 \cdot 0.5 \cdot 0.5 \cdot 0.8 = 0.04. The total is P(O)=∑q1πq1bq1(x)⋅0.5⋅(0.2+0.5)⋅0.5⋅(0.8+0.5)=(0.16+0.4)⋅0.35⋅0.65=0.1274P(O) = \sum_{q_1} \pi_{q_1} b_{q_1}(x) \cdot 0.5 \cdot (0.2 + 0.5) \cdot 0.5 \cdot (0.8 + 0.5) = (0.16 + 0.4) \cdot 0.35 \cdot 0.65 = 0.1274. The counts on QQ give π=(0,1)\pi = (0, 1), a21=a22=0.5a_{2 1} = a_{2 2} = 0.5, row 1 of AA unchanged, b1=(1,0)b_1 = (1, 0) and b2=(0.5,0.5)b_2 = (0.5, 0.5). Now every path starts in state 2, so P(O)=0.5⋅0.5⋅(0+0.5)⋅0.5⋅(1+0.5)=0.09375<0.1274P(O) = 0.5 \cdot 0.5 \cdot (0 + 0.5) \cdot 0.5 \cdot (1 + 0.5) = 0.09375 < 0.1274, while the best path has P(O,Q)=1⋅0.5⋅0.5⋅0.5⋅0.5⋅1=0.0625>0.04P(O, Q) = 1 \cdot 0.5 \cdot 0.5 \cdot 0.5 \cdot 0.5 \cdot 1 = 0.0625 > 0.04. The test test_total_likelihood_can_decrease checks these numbers. □\square

Complexity

A round runs the Viterbi algorithm on each sequence, which takes Θ(TrN2)\Theta(T_r N^2) time for a sequence of TrT_r frames, and counts along the paths in Θ(Tr)\Theta(T_r) time. With T=∑rTrT = \sum_r T_r frames in total, a round takes Θ(TN2)\Theta(T N^2) time and kk rounds take Θ(kTN2)\Theta(k T N^2). The normalization adds Θ(N2+NM)\Theta(N^2 + N M) per round. A left-to-right model with a self loop and one move per state takes Θ(TN)\Theta(T N) time per round, as in forced alignment.

The back pointers of one sequence take Θ(TrN)\Theta(T_r N) space, the paths take Θ(T)\Theta(T) and the model and the counts take Θ(N2+NM)\Theta(N^2 + N M). The bound in the front matter allows all back pointers at once.

A Baum-Welch round also takes Θ(TN2)\Theta(T N^2) time, so the saving of Viterbi training is a constant factor: one max pass and a traceback in place of a forward pass, a backward pass and the posteriors, and integer counts in place of sums of posteriors. With Gaussian mixtures, each frame updates only the statistics of one state, which is a larger saving.

Properties

  • Monotone in the best-path likelihood. F(λ)F(\lambda) never decreases (a theorem). The total likelihood P(O∣λ)P(O \mid \lambda) can decrease, as the example shows.
  • Finite stop. In exact arithmetic the algorithm stops after finitely many rounds (a theorem). In practice it stops after a few rounds, often fewer than Baum-Welch needs, but this is an observation and not a bound.
  • Local optimum. The result depends on the start model. The test test_learns_a_left_to_right_model shows a start with almost flat emissions that ends with a much lower objective than the uniform segmentation start.
  • Zeros stay zero. A transition or emission with probability 0 is never on a best path with finite score, so it gets no counts and stays 0. A left-to-right topology stays left-to-right.
  • Hard labels. Every frame belongs to one state. This makes the statistics simple, and it gives labels for other uses, for example the targets of a hybrid DNN-HMM.
  • Biased estimates. Hard counts favor the winning state at every frame, so the estimates are biased when the states overlap. When the best path holds most of the probability mass, the two methods give nearly the same result (a heuristic).

Variants and improvements

  • Baum-Welch. Replace the hard counts by the posteriors of the forward-backward algorithm. This is EM, and it never decreases the total likelihood. Baum-Welch is the soft-count version and Viterbi training is the hard-count version of the same alternation.
  • Viterbi then Baum-Welch. A common recipe runs a few rounds of Viterbi training from a uniform segmentation, and then Baum-Welch from the result. Rabiner 1989 describes segmental k-means as a way to get the initial estimates.
  • Training with transcripts. In speech, the HMM of each utterance is built from its transcript, and line L3 is forced alignment. This is the usual alignment step of recognizer training.
  • N-best or beam paths. Count along a few best paths, or along the paths inside a beam, to get between hard and soft counts.
  • Continuous outputs. Re-estimate each state's Gaussian mixture from its frames, by k-means and then one fit of the mixture, or by one EM step on the frames of the state.

When to use it

Use Viterbi training to start an HMM from a rough model, to train when the best path dominates (well separated states, as in speech with good features), and when you need a hard label for every frame. Use Baum-Welch when the states overlap, when the data are few, or when you need the maximum likelihood estimate. In speech, both appear in one recipe: Viterbi alignments give the first models and the frame labels, and Baum-Welch refines the models.

Pitfalls

  • A poor start. A state can lose all its frames, and then its rows keep the old values and never change. Start from a uniform segmentation or from a trained smaller model.
  • Zero counts. A symbol that a state never emits in the paths gets probability 0, and an unseen test sequence can then have probability 0. Smooth the counts or floor the probabilities.
  • The wrong objective. Do not report the total likelihood as the training curve of Viterbi training and expect it to rise. Track FF.
  • Products of probabilities. Use log space. A product over a few hundred frames underflows in double precision.
  • Ties in the alignment. Different tie rules give different paths and different counts. Fix the tie rule if you need reproducible models.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

nlslog.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the natural-language-and-speech pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Log-space arithmetic and semirings for the natural-language-and-speech pages.

Every log is the natural log. A probability of 0 is NEG_INF (float("-inf")),
never a large negative number. A cost is -log p, so a probability of 0 is a
cost of POS_INF.

The semirings are (K, plus, times, zero, one) as on the weighted-automaton page:

    PROB      probabilities         plus = +        times = *   zero = 0       one = 1
    LOG       log probabilities     plus = log_add  times = +   zero = -inf    one = 0
    VITERBI   log probabilities     plus = max      times = +   zero = -inf    one = 0
    TROPICAL  costs -log p          plus = min      times = +   zero = +inf    one = 0
    LOG_COST  costs -log p          plus = -log_add(-a, -b), times = +, zero = +inf, one = 0
    BOOLEAN   truth values          plus = or       times = and zero = False   one = True
    COUNTING  path counts           plus = +        times = *   zero = 0       one = 1

This module holds no algorithm of any page: no forward, Viterbi, CKY, Eisner,
CTC or DTW recursion. The pages build their dynamic programs on top of it.
"""

import math
from dataclasses import dataclass
from typing import Any, Callable, Iterable, List, Sequence

NEG_INF = float("-inf")
POS_INF = float("inf")


def safe_log(p) -> float:
    """Return log p, and NEG_INF for p = 0. Raise ValueError for p < 0."""
    if p < 0:
        raise ValueError("log of a negative number")
    if p == 0:
        return NEG_INF
    return math.log(p)


def log_add(a: float, b: float) -> float:
    """Return log(exp(a) + exp(b)) = max(a, b) + log(1 + exp(-|a - b|)).

    log_add(NEG_INF, NEG_INF) is NEG_INF. No exp of a large number is taken.
    """
    if a < b:
        a, b = b, a
    if b == NEG_INF or a == POS_INF:
        return a
    return a + math.log1p(math.exp(b - a))


def log_sum(xs: Iterable[float]) -> float:
    """Return log(sum of exp(x)) over xs. An empty input gives NEG_INF."""
    xs = list(xs)
    if not xs:
        return NEG_INF
    m = max(xs)
    if m == NEG_INF or m == POS_INF:
        return m
    return m + math.log(math.fsum(math.exp(x - m) for x in xs))


def log_normalize(xs: Sequence[float]) -> List[float]:
    """Return the list x - log_sum(xs): log values whose exps sum to 1.

    Raise ValueError if every value is NEG_INF (nothing to normalize).
    """
    z = log_sum(xs)
    if z == NEG_INF:
        raise ValueError("every weight is zero")
    return [x - z for x in xs]


def log_softmax(xs: Sequence[float]) -> List[float]:
    """Return log softmax(xs): the logits xs turned into log probabilities."""
    return log_normalize(xs)


def softmax(xs: Sequence[float], temperature: float = 1.0) -> List[float]:
    """Return the probabilities exp(x / temperature) / sum, computed stably.

    The temperature must be positive. Logits of NEG_INF get probability 0.
    """
    if not temperature > 0:
        raise ValueError("the temperature must be positive")
    m = max(xs)
    if m == NEG_INF:
        raise ValueError("every logit is -inf")
    es = [math.exp((x - m) / temperature) for x in xs]
    s = math.fsum(es)
    return [e / s for e in es]


def argmax(xs: Sequence[Any]) -> int:
    """Return the first index of a largest value. Raise ValueError if xs is empty."""
    if len(xs) == 0:
        raise ValueError("argmax of an empty sequence")
    best = 0
    for i in range(1, len(xs)):
        if xs[i] > xs[best]:
            best = i
    return best


@dataclass(frozen=True)
class Semiring:
    """A semiring (K, plus, times, zero, one). idempotent is True when a plus a = a."""

    name: str
    plus: Callable[[Any, Any], Any]
    times: Callable[[Any, Any], Any]
    zero: Any
    one: Any
    idempotent: bool


def _add(a, b):
    return a + b


def _mul(a, b):
    return a * b


def _log_add_cost(a: float, b: float) -> float:
    return -log_add(-a, -b)


PROB = Semiring("probability", _add, _mul, 0, 1, False)
LOG = Semiring("log", log_add, _add, NEG_INF, 0.0, False)
VITERBI = Semiring("viterbi", max, _add, NEG_INF, 0.0, True)
TROPICAL = Semiring("tropical", min, _add, POS_INF, 0.0, True)
LOG_COST = Semiring("log-cost", _log_add_cost, _add, POS_INF, 0.0, False)
BOOLEAN = Semiring("boolean", lambda a, b: a or b, lambda a, b: a and b, False, True, True)
COUNTING = Semiring("counting", _add, _mul, 0, 1, False)


def sr_sum(sr: Semiring, xs: Iterable[Any]) -> Any:
    """Return the semiring sum of xs, and sr.zero for an empty input."""
    acc = sr.zero
    for x in xs:
        acc = sr.plus(acc, x)
    return acc


def sr_prod(sr: Semiring, xs: Iterable[Any]) -> Any:
    """Return the semiring product of xs, and sr.one for an empty input."""
    acc = sr.one
    for x in xs:
        acc = sr.times(acc, x)
    return acc
viterbi_training.py 139 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/viterbi-training/. The authors are listed in prov/W6039V.jsonl.

"""Viterbi training (segmental k-means) of a discrete hidden Markov model.

lambda = (pi, A, B) with N states 0..N-1 and M symbols 0..M-1:
pi[i] = P(q_1 = i), A[i][j] = P(q_(t+1) = j | q_t = i), B[j][k] = P(o_t = k | q_t = j).

Each round aligns every training sequence with its best state path (the
Viterbi path) and then sets the parameters to the relative frequencies of the
hard counts along those paths. The objective is the sum over the sequences of
max_Q log P(O, Q | lambda), the log joint of the best path. It never decreases.
The total likelihood log P(O | lambda) can decrease; the tests show a case.

Tie rule of the alignment: the smallest state index wins (as on the
viterbi-algorithm page). A row with no counts keeps its old values.
"""

import math
from typing import List, Sequence

from nlslog import NEG_INF, log_sum, safe_log


def viterbi_path(log_pi, log_A, log_B, obs):
    """Return (path, score) of a most likely state path, in log space."""
    N, T = len(log_pi), len(obs)
    delta = [log_pi[j] + log_B[j][obs[0]] for j in range(N)]
    back = [[0] * N]
    for t in range(1, T):
        new, ptr = [], []
        for j in range(N):
            b = 0
            for i in range(1, N):
                if delta[i] + log_A[i][j] > delta[b] + log_A[b][j]:
                    b = i
            ptr.append(b)
            new.append(delta[b] + log_A[b][j] + log_B[j][obs[t]])
        delta = new
        back.append(ptr)
    last = 0
    for j in range(1, N):
        if delta[j] > delta[last]:
            last = j
    path = [last]
    for t in range(T - 1, 0, -1):
        path.append(back[t][path[-1]])
    path.reverse()
    return path, delta[last]


def _logs(m):
    return [[safe_log(p) for p in row] for row in m]


def hard_counts(seqs, paths, N, M):
    """Return the counts (n_pi, n_A, n_B) of starts, transitions and emissions on the paths."""
    n_pi = [0] * N
    n_A = [[0] * N for _ in range(N)]
    n_B = [[0] * M for _ in range(N)]
    for obs, q in zip(seqs, paths):
        n_pi[q[0]] += 1
        for t in range(len(obs)):
            n_B[q[t]][obs[t]] += 1
            if t > 0:
                n_A[q[t - 1]][q[t]] += 1
    return n_pi, n_A, n_B


def normalize_counts(counts, pi, A, B):
    """Return (pi, A, B) as relative frequencies; a row with no counts keeps its old values."""
    n_pi, n_A, n_B = counts

    def norm(row, old):
        s = sum(row)
        return [c / s for c in row] if s > 0 else list(old)

    return norm(n_pi, pi), [norm(r, o) for r, o in zip(n_A, A)], [norm(r, o) for r, o in zip(n_B, B)]


def reestimate(seqs, paths, pi, A, B):
    """Return (pi, A, B) from the hard counts along the given paths."""
    return normalize_counts(hard_counts(seqs, paths, len(pi), len(B[0])), pi, A, B)


def uniform_segmentation_start(seqs, N, M):
    """Return a left-to-right start model from equal segments of each sequence.

    Sequence t = 0..T-1 goes to state floor(N t / T). The transition rows allow
    only a self loop and a move to the next state, so zeros of this topology
    stay zero during training. Every sequence needs at least N frames.
    """
    paths = [[N * t // len(o) for t in range(len(o))] for o in seqs]
    flat_A = [[0.5 if j in (i, i + 1) else 0.0 for j in range(N)] for i in range(N)]
    flat_A[N - 1][N - 1] = 1.0
    flat_B = [[1.0 / M] * M for _ in range(N)]
    pi = [1.0] + [0.0] * (N - 1)
    return reestimate(seqs, paths, pi, flat_A, flat_B)


def viterbi_training(seqs: Sequence[Sequence[int]], pi, A, B, max_rounds: int = 100, tol: float = 1e-12):
    """Run Viterbi training from (pi, A, B).

    Return (pi, A, B, history) where history[k] is the objective F after the
    alignment of round k + 1. Stop when F does not grow by more than tol, or
    after max_rounds rounds. Raise ValueError if a sequence has probability 0.
    """
    pi, A, B = list(pi), [list(r) for r in A], [list(r) for r in B]
    history: List[float] = []
    F_old = NEG_INF  # @line L1
    for _ in range(max_rounds):  # @line L2
        lp, lA, lB = [safe_log(p) for p in pi], _logs(A), _logs(B)
        paths, F = [], 0.0
        for obs in seqs:  # @line L3
            q, s = viterbi_path(lp, lA, lB, obs)
            if s == NEG_INF:
                raise ValueError("a training sequence has probability 0")
            paths.append(q)
            F += s  # @line L4
        history.append(F)
        if F <= F_old + tol:  # @line L5
            break
        F_old = F  # @line L6
        counts = hard_counts(seqs, paths, len(pi), len(B[0]))  # @line L7
        pi, A, B = normalize_counts(counts, pi, A, B)  # @line L8
    return pi, A, B, history  # @line L9


def log_likelihood(seqs, pi, A, B):
    """Return sum over the sequences of log P(O | lambda), by the forward recursion."""
    lp, lA, lB = [safe_log(p) for p in pi], _logs(A), _logs(B)
    N = len(pi)
    total = 0.0
    for obs in seqs:
        a = [lp[j] + lB[j][obs[0]] for j in range(N)]
        for t in range(1, len(obs)):
            a = [log_sum(a[i] + lA[i][j] for i in range(N)) + lB[j][obs[t]] for j in range(N)]
        total += log_sum(a)
    return total
test_viterbi_training.py 158 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/viterbi-training/. The authors are listed in prov/W6039V.jsonl.

import math
import random
from itertools import product

import pytest

from nlslog import safe_log
from viterbi_training import (
    hard_counts,
    log_likelihood,
    reestimate,
    uniform_segmentation_start,
    viterbi_path,
    viterbi_training,
)


def joint(pi, A, B, obs, q):
    s = safe_log(pi[q[0]]) + safe_log(B[q[0]][obs[0]])
    for t in range(1, len(obs)):
        s += safe_log(A[q[t - 1]][q[t]]) + safe_log(B[q[t]][obs[t]])
    return s


def best_brute(pi, A, B, obs):
    N = len(pi)
    return max(joint(pi, A, B, obs, q) for q in product(range(N), repeat=len(obs)))


def objective(seqs, pi, A, B):
    return sum(best_brute(pi, A, B, o) for o in seqs)


def row(rng, n):
    xs = [rng.uniform(0.05, 1.0) for _ in range(n)]
    s = sum(xs)
    return [x / s for x in xs]


def random_hmm(rng, N, M):
    return row(rng, N), [row(rng, N) for _ in range(N)], [row(rng, M) for _ in range(N)]


def logs(m):
    return [[safe_log(p) for p in r] for r in m]


def test_alignment_step_against_brute_force():
    rng = random.Random(1)
    for _ in range(100):
        N, M = rng.randint(1, 3), rng.randint(2, 3)
        pi, A, B = random_hmm(rng, N, M)
        obs = [rng.randrange(M) for _ in range(rng.randint(1, 6))]
        q, s = viterbi_path([safe_log(p) for p in pi], logs(A), logs(B), obs)
        assert s == pytest.approx(best_brute(pi, A, B, obs), abs=1e-9)
        assert joint(pi, A, B, obs, q) == pytest.approx(s, abs=1e-9)


def test_reestimate_maximizes_the_joint_of_fixed_paths():
    rng = random.Random(2)
    for _ in range(30):
        N, M = 2, 3
        pi, A, B = random_hmm(rng, N, M)
        seqs = [[rng.randrange(M) for _ in range(rng.randint(2, 6))] for _ in range(3)]
        paths = [[rng.randrange(N) for _ in o] for o in seqs]
        p2, A2, B2 = reestimate(seqs, paths, pi, A, B)
        best = sum(joint(p2, A2, B2, o, q) for o, q in zip(seqs, paths))
        for _ in range(50):
            p3, A3, B3 = random_hmm(rng, N, M)
            assert sum(joint(p3, A3, B3, o, q) for o, q in zip(seqs, paths)) <= best + 1e-12


def test_counts():
    n_pi, n_A, n_B = hard_counts([[0, 1, 1], [1, 0]], [[0, 0, 1], [1, 1]], 2, 2)
    assert n_pi == [1, 1]
    assert n_A == [[1, 1], [0, 1]]
    assert n_B == [[1, 1], [1, 2]]


def test_objective_never_decreases_and_stops():
    rng = random.Random(3)
    for _ in range(40):
        N, M = rng.randint(2, 3), rng.randint(2, 4)
        pi, A, B = random_hmm(rng, N, M)
        seqs = [[rng.randrange(M) for _ in range(rng.randint(2, 6))] for _ in range(rng.randint(1, 4))]
        _, _, _, hist = viterbi_training(seqs, pi, A, B, max_rounds=200)
        assert len(hist) < 200
        assert all(hist[k + 1] >= hist[k] - 1e-9 for k in range(len(hist) - 1))
        assert hist[0] == pytest.approx(objective(seqs, pi, A, B), abs=1e-9)


def test_rows_sum_to_one():
    rng = random.Random(4)
    pi, A, B = random_hmm(rng, 3, 4)
    seqs = [[rng.randrange(4) for _ in range(8)] for _ in range(5)]
    p2, A2, B2, _ = viterbi_training(seqs, pi, A, B)
    for r in [p2] + A2 + B2:
        assert sum(r) == pytest.approx(1.0, abs=1e-12)
        assert all(0 <= x <= 1 for x in r)


def test_total_likelihood_can_decrease():
    # The example of the page: O = (x, y, x), two states.
    seqs = [[0, 1, 0]]
    pi, A, B = [0.2, 0.8], [[0.5, 0.5], [0.5, 0.5]], [[0.8, 0.2], [0.5, 0.5]]
    p2, A2, B2, hist = viterbi_training(seqs, pi, A, B, max_rounds=1)
    assert math.exp(hist[0]) == pytest.approx(0.04, abs=1e-12)
    assert p2 == [0.0, 1.0] and B2 == [[1.0, 0.0], [0.5, 0.5]]
    assert math.exp(log_likelihood(seqs, pi, A, B)) == pytest.approx(0.1274, abs=1e-12)
    assert math.exp(log_likelihood(seqs, p2, A2, B2)) == pytest.approx(0.09375, abs=1e-12)
    assert math.exp(objective(seqs, p2, A2, B2)) == pytest.approx(0.0625, abs=1e-12)


def sample(rng, pi, A, B, T):
    def draw(p):
        u, c = rng.random(), 0.0
        for i, x in enumerate(p):
            c += x
            if u < c:
                return i
        return len(p) - 1

    q, out = draw(pi), []
    for _ in range(T):
        out.append(draw(B[q]))
        q = draw(A[q])
    return out


def test_learns_a_left_to_right_model():
    rng = random.Random(5)
    pi = [1.0, 0.0, 0.0]
    A = [[0.8, 0.2, 0.0], [0.0, 0.8, 0.2], [0.0, 0.0, 1.0]]
    B = [[0.9, 0.05, 0.05], [0.05, 0.9, 0.05], [0.05, 0.05, 0.9]]
    seqs = [sample(rng, pi, A, B, 20) for _ in range(30)]
    # A start from equal segments learns the model.
    p0, A0, B0 = uniform_segmentation_start(seqs, 3, 3)
    p2, A2, B2, hist = viterbi_training(seqs, p0, A0, B0)
    assert all(hist[k + 1] >= hist[k] - 1e-9 for k in range(len(hist) - 1))
    for j in range(3):
        assert B2[j][j] > 0.85
    assert A2[0][2] == 0.0 and A2[1][0] == 0.0  # zeros of the topology stay zero
    assert abs(A2[0][0] - 0.8) < 0.1 and abs(A2[1][1] - 0.8) < 0.1
    good = hist[-1]
    # A near-flat start gets stuck at a worse fixed point: a local optimum.
    init_A = [[0.5, 0.5, 0.0], [0.0, 0.5, 0.5], [0.0, 0.0, 1.0]]
    init_B = [[0.4, 0.3, 0.3], [0.3, 0.4, 0.3], [0.3, 0.3, 0.4]]
    _, A3, B3, hist3 = viterbi_training(seqs, pi, init_A, init_B)
    assert hist3[-1] < good - 100
    assert A3[0] == [0.0, 1.0, 0.0]


def test_zero_probability_sequence():
    with pytest.raises(ValueError):
        viterbi_training([[1]], [1.0, 0.0], [[1.0, 0.0], [0.0, 1.0]], [[1.0, 0.0], [0.0, 1.0]])

History

Juang and Rabiner 1990 described the segmental k-means algorithm: alternate a Viterbi segmentation of the training data with a k-means clustering of the frames of each state, and re-estimate the model. They showed that it converges in the likelihood of the best state path. The method was already part of the training of speech recognizers at that time, often as the start for Baum-Welch (Rabiner 1989). Gales and Young 2008 describe the alignment step and the re-estimation in the context of modern recognizers.

References

  1. Biing-Hwang Juang and Lawrence R. Rabiner, The segmental K-means algorithm for estimating parameters of hidden Markov models, IEEE Transactions on Acoustics, Speech, and Signal Processing 38(9), 1990, pages 1639 to 1641, the algorithm and its convergence in the best-path likelihood
  2. Lawrence R. Rabiner, A tutorial on hidden Markov models and selected applications in speech recognition, Proceedings of the IEEE 77(2), 1989, pages 257 to 286, the discussion of initial estimates of the HMM parameters by segmental k-means
  3. Mark Gales and Steve Young, The application of hidden Markov models in speech recognition, Foundations and Trends in Signal Processing 1(3), 2008, pages 195 to 304, the chapter on parameter estimation

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example