Algorithm Search⌘K

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
Properties
deterministicnot exactofflineiterative
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 μm\mu_m by Aμm+bA \mu_m + b, 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 MM Gaussians, for example the Gaussians of all HMM states of a GMM-HMM acoustic model. Gaussian mm has the mean μm∈Rn\mu_m \in \mathbb{R}^n and the diagonal covariance Σm=diag(σm,12,…,σm,n2)\Sigma_m = \mathrm{diag}(\sigma^2_{m,1}, \ldots, \sigma^2_{m,n}). Each Gaussian belongs to one of RR regression classes, r(m)r(m). The input is a sequence of TT adaptation frames o1,…,oTo_1, \ldots, o_T 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 ξm=(1,μm,1,…,μm,n)⊤\xi_m = (1, \mu_{m,1}, \ldots, \mu_{m,n})^\top. For each class rr, the unknown is an n×(n+1)n \times (n+1) matrix Wr=[ br∣Ar ]W_r = [\,b_r \mid A_r\,], and the adapted mean is

μ^m=Wr(m) ξm=Ar(m)μm+br(m).\hat\mu_m = W_{r(m)}\, \xi_m = A_{r(m)} \mu_m + b_{r(m)}.

The task is to find the transforms that maximize the likelihood p(o1,…,oT∣W1,…,WR)p(o_1, \ldots, o_T \mid W_1, \ldots, W_R) 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 γm(t)\gamma_m(t) 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 occm=∑tγm(t)\mathrm{occ}_m = \sum_t \gamma_m(t) and the first-order sum sm=∑tγm(t) ots_m = \sum_t \gamma_m(t)\, o_t. With diagonal covariances, row ii of WrW_r, written wr,iw_{r,i}, maximizes a separate quadratic function, and its maximizer solves the (n+1)×(n+1)(n+1) \times (n+1) system Gr,iwr,i=kr,iG_{r,i} w_{r,i} = k_{r,i} with

Gr,i=∑m:r(m)=roccmσm,i2 ξmξm⊤,kr,i=∑m:r(m)=rsm,iσm,i2 ξm.G_{r,i} = \sum_{m: r(m) = r} \frac{\mathrm{occ}_m}{\sigma^2_{m,i}}\, \xi_m \xi_m^\top, \qquad k_{r,i} = \sum_{m: r(m) = r} \frac{s_{m,i}}{\sigma^2_{m,i}}\, \xi_m.
  1. MLLR(O, μ, σ², class, iters) ▷ μ: speaker independent means, ξ_m = (1, μ_m)
  2. 1W_r ← [0 | I] for r = 1 .. R ▷ start from the unchanged model
  3. 2repeat iters times
  4. 3μ̂_m ← W_{r(m)} ξ_m for every m
  5. 4γ_m(t) ← posterior of Gaussian m at frame t under the means μ̂ ▷ E-step, in log space
  6. 5occ_m ← Σ_t γ_m(t), s_m ← Σ_t γ_m(t) o_t
  7. 6for each class r and each row i = 1 .. n do ▷ M-step
  8. 7G ← Σ_{m in r} (occ_m / σ²_{m,i}) ξ_m ξ_mᵀ, k ← Σ_{m in r} (s_{m,i} / σ²_{m,i}) ξ_m
  9. 8w_{r,i} ← the solution of G w = k
  10. 9return W_1 .. W_R

Line L3 always starts from the speaker independent means ξm\xi_m, 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 n=1n = 1 and one class with four Gaussians, all with σ2=1\sigma^2 = 1. The speaker independent means are μ=0,1,3,2\mu = 0, 1, 3, 2. The E-step gave these statistics:

Gaussian mm μm\mu_m occm\mathrm{occ}_m sms_m data mean sm/occms_m / \mathrm{occ}_m
1 0 4 4 1
2 1 2 4 2
3 3 2 16 8
4 2 0 0 none

With ξm=(1,μm)\xi_m = (1, \mu_m), the system of line L7 is

G=(∑occm∑occmμm∑occmμm∑occmμm2)=(88820),k=(∑sm∑smμm)=(2452).G = \begin{pmatrix} \sum \mathrm{occ}_m & \sum \mathrm{occ}_m \mu_m \\ \sum \mathrm{occ}_m \mu_m & \sum \mathrm{occ}_m \mu_m^2 \end{pmatrix} = \begin{pmatrix} 8 & 8 \\ 8 & 20 \end{pmatrix}, \qquad k = \begin{pmatrix} \sum s_m \\ \sum s_m \mu_m \end{pmatrix} = \begin{pmatrix} 24 \\ 52 \end{pmatrix}.

