Algorithmadvanced
MAP speaker adaptation
Also called maximum a posteriori adaptation, Gauvain-Lee adaptation.
Adapt acoustic model parameters by MAP estimation with the speaker-independent model as prior, so well-observed Gaussians move most.
- Time
- O(k T M n) worst
- Space
- O(M n) extra
- Where
- M = the number of Gaussians; T = the number of adaptation frames; k = the number of EM iterations; n = the feature dimension
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jean Luc Gauvain, Chin Hui Lee, 1994
MAP speaker adaptation moves the Gaussians of a speaker independent model toward the data of one speaker, and it uses the old model as a prior. Each new mean is a weighted average of the old mean and the mean of the data assigned to that Gaussian, . A Gaussian that saw much data moves almost to the data mean, and a Gaussian that saw none stays where it was. With more and more data, the result tends to the speaker dependent maximum likelihood model.
In plain words
A speech model stores many small averages, each one describing a sound piece. You get some speech from a new speaker, and you want to move each average toward how this speaker sounds.
For each average, look at the speech that matches it, and count how much there is. If there is a lot, trust the new speech and move the average almost all the way to it. If there is a little, move it only a little. If there is none, leave it. A single number controls how much speech counts as "a lot".
This is a cautious kind of learning: the old model is the starting belief, and the new speech changes it in proportion to the evidence.
The problem
The prior model is a mixture of Gaussians, or the Gaussians of the states of a GMM-HMM acoustic model. Gaussian has the weight , the mean and the diagonal covariance . The input is frames of the target speaker, with a transcript in the HMM case. The prior on the means is
with one constant . A large means a tight prior. The task is to find the means that maximize the posterior with the weights and covariances fixed. Gauvain and Lee 1994 solve the more general problem in which the weights and the covariances have priors too.
The algorithm
MAP-EM is EM with a penalty from the prior. The E-step is the same as in maximum likelihood EM. The M-step mixes the prior mean with the statistics.
MAP-ADAPT(O, c, μ⁰, Σ, τ, iters)- 1
μ_m ← μ⁰_m for every m - 2
repeat iters times - 3
γ_m(t) ← c_m N(o_t; μ_m, Σ_m) / Σ_j c_j N(o_t; μ_j, Σ_j) for every t, m ▷ in log space - 4
n_m ← Σ_t γ_m(t), s_m ← Σ_t γ_m(t) o_t - 5
μ_m ← (τ μ⁰_m + s_m) / (τ + n_m) - 6
return μ
Line L5 always shrinks toward the prior mean , not toward the mean of the last iteration. Write and . Then line L5 is
the form of Reynolds, Quatieri and Dunn 2000, who call the relevance factor . In practice one iteration is common, mainly in speaker verification. In an HMM system the posteriors of line L3 come from the forward-backward algorithm over the transcript.
Example
One Gaussian. Take , , , and data whose mean is . Every frame belongs to the one Gaussian, so :
| frames | ||
|---|---|---|
| 4 | 0.2 | 0.4 |
| 16 | 0.5 | 1.0 |
| 64 | 0.8 | 1.6 |
At the new mean is halfway between the prior and the data. So acts as a number of "virtual frames" of prior data.
Two Gaussians. Take , , , and the four frames . The posterior of Gaussian 2 at frame is :
| frame | 0.5 | 1.5 | 2.5 | 3.0 |
|---|---|---|---|---|
| 0.731059 | 0.952574 | 0.993307 | 0.997527 |
So and . The new means are:
| 16 | 0.019940 | -0.965986 | 0.186763 | 1.182763 |
| 2 | 0.139982 | -0.761219 | 0.647544 | 1.633676 |
Gaussian 2 has most of the data and moves much more than Gaussian 1. With , the means would be the data means , which is one step of maximum likelihood EM.
Correctness
The proof is in proofs/correctness.md. For fixed posteriors, the expected complete-data log likelihood plus the log prior separates over the Gaussians and the coordinates. Each part is a strictly concave quadratic in one coordinate of one mean, and its maximizer is line L5. The Jensen argument of EM then shows that each iteration does not decrease the log posterior . For one Gaussian the result is the exact posterior mean of a Gaussian mean with a Gaussian conjugate prior. For a mixture, MAP-EM finds a stationary point, which can be a local maximum.
Proof: The MAP mean update maximizes the penalized auxiliary function and never lowers the log posteriorfull
We use the notation of the page. The prior model is a mixture of Gaussians with weights , means and diagonal covariances . The weights and the covariances are fixed. The unknown means have the prior
The data are the frames , and . MAP estimation maximizes the log posterior up to a constant, . All logs are natural logs.
Fix the current means . Let be the posterior of Gaussian at frame under them (line L3), and let and (line L4). The penalized auxiliary function is
Lemma 1 (the M-step). has the unique maximizer for every , the update of line L5.
Proof. Collect the terms of that depend on coordinate of . With diagonal covariances they are
and no other term depends on . The second derivative is , so is strictly concave, and its maximum is where the derivative is zero:
Theorem 2 (MAP-EM is monotone). Let be the means of line L5 computed from the posteriors of . Then .
Proof. Write , so that is a distribution over . By Jensen's inequality for the concave log, for any ,
Sum over and add to both sides: . By Lemma 1, .
So the iteration of lines L2 to L5 climbs the posterior, and at a fixed point the gradient of is zero. Like any EM, it can stop at a local maximum.
Proposition 3 (one Gaussian: the exact posterior). If , then for every frame, and the update is the mean of the exact posterior distribution of , which is
Proof. The prior is Gaussian and the likelihood of a Gaussian mean with a known covariance is Gaussian in the mean, so the posterior is Gaussian (conjugate prior). Its precision is the sum of the prior precision and the data precision , and its mean is the precision weighted average of and the sample mean : . One update with and gives the same value, and further iterations do not change it, because the posteriors stay 1.
For the posterior of the means is a mixture over all assignments of frames to Gaussians, and the MAP-EM result is only a mode of it.
Proposition 4 (the relevance factor form). With and for , the form of Reynolds, Quatieri and Dunn, , equals one step of line L5 with .
Proof. . For both forms give .
Remark (what is not claimed). Gauvain and Lee 1994 also place a Dirichlet prior on the weights and a normal-Wishart prior on the means and precisions jointly, and give EM updates for all of them. The weight and variance updates of Reynolds et al. 2000 are a one-step heuristic with the same form; they are not shown here to be the maximizer of a posterior. The value is a choice made on development data, not a result.
Complexity
In the real RAM, line L3 evaluates Gaussians of dimension at each of frames, , and line L4 costs the same. Line L5 costs . With iterations the time is . The extra memory is for the statistics; the posteriors are added frame by frame and need not be stored. In a large system, most of the time goes into the E-step, as in ML training.
Properties
- Asymptotic behavior. As with fixed, and the MAP mean tends to the ML mean. For an infinite amount of data, MAP adaptation and ML training agree.
- Local update. Only Gaussians with data move. This is the main difference from MLLR, where a shared transform moves every Gaussian of a class. With little data MLLR is better, and with much data MAP is better; Gales and Young 2008 describe this trade-off.
- A heuristic constant. The relevance factor of Reynolds et al. 2000 was chosen by experiment, and other systems tune the value on development data. It is a heuristic, not a result of the theory.
- Monotone MAP-EM. Each iteration does not decrease the log posterior (Theorem 2 of the proof).
- Aligned components. The adapted model keeps the order and the meaning of the components of the prior model. This makes MAP-adapted models easy to compare: the stacked adapted means form a fixed-length "GMM supervector" for each speaker. The i-vector extractor uses the same statistics and .
Variants and improvements
- Weights and variances. Reynolds et al. 2000 also adapt the weights, with chosen so that the weights sum to 1, and the variances, per dimension. In their speaker verification experiments, adapting only the means gave the best results; this is a measurement on their data. The code implements both forms.
- Separate factors. Use a separate for the weights, the means and the variances, as in the general Gauvain and Lee formulas.
- MAP on top of MLLR. Use the MLLR-adapted model as the prior mean, so that unseen Gaussians also move, and refine the Gaussians with much data by MAP.
- Joint factor analysis and eigenvoices. Constrain the supervector of adapted means to a low-dimensional subspace. With little data, this moves all Gaussians in a coordinated way. The i-vector model is the later form of this idea.
When to use it
Use MAP adaptation when the target speaker or condition has enough data to see most Gaussians several times, for example minutes of speech for a GMM-HMM recognizer, or when the model must keep the components of the prior model aligned, as in GMM-UBM speaker verification. With only a few seconds of data, use MLLR or another transform with few parameters, or combine the two.
Pitfalls
- Shrinking toward the wrong mean. Line L5 shrinks toward the prior mean at every iteration. Shrinking toward the last iterate makes the prior weaker at each step.
- Too small a relevance factor. With near 0, a Gaussian that saw one or two frames jumps to them. The model then fits noise, and its variance is no longer correct for the new mean.
- Posteriors from the wrong model. In speaker verification, the posteriors come from the universal background model. In iterative MAP-EM, they come from the current adapted model. Mixing the two changes the result.
- Variance adaptation without a floor. The adapted variance formula subtracts and can give values near 0 with very little data. Floor the variances.
- Products of densities. Compute the posteriors of line L3 in log space with the log-sum-exp trick; densities of frames far from every mean are 0 in double precision.
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
# Part of https://algorithm.tamnd.com/map-speaker-adaptation/. The authors are listed in prov/TAZK46.jsonl.
"""MAP adaptation of the means of a Gaussian mixture (Gauvain and Lee 1994).
The prior model is a mixture of M Gaussians with diagonal covariances: weights
c[m], means mu0[m] and variances var[m]. The prior on the mean of Gaussian m is
N(mu0[m], var[m] / tau), independent over m, and the weights and variances are
fixed. One EM step of MAP estimation is
mu_m = (tau mu0_m + sum_t gamma_m(t) o_t) / (tau + sum_t gamma_m(t)),
where gamma_m(t) is the posterior of Gaussian m at frame t under the current
means. map_adapt iterates this step; one step is the usual practice.
reynolds_adapt is the one-step form of Reynolds, Quatieri and Dunn 2000, which
also adapts the weights and the variances with the coefficient
alpha_m = n_m / (n_m + r) for a relevance factor r. For the means it gives the
same value as one step of map_adapt with tau = r.
Every log is the natural log. Posteriors are computed in log space.
"""
import math
from typing import List, Sequence, Tuple
from nlslog import log_sum
Vector = List[float]
Matrix = List[List[float]]
LOG_2PI = math.log(2.0 * math.pi)
def log_gauss_diag(x: Sequence[float], mu: Sequence[float], var: Sequence[float]) -> float:
"""Return log N(x; mu, diag(var))."""
s = 0.0
for xi, mi, vi in zip(x, mu, var):
s += LOG_2PI + math.log(vi) + (xi - mi) * (xi - mi) / vi
return -0.5 * s
def posteriors(frame: Sequence[float], weights: Sequence[float], means: Sequence[Sequence[float]],
variances: Sequence[Sequence[float]]) -> Tuple[Vector, float]:
"""Return (gamma, log p(frame)) for a diagonal Gaussian mixture."""
lp = [math.log(w) + log_gauss_diag(frame, m, v) if w > 0 else float("-inf")
for w, m, v in zip(weights, means, variances)]
z = log_sum(lp)
return [math.exp(x - z) for x in lp], z
def statistics(frames: Sequence[Sequence[float]], weights: Sequence[float], means: Sequence[Sequence[float]],
variances: Sequence[Sequence[float]]) -> Tuple[Vector, Matrix, Matrix, float]:
"""Return (n, s, q, log likelihood): n_m = sum gamma, s_m = sum gamma o, q_m = sum gamma o^2 per dimension."""
M, d = len(means), len(means[0])
n = [0.0] * M
s = [[0.0] * d for _ in range(M)]
q = [[0.0] * d for _ in range(M)]
ll = 0.0
for o in frames:
g, z = posteriors(o, weights, means, variances) # @line L3
ll += z
for m in range(M):
gm = g[m]
if gm > 0.0:
n[m] += gm # @line L4
for i in range(d):
s[m][i] += gm * o[i]
q[m][i] += gm * o[i] * o[i]
return n, s, q, ll
def map_means(mu0: Sequence[Sequence[float]], n: Sequence[float], s: Sequence[Sequence[float]], tau: float) -> Matrix:
"""Return mu_m = (tau mu0_m + s_m) / (tau + n_m). Needs tau > 0 or n_m > 0."""
out = []
for m in range(len(mu0)):
den = tau + n[m]
if den <= 0.0:
raise ValueError("tau + n_m must be positive")
out.append([(tau * a + b) / den for a, b in zip(mu0[m], s[m])]) # @line L5
return out
def log_prior(means: Sequence[Sequence[float]], mu0: Sequence[Sequence[float]],
variances: Sequence[Sequence[float]], tau: float) -> float:
"""Return sum_m log N(mu_m; mu0_m, diag(var_m) / tau)."""
return math.fsum(log_gauss_diag(mu, m0, [v / tau for v in var]) for mu, m0, var in zip(means, mu0, variances))
def map_adapt(frames: Sequence[Sequence[float]], weights: Sequence[float], mu0: Sequence[Sequence[float]],
variances: Sequence[Sequence[float]], tau: float, iterations: int = 1) -> Tuple[Matrix, List[float]]:
"""Run MAP-EM on the means. Return (means, objective values).
The objective is log p(frames | means) + log prior(means), given before
each iteration and after the last one (tau > 0 for the prior term).
"""
means = [list(map(float, m)) for m in mu0] # @line L1
history = []
for _ in range(iterations): # @line L2
n, s, _, ll = statistics(frames, weights, means, variances)
history.append(ll + log_prior(means, mu0, variances, tau))
means = map_means(mu0, n, s, tau)
ll = statistics(frames, weights, means, variances)[3]
history.append(ll + log_prior(means, mu0, variances, tau))
return means, history # @line L6
def reynolds_adapt(frames: Sequence[Sequence[float]], weights: Sequence[float], means: Sequence[Sequence[float]],
variances: Sequence[Sequence[float]], r: float = 16.0, adapt: str = "wmv",
var_floor: float = 1e-6) -> Tuple[Vector, Matrix, Matrix]:
"""One-step adaptation of weights (w), means (m) and variances (v) with alpha_m = n_m / (n_m + r).
Return (weights, means, variances); the parts not named in adapt stay.
"""
T = len(frames)
M, d = len(means), len(means[0])
n, s, q, _ = statistics(frames, weights, means, variances)
alpha = [n[m] / (n[m] + r) if n[m] + r > 0 else 0.0 for m in range(M)]
new_w = list(weights)
if "w" in adapt:
raw = [alpha[m] * n[m] / T + (1.0 - alpha[m]) * weights[m] for m in range(M)]
z = math.fsum(raw)
new_w = [x / z for x in raw]
new_mu = [list(mu) for mu in means]
new_var = [list(v) for v in variances]
for m in range(M):
if n[m] <= 0.0:
continue
E = [x / n[m] for x in s[m]]
E2 = [x / n[m] for x in q[m]]
mu_hat = [alpha[m] * E[i] + (1.0 - alpha[m]) * means[m][i] for i in range(d)]
if "m" in adapt:
new_mu[m] = mu_hat
if "v" in adapt:
# Reynolds et al. 2000: the second moment is interpolated, then the square of the adapted mean is removed.
new_var[m] = [max(var_floor, alpha[m] * E2[i] + (1.0 - alpha[m]) * (variances[m][i] + means[m][i] ** 2)
- mu_hat[i] ** 2) for i in range(d)]
return new_w, new_mu, new_var
nlslog.py 152 lines
# 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
test_map_speaker_adaptation.py 166 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/map-speaker-adaptation/. The authors are listed in prov/TAZK46.jsonl.
import math
import random
from fractions import Fraction as F
import pytest
from map_speaker_adaptation import (
log_gauss_diag,
log_prior,
map_adapt,
map_means,
posteriors,
reynolds_adapt,
statistics,
)
def mixture(rng, weights, means, variances, T):
out = []
for _ in range(T):
u, m, acc = rng.random(), 0, weights[0]
while u > acc and m < len(weights) - 1:
m += 1
acc += weights[m]
out.append([rng.gauss(mu, math.sqrt(v)) for mu, v in zip(means[m], variances[m])])
return out
def test_one_gaussian_exact_values():
# Prior mean 0, data mean 2, tau = 16: n = 4, 16, 64 give alpha = 1/5, 1/2, 4/5.
for n, want in ((4, F(2, 5)), (16, F(1)), (64, F(8, 5))):
(mu,) = map_means([[F(0)]], [F(n)], [[F(2 * n)]], F(16))
assert mu[0] == want
def test_one_gaussian_is_the_conjugate_posterior_mean():
rng = random.Random(1)
var, mu0, tau = 2.5, 1.0, 7.0
xs = [rng.gauss(3.0, math.sqrt(var)) for _ in range(20)]
means, _ = map_adapt([[x] for x in xs], [1.0], [[mu0]], [[var]], tau, iterations=1)
# Posterior of a normal mean with known variance: precisions add.
prior_prec, data_prec = tau / var, len(xs) / var
want = (prior_prec * mu0 + data_prec * (sum(xs) / len(xs))) / (prior_prec + data_prec)
assert means[0][0] == pytest.approx(want, abs=1e-12)
def test_page_example_two_components():
frames = [[0.5], [1.5], [2.5], [3.0]]
w, mu0, var = [0.5, 0.5], [[-1.0], [1.0]], [[1.0], [1.0]]
n, s, _, _ = statistics(frames, w, mu0, var)
assert n[0] == pytest.approx(0.325533, abs=1e-6)
assert n[1] == pytest.approx(3.674467, abs=1e-6)
m16 = map_means(mu0, n, s, 16.0)
m2 = map_means(mu0, n, s, 2.0)
assert [m16[0][0], m16[1][0]] == pytest.approx([-0.965986, 1.182763], abs=1e-6)
assert [m2[0][0], m2[1][0]] == pytest.approx([-0.761219, 1.633676], abs=1e-6)
def test_limits_of_tau():
rng = random.Random(2)
w = [0.3, 0.7]
mu0 = [[0.0, 0.0], [3.0, 1.0]]
var = [[1.0, 0.5], [0.7, 1.2]]
frames = mixture(rng, w, [[0.5, 0.2], [2.5, 1.5]], var, 60)
n, s, _, _ = statistics(frames, w, mu0, var)
ml = [[x / n[m] for x in s[m]] for m in range(2)]
assert map_means(mu0, n, s, 0.0) == [pytest.approx(row, abs=1e-12) for row in ml]
big = map_means(mu0, n, s, 1e12)
for a, b in zip(big, mu0):
assert a == pytest.approx(b, abs=1e-9)
def test_map_em_never_decreases_the_log_posterior():
rng = random.Random(3)
w = [0.25, 0.25, 0.25, 0.25]
mu0 = [[-2.0, 0.0], [2.0, 0.0], [0.0, 2.0], [0.0, -2.0]]
var = [[1.0, 1.0], [0.8, 1.0], [1.0, 0.6], [1.2, 1.0]]
frames = mixture(rng, w, [[-1.0, 1.0], [3.0, 0.5], [0.5, 3.0], [0.0, -1.0]], var, 150)
_, hist = map_adapt(frames, w, mu0, var, tau=4.0, iterations=12)
for a, b in zip(hist, hist[1:]):
assert b >= a - 1e-9
assert hist[-1] > hist[0]
def test_m_step_is_a_stationary_point_of_the_auxiliary_function():
rng = random.Random(4)
w = [0.5, 0.5]
mu0 = [[0.0, 1.0], [2.0, -1.0]]
var = [[1.0, 2.0], [0.5, 1.0]]
tau = 3.0
frames = mixture(rng, w, mu0, var, 40)
gam = [posteriors(o, w, mu0, var)[0] for o in frames]
n, s, _, _ = statistics(frames, w, mu0, var)
new = map_means(mu0, n, s, tau)
def objective(means):
q = math.fsum(g[m] * log_gauss_diag(o, means[m], var[m]) for o, g in zip(frames, gam) for m in range(2))
return q + log_prior(means, mu0, var, tau)
h = 1e-6
best = objective(new)
for m in range(2):
for i in range(2):
up = [row[:] for row in new]
dn = [row[:] for row in new]
up[m][i] += h
dn[m][i] -= h
assert abs((objective(up) - objective(dn)) / (2 * h)) < 1e-5
up[m][i] += 0.1
assert objective(up) < best
def test_reynolds_adapt():
rng = random.Random(5)
w = [0.2, 0.5, 0.3]
mu = [[-2.0], [0.0], [3.0]]
var = [[1.0], [0.5], [2.0]]
frames = mixture(rng, w, [[-1.5], [0.5], [3.0]], [[1.2], [0.4], [1.5]], 80)
n, s, q, _ = statistics(frames, w, mu, var)
# Weights sum to 1 and the means agree with one MAP step with tau = r.
nw, nm, nv = reynolds_adapt(frames, w, mu, var, r=16.0)
assert math.fsum(nw) == pytest.approx(1.0, abs=1e-12)
assert nm == [pytest.approx(row, abs=1e-12) for row in map_means(mu, n, s, 16.0)]
assert all(v[0] > 0 for v in nv)
# r = 0 gives the maximum likelihood re-estimate of one EM step.
w0, m0, v0 = reynolds_adapt(frames, w, mu, var, r=0.0)
T = len(frames)
for m in range(3):
assert w0[m] == pytest.approx(n[m] / T, abs=1e-12)
E = s[m][0] / n[m]
assert m0[m][0] == pytest.approx(E, abs=1e-12)
assert v0[m][0] == pytest.approx(q[m][0] / n[m] - E * E, abs=1e-9)
# A huge r leaves the model unchanged.
wb, mb, vb = reynolds_adapt(frames, w, mu, var, r=1e12)
assert wb == pytest.approx(w, abs=1e-9)
assert [x[0] for x in mb] == pytest.approx([x[0] for x in mu], abs=1e-9)
assert [x[0] for x in vb] == pytest.approx([x[0] for x in var], abs=1e-6)
# Only the named parts change.
ww, wm, wv = reynolds_adapt(frames, w, mu, var, r=16.0, adapt="m")
assert ww == w and wv == var
def test_component_without_data_keeps_its_prior_mean():
frames = [[0.0], [0.1], [-0.1]]
w = [0.5, 0.5]
mu0 = [[0.0], [1000.0]]
var = [[1.0], [1.0]]
means, _ = map_adapt(frames, w, mu0, var, tau=16.0)
assert means[1][0] == pytest.approx(1000.0, abs=1e-9)
def test_log_space_where_plain_densities_underflow():
w = [0.5, 0.5]
mu0 = [[0.0], [10.0]]
var = [[1.0], [1.0]]
x = [-900.0]
assert [wi * math.exp(-0.5 * (x[0] - m[0]) ** 2) for wi, m in zip(w, mu0)] == [0.0, 0.0]
g, z = posteriors(x, w, mu0, var)
assert g[0] == pytest.approx(1.0) and g[1] < 1e-300
assert math.isfinite(z)
means, _ = map_adapt([x], w, mu0, var, tau=1.0)
assert means[0][0] == pytest.approx(-450.0, abs=1e-9)
assert means[1][0] == pytest.approx(10.0, abs=1e-9)
History
Gauvain and Lee 1994 gave the MAP estimate of the parameters of Gaussian mixture HMMs, with Dirichlet priors on the weights and normal-Wishart priors on the means and precisions, and EM updates for all of them. They used it for speaker adaptation and for training with little data. Reynolds, Quatieri and Dunn 2000 made the one-step mean update with a relevance factor the standard way to build speaker models from a universal background model. Joint factor analysis and the i-vector model later replaced the free per-Gaussian update with a low-dimensional one for speaker recognition.
References
- Jean-Luc Gauvain and Chin-Hui Lee, Maximum a posteriori estimation for multivariate Gaussian mixture observations of Markov chains, IEEE Transactions on Speech and Audio Processing 2(2), 1994, pages 291 to 298, the choice of the Dirichlet and normal-Wishart priors and the EM re-estimation formulas for the weights, means and covariances
- Douglas A. Reynolds, Thomas F. Quatieri and Robert B. Dunn, Speaker verification using adapted Gaussian mixture models, Digital Signal Processing 10(1-3), 2000, pages 19 to 41, the section on the adapted speaker model (the data-dependent adaptation coefficients and the relevance factor)
- 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 adaptation and normalization
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 TAZK46 Edit this page History Report an error Markdown