Algorithm Search⌘K

Algorithmadvanced

PLDA scoring

Also called probabilistic linear discriminant analysis, PLDA, two-covariance PLDA scoring.

Score two speaker embeddings by the closed form log likelihood ratio that they share one latent speaker variable in a Gaussian PLDA model.

Time
O(d^3 + N d^2) worst
Space
O(d^2) extra
Where
N = the number of trials; d = the embedding dimension; n = the number of enrollment embeddings of a speaker
Properties
deterministicexactofflineiterative
Origin
Sergey Ioffe, Simon J. D. Prince, James H. Elder, 2007

PLDA scoring compares two speaker embeddings, such as i-vectors or x-vectors, and returns the log likelihood ratio that they come from the same speaker. It uses a Gaussian model in which every embedding is the sum of a speaker part, shared by all embeddings of that speaker, and a session part, new for each recording. Under this model the ratio has a closed form: a quadratic function of the two embeddings.

In plain words

Recordings of one person do not give identical embeddings. The microphone, the room and the words change them. PLDA learns two kinds of spread: how much embeddings of different people differ, and how much embeddings of one person differ from recording to recording.

To compare two recordings, ask two questions. How likely are these two embeddings if one person made both? How likely are they if two different people made them? The score is the log of the ratio of the two answers. Two embeddings that are close count as strong evidence when people differ a lot and one person's recordings differ little. They count as weak evidence when the reverse is true.

The problem

This is the scoring step of speaker verification. The input is two embeddings x1,x2∈Rdx_1, x_2 \in \mathbb{R}^d and the model parameters. The two-covariance model says that an embedding of speaker ss is

x=m+ys+e,ys∼N(0,B),e∼N(0,W),x = m + y_s + e, \qquad y_s \sim \mathcal{N}(0, B), \qquad e \sim \mathcal{N}(0, W),

where mm is the mean, BB is the between-speaker covariance and WW is the within-speaker covariance. All embeddings of one speaker share ysy_s, and each embedding has its own ee. The output is the log likelihood ratio of HsH_s (same speaker) against HdH_d (different speakers),

LLR(x1,x2)=log⁡p(x1,x2∣Hs)p(x1,x2∣Hd).\text{LLR}(x_1, x_2) = \log \frac{p(x_1, x_2 \mid H_s)}{p(x_1, x_2 \mid H_d)}.

The parameters are trained on embeddings of many speakers with labels, by EM; this page takes them as given.

The algorithm

Write A=B+WA = B + W for the total covariance. Under HdH_d the pair (x1−m,x2−m)(x_1 - m, x_2 - m) is Gaussian with independent blocks of covariance AA. Under HsH_s the blocks have covariance AA and cross covariance BB. The ratio of these two densities in 2d2d dimensions reduces to a form in dd dimensions:

  1. PREPARE(B, W)
  2. 1A ← B + W, Λ ← A⁻¹
  3. 2S ← A - B Λ B, Γ ← S⁻¹ ▷ S is a Schur complement
  4. 3Q ← Λ - Γ, P ← Λ B Γ
  5. 4c ← ½ (log|A| - log|S|)
  6. SCORE(x₁, x₂, m)
  7. 5u ← x₁ - m, v ← x₂ - m
  8. 6return ½ uᵀQu + ½ vᵀQv + uᵀPv + c
  9. SCORE-MULTI(x₁..xₙ, x_t, m, B, W) ▷ several enrollment embeddings
  10. 7Cₙ ← (B⁻¹ + n W⁻¹)⁻¹
  11. 8μₙ ← Cₙ W⁻¹ Σᵢ (xᵢ - m)
  12. 9return log N(x_t; m + μₙ, W + Cₙ) - log N(x_t; m, A)

L1 to L4 depend only on the model, so they run once. Each trial then costs two quadratic forms. With several enrollment embeddings of one speaker, L7 and L8 compute the posterior of the speaker variable yy, and L9 compares the predictive density of the test embedding with the density for an unknown speaker. With one enrollment embedding, L9 gives the same value as L6. The code computes the inverses and log determinants with the Cholesky decomposition.

Example

Take d=1d = 1, m=0m = 0, B=3B = 3 and W=1W = 1. Then A=4A = 4, Λ=1/4\Lambda = 1/4, S=4−9/4=7/4S = 4 - 9/4 = 7/4 and Γ=4/7\Gamma = 4/7. So Q=1/4−4/7=−9/28Q = 1/4 - 4/7 = -9/28, P=(1/4)⋅3⋅(4/7)=3/7P = (1/4) \cdot 3 \cdot (4/7) = 3/7 and c=12log⁡(16/7)=0.413339c = \frac12 \log(16/7) = 0.413339.