The determinant is 8⋅20−8⋅8=968 \cdot 20 - 8 \cdot 8 = 96, so b=(20⋅24−8⋅52)/96=2/3b = (20 \cdot 24 - 8 \cdot 52)/96 = 2/3 and a=(8⋅52−8⋅24)/96=7/3a = (8 \cdot 52 - 8 \cdot 24)/96 = 7/3. The adapted means are μ^=7/3⋅μ+2/3\hat\mu = 7/3 \cdot \mu + 2/3:

Gaussian mm 1 2 3 4
μ^m\hat\mu_m 0.6667 3 7.6667 5.3333

This is a weighted least squares line through the points (μm,sm/occm)(\mu_m, s_m / \mathrm{occ}_m) with the weights occm/σm2\mathrm{occ}_m / \sigma^2_m. The weighted squared error ∑moccm(sm/occm−μ^m)2\sum_m \mathrm{occ}_m (s_m/\mathrm{occ}_m - \hat\mu_m)^2 falls from 56 for the unchanged means to 8/38/3. A shift alone, μ^=μ+b\hat\mu = \mu + b, gives b=2b = 2 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 w⊤Gr,iw−2w⊤kr,iw^\top G_{r,i} w - 2 w^\top k_{r,i}, one for each class and row, in disjoint variables. Each Gr,iG_{r,i} is positive semidefinite, and it is positive definite exactly when the class has n+1n+1 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 MM Gaussians with speaker independent means μm∈Rn\mu_m \in \mathbb{R}^n, diagonal covariances Σm=diag(σm,12,…,σm,n2)\Sigma_m = \mathrm{diag}(\sigma^2_{m,1}, \ldots, \sigma^2_{m,n}) with σm,i2>0\sigma^2_{m,i} > 0, and mixture weights cmc_m. Gaussian mm belongs to the regression class r(m)r(m). The extended mean is ξm=(1,μm)⊤∈Rn+1\xi_m = (1, \mu_m)^\top \in \mathbb{R}^{n+1}. A set of transforms W=(W1,…,WR)\mathcal{W} = (W_1, \ldots, W_R), each of size n×(n+1)n \times (n+1), gives the adapted means μ^m=Wr(m)ξm\hat\mu_m = W_{r(m)} \xi_m. Row ii of WrW_r is wr,i⊤w_{r,i}^\top, so μ^m,i=wr(m),i⊤ξm\hat\mu_{m,i} = w_{r(m),i}^\top \xi_m. All logs are natural logs. Write p(O∣W)p(O \mid \mathcal{W}) for the likelihood of the frames o1,…,oTo_1, \ldots, o_T under the mixture with the adapted means; the weights and covariances do not change.

Fix the current transforms Wold\mathcal{W}^{\mathrm{old}} and let γm(t)\gamma_m(t) be the posterior of Gaussian mm at frame tt under them, as in line L4. Let occm=∑tγm(t)\mathrm{occ}_m = \sum_t \gamma_m(t) and sm=∑tγm(t)ots_m = \sum_t \gamma_m(t) o_t, as in line L5. The auxiliary function is

Q(W)=∑t=1T∑m=1Mγm(t)log⁡(cm N(ot;Wr(m)ξm,Σm)).\mathcal{Q}(\mathcal{W}) = \sum_{t=1}^{T} \sum_{m=1}^{M} \gamma_m(t) \log \big( c_m\, \mathcal{N}(o_t; W_{r(m)} \xi_m, \Sigma_m) \big).

Lemma 1 (the auxiliary function separates by rows). There is a constant KK that does not depend on W\mathcal{W} such that

Q(W)=K−12∑r=1R∑i=1n(wr,i⊤Gr,i wr,i−2 wr,i⊤kr,i),\mathcal{Q}(\mathcal{W}) = K - \frac{1}{2} \sum_{r=1}^{R} \sum_{i=1}^{n} \big( w_{r,i}^\top G_{r,i}\, w_{r,i} - 2\, w_{r,i}^\top k_{r,i} \big),

with Gr,i=∑m:r(m)=r(occm/σm,i2) ξmξm⊤G_{r,i} = \sum_{m: r(m) = r} (\mathrm{occ}_m / \sigma^2_{m,i})\, \xi_m \xi_m^\top and kr,i=∑m:r(m)=r(sm,i/σm,i2) ξmk_{r,i} = \sum_{m: r(m) = r} (s_{m,i} / \sigma^2_{m,i})\, \xi_m, the matrices of line L7.

Proof. With a diagonal covariance,

