Algorithmadvanced
Maximum likelihood linear regression
Also called MLLR, MLLR mean adaptation.
Adapt Gaussian means of an acoustic model to a speaker by affine maps shared over classes of Gaussians, fit by EM on little data.
- Time
- O(k (T M n + M n^3 + R n^4)) worst
- Space
- O(M n + R n^2) extra
- Where
- M = the number of Gaussians; R = the number of regression classes; 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
- Christopher J. Leggetter, Philip C. Woodland, 1995
Maximum likelihood linear regression (MLLR) adapts a speaker independent acoustic model to a new speaker with a small amount of speech. It replaces each Gaussian mean by , where one affine map is shared by a whole class of Gaussians, and it fits the map by maximum likelihood with the EM algorithm. Because the map is shared, Gaussians that saw no adaptation data also move. With diagonal covariances, each row of the map is the solution of a small weighted least squares problem, so the M-step is closed form.
In plain words
A speech recognizer stores, for each small piece of each sound, an average of what that piece looks like. These averages come from many speakers. A new speaker sounds a bit different, and the error rate goes up. You have a few sentences from the new speaker, much too little to learn every average again.
The idea is to assume that the new speaker shifts and stretches all the averages in the same way. Learn one such shift and stretch from the few sentences, and apply it to every average, even to the sounds that the speaker did not say. With more data, use a few separate shifts, one for each group of similar sounds, for example one for the vowels and one for the consonants.
The problem
The model has Gaussians, for example the Gaussians of all HMM states of a GMM-HMM acoustic model. Gaussian has the mean and the diagonal covariance . Each Gaussian belongs to one of regression classes, . The input is a sequence of adaptation frames of the new speaker, usually with a transcript (supervised adaptation) or with the output of a first recognition pass (unsupervised adaptation).
Write the extended mean . For each class , the unknown is an matrix , and the adapted mean is
The task is to find the transforms that maximize the likelihood of the adaptation data under the model with the adapted means. The weights, the transitions and the covariances stay as they are.
The algorithm
EM alternates between the posteriors of each Gaussian at each frame (the E-step) and a new set of transforms (the M-step). The M-step needs only two statistics per Gaussian, the occupancy and the first-order sum . With diagonal covariances, row of , written , maximizes a separate quadratic function, and its maximizer solves the system with
MLLR(O, μ, σ², class, iters) ▷ μ: speaker independent means, ξ_m = (1, μ_m)- 1
W_r ← [0 | I] for r = 1 .. R ▷ start from the unchanged model - 2
repeat iters times - 3
μ̂_m ← W_{r(m)} ξ_m for every m - 4
γ_m(t) ← posterior of Gaussian m at frame t under the means μ̂ ▷ E-step, in log space - 5
occ_m ← Σ_t γ_m(t), s_m ← Σ_t γ_m(t) o_t - 6
for each class r and each row i = 1 .. n do ▷ M-step - 7
G ← Σ_{m in r} (occ_m / σ²_{m,i}) ξ_m ξ_mᵀ, k ← Σ_{m in r} (s_{m,i} / σ²_{m,i}) ξ_m - 8
w_{r,i} ← the solution of G w = k - 9
return W_1 .. W_R
Line L3 always starts from the speaker independent means , not from the means of the last iteration. The posteriors of line L4 come from the current adapted model: in a Gaussian mixture they are the component posteriors, and in an HMM system they come from the forward-backward algorithm over the transcript. Many systems run only one or two iterations.
Example
Take and one class with four Gaussians, all with . The speaker independent means are . The E-step gave these statistics:
| Gaussian | data mean | |||
|---|---|---|---|---|
| 1 | 0 | 4 | 4 | 1 |
| 2 | 1 | 2 | 4 | 2 |
| 3 | 3 | 2 | 16 | 8 |
| 4 | 2 | 0 | 0 | none |
With , the system of line L7 is
The determinant is , so and . The adapted means are :
| Gaussian | 1 | 2 | 3 | 4 |
|---|---|---|---|---|
| 0.6667 | 3 | 7.6667 | 5.3333 |
This is a weighted least squares line through the points with the weights . The weighted squared error falls from 56 for the unchanged means to . A shift alone, , gives and an error of 24. Gaussian 4 saw no data, but it moves from 2 to 5.3333, because it shares the transform. MAP adaptation would leave it at 2.
Correctness
The proof is in proofs/correctness.md. With diagonal covariances, the EM auxiliary function is a constant minus one half of a sum of quadratic forms , one for each class and row, in disjoint variables. Each is positive semidefinite, and it is positive definite exactly when the class has affinely independent means with nonzero occupancy. Then line L8 gives the unique maximizer of the auxiliary function, and the usual EM argument (Jensen's inequality) shows that the likelihood of the adaptation data does not decrease from one iteration to the next. EM reaches a stationary point, not always the global maximum.
Proof: The MLLR update maximizes the EM auxiliary function and never lowers the likelihoodfull
We use the notation of the page. There are Gaussians with speaker independent means , diagonal covariances with , and mixture weights . Gaussian belongs to the regression class . The extended mean is . A set of transforms , each of size , gives the adapted means . Row of is , so . All logs are natural logs. Write for the likelihood of the frames under the mixture with the adapted means; the weights and covariances do not change.
Fix the current transforms and let be the posterior of Gaussian at frame under them, as in line L4. Let and , as in line L5. The auxiliary function is
Lemma 1 (the auxiliary function separates by rows). There is a constant that does not depend on such that
with and , the matrices of line L7.
Proof. With a diagonal covariance,
The terms , and do not depend on ; they go into . What is left is
Put , so , and group the Gaussians by class.
Each pair owns its own vector , and no other term of the sum depends on it. So is a sum of quadratic functions in disjoint variables, and it is maximized by maximizing each one alone.
Lemma 2 (when the system has one solution). Each is symmetric and positive semidefinite. It is positive definite if and only if the extended means of the Gaussians of class with span . This holds if and only if these Gaussians include means that are affinely independent.
Proof. For , , and each weight is positive when . The sum is 0 exactly when is orthogonal to every with . Such a nonzero exists if and only if these do not span . Finally, the vectors span if and only if the points are not all in one affine hyperplane, that is, if and only if of them are affinely independent.
The condition does not depend on . If it fails, line L8 meets a singular system, and the code raises an error. A recognizer then uses a smaller set of classes, so that each class has enough data.
Theorem 1 (the M-step). If every is positive definite, the transforms of line L8, , are the unique maximizer of .
Proof. By Lemma 1 it is enough to maximize for each pair, with positive definite by Lemma 2. Let . For any , with ,
which one checks by expanding both sides and using . The last term is negative unless .
Theorem 2 (the likelihood does not decrease). Let be the transforms of line L8, computed from the statistics of . Then .
Proof. Write . For each frame, is a probability distribution over . For any , by the concavity of log (Jensen's inequality),
Sum over : . The old transforms are one of the candidates over which line L8 maximizes, because the old means are with the same . So by Theorem 1, and the right side is at least 0 for .
The argument needs that each iteration estimates the transform from the speaker independent means , with the posteriors of the current adapted model. It is the same in an HMM system, where is the posterior of state and Gaussian from the forward-backward algorithm and the sum over in the proof is a sum over state sequences and Gaussians.
Remark (what is not claimed). EM converges to a stationary point of the likelihood, which need not be the global maximum. With full covariances, the rows do not separate, because the quadratic form couples all coordinates of ; the maximizer then solves one linear system in all entries of at once. In floating point, Gaussian elimination with partial pivoting gives the solution of a nearby system, so the computed satisfies Theorem 1 only up to rounding.
Complexity
In the real RAM, one E-step evaluates diagonal Gaussians at each of frames, , and the statistics cost the same. For each Gaussian, the outer product is added into matrices with different scales, , so the matrices cost . The systems of size cost each by Gaussian elimination, so . With iterations the total is . In a real system dominates: for the solves are about operations per class, which is small next to the E-step over thousands of Gaussians.
The extra memory is for the statistics and the adapted means and for the transforms. The statistics are added frame by frame, so the posteriors need not be stored.
Properties
- Shared parameters. A global transform has parameters, 1560 for , against means. This is why MLLR works with a few sentences.
- Unseen Gaussians move. Every Gaussian of a class moves with the class, as Gaussian 4 of the example shows.
- Closed form M-step. For diagonal covariances each row is one linear solve. For full covariances the rows are coupled, and the M-step is one larger system.
- Monotone EM. The likelihood of the adaptation data never goes down (Theorem 2 of the proof).
- No limit at large data. With a fixed number of classes, more data does not make MLLR as good as a speaker dependent model, because the transform has a fixed number of parameters. More classes help, up to the data that each class can support.
- Measured gain. Leggetter and Woodland 1995 report, in the abstract, a 37% reduction in word error rate with supervised adaptation and 32% with unsupervised adaptation, on the ARPA Resource Management (RM1) data with 40 adaptation sentences, relative to the speaker independent model. This is a measurement on that task.
Variants and improvements
- Regression class trees. Cluster the Gaussians into a binary tree by the closeness of their means. Walk the tree, and give a node its own transform only if its occupancy is above a threshold; otherwise use the transform of the parent. The number of transforms then grows with the amount of data.
- Block diagonal and diagonal transforms. For features with static, delta and delta-delta parts, a block diagonal with three blocks has fewer parameters. A diagonal is a per-dimension scale and shift.
- Bias only. gives a shift of all means, the model-space counterpart of cepstral mean normalization.
- Variance MLLR. A second transform adapts the covariances, estimated after the means.
- Constrained MLLR (CMLLR). Gales 1998 uses the same matrix for the mean and the covariance: and . This is the same as a transform of the features, with , plus the Jacobian term in the likelihood. There is no closed form; each row is updated in turn by solving a quadratic equation, and the process is iterated. Because it acts on features, it is also called feature-space MLLR (fMLLR), and it is used to normalize the input of neural network acoustic models.
- Speaker adaptive training. Estimate a transform for each training speaker, and train the canonical model on the transformed data. The model then holds less speaker variation, and adaptation at test time works better.
- Other uses of the statistics. The same occupancies and first-order sums are the input of MAP adaptation and of the i-vector extractor. MAP and MLLR are often combined: MLLR moves all Gaussians first, and MAP then refines the ones with much data.
When to use it
Use MLLR when a GMM-HMM recognizer must adapt to a speaker or a channel with a few seconds to a few minutes of speech, and when a transcript or a first-pass recognition is available. With a large amount of speaker data, MAP adaptation or full retraining gives a better model. For neural network acoustic models, the feature-space form (fMLLR) is the usual choice, because the network has no Gaussians to transform.
Pitfalls
- Too few Gaussians with data in a class. If fewer than affinely independent means have data, is singular. Use a regression class tree with an occupancy threshold, or fall back to a global or a bias-only transform.
- Updating from the adapted means. Each iteration must estimate the transform from the speaker independent means, with the posteriors of the current adapted model. Composing a new transform on top of the last adapted means also works, but then the transforms must be multiplied, and the code must not mix the two.
- Errors in unsupervised adaptation. A first-pass transcript with many errors gives posteriors for the wrong states, and adaptation can make the model worse. Use confidence scores to drop unreliable frames.
- Silence. Silence frames are many and carry little speaker information. Give silence its own class, or leave it out.
- Full covariances. The row by row formula holds only for diagonal covariances. With full covariances, the rows are coupled.
- Products of densities. The posteriors need the sum of weighted densities. Compute them in log space with the log-sum-exp trick; a frame far from all means gives densities that 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/maximum-likelihood-linear-regression/. The authors are listed in prov/TR4HQ1.jsonl.
"""Maximum likelihood linear regression (MLLR) of Gaussian means.
The model is a set of M Gaussians with diagonal covariances, given by the
speaker-independent means mu[m] (n numbers each), the variances var[m] and,
for the EM driver, the mixture weights w[m]. Each Gaussian belongs to one
regression class r(m). MLLR replaces each mean by
mu'_m = W_r xi_m, xi_m = (1, mu_m[0], ..., mu_m[n-1]),
where W_r = [b | A] is an n x (n + 1) matrix shared by all the Gaussians of
class r. With diagonal covariances the maximum of the EM auxiliary function
separates by rows: row i of W_r solves G_i w = k_i with
G_i = sum_m (occ_m / var_m[i]) xi_m xi_m^T, k_i = sum_m (s_m[i] / var_m[i]) xi_m,
where occ_m = sum_t gamma_m(t) and s_m = sum_t gamma_m(t) o_t are the
occupancy and the first-order statistic of Gaussian m (Leggetter and Woodland
1995). The posteriors gamma_m(t) here come from a Gaussian mixture; in an HMM
system they come from the forward-backward algorithm, and the M-step
(estimate_transforms) is the same. Every log is the natural log.
"""
import math
from typing import List, Optional, 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 extended(mu: Sequence[float]) -> Vector:
"""Return the extended mean vector xi = (1, mu)."""
return [1.0] + [float(v) for v in mu]
def identity_transform(n: int) -> Matrix:
"""Return W = [0 | I], which leaves every mean unchanged."""
return [[0.0] + [1.0 if j == i else 0.0 for j in range(n)] for i in range(n)]
def apply_transform(W: Matrix, mu: Sequence[float]) -> Vector:
"""Return W xi = A mu + b."""
xi = extended(mu)
return [math.fsum(a * x for a, x in zip(row, xi)) for row in W]
def solve(G: Matrix, k: Sequence[float]) -> Vector:
"""Solve G w = k by Gaussian elimination with partial pivoting.
Raise ValueError if G is singular (relative pivot below 1e-12).
"""
n = len(G)
a = [list(map(float, G[i])) + [float(k[i])] for i in range(n)]
scale = max((abs(v) for row in G for v in row), default=0.0)
if scale == 0.0:
raise ValueError("singular system: no data in this class")
for c in range(n):
p = max(range(c, n), key=lambda r: abs(a[r][c]))
if abs(a[p][c]) <= 1e-12 * scale:
raise ValueError("singular system: the class needs n + 1 affinely independent means with data")
a[c], a[p] = a[p], a[c]
for r in range(c + 1, n):
f = a[r][c] / a[c][c]
if f != 0.0:
for j in range(c, n + 1):
a[r][j] -= f * a[c][j]
w = [0.0] * n
for c in range(n - 1, -1, -1):
s = a[c][n] - math.fsum(a[c][j] * w[j] for j in range(c + 1, n))
w[c] = s / a[c][c]
return w
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, in log space."""
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 accumulate(frames: Sequence[Sequence[float]], weights: Sequence[float], means: Sequence[Sequence[float]],
variances: Sequence[Sequence[float]]) -> Tuple[Vector, Matrix, float]:
"""E-step: return (occ, s, log likelihood) under the mixture with these means."""
M, n = len(means), len(means[0])
occ = [0.0] * M
s = [[0.0] * n for _ in range(M)]
total = 0.0
for o in frames:
g, z = posteriors(o, weights, means, variances) # @line L4
total += z
for m in range(M):
if g[m] > 0.0:
occ[m] += g[m] # @line L5
sm = s[m]
for i in range(n):
sm[i] += g[m] * o[i]
return occ, s, total
def estimate_transforms(means: Sequence[Sequence[float]], variances: Sequence[Sequence[float]],
occ: Sequence[float], s: Sequence[Sequence[float]],
classes: Optional[Sequence[int]] = None) -> List[Matrix]:
"""M-step: return one n x (n + 1) transform per regression class.
means are the speaker-independent means; classes[m] is the class of
Gaussian m (all 0 when None, a global transform). Row i of W_r solves
G_i w = k_i. Raise ValueError if a class has too little data.
"""
M, n = len(means), len(means[0])
if classes is None:
classes = [0] * M
R = max(classes) + 1
Ws = []
for r in range(R): # @line L6
members = [m for m in range(M) if classes[m] == r]
xis = [extended(means[m]) for m in members]
W = []
for i in range(n):
G = [[0.0] * (n + 1) for _ in range(n + 1)]
k = [0.0] * (n + 1)
for m, xi in zip(members, xis):
c = occ[m] / variances[m][i]
d = s[m][i] / variances[m][i]
for p in range(n + 1):
k[p] += d * xi[p] # @line L7
cp = c * xi[p]
row = G[p]
for q in range(n + 1):
row[q] += cp * xi[q]
W.append(solve(G, k)) # @line L8
Ws.append(W)
return Ws
def adapt_means(means: Sequence[Sequence[float]], Ws: Sequence[Matrix],
classes: Optional[Sequence[int]] = None) -> Matrix:
"""Return the adapted means mu'_m = W_{r(m)} xi_m."""
if classes is None:
classes = [0] * len(means)
return [apply_transform(Ws[classes[m]], mu) for m, mu in enumerate(means)] # @line L3
def mllr(frames: Sequence[Sequence[float]], weights: Sequence[float], means: Sequence[Sequence[float]],
variances: Sequence[Sequence[float]], classes: Optional[Sequence[int]] = None,
iterations: int = 5) -> Tuple[List[Matrix], Matrix, List[float]]:
"""Run MLLR by EM on unlabeled adaptation frames.
Return (transforms, adapted means, log likelihoods), where the list of log
likelihoods holds the value before each iteration and after the last one.
The weights and variances stay fixed.
"""
if classes is None:
classes = [0] * len(means)
n = len(means[0])
R = max(classes) + 1
Ws = [identity_transform(n) for _ in range(R)] # @line L1
history = []
for _ in range(iterations): # @line L2
cur = adapt_means(means, Ws, classes)
occ, s, ll = accumulate(frames, weights, cur, variances)
history.append(ll)
Ws = estimate_transforms(means, variances, occ, s, classes)
cur = adapt_means(means, Ws, classes)
history.append(accumulate(frames, weights, cur, variances)[2])
return Ws, cur, history # @line L9
def auxiliary(means: Sequence[Sequence[float]], variances: Sequence[Sequence[float]], occ: Sequence[float],
s: Sequence[Sequence[float]], Ws: Sequence[Matrix], classes: Optional[Sequence[int]] = None) -> float:
"""Return the part of the EM auxiliary function that depends on the transforms.
It is -1/2 sum_m sum_i (occ_m mu'_{m,i}^2 - 2 s_{m,i} mu'_{m,i}) / var_{m,i}.
"""
adapted = adapt_means(means, Ws, classes)
tot = 0.0
for m, mu in enumerate(adapted):
for i in range(len(mu)):
tot += (occ[m] * mu[i] * mu[i] - 2.0 * s[m][i] * mu[i]) / variances[m][i]
return -0.5 * tot
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_maximum_likelihood_linear_regression.py 178 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maximum-likelihood-linear-regression/. The authors are listed in prov/TR4HQ1.jsonl.
import math
import random
import pytest
from maximum_likelihood_linear_regression import (
accumulate,
adapt_means,
apply_transform,
auxiliary,
estimate_transforms,
identity_transform,
log_gauss_diag,
mllr,
posteriors,
solve,
)
def sample_frames(rng, weights, means, variances, T):
out = []
for _ in range(T):
u = rng.random()
m = 0
acc = 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_page_example():
# 1-dimensional means 0, 1, 3 with unit variances, occupancies 4, 2, 2 and
# data means 1, 2, 8: the transform is mu' = (7/3) mu + 2/3.
means = [[0.0], [1.0], [3.0], [2.0]]
variances = [[1.0]] * 4
occ = [4.0, 2.0, 2.0, 0.0]
s = [[4.0], [4.0], [16.0], [0.0]]
(W,) = estimate_transforms(means, variances, occ, s)
assert W[0][0] == pytest.approx(2.0 / 3.0, abs=1e-12)
assert W[0][1] == pytest.approx(7.0 / 3.0, abs=1e-12)
adapted = adapt_means(means, [W])
assert [round(a[0], 9) for a in adapted] == [round(2 / 3, 9), 3.0, round(23 / 3, 9), round(16 / 3, 9)]
def test_planted_transform_recovered_from_exact_statistics():
rng = random.Random(1)
n, M = 3, 7
means = [[rng.uniform(-3, 3) for _ in range(n)] for _ in range(M)]
variances = [[rng.uniform(0.5, 2.0) for _ in range(n)] for _ in range(M)]
W_true = [[rng.uniform(-1, 1)] + [(1.0 if i == j else 0.0) + rng.uniform(-0.3, 0.3) for j in range(n)]
for i in range(n)]
occ = [rng.uniform(1, 20) for _ in range(M)]
s = [[o * v for v in apply_transform(W_true, mu)] for o, mu in zip(occ, means)]
(W,) = estimate_transforms(means, variances, occ, s)
for i in range(n):
for j in range(n + 1):
assert W[i][j] == pytest.approx(W_true[i][j], abs=1e-9)
def test_identity_when_data_match_the_model():
rng = random.Random(2)
n, M = 2, 4
means = [[rng.uniform(-3, 3) for _ in range(n)] for _ in range(M)]
variances = [[1.0, 2.0]] * M
occ = [3.0, 1.0, 5.0, 2.0]
s = [[o * v for v in mu] for o, mu in zip(occ, means)]
(W,) = estimate_transforms(means, variances, occ, s)
I = identity_transform(n)
for i in range(n):
for j in range(n + 1):
assert W[i][j] == pytest.approx(I[i][j], abs=1e-9)
def test_m_step_maximizes_the_auxiliary_function():
rng = random.Random(3)
n, M = 2, 5
means = [[rng.uniform(-3, 3) for _ in range(n)] for _ in range(M)]
variances = [[rng.uniform(0.5, 2.0) for _ in range(n)] for _ in range(M)]
occ = [rng.uniform(0.5, 5) for _ in range(M)]
s = [[o * rng.uniform(-4, 4) for _ in range(n)] for o in occ]
Ws = estimate_transforms(means, variances, occ, s)
best = auxiliary(means, variances, occ, s, Ws)
for _ in range(50):
P = [[[v + rng.uniform(-0.1, 0.1) for v in row] for row in Ws[0]]]
assert auxiliary(means, variances, occ, s, P) < best
h = 1e-6
for i in range(n):
for j in range(n + 1):
up = [[row[:] for row in Ws[0]]]
dn = [[row[:] for row in Ws[0]]]
up[0][i][j] += h
dn[0][i][j] -= h
g = (auxiliary(means, variances, occ, s, up) - auxiliary(means, variances, occ, s, dn)) / (2 * h)
assert abs(g) < 1e-5
def test_em_recovers_planted_transform_and_likelihood_never_decreases():
rng = random.Random(4)
weights = [0.25, 0.25, 0.25, 0.25]
means = [[-4.0, 0.0], [4.0, 0.0], [0.0, 4.0], [0.0, -4.0]]
variances = [[0.5, 0.5], [0.5, 0.8], [0.6, 0.5], [0.5, 0.5]]
W_true = [[1.0, 1.1, 0.2], [-0.5, -0.1, 0.9]]
adapted_true = [apply_transform(W_true, mu) for mu in means]
frames = sample_frames(rng, weights, adapted_true, variances, 800)
Ws, adapted, history = mllr(frames, weights, means, variances, iterations=8)
for a, b in zip(history, history[1:]):
assert b >= a - 1e-9
assert history[-1] > history[0] + 100
for i in range(2):
for j in range(3):
assert Ws[0][i][j] == pytest.approx(W_true[i][j], abs=0.1)
def test_regression_classes_are_independent():
rng = random.Random(5)
n = 2
means = [[rng.uniform(-3, 3) for _ in range(n)] for _ in range(6)]
variances = [[1.0, 1.0]] * 6
classes = [0, 0, 0, 1, 1, 1]
W0 = [[0.5, 1.0, 0.1], [0.0, -0.2, 1.2]]
W1 = [[-1.0, 0.8, 0.0], [2.0, 0.0, 0.7]]
occ = [2.0] * 6
s = [[2.0 * v for v in apply_transform([W0, W1][classes[m]], means[m])] for m in range(6)]
Ws = estimate_transforms(means, variances, occ, s, classes)
for W, Wt in zip(Ws, [W0, W1]):
for i in range(n):
for j in range(n + 1):
assert W[i][j] == pytest.approx(Wt[i][j], abs=1e-9)
def test_too_little_data_is_singular():
# Two Gaussians cannot fix a 2 x 3 transform: G has rank 2.
means = [[0.0, 0.0], [1.0, 1.0], [5.0, 5.0]]
variances = [[1.0, 1.0]] * 3
occ = [3.0, 3.0, 0.0]
s = [[0.0, 0.0], [3.0, 3.0], [0.0, 0.0]]
with pytest.raises(ValueError):
estimate_transforms(means, variances, occ, s)
with pytest.raises(ValueError):
solve([[0.0, 0.0], [0.0, 0.0]], [1.0, 1.0])
def test_solve_against_known_solution():
G = [[4.0, 1.0, 2.0], [1.0, 3.0, 0.0], [2.0, 0.0, 5.0]]
x = [1.0, -2.0, 0.5]
k = [sum(a * b for a, b in zip(row, x)) for row in G]
assert solve(G, k) == pytest.approx(x, abs=1e-12)
def test_log_space_posteriors_where_plain_densities_underflow():
weights = [0.5, 0.5]
means = [[0.0], [2.0]]
variances = [[1.0], [1.0]]
x = [1000.0]
plain = [w * math.exp(-0.5 * (x[0] - m[0]) ** 2) for w, m in zip(weights, means)]
assert plain == [0.0, 0.0]
g, z = posteriors(x, weights, means, variances)
assert sum(g) == pytest.approx(1.0)
assert g[1] == pytest.approx(1.0)
assert g[0] < 1e-300
assert math.isfinite(z)
assert z == pytest.approx(math.log(0.5) + log_gauss_diag(x, means[1], variances[1]) + math.log1p(math.exp(-1996.0)))
def test_accumulate_statistics():
weights = [1.0]
means = [[0.0, 0.0]]
variances = [[1.0, 1.0]]
frames = [[1.0, 2.0], [3.0, -1.0]]
occ, s, ll = accumulate(frames, weights, means, variances)
assert occ == [2.0]
assert s == [[4.0, 1.0]]
assert ll == pytest.approx(sum(log_gauss_diag(o, means[0], variances[0]) for o in frames))
History
Leggetter and Woodland published MLLR in 1995 for continuous density HMMs, after earlier work on speaker adaptation by MAP estimation (Gauvain and Lee 1994) and by spectral mapping. They introduced the regression classes that share one transform among many Gaussians. Gales and Woodland then adapted the variances with a second transform, and Gales 1998 described the constrained form, the basis of fMLLR and of speaker adaptive training with feature transforms. Gales and Young 2008 survey these methods.
References
- C. J. Leggetter and P. C. Woodland, Maximum likelihood linear regression for speaker adaptation of continuous density hidden Markov models, Computer Speech and Language 9(2), 1995, pages 171 to 185, the derivation of the mean transform, its row by row solution for diagonal covariances, and the regression classes
- M. J. F. Gales, Maximum likelihood linear transformations for HMM-based speech recognition, Computer Speech and Language 12, 1998, pages 75 to 98, the unconstrained and constrained transforms and the iterative row by row estimate of the constrained transform
- 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 TR4HQ1 Edit this page History Report an error Markdown