x1x_1 x2x_2 LLR
1 1 0.520482
2 2 0.841911
0 0 0.413339
1 -1 -0.336661
3 0 -1.033089

Equal embeddings far from the mean give more evidence than equal embeddings near it: (2,2)(2, 2) scores more than (1,1)(1, 1), and (0,0)(0, 0) scores least of the three. Two embeddings at the mean also fit the different-speaker hypothesis well, because most speakers are near the mean. Embeddings on opposite sides of the mean give a negative score.

Correctness

The proof is in proofs/correctness.md. Both hypotheses give Gaussian densities for the pair. The inverse of the joint covariance under HsH_s has the blocks Γ\Gamma on the diagonal and −ΛBΓ-\Lambda B \Gamma off it, and its determinant is ∣A∣∣S∣|A| |S|. Subtracting the two log densities gives L6 exactly. The same proof shows that PP is symmetric, so the score is symmetric in x1x_1 and x2x_2, and that QQ is negative semidefinite and c≥0c \ge 0. The multi-enrollment score follows from the conjugate Gaussian posterior of yy. The closed form needs WW positive definite but allows a singular BB, for example B=FF⊤B = F F^\top of low rank.

Proof: The PLDA closed form is the exact log likelihood ratio of the two-covariance modelfull

We use the notation of the page. Embeddings have dimension dd. In the two-covariance model an embedding of speaker ss is x=m+ys+ex = m + y_s + e, with ys∼N(0,B)y_s \sim \mathcal{N}(0, B) shared by all embeddings of ss, and e∼N(0,W)e \sim \mathcal{N}(0, W) new for each embedding. All yy and ee are independent. BB is symmetric positive semidefinite and WW is symmetric positive definite. Write A=B+WA = B + W, u=x1−mu = x_1 - m, v=x2−mv = x_2 - m, and all logs are natural logs.

HsH_s is the hypothesis that x1x_1 and x2x_2 come from the same speaker, and HdH_d is the hypothesis that they come from two different speakers.

Lemma 1 (the two joint densities). Under HdH_d, (u,v)∼N(0,diag⁡(A,A))(u, v) \sim \mathcal{N}(0, \operatorname{diag}(A, A)). Under HsH_s, (u,v)∼N(0,J)(u, v) \sim \mathcal{N}(0, J) with

J=(ABBA).J = \begin{pmatrix} A & B \\ B & A \end{pmatrix}.

AA, JJ and S=A−BA−1BS = A - B A^{-1} B are positive definite.

Proof. Under HdH_d, u=y+e1u = y + e_1 and v=y′+e2v = y' + e_2 with independent y,y′y, y', so uu and vv are independent with covariance B+W=AB + W = A. Under HsH_s, u=y+e1u = y + e_1 and v=y+e2v = y + e_2. Then Cov⁡(u)=Cov⁡(v)=A\operatorname{Cov}(u) = \operatorname{Cov}(v) = A and Cov⁡(u,v)=Cov⁡(y)=B\operatorname{Cov}(u, v) = \operatorname{Cov}(y) = B. Both are linear maps of Gaussian vectors, so both are Gaussian. JJ is the sum of (BBBB)\begin{pmatrix} B & B \\ B & B \end{pmatrix}, which is positive semidefinite because (a,b)(a, b) gives (a+b)⊤B(a+b)≥0(a + b)^\top B (a + b) \ge 0, and diag⁡(W,W)\operatorname{diag}(W, W), which is positive definite. So JJ is positive definite. AA is a diagonal block of JJ, so AA is positive definite. SS is the Schur complement of the block AA in JJ, and det⁡J=det⁡Adet⁡S\det J = \det A \det S. The Schur complement of a positive definite matrix is positive definite. □\square

Lemma 2 (the inverse of JJ). Write Λ=A−1\Lambda = A^{-1} and Γ=S−1\Gamma = S^{-1}. Then

J−1=(Γ−ΛBΓ−ΛBΓΓ),J^{-1} = \begin{pmatrix} \Gamma & -\Lambda B \Gamma \\ -\Lambda B \Gamma & \Gamma \end{pmatrix},

and ΛBΓ\Lambda B \Gamma is symmetric.