log⁡N(ot;μ^m,Σm)=−12∑i=1n(log⁡(2πσm,i2)+(ot,i−μ^m,i)2σm,i2).\log \mathcal{N}(o_t; \hat\mu_m, \Sigma_m) = -\frac{1}{2} \sum_{i=1}^{n} \Big( \log(2\pi\sigma^2_{m,i}) + \frac{(o_{t,i} - \hat\mu_{m,i})^2}{\sigma^2_{m,i}} \Big).

The terms log⁡cm\log c_m, log⁡(2πσm,i2)\log(2\pi\sigma^2_{m,i}) and ot,i2/σm,i2o_{t,i}^2 / \sigma^2_{m,i} do not depend on W\mathcal{W}; they go into KK. What is left is

−12∑m∑i1σm,i2∑tγm(t)(μ^m,i2−2ot,iμ^m,i)=−12∑m∑ioccm μ^m,i2−2sm,i μ^m,iσm,i2.-\frac{1}{2} \sum_m \sum_i \frac{1}{\sigma^2_{m,i}} \sum_t \gamma_m(t) \big( \hat\mu_{m,i}^2 - 2 o_{t,i} \hat\mu_{m,i} \big) = -\frac{1}{2} \sum_m \sum_i \frac{\mathrm{occ}_m\, \hat\mu_{m,i}^2 - 2 s_{m,i}\, \hat\mu_{m,i}}{\sigma^2_{m,i}}.

Put μ^m,i=wr(m),i⊤ξm\hat\mu_{m,i} = w_{r(m),i}^\top \xi_m, so μ^m,i2=wr(m),i⊤ξmξm⊤wr(m),i\hat\mu_{m,i}^2 = w_{r(m),i}^\top \xi_m \xi_m^\top w_{r(m),i}, and group the Gaussians by class. □\square

Each pair (r,i)(r, i) owns its own vector wr,iw_{r,i}, and no other term of the sum depends on it. So Q\mathcal{Q} is a sum of nRnR quadratic functions in disjoint variables, and it is maximized by maximizing each one alone.

Lemma 2 (when the system has one solution). Each Gr,iG_{r,i} is symmetric and positive semidefinite. It is positive definite if and only if the extended means ξm\xi_m of the Gaussians of class rr with occm>0\mathrm{occ}_m > 0 span Rn+1\mathbb{R}^{n+1}. This holds if and only if these Gaussians include n+1n+1 means that are affinely independent.

Proof. For v∈Rn+1v \in \mathbb{R}^{n+1}, v⊤Gr,iv=∑m(occm/σm,i2)(v⊤ξm)2≥0v^\top G_{r,i} v = \sum_m (\mathrm{occ}_m / \sigma^2_{m,i}) (v^\top \xi_m)^2 \ge 0, and each weight is positive when occm>0\mathrm{occ}_m > 0. The sum is 0 exactly when vv is orthogonal to every ξm\xi_m with occm>0\mathrm{occ}_m > 0. Such a nonzero vv exists if and only if these ξm\xi_m do not span Rn+1\mathbb{R}^{n+1}. Finally, the vectors (1,μm)(1, \mu_m) span Rn+1\mathbb{R}^{n+1} if and only if the points μm\mu_m are not all in one affine hyperplane, that is, if and only if n+1n+1 of them are affinely independent. □\square

The condition does not depend on ii. 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 Gr,iG_{r,i} is positive definite, the transforms of line L8, wr,i=Gr,i−1kr,iw_{r,i} = G_{r,i}^{-1} k_{r,i}, are the unique maximizer of Q\mathcal{Q}.

Proof. By Lemma 1 it is enough to maximize f(w)=−12(w⊤Gw−2w⊤k)f(w) = -\frac{1}{2}(w^\top G w - 2 w^\top k) for each pair, with GG positive definite by Lemma 2. Let w∗=G−1kw^* = G^{-1} k. For any ww, with d=w−w∗d = w - w^*,

f(w)=f(w∗)−12d⊤Gd,f(w) = f(w^*) - \frac{1}{2} d^\top G d,

which one checks by expanding both sides and using Gw∗=kG w^* = k. The last term is negative unless d=0d = 0. □\square

Theorem 2 (the likelihood does not decrease). Let Wnew\mathcal{W}^{\mathrm{new}} be the transforms of line L8, computed from the statistics of Wold\mathcal{W}^{\mathrm{old}}. Then log⁡p(O∣Wnew)≥log⁡p(O∣Wold)\log p(O \mid \mathcal{W}^{\mathrm{new}}) \ge \log p(O \mid \mathcal{W}^{\mathrm{old}}).

Proof. Write p(ot,m∣W)=cmN(ot;Wr(m)ξm,Σm)p(o_t, m \mid \mathcal{W}) = c_m \mathcal{N}(o_t; W_{r(m)} \xi_m, \Sigma_m). For each frame, γm(t)=p(ot,m∣Wold)/p(ot∣Wold)\gamma_m(t) = p(o_t, m \mid \mathcal{W}^{\mathrm{old}}) / p(o_t \mid \mathcal{W}^{\mathrm{old}}) is a probability distribution over mm. For any W\mathcal{W}, by the concavity of log (Jensen's inequality),

log⁡p(ot∣W)p(ot∣Wold)=log⁡∑mγm(t)p(ot,m∣W)p(ot,m∣Wold)≥∑mγm(t)log⁡p(ot,m∣W)p(ot,m∣Wold).\log \frac{p(o_t \mid \mathcal{W})}{p(o_t \mid \mathcal{W}^{\mathrm{old}})} = \log \sum_m \gamma_m(t) \frac{p(o_t, m \mid \mathcal{W})}{p(o_t, m \mid \mathcal{W}^{\mathrm{old}})} \ge \sum_m \gamma_m(t) \log \frac{p(o_t, m \mid \mathcal{W})}{p(o_t, m \mid \mathcal{W}^{\mathrm{old}})}.

Sum over tt: log⁡p(O∣W)−log⁡p(O∣Wold)≥Q(W)−Q(Wold)\log p(O \mid \mathcal{W}) - \log p(O \mid \mathcal{W}^{\mathrm{old}}) \ge \mathcal{Q}(\mathcal{W}) - \mathcal{Q}(\mathcal{W}^{\mathrm{old}}). The old transforms are one of the candidates over which line L8 maximizes, because the old means are Wr(m)oldξmW^{\mathrm{old}}_{r(m)} \xi_m with the same ξm\xi_m. So Q(Wnew)≥Q(Wold)\mathcal{Q}(\mathcal{W}^{\mathrm{new}}) \ge \mathcal{Q}(\mathcal{W}^{\mathrm{old}}) by Theorem 1, and the right side is at least 0 for W=Wnew\mathcal{W} = \mathcal{W}^{\mathrm{new}}. □\square

The argument needs that each iteration estimates the transform from the speaker independent means ξm\xi_m, with the posteriors of the current adapted model. It is the same in an HMM system, where γm(t)\gamma_m(t) is the posterior of state and Gaussian mm from the forward-backward algorithm and the sum over mm 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 μ^m\hat\mu_m; the maximizer then solves one linear system in all n(n+1)n(n+1) entries of WrW_r at once. In floating point, Gaussian elimination with partial pivoting gives the solution of a nearby system, so the computed WW satisfies Theorem 1 only up to rounding.

Complexity

In the real RAM, one E-step evaluates MM diagonal Gaussians at each of TT frames, O(TMn)O(T M n), and the statistics cost the same. For each Gaussian, the outer product ξmξm⊤\xi_m \xi_m^\top is added into nn matrices Gr,iG_{r,i} with different scales, O(n⋅n2)O(n \cdot n^2), so the matrices cost O(Mn3)O(M n^3). The RnR n systems of size n+1n+1 cost O(n3)O(n^3) each by Gaussian elimination, so O(Rn4)O(R n^4). With kk iterations the total is O(k(TMn+Mn3+Rn4))O(k (T M n + M n^3 + R n^4)). In a real system TMnT M n dominates: for n=39n = 39 the solves are about 403⋅39≈2.5⋅10640^3 \cdot 39 \approx 2.5 \cdot 10^6 operations per class, which is small next to the E-step over thousands of Gaussians.

The extra memory is O(Mn)O(M n) for the statistics and the adapted means and O(Rn2)O(R n^2) for the transforms. The statistics are added frame by frame, so the posteriors need not be stored.

Properties

  • Shared parameters. A global transform has n(n+1)n(n+1) parameters, 1560 for n=39n = 39, against MnM n 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 AA with three blocks has fewer parameters. A diagonal AA is a per-dimension scale and shift.
  • Bias only. A=IA = I gives a shift of all means, the model-space counterpart of cepstral mean normalization.
  • Variance MLLR. A second transform Σ^m=HΣmH⊤\hat\Sigma_m = H \Sigma_m H^\top adapts the covariances, estimated after the means.
  • Constrained MLLR (CMLLR). Gales 1998 uses the same matrix for the mean and the covariance: μ^=A′μ−b′\hat\mu = A' \mu - b' and Σ^=A′ΣA′⊤\hat\Sigma = A' \Sigma A'^\top. This is the same as a transform of the features, o^=Ao+b\hat o = A o + b with A=A′−1A = A'^{-1}, plus the Jacobian term log⁡∣det⁡A∣\log |\det A| 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 n+1n + 1 affinely independent means have data, GG 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 MM 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.

maximum_likelihood_linear_regression.pyI0RawGitHub
# 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

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

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