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.
- Solves
- HMM parameter learning
- 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
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Biing Hwang Juang, Lawrence R. Rabiner, 1990
Viterbi training estimates the parameters 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 over symbols, a number of states , and a start model . Write for the natural log, with . Viterbi training looks for a model with a large value of
the log joint probability of the best state path of each sequence. Compare the objective of Baum-Welch, the total log likelihood , 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 is a table. In a GMM-HMM acoustic model the outputs are feature vectors, and the update of fits a Gaussian mixture to the frames that the paths give to state . 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
VITERBI-TRAINING(O^1 .. O^R, λ, K, tol)- 1
F_old ← -∞ - 2
for round ← 1 to K do - 3
for r ← 1 to R do Q^r, s_r ← VITERBI(λ, O^r) ▷ best path and its log joint - 4
F ← s_1 + ... + s_R - 5
if F ≤ F_old + tol then return λ - 6
F_old ← F - 7
count along Q^1 .. Q^R: n_i starts in i, n_ij steps i → j, c_jk frames in j with symbol k - 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 - 9
return λ
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 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 equal parts, give part to state , and estimate from these paths. The function uniform_segmentation_start of the code does this.
Example
Take states and the symbols . The single training sequence is . The start model has , for all , and , where .
Round 1. The transitions are uniform, so the best path takes the best state at each frame: state 2 first, because , then state 2 for (), then state 1 for (). The path has . The counts are one start in state 2, the steps and , the emissions in state 2 and in state 1. So , row 2 of becomes , row 1 has no counts and keeps , and .
Round 2. The best path is again , now with . The counts are the same, so the model does not change.
Round 3. The objective is again , so line L5 stops. The values of were , and .
The total likelihood went the other way. Under the start model , and under the final model . 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 , the log joint splits into one term for each row of , and . By Gibbs' inequality, the relative frequencies of line L8 maximize each term, so they maximize . This is a theorem. Then
because is a maximum over paths. So 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 .
Proof: Viterbi training never lowers the best-path likelihood and stopsfull
We use the notation of the page: a discrete HMM with states and symbols, and training sequences . All logs are natural logs, and . For a tuple of state paths , one path per sequence, write
Round of the algorithm starts with the model . Lines L3 and L4 compute a tuple of Viterbi paths and . The Viterbi algorithm returns a best path (see the viterbi-algorithm page), so . If the round does not stop at line L5, lines L7 and L8 set to the relative frequencies of the counts along .
Lemma 1 (the update step). For a fixed tuple , the relative frequencies of lines L7 and L8 maximize over all models . A row with no counts may take any value without changing .
Proof. Let be the number of paths that start in , the number of steps and the number of frames in state with the symbol . Then
The rows , and appear in separate terms, and each term has the form with counts and a distribution . If , Gibbs' inequality gives , with equality at . If the term is for every .
Theorem 1 (monotone objective). for every round that updates the model.
Proof. . The first inequality is the definition of , and the second is Lemma 1.
Write . The proof of Theorem 1 also gives the sandwich
Theorem 2 (termination). In exact arithmetic with tol , the algorithm stops after finitely many rounds. If is the number of tuples of state paths, at most rounds update the model.
Proof. A round updates the model only if , so the values strictly increase along the rounds that update the model. Assume that two updating rounds have . By (S), . If , then , which is false. So . Then comes from the same counts as . The relative frequencies are the same, and a row with no counts keeps the value of , so . Then and round 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 tuples, which is finite.
With tol or with the round limit, the code stops no later. In floating point the values are rounded, so Theorem 1 holds up to rounding errors; the tests allow .
Proposition (the total likelihood can go down). Theorem 1 is about , the log likelihood of the best path. The total log likelihood can decrease in a round.
Proof by example. Take , with the symbols , one sequence , , for all , and . With uniform transitions, the best path takes the state of largest at the first frame and of largest later: , with . The total is . The counts on give , , row 1 of unchanged, and . Now every path starts in state 2, so , while the best path has . The test test_total_likelihood_can_decrease checks these numbers.
Complexity
A round runs the Viterbi algorithm on each sequence, which takes time for a sequence of frames, and counts along the paths in time. With frames in total, a round takes time and rounds take . The normalization adds per round. A left-to-right model with a self loop and one move per state takes time per round, as in forced alignment.
The back pointers of one sequence take space, the paths take and the model and the counts take . The bound in the front matter allows all back pointers at once.
A Baum-Welch round also takes 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. never decreases (a theorem). The total likelihood 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 .
- 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.
# 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag W6039V Edit this page History Report an error Markdown