Proof. The block inverse formula for (ABBA)\begin{pmatrix} A & B \\ B & A \end{pmatrix} gives the lower right block S−1=ΓS^{-1} = \Gamma and the upper right block −A−1BS−1=−ΛBΓ-A^{-1} B S^{-1} = -\Lambda B \Gamma. Swap the two halves of the coordinates: the permutation maps JJ to itself, so it also maps J−1J^{-1} to itself. Thus the upper left block equals the lower right block Γ\Gamma, and the lower left block equals the upper right block. J−1J^{-1} is symmetric, so the lower left block is also the transpose of the upper right block. Hence ΛBΓ=(ΛBΓ)⊤\Lambda B \Gamma = (\Lambda B \Gamma)^\top. □\square

Theorem 3 (the closed form). With Q=Λ−ΓQ = \Lambda - \Gamma, P=ΛBΓP = \Lambda B \Gamma and c=12(log⁡det⁡A−log⁡det⁡S)c = \frac12 (\log \det A - \log \det S),

log⁡p(x1,x2∣Hs)p(x1,x2∣Hd)=12u⊤Qu+12v⊤Qv+u⊤Pv+c.\log \frac{p(x_1, x_2 \mid H_s)}{p(x_1, x_2 \mid H_d)} = \tfrac12 u^\top Q u + \tfrac12 v^\top Q v + u^\top P v + c.

Lines L1 to L6 compute this value.

Proof. For a Gaussian N(0,K)\mathcal{N}(0, K) in dimension kk, log⁡p(z)=−12(klog⁡2π+log⁡det⁡K+z⊤K−1z)\log p(z) = -\frac12 (k \log 2\pi + \log \det K + z^\top K^{-1} z). The two densities have the same dimension 2d2d, so the terms 2dlog⁡2π2d \log 2\pi cancel. By Lemma 1, log⁡det⁡J=log⁡det⁡A+log⁡det⁡S\log \det J = \log \det A + \log \det S and log⁡det⁡diag⁡(A,A)=2log⁡det⁡A\log \det \operatorname{diag}(A, A) = 2 \log \det A. The difference of the log determinant terms is −12(log⁡det⁡A+log⁡det⁡S)+log⁡det⁡A=c-\frac12(\log \det A + \log \det S) + \log \det A = c. By Lemma 2 the quadratic form under HsH_s is u⊤Γu+v⊤Γv−2u⊤ΛBΓvu^\top \Gamma u + v^\top \Gamma v - 2 u^\top \Lambda B \Gamma v, and under HdH_d it is u⊤Λu+v⊤Λvu^\top \Lambda u + v^\top \Lambda v. Thus the log ratio is

−12(u⊤Γu+v⊤Γv−2u⊤Pv)+12(u⊤Λu+v⊤Λv)+c,-\tfrac12 (u^\top \Gamma u + v^\top \Gamma v - 2 u^\top P v) + \tfrac12 (u^\top \Lambda u + v^\top \Lambda v) + c,

which is the stated form. L1 forms AA, L2 forms SS and its inverse, L3 forms QQ and PP, L4 forms cc, and L5 and L6 evaluate the form. □\square

Corollary 4 (properties). The score is symmetric in x1x_1 and x2x_2. c≥0c \ge 0, and QQ is negative semidefinite. If BB is positive definite, QQ is negative definite and c>0c > 0. If B=0B = 0, the score is 00 for all inputs.

Proof. Symmetry follows from P=P⊤P = P^\top (Lemma 2), since then u⊤Pv=v⊤Puu^\top P v = v^\top P u. S=A−BA−1BS = A - B A^{-1} B with BA−1BB A^{-1} B positive semidefinite, so S⪯AS \preceq A. For positive definite matrices, S⪯AS \preceq A implies S−1⪰A−1S^{-1} \succeq A^{-1} and det⁡S≤det⁡A\det S \le \det A. Thus Q=A−1−S−1⪯0Q = A^{-1} - S^{-1} \preceq 0 and c≥0c \ge 0. If BB is positive definite, BA−1BB A^{-1} B is positive definite, the inequalities are strict, and so Q≺0Q \prec 0 and c>0c > 0. If B=0B = 0, then S=AS = A, so Q=0Q = 0, P=0P = 0 and c=0c = 0. □\square

Theorem 5 (several enrollment embeddings). Let BB be positive definite. Suppose x1,…,xnx_1, \ldots, x_n are the enrollment embeddings of one speaker and xtx_t is a test embedding. HsH_s says that xtx_t comes from the same speaker. HdH_d says that it comes from another speaker. Write Cn=(B−1+nW−1)−1C_n = (B^{-1} + n W^{-1})^{-1} and μn=CnW−1∑i(xi−m)\mu_n = C_n W^{-1} \sum_i (x_i - m). Then

log⁡p(x1,…,xn,xt∣Hs)p(x1,…,xn,xt∣Hd)=log⁡N(xt;m+μn,W+Cn)−log⁡N(xt;m,A).\log \frac{p(x_1, \ldots, x_n, x_t \mid H_s)}{p(x_1, \ldots, x_n, x_t \mid H_d)} = \log \mathcal{N}(x_t; m + \mu_n, W + C_n) - \log \mathcal{N}(x_t; m, A).

For n=1n = 1 this equals the value of Theorem 3. Lines L7 to L9 compute it.

Proof. Under both hypotheses, the enrollment embeddings have the same density p(x1,…,xn)p(x_1, \ldots, x_n). Under HdH_d, xtx_t is independent of them and has density N(m,A)\mathcal{N}(m, A). Under HsH_s, write the joint density as p(x1,…,xn) p(xt∣x1,…,xn)p(x_1, \ldots, x_n) \, p(x_t \mid x_1, \ldots, x_n). Thus the ratio is p(xt∣x1,…,xn,Hs)/N(xt;m,A)p(x_t \mid x_1, \ldots, x_n, H_s) / \mathcal{N}(x_t; m, A). Given yy, the xi−mx_i - m are independent N(y,W)\mathcal{N}(y, W). The prior N(0,B)\mathcal{N}(0, B) is conjugate, and the log posterior of yy is, up to a constant, −12y⊤(B−1+nW−1)y+y⊤W−1∑i(xi−m)-\frac12 y^\top (B^{-1} + n W^{-1}) y + y^\top W^{-1} \sum_i (x_i - m). So the posterior is N(μn,Cn)\mathcal{N}(\mu_n, C_n). Given the enrollment data, xt=m+y+etx_t = m + y + e_t, with yy from this posterior and et∼N(0,W)e_t \sim \mathcal{N}(0, W) independent of it. So xt∼N(m+μn,Cn+W)x_t \sim \mathcal{N}(m + \mu_n, C_n + W). For n=1n = 1, both theorems compute the log of the same ratio of densities, so the values are equal. □\square

Proposition 6 (the Prince-Elder parameters). In the model x=m+Fh+Gw+εx = m + F h + G w + \varepsilon, with h∼N(0,I)h \sim \mathcal{N}(0, I) shared by a speaker, w∼N(0,I)w \sim \mathcal{N}(0, I) new for each embedding, and ε∼N(0,Σ)\varepsilon \sim \mathcal{N}(0, \Sigma) with diagonal Σ\Sigma, the speaker term y=Fhy = F h has covariance B=FF⊤B = F F^\top and the session term Gw+εG w + \varepsilon has covariance W=GG⊤+ΣW = G G^\top + \Sigma. So the scores of Theorems 3 and 5 apply with these BB and WW.

Proof. Cov⁡(Fh)=FIF⊤\operatorname{Cov}(F h) = F I F^\top, and the session term is a sum of independent zero mean Gaussians, so its covariance is the sum of GG⊤G G^\top and Σ\Sigma. The scores depend on the model only through the joint distribution of the embeddings, which is the same as that of the two-covariance model with these BB and WW. □\square

Remark. The theorems hold for the model. They do not say that real embeddings are Gaussian. Length normalization and LDA before PLDA are heuristics that make the embeddings closer to Gaussian. The ratio is a calibrated likelihood ratio only to the extent that the model fits.

Complexity

In the real RAM, PREPARE inverts two d×dd \times d matrices and computes two log determinants, in O(d3)O(d^3) time and O(d2)O(d^2) memory. Each trial costs O(d2)O(d^2) for the quadratic forms, so NN trials cost O(d3+Nd2)O(d^3 + N d^2). For a speaker with nn enrollment embeddings, L7 and L8 cost O(d3+nd)O(d^3 + n d) once, and each test embedding then costs O(d2)O(d^2) if the inverse and log determinant of W+CnW + C_n are kept. With dd often 150 to 400 after LDA, scoring is cheap next to computing the embeddings.

Properties

  • Exact for the model. The score is the exact log likelihood ratio of the two-covariance model (a theorem). How well it fits real embeddings is a question of measurement.
  • Symmetric. LLR(x1,x2)=LLR(x2,x1)\text{LLR}(x_1, x_2) = \text{LLR}(x_2, x_1).
  • No speaker model. Enrollment stores an embedding, or the sufficient statistics nn and ∑i(xi−m)\sum_i (x_i - m). No per-speaker training is needed.
  • Uses the mean. The score depends on where the pair lies, not only on the distance between the two embeddings, unlike cosine similarity.
  • Not a calibrated ratio in practice. Real embeddings are not Gaussian, so the scores are often calibrated with an affine map before a Bayes threshold is applied.

Variants and improvements

  • The Prince-Elder form. x=m+Fh+Gw+εx = m + F h + G w + \varepsilon, with a speaker factor hh, a session factor ww and diagonal noise. With ε∼N(0,Σ)\varepsilon \sim \mathcal{N}(0, \Sigma), it is the two-covariance model with B=FF⊤B = F F^\top and W=GG⊤+ΣW = G G^\top + \Sigma. Low rank FF and GG reduce the number of parameters.
  • Simplified PLDA. Drop GG and let the noise covariance be full.
  • Heavy-tailed PLDA. Student's t priors in place of Gaussians, which fit raw i-vectors better.
  • Length normalization. Center, whiten and scale each embedding to unit length before Gaussian PLDA. In the experiments of Garcia-Romero and Espy-Wilson 2011, Gaussian PLDA after length normalization did about as well as heavy-tailed PLDA, at a lower cost (a measurement).
  • LDA first. Reduce the dimension with linear discriminant analysis (for example to 150) before PLDA.
  • Discriminative training. Train the parameters QQ, PP and cc of the quadratic form directly, for example with logistic regression on trial pairs.

When to use it

Use PLDA when speakers are represented by fixed-length embeddings and the training set has many speakers with several recordings each. It is the usual back end for i-vectors and x-vectors. When the embeddings come from a network trained with an angular margin loss, plain cosine scoring is a common choice. It needs no trained back end, and whether it matches PLDA depends on the system and the data.

Pitfalls

  • Wrong data for the parameters. BB and WW trained on one language or channel do not fit another. Adapt them, or at least recompute the mean on data from the new domain.
  • Skipping length normalization. Gaussian PLDA on raw embeddings fits poorly, because their norms vary a lot.
  • Singular matrices. WW must be positive definite. With low-rank GG and no noise term, WW is singular and the inverse fails. Add a diagonal term.
  • Joint densities in 2d2d dimensions. Computing the two joint densities directly costs O(d3)O(d^3) per trial and loses precision. Use the closed form.
  • Averaging enrollment scores. Averaging the LLRs of nn enrollment embeddings is not the LLR of the enrollment set. Use SCORE-MULTI, or average the embeddings and accept an approximation.

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.

plda_scoring.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/plda-scoring/. The authors are listed in prov/MHT9KM.jsonl.

"""PLDA scoring in the two-covariance model.

An embedding (i-vector or x-vector) of dimension d is modeled as

    x = m + y + e,   y ~ N(0, B) (the speaker),   e ~ N(0, W) (the session),

with y shared by all embeddings of one speaker. B and W are symmetric positive
definite matrices given as lists of rows; the code does not train them. With
A = B + W (the total covariance), the log likelihood ratio of "same speaker"
against "different speakers" for two embeddings is the closed form

    LLR(x1, x2) = 1/2 u'Qu + 1/2 v'Qv + u'Pv + c,   u = x1 - m, v = x2 - m,
    Q = A^-1 - (A - B A^-1 B)^-1,   P = A^-1 B (A - B A^-1 B)^-1,
    c = 1/2 (log|A| - log|A - B A^-1 B|).

score_multi scores a test embedding against several enrollment embeddings
through the posterior of the speaker variable. prince_elder_to_two_cov turns
the parameters (F, G, Sigma) of Prince and Elder 2007 into B and W. Every log
is the natural log.
"""

import math
from typing import List, Sequence, Tuple

Vector = List[float]
Matrix = List[List[float]]


def mat_add(X: Sequence[Sequence[float]], Y: Sequence[Sequence[float]], s: float = 1.0) -> Matrix:
    """Return X + s Y."""
    return [[a + s * b for a, b in zip(rx, ry)] for rx, ry in zip(X, Y)]


def mat_mul(X: Sequence[Sequence[float]], Y: Sequence[Sequence[float]]) -> Matrix:
    """Return the product X Y."""
    cols = list(zip(*Y))
    return [[math.fsum(a * b for a, b in zip(row, col)) for col in cols] for row in X]


def mat_vec(X: Sequence[Sequence[float]], v: Sequence[float]) -> Vector:
    """Return X v."""
    return [math.fsum(a * b for a, b in zip(row, v)) for row in X]


def dot(u: Sequence[float], v: Sequence[float]) -> float:
    return math.fsum(a * b for a, b in zip(u, v))


def transpose(X: Sequence[Sequence[float]]) -> Matrix:
    return [list(c) for c in zip(*X)]


def symmetrize(X: Sequence[Sequence[float]]) -> Matrix:
    n = len(X)
    return [[0.5 * (X[i][j] + X[j][i]) for j in range(n)] for i in range(n)]


def cholesky(S: Sequence[Sequence[float]]) -> Matrix:
    """Return the lower triangular L with L L' = S. Raise ValueError if S is not positive definite."""
    n = len(S)
    L = [[0.0] * n for _ in range(n)]
    for i in range(n):
        for j in range(i + 1):
            s = S[i][j] - math.fsum(L[i][k] * L[j][k] for k in range(j))
            if i == j:
                if s <= 0.0:
                    raise ValueError("the matrix is not positive definite")
                L[i][i] = math.sqrt(s)
            else:
                L[i][j] = s / L[j][j]
    return L


def logdet(S: Sequence[Sequence[float]]) -> float:
    """Return log det S for a positive definite S."""
    L = cholesky(S)
    return 2.0 * math.fsum(math.log(L[i][i]) for i in range(len(S)))


def inverse(S: Sequence[Sequence[float]]) -> Matrix:
    """Return the inverse of a positive definite S, through its Cholesky factor."""
    n = len(S)
    L = cholesky(S)
    inv = []
    for col in range(n):
        e = [1.0 if i == col else 0.0 for i in range(n)]
        z = [0.0] * n
        for i in range(n):
            z[i] = (e[i] - math.fsum(L[i][k] * z[k] for k in range(i))) / L[i][i]
        x = [0.0] * n
        for i in range(n - 1, -1, -1):
            x[i] = (z[i] - math.fsum(L[k][i] * x[k] for k in range(i + 1, n))) / L[i][i]
        inv.append(x)
    return symmetrize(transpose(inv))


def log_gauss(x: Sequence[float], mean: Sequence[float], S: Sequence[Sequence[float]]) -> float:
    """Return log N(x; mean, S) for a full covariance S."""
    diff = [a - b for a, b in zip(x, mean)]
    Si = inverse(S)
    return -0.5 * (len(x) * math.log(2.0 * math.pi) + logdet(S) + dot(diff, mat_vec(Si, diff)))


def prepare(B: Sequence[Sequence[float]], W: Sequence[Sequence[float]]) -> Tuple[Matrix, Matrix, float]:
    """Return (Q, P, c) of the closed form for between covariance B and within covariance W."""
    A = mat_add(B, W)  # @line L1
    Ai = inverse(A)
    S = symmetrize(mat_add(A, mat_mul(mat_mul(B, Ai), B), -1.0))  # A - B A^-1 B, the Schur complement
    Si = inverse(S)  # @line L2
    Q = symmetrize(mat_add(Ai, Si, -1.0))
    P = symmetrize(mat_mul(mat_mul(Ai, B), Si))  # @line L3
    c = 0.5 * (logdet(A) - logdet(S))  # @line L4
    return Q, P, c


def score(x1: Sequence[float], x2: Sequence[float], m: Sequence[float], prepared: Tuple[Matrix, Matrix, float]) -> float:
    """Return the closed form LLR of same speaker against different speakers."""
    Q, P, c = prepared
    u = [a - b for a, b in zip(x1, m)]  # @line L5
    v = [a - b for a, b in zip(x2, m)]
    return 0.5 * dot(u, mat_vec(Q, u)) + 0.5 * dot(v, mat_vec(Q, v)) + dot(u, mat_vec(P, v)) + c  # @line L6


def score_multi(enroll: Sequence[Sequence[float]], test: Sequence[float], m: Sequence[float],
                B: Sequence[Sequence[float]], W: Sequence[Sequence[float]]) -> float:
    """Return log p(test | enroll, same speaker) - log p(test | other speaker).

    The posterior of the speaker variable given n enrollment embeddings is
    N(mu_n, C_n) with C_n = (B^-1 + n W^-1)^-1 and mu_n = C_n W^-1 sum (x_i - m).
    The test embedding then has the predictive density N(m + mu_n, W + C_n).
    """
    n = len(enroll)
    if n == 0:
        raise ValueError("no enrollment embeddings")
    d = len(m)
    Wi = inverse(W)
    Cn = inverse(mat_add(inverse(B), Wi, float(n)))  # @line L7
    tot = [math.fsum(x[i] - m[i] for x in enroll) for i in range(d)]
    mu = mat_vec(Cn, mat_vec(Wi, tot))  # @line L8
    same = log_gauss(test, [a + b for a, b in zip(m, mu)], mat_add(W, Cn))
    diff = log_gauss(test, m, mat_add(B, W))
    return same - diff  # @line L9


def prince_elder_to_two_cov(F: Sequence[Sequence[float]], G: Sequence[Sequence[float]],
                            Sigma: Sequence[float]) -> Tuple[Matrix, Matrix]:
    """Map x = m + F h + G w + eps, eps ~ N(0, diag(Sigma)), to B = F F' and W = G G' + diag(Sigma)."""
    B = mat_mul(F, transpose(F))
    W = mat_mul(G, transpose(G)) if G and G[0] else [[0.0] * len(F) for _ in F]
    for i, s in enumerate(Sigma):
        W[i][i] += s
    return B, W
test_plda_scoring.py 163 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/plda-scoring/. The authors are listed in prov/MHT9KM.jsonl.

import math
import os
import random
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

import pytest

from plda_scoring import (
    cholesky,
    inverse,
    log_gauss,
    logdet,
    mat_mul,
    prepare,
    prince_elder_to_two_cov,
    score,
    score_multi,
)


def random_spd(rng, d, scale=1.0):
    R = [[rng.gauss(0.0, 1.0) for _ in range(d)] for _ in range(d)]
    S = mat_mul(R, [list(c) for c in zip(*R)])
    for i in range(d):
        S[i][i] += 0.5 * d
    return [[scale * v for v in row] for row in S]


def block(rows_of_blocks):
    out = []
    for brow in rows_of_blocks:
        for r in range(len(brow[0])):
            out.append([v for blk in brow for v in blk[r]])
    return out


def zeros(d):
    return [[0.0] * d for _ in range(d)]


def joint_llr(enroll, test, m, B, W):
    """Brute force: joint Gaussian of all embeddings under one speaker, against the test from a new speaker."""
    A = [[b + w for b, w in zip(rb, rw)] for rb, rw in zip(B, W)]
    xs = list(enroll) + [test]
    k = len(xs)
    big = block([[A if i == j else B for j in range(k)] for i in range(k)])
    flat = [v for x in xs for v in x]
    mean = [v for _ in range(k) for v in m]
    same = log_gauss(flat, mean, big)
    k1 = len(enroll)
    big1 = block([[A if i == j else B for j in range(k1)] for i in range(k1)])
    flat1 = [v for x in enroll for v in x]
    mean1 = [v for _ in range(k1) for v in m]
    enroll_only = log_gauss(flat1, mean1, big1)
    return same - enroll_only - log_gauss(test, m, A)


def test_closed_form_matches_joint_gaussian():
    rng = random.Random(1)
    for d in (1, 2, 3):
        B = random_spd(rng, d)
        W = random_spd(rng, d, 0.5)
        m = [rng.uniform(-1.0, 1.0) for _ in range(d)]
        prep = prepare(B, W)
        for _ in range(5):
            x1 = [rng.gauss(0.0, 2.0) for _ in range(d)]
            x2 = [rng.gauss(0.0, 2.0) for _ in range(d)]
            assert score(x1, x2, m, prep) == pytest.approx(joint_llr([x1], x2, m, B, W), abs=1e-9)


def test_symmetry_and_signs():
    rng = random.Random(2)
    d = 3
    B = random_spd(rng, d)
    W = random_spd(rng, d)
    Q, P, c = prepare(B, W)
    m = [0.0] * d
    x1 = [0.3, -1.2, 0.7]
    x2 = [1.1, 0.4, -0.5]
    assert score(x1, x2, m, (Q, P, c)) == pytest.approx(score(x2, x1, m, (Q, P, c)), abs=1e-12)
    for i in range(d):
        for j in range(d):
            assert P[i][j] == pytest.approx(P[j][i], abs=1e-12)
    # Q is negative definite, so -Q has a Cholesky factor.
    cholesky([[-v for v in row] for row in Q])
    assert c > 0.0


def test_multi_enrollment_matches_joint_gaussian():
    rng = random.Random(3)
    d = 2
    B = random_spd(rng, d)
    W = random_spd(rng, d, 0.7)
    m = [0.5, -0.5]
    for n in (1, 2, 4):
        enroll = [[rng.gauss(0.0, 1.5) for _ in range(d)] for _ in range(n)]
        test = [rng.gauss(0.0, 1.5) for _ in range(d)]
        assert score_multi(enroll, test, m, B, W) == pytest.approx(joint_llr(enroll, test, m, B, W), abs=1e-9)


def test_one_enrollment_equals_closed_form():
    rng = random.Random(4)
    d = 3
    B = random_spd(rng, d)
    W = random_spd(rng, d)
    m = [0.1, 0.2, 0.3]
    prep = prepare(B, W)
    x1 = [1.0, -0.5, 0.25]
    x2 = [0.75, -0.25, 0.5]
    assert score_multi([x1], x2, m, B, W) == pytest.approx(score(x1, x2, m, prep), abs=1e-9)


def test_tiny_between_covariance_gives_zero():
    B = [[1e-9, 0.0], [0.0, 1e-9]]
    W = [[1.0, 0.2], [0.2, 1.5]]
    prep = prepare(B, W)
    assert abs(score([3.0, -2.0], [-1.0, 4.0], [0.0, 0.0], prep)) < 1e-6


def test_page_example():
    prep = prepare([[3.0]], [[1.0]])
    Q, P, c = prep
    assert Q[0][0] == pytest.approx(-9.0 / 28.0, abs=1e-12)
    assert P[0][0] == pytest.approx(3.0 / 7.0, abs=1e-12)
    assert c == pytest.approx(0.5 * math.log(16.0 / 7.0), abs=1e-12)
    expected = {(1.0, 1.0): 0.520482, (1.0, -1.0): -0.336661, (0.0, 0.0): 0.413339,
                (2.0, 2.0): 0.841911, (3.0, 0.0): -1.033089}
    for (a, b), v in expected.items():
        assert score([a], [b], [0.0], prep) == pytest.approx(v, abs=1e-6)


def test_prince_elder_map():
    F = [[1.0], [2.0]]
    G = [[0.5], [0.0]]
    Sigma = [0.1, 0.3]
    B, W = prince_elder_to_two_cov(F, G, Sigma)
    assert B == [[1.0, 2.0], [2.0, 4.0]]
    assert W[0][0] == pytest.approx(0.35)
    assert W[0][1] == pytest.approx(0.0)
    assert W[1][1] == pytest.approx(0.3)
    # B is singular here (rank one), which the closed form allows because A and the Schur complement stay definite.
    prep = prepare(B, W)
    x1, x2 = [0.4, 1.1], [0.6, 0.9]
    assert score(x1, x2, [0.0, 0.0], prep) == pytest.approx(joint_llr([x1], x2, [0.0, 0.0], B, W), abs=1e-9)


def test_linear_algebra_helpers():
    S = [[4.0, 2.0], [2.0, 3.0]]
    assert logdet(S) == pytest.approx(math.log(8.0), abs=1e-12)
    Si = inverse(S)
    prod = mat_mul(S, Si)
    for i in range(2):
        for j in range(2):
            assert prod[i][j] == pytest.approx(1.0 if i == j else 0.0, abs=1e-12)
    with pytest.raises(ValueError):
        cholesky([[1.0, 2.0], [2.0, 1.0]])
    with pytest.raises(ValueError):
        score_multi([], [0.0], [0.0], [[1.0]], [[1.0]])

History

Ioffe 2006 and Prince and Elder 2007 proposed probabilistic LDA for face recognition. Both write the observation as a class-dependent part plus a within-class part and score identity by comparing hypotheses, with a closed form likelihood. Speaker recognition took PLDA up for i-vectors around 2010, first with heavy-tailed priors and then, after length normalization (Garcia-Romero and Espy-Wilson 2011), with Gaussian priors. When x-vectors replaced i-vectors in 2018, the back end of LDA, length normalization and PLDA stayed the same.

References

  1. Simon J. D. Prince and James H. Elder, Probabilistic linear discriminant analysis for inferences about identity, IEEE 11th International Conference on Computer Vision (ICCV), 2007, the model with a signal subspace and a noise subspace, and the likelihood of a match
  2. Sergey Ioffe, Probabilistic linear discriminant analysis, European Conference on Computer Vision (ECCV), Lecture Notes in Computer Science 3954, 2006, the generative model with a Gaussian prior on the class centers
  3. Daniel Garcia-Romero and Carol Y. Espy-Wilson, Analysis of i-vector length normalization in speaker recognition systems, Interspeech 2011, the Gaussian PLDA model for i-vectors and the length normalization before it

Where this leads

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