Algorithm Search⌘K

Algorithmadvanced

Cross-lingual embedding mapping

Also called bilingual embedding mapping, orthogonal Procrustes mapping.

Learn a linear, often orthogonal, map from the embedding space of one language to another from a seed dictionary, solved in closed form by SVD.

Time
O(n d^2 + d^3) worst
Space
O(d^2) extra
Where
d = the dimension of the vectors; n = the number of word pairs in the seed dictionary
Properties
deterministicexactofflineiterative
Origin
Tomas Mikolov, Quoc V. Le, Ilya Sutskever, 2013

Cross-lingual embedding mapping learns a matrix WW that sends the word vectors of a source language into the vector space of a target language, so that the image of a word lies near the vector of its translation. It needs word vectors trained separately on text in each language and a seed dictionary of a few thousand translation pairs. Mikolov, Le and Sutskever (2013) fitted WW by least squares. Xing, Wang, Liu and Lin (2015) normalized the vectors to unit length and required WW to be orthogonal, so that the map keeps all distances and angles within the source space. The orthogonal fit is the orthogonal Procrustes problem, and its solution is W=UV⊤W = U V^\top from the singular value decomposition UΣV⊤U \Sigma V^\top of the d×dd \times d matrix Y⊤XY^\top X (Schönemann 1966). After the map, a source word is translated to the target word nearest to its image, often by CSLS rather than plain cosine.

In plain words

Word vectors trained on English text and on Spanish text have a similar shape: "dog" is near "cat" in both, and "king" is to "queen" in both as "man" is to "woman". But the two spaces are not lined up, because each training run places its vectors in an arbitrary orientation.

Given a short list of known translations, find the turn (and possibly a mirror flip) of the English space that brings each listed English word as close as possible to its Spanish translation. A turn does not stretch anything, so the English space keeps its shape.

There is an exact recipe for the best turn, using a standard matrix factorization. After the turn, translate any English word by finding the Spanish word closest to where it lands.

The problem

The input is a seed dictionary of nn pairs, given as two matrices X,Y∈Rn×dX, Y \in \mathbb{R}^{n \times d} whose row ii holds the source vector x⃗i\vec x_i and the target vector y⃗i\vec y_i of pair ii. The orthogonal mapping problem is

min⁡W∈O(d)∑i=1n∥Wx⃗i−y⃗i∥2=min⁡W∈O(d)∥XW⊤−Y∥F2,\min_{W \in O(d)} \sum_{i=1}^{n} \|W \vec x_i - \vec y_i\|^2 = \min_{W \in O(d)} \|X W^\top - Y\|_F^2,

where O(d)O(d) is the set of orthogonal d×dd \times d matrices (W⊤W=IW^\top W = I). It allows rotations and reflections. The unconstrained version, over all d×dd \times d matrices, is the least squares map of Mikolov et al. With columns instead of rows, as in Conneau et al., the matrix Y⊤XY^\top X is written YX⊤Y X^\top.

For an orthogonal WW, ∥Wx⃗i−y⃗i∥2=∥x⃗i∥2+∥y⃗i∥2−2 y⃗i⊤Wx⃗i\|W \vec x_i - \vec y_i\|^2 = \|\vec x_i\|^2 + \|\vec y_i\|^2 - 2\,\vec y_i^\top W \vec x_i, so the problem is the same as maximizing ∑iy⃗i⊤Wx⃗i=tr⁡(W⊤M)\sum_i \vec y_i^\top W \vec x_i = \operatorname{tr}(W^\top M) with M=Y⊤XM = Y^\top X.

The algorithm

  1. ORTHOGONAL-MAP(X, Y)
  2. 1scale every row of X and of Y to unit length (optionally center first)
  3. 2M ← Y^T X ▷ d × d, a sum of n outer products
  4. 3U, Σ, V ← SVD(M) ▷ M = U Σ V^T
  5. 4W ← U V^T
  6. 5return W ▷ translate x by the target nearest to W x

Line L1 makes the squared distance a function of the cosine, which is the measure used for retrieval. Line L2 is the only step that reads the dictionary: M=∑iy⃗ix⃗i⊤M = \sum_i \vec y_i \vec x_i^\top. Line L3 takes the SVD of this small matrix, and line L4 drops the singular values: WW is the orthogonal factor of the polar decomposition of MM. The code computes the SVD by the one-sided Jacobi method and checks WW against the Newton iteration W←(W+W−⊤)/2W \leftarrow (W + W^{-\top})/2 for the polar factor.

Example

Take d=2d = 2 and three pairs, without normalization: XX has the rows (1,0)(1, 0), (0,1)(0, 1), (1,1)(1, 1) and YY the rows (0.9,0.5)(0.9, 0.5), (−0.5,0.9)(-0.5, 0.9), (0.4,1.3)(0.4, 1.3).

step line value
M=Y⊤XM = Y^\top X L2 (1.3−0.11.82.2)\begin{pmatrix} 1.3 & -0.1 \\ 1.8 & 2.2 \end{pmatrix}
singular values L3 2.9530, 1.0295
W=UV⊤W = U V^\top L4 (0.8789−0.47710.47710.8789)\begin{pmatrix} 0.8789 & -0.4771 \\ 0.4771 & 0.8789 \end{pmatrix}
loss ∑i∥Wx⃗i−y⃗i∥2\sum_i \|W \vec x_i - \vec y_i\|^2 0.0051

WW is the rotation by 28.50°28.50°. In two dimensions the best rotation has the angle atan2⁡(M21−M12,M11+M22)=atan2⁡(1.9,3.5)\operatorname{atan2}(M_{21} - M_{12}, M_{11} + M_{22}) = \operatorname{atan2}(1.9, 3.5), which agrees. The identity map has the loss 0.97. The least squares map is (0.9−0.50.46670.8667)\begin{pmatrix} 0.9 & -0.5 \\ 0.4667 & 0.8667 \end{pmatrix} with a smaller loss, 0.0033, but it is not orthogonal: the entries of WW⊤−IW W^\top - I reach 0.06.

The reflection case. Take X=IX = I and Y=diag⁡(1,−1)Y = \operatorname{diag}(1, -1) (the rows (1,0)(1, 0) and (0,−1)(0, -1)). Then M=diag⁡(1,−1)M = \operatorname{diag}(1, -1), and the algorithm returns W=diag⁡(1,−1)W = \operatorname{diag}(1, -1), a reflection with loss 0. Every rotation by an angle θ\theta has the loss (2−2cos⁡θ)+(2+2cos⁡θ)=4(2 - 2\cos\theta) + (2 + 2\cos\theta) = 4.

Correctness

For orthogonal WW, write Z=V⊤W⊤UZ = V^\top W^\top U, which is orthogonal. Then tr⁡(W⊤M)=tr⁡(W⊤UΣV⊤)=tr⁡(ZΣ)=∑kzkkσk≤∑kσk\operatorname{tr}(W^\top M) = \operatorname{tr}(W^\top U \Sigma V^\top) = \operatorname{tr}(Z \Sigma) = \sum_k z_{kk} \sigma_k \le \sum_k \sigma_k, because every entry of an orthogonal matrix is at most 1 in absolute value and σk≥0\sigma_k \ge 0. The bound is reached at Z=IZ = I, that is W=UV⊤W = U V^\top, which line L4 returns. When MM is nonsingular the maximizer is unique. The full proof, with the rank-deficient case, is in the proof file.

Difference from Kabsch. The Kabsch algorithm solves the same problem for molecules over the rotations only (det⁡W=+1\det W = +1), because no rigid motion turns a molecule into its mirror image. It replaces UV⊤U V^\top by Udiag⁡(1,…,1,s)V⊤U \operatorname{diag}(1, \ldots, 1, s) V^\top with s=sign⁡det⁡(UV⊤)s = \operatorname{sign}\det(U V^\top), and it centers both point sets to remove the translation. For word vectors a reflection is as good as a rotation: it keeps every dot product and every distance, so no sign fix is needed, and the minimum over O(d)O(d) is never worse than the minimum over rotations. In the reflection example above, the Kabsch answer would be a rotation with loss 4 instead of the reflection with loss 0.

Proof: W = U V^T is an orthogonal map of least squared error, and it is the only one when M is nonsingularfull

Let X,Y∈Rn×dX, Y \in \mathbb{R}^{n \times d} hold the source vectors x⃗i\vec x_i and the target vectors y⃗i\vec y_i as rows (after line L1). Let M=Y⊤XM = Y^\top X (line L2) and let M=UΣV⊤M = U \Sigma V^\top be a singular value decomposition (line L3): UU and VV are orthogonal d×dd \times d matrices and Σ=diag⁡(σ1,…,σd)\Sigma = \operatorname{diag}(\sigma_1, \ldots, \sigma_d) with σk≥0\sigma_k \ge 0. We prove that W=UV⊤W = U V^\top (line L4) is orthogonal and minimizes

f(W)=∑i=1n∥Wx⃗i−y⃗i∥2f(W) = \sum_{i=1}^{n} \|W \vec x_i - \vec y_i\|^2

over all orthogonal WW, and that it is the only minimizer when MM is nonsingular.

Step 1. W=UV⊤W = U V^\top is orthogonal.

W⊤W=VU⊤UV⊤=VV⊤=IW^\top W = V U^\top U V^\top = V V^\top = I, because UU and VV are orthogonal. □\square

Step 2. Over orthogonal maps, minimizing ff is maximizing tr⁡(W⊤M)\operatorname{tr}(W^\top M).

For an orthogonal WW, ∥Wx⃗i∥=∥x⃗i∥\|W \vec x_i\| = \|\vec x_i\|, so

∥Wx⃗i−y⃗i∥2=∥x⃗i∥2+∥y⃗i∥2−2 y⃗i⊤Wx⃗i.\|W \vec x_i - \vec y_i\|^2 = \|\vec x_i\|^2 + \|\vec y_i\|^2 - 2\,\vec y_i^\top W \vec x_i.

Summing over ii, f(W)=∥X∥F2+∥Y∥F2−2∑iy⃗i⊤Wx⃗if(W) = \|X\|_F^2 + \|Y\|_F^2 - 2 \sum_i \vec y_i^\top W \vec x_i. The first two terms do not depend on WW. For the last term, y⃗i⊤Wx⃗i=tr⁡(Wx⃗iy⃗i⊤)\vec y_i^\top W \vec x_i = \operatorname{tr}(W \vec x_i \vec y_i^\top), and ∑ix⃗iy⃗i⊤=X⊤Y=M⊤\sum_i \vec x_i \vec y_i^\top = X^\top Y = M^\top, so

∑iy⃗i⊤Wx⃗i=tr⁡(WM⊤)=tr⁡(MW⊤)=tr⁡(W⊤M).\sum_i \vec y_i^\top W \vec x_i = \operatorname{tr}(W M^\top) = \operatorname{tr}(M W^\top) = \operatorname{tr}(W^\top M).

So f(W)=∥X∥F2+∥Y∥F2−2tr⁡(W⊤M)f(W) = \|X\|_F^2 + \|Y\|_F^2 - 2\operatorname{tr}(W^\top M), and an orthogonal WW minimizes ff exactly when it maximizes g(W)=tr⁡(W⊤M)g(W) = \operatorname{tr}(W^\top M). □\square

Step 3. g(W)≤∑kσkg(W) \le \sum_k \sigma_k for every orthogonal WW.

Let Z=V⊤W⊤UZ = V^\top W^\top U. It is a product of orthogonal matrices, so it is orthogonal. By the cyclic property of the trace,

g(W)=tr⁡(W⊤UΣV⊤)=tr⁡(V⊤W⊤UΣ)=tr⁡(ZΣ)=∑k=1dzkkσk.g(W) = \operatorname{tr}(W^\top U \Sigma V^\top) = \operatorname{tr}(V^\top W^\top U \Sigma) = \operatorname{tr}(Z \Sigma) = \sum_{k=1}^{d} z_{kk} \sigma_k.

Each column of ZZ is a unit vector, so ∣zkk∣≤1|z_{kk}| \le 1. Since σk≥0\sigma_k \ge 0, zkkσk≤σkz_{kk}\sigma_k \le \sigma_k for every kk, and g(W)≤∑kσkg(W) \le \sum_k \sigma_k. □\square

Step 4. W=UV⊤W = U V^\top reaches the bound.

For W=UV⊤W = U V^\top, Z=V⊤VU⊤U=IZ = V^\top V U^\top U = I, so g(W)=∑kσkg(W) = \sum_k \sigma_k. With Steps 2 and 3, f(UV⊤)≤f(W)f(U V^\top) \le f(W) for every orthogonal WW. With Step 1, line L4 returns an orthogonal minimizer. Line L5 returns it unchanged. □\square

Step 5. The minimizer is unique when MM is nonsingular.

If MM is nonsingular, then every σk>0\sigma_k > 0. Let WW be any orthogonal minimizer. By Step 4, g(W)=∑kσkg(W) = \sum_k \sigma_k, so ∑k(1−zkk)σk=0\sum_k (1 - z_{kk})\sigma_k = 0. Every term is at least 0, so zkk=1z_{kk} = 1 for every kk. A unit column with the diagonal entry 1 has all other entries 0, so Z=IZ = I. Then V⊤W⊤U=IV^\top W^\top U = I gives W⊤=VU⊤W^\top = V U^\top, that is W=UV⊤W = U V^\top.

This does not depend on which SVD line L3 returns. When the singular values are distinct, UU and VV are unique up to the signs of matching columns, and a sign change of column kk in both UU and VV leaves UV⊤U V^\top unchanged. In every case, the argument above shows that each orthogonal minimizer is equal to UV⊤U V^\top for the SVD in hand, so all SVDs give the same WW. □\square

Step 6. The singular case.

If some σk=0\sigma_k = 0, then zkkz_{kk} is free in Step 5, and the minimizer can fail to be unique. Step 4 still holds for any SVD, including one whose columns of UU for the zero singular values are any orthonormal completion, which is how the code builds them. So line L4 always returns a minimizer, though not always the only one. For example, with n=1n = 1, d=2d = 2, x⃗1=(1,0)\vec x_1 = (1, 0) and y⃗1=(0,1)\vec y_1 = (0, 1), both the rotation by 90°90° and the reflection that swaps the two axes send x⃗1\vec x_1 to y⃗1\vec y_1 with error 0. ■\blacksquare

Remark. The bound of Step 3 uses all orthogonal ZZ, including those with determinant −1-1. If WW must be a rotation (det⁡W=1\det W = 1), the bound is not always reached, and the answer is the Kabsch correction Udiag⁡(1,…,1,s)V⊤U \operatorname{diag}(1, \ldots, 1, s) V^\top with s=det⁡(UV⊤)s = \det(U V^\top). The mapping of word vectors allows reflections, so it does not need this correction.

Complexity

Line L1 costs O(nd)O(nd). Line L2 costs O(nd2)O(nd^2). Lines L3 and L4 work on a d×dd \times d matrix and cost O(d3)O(d^3) for an SVD to fixed precision (the Jacobi method used here needs a few sweeps of O(d3)O(d^3) each in practice). The total is O(nd2+d3)O(nd^2 + d^3) time and O(d2)O(d^2) extra space beyond the input. Since dd is a few hundred and nn a few thousand, this is small next to the training of the vectors. Translating one word afterwards is a nearest neighbour search over the target vocabulary, O(Vd)O(Vd) by brute force, or faster with an index (k-nearest neighbor search).

Properties

  • Isometry. An orthogonal WW keeps the norms, the dot products and the distances of the source space, so monolingual similarity is unchanged.
  • Closed form. No learning rate, no iterations over the data, and the answer is the global optimum.
  • Unique when MM is nonsingular. With n<dn < d or a degenerate dictionary, MM is singular, and the optimum is not unique; any completion of UU and VV gives an optimal WW.
  • Symmetric. The map for the opposite direction is W⊤W^\top, since the problem with XX and YY swapped has M⊤=VΣU⊤M^\top = V \Sigma U^\top and the answer VU⊤=W⊤V U^\top = W^\top.
  • Linear. The method assumes that the two spaces differ by a rotation or reflection; it cannot fix differences in shape between the spaces.

Variants and improvements

  • Least squares. Mikolov et al. fit an unconstrained WW, the ordinary least squares solution W=(Y⊤X)(X⊤X)−1W = (Y^\top X)(X^\top X)^{-1} when XX has full column rank. It fits the seed pairs better but distorts the source space.
  • Refinement. Conneau et al. alternate two steps: build a new dictionary from the mutual nearest neighbours of the mapped words, then refit WW by Procrustes. This can start from a very small dictionary, or from an unsupervised one found by adversarial training.
  • Retrieval. Plain nearest neighbour retrieval suffers from hubness: a few target words are nearest to many mapped words. CSLS corrects for it and gives a large gain in precision.
  • Preprocessing. Unit length, then centering, then unit length again is a common normalization before line L2. Centering keeps the problem a pure rotation by removing the mean of each space, as Kabsch does with the translation.
  • Scaling. Allowing W=c QW = c\,Q with an orthogonal QQ and a scalar c>0c > 0 adds one degree of freedom and gives the same QQ.

When to use it

Use the orthogonal map when the two monolingual spaces are trained in the same way and you have a seed dictionary of a few thousand pairs, or a way to build one. It is the standard supervised baseline for bilingual lexicon induction. Use least squares only when the spaces have clearly different shapes and the dictionary is large, since it overfits the seed pairs. For distant languages or very different corpora, the linear assumption is weaker, and methods that learn both spaces jointly may do better.

Pitfalls

  • The order of the factors. Line L2 must form Y⊤XY^\top X (target by source) for a map x⃗↦Wx⃗\vec x \mapsto W\vec x. With X⊤YX^\top Y, the result is W⊤W^\top, the inverse map, which is not optimal in general.
  • Keeping the singular values. Line L4 must drop Σ\Sigma. UΣV⊤U \Sigma V^\top is MM itself, not an orthogonal matrix.
  • Adding the Kabsch sign fix. Copying the determinant correction from molecular superposition into line L4 restricts the answer to rotations and can give a worse map. Embeddings have no handedness, so reflections are allowed.
  • Normalizing after the fit. The normalization of line L1 must be applied before line L2 and also to every vector translated later. A map fitted on unit vectors and applied to raw vectors gives images of the wrong scale, which matters for distances though not for cosines.
  • Duplicate source words. A dictionary with several translations of one word gives it several rows; this is allowed, but it weights that word more in MM.

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.

cross_lingual_embedding_mapping.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cross-lingual-embedding-mapping/. The authors are listed in prov/CP9A01.jsonl.

"""Linear and orthogonal maps between two embedding spaces.

X and Y are lists of n rows of length d. Row i of Y is the vector of the
translation of the word of row i of X (the seed dictionary). A map W is a
d x d matrix that sends a source vector x to W x.

procrustes_map solves min ||W X^T - Y^T||_F over orthogonal W. The answer is
W = U V^T, where U S V^T is the singular value decomposition of M = Y^T X
(Schönemann 1966). The SVD is a one-sided Jacobi method in pure Python.
polar_newton is an independent check: the Newton iteration for the
orthogonal polar factor of a nonsingular M gives the same W.

least_squares_map is the unconstrained map of Mikolov, Le and Sutskever 2013.
"""

import math
from typing import Sequence

Matrix = list[list[float]]


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


def matmul(a: Sequence[Sequence[float]], b: Sequence[Sequence[float]]) -> Matrix:
    bt = transpose(b)
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def identity(d: int) -> Matrix:
    return [[1.0 if i == j else 0.0 for j in range(d)] for i in range(d)]


def apply(w: Sequence[Sequence[float]], x: Sequence[float]) -> list[float]:
    return [sum(a * b for a, b in zip(row, x)) for row in w]


def normalize_rows(x: Sequence[Sequence[float]], center: bool = False) -> Matrix:
    """Optionally subtract the mean row, then scale each row to unit length."""
    rows = [list(map(float, r)) for r in x]
    if center and rows:
        mean = [sum(c) / len(rows) for c in zip(*rows)]
        rows = [[a - m for a, m in zip(r, mean)] for r in rows]
    out = []
    for r in rows:
        nrm = math.sqrt(sum(a * a for a in r))
        out.append([a / nrm for a in r] if nrm > 0 else r)
    return out


def svd(m: Sequence[Sequence[float]], tol: float = 1e-15, max_sweeps: int = 100):
    """Return U, s, V with M = U diag(s) V^T for a square matrix M.

    One-sided Jacobi (Hestenes): rotate pairs of columns of A = M until they
    are orthogonal, and apply the same rotations to V. Then the column norms
    are the singular values and the normalized columns are the columns of U.
    Columns of U for zero singular values are completed to an orthonormal basis.
    """
    d = len(m)
    a = [list(map(float, r)) for r in m]
    v = identity(d)
    for _ in range(max_sweeps):
        rotated = False
        for p in range(d - 1):
            for q in range(p + 1, d):
                alpha = sum(a[i][p] ** 2 for i in range(d))
                beta = sum(a[i][q] ** 2 for i in range(d))
                gamma = sum(a[i][p] * a[i][q] for i in range(d))
                if abs(gamma) <= tol * math.sqrt(alpha * beta) or gamma == 0.0:
                    continue
                rotated = True
                zeta = (beta - alpha) / (2.0 * gamma)
                t = (1.0 if zeta >= 0 else -1.0) / (abs(zeta) + math.sqrt(1.0 + zeta * zeta))
                c = 1.0 / math.sqrt(1.0 + t * t)
                s = c * t
                for mat in (a, v):
                    for i in range(d):
                        x, y = mat[i][p], mat[i][q]
                        mat[i][p] = c * x - s * y
                        mat[i][q] = s * x + c * y
        if not rotated:
            break
    sv = [math.sqrt(sum(a[i][j] ** 2 for i in range(d))) for j in range(d)]
    order = sorted(range(d), key=lambda j: -sv[j])
    s = [sv[j] for j in order]
    v = [[v[i][j] for j in order] for i in range(d)]
    cols: list[list[float]] = []
    scale = s[0] if s and s[0] > 0 else 1.0
    for k, j in enumerate(order):
        if s[k] > 1e-12 * scale:
            cols.append([a[i][j] / s[k] for i in range(d)])
        else:
            cols.append(None)  # type: ignore[arg-type]
    basis = iter(identity(d))
    for k in range(d):
        if cols[k] is not None:
            continue
        while True:  # Gram-Schmidt on the unit vectors until one is independent
            e = next(basis)
            for c in cols:
                if c is not None:
                    dot = sum(x * y for x, y in zip(e, c))
                    e = [x - dot * y for x, y in zip(e, c)]
            nrm = math.sqrt(sum(x * x for x in e))
            if nrm > 1e-6:
                cols[k] = [x / nrm for x in e]
                break
    u = transpose(cols)
    return u, s, v


def procrustes_map(x: Sequence[Sequence[float]], y: Sequence[Sequence[float]]) -> Matrix:
    """The orthogonal W that minimizes sum_i |W x_i - y_i|^2."""
    m = matmul(transpose(y), x)  # @line L2
    u, _, v = svd(m)  # @line L3
    return matmul(u, transpose(v))  # @line L4


def fit_orthogonal(x, y, normalize: bool = True, center: bool = False) -> Matrix:
    """The full method: optional unit length (and centering), then Procrustes."""
    if normalize:
        x, y = normalize_rows(x, center), normalize_rows(y, center)  # @line L1
    return procrustes_map(x, y)  # @line L5


def inverse(m: Sequence[Sequence[float]]) -> Matrix:
    """Gauss-Jordan inverse with partial pivoting."""
    d = len(m)
    a = [list(map(float, r)) + [1.0 if i == j else 0.0 for j in range(d)] for i, r in enumerate(m)]
    for c in range(d):
        p = max(range(c, d), key=lambda r: abs(a[r][c]))
        if abs(a[p][c]) < 1e-300:
            raise ValueError("singular matrix")
        a[c], a[p] = a[p], a[c]
        piv = a[c][c]
        a[c] = [t / piv for t in a[c]]
        for r in range(d):
            if r != c and a[r][c] != 0.0:
                f = a[r][c]
                a[r] = [s - f * t for s, t in zip(a[r], a[c])]
    return [row[d:] for row in a]


def polar_newton(m: Sequence[Sequence[float]], iters: int = 100, tol: float = 1e-15) -> Matrix:
    """Orthogonal polar factor of a nonsingular M by W <- (W + W^-T) / 2."""
    w = [list(map(float, r)) for r in m]
    for _ in range(iters):
        nxt = [[(a + b) / 2.0 for a, b in zip(r1, r2)] for r1, r2 in zip(w, transpose(inverse(w)))]
        diff = max(abs(a - b) for r1, r2 in zip(nxt, w) for a, b in zip(r1, r2))
        w = nxt
        if diff < tol:
            break
    return w


def least_squares_map(x: Sequence[Sequence[float]], y: Sequence[Sequence[float]]) -> Matrix:
    """The unconstrained W = (Y^T X)(X^T X)^-1; needs n >= d and X of full rank."""
    return matmul(matmul(transpose(y), x), inverse(matmul(transpose(x), x)))


def loss(w: Sequence[Sequence[float]], x, y) -> float:
    return sum(sum((a - b) ** 2 for a, b in zip(apply(w, xi), yi)) for xi, yi in zip(x, y))


def orthogonality_error(w: Sequence[Sequence[float]]) -> float:
    g = matmul(w, transpose(w))
    return max(abs(g[i][j] - (1.0 if i == j else 0.0)) for i in range(len(g)) for j in range(len(g)))


def cosine(u: Sequence[float], v: Sequence[float]) -> float:
    nu = math.sqrt(sum(a * a for a in u))
    nv = math.sqrt(sum(a * a for a in v))
    return sum(a * b for a, b in zip(u, v)) / (nu * nv)


def translate(w, source: dict[str, Sequence[float]], target: dict[str, Sequence[float]]) -> dict[str, str]:
    """Nearest target word by cosine for each mapped source word (ties: the first in sorted order)."""
    out = {}
    for s, vec in source.items():
        z = apply(w, vec)
        best = max(sorted(target), key=lambda t: cosine(z, target[t]))
        out[s] = best
    return out


def precision_at_1(pred: dict[str, str], gold: dict[str, set[str]]) -> float:
    return sum(1 for s in gold if pred.get(s) in gold[s]) / len(gold)
test_cross_lingual_embedding_mapping.py 165 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cross-lingual-embedding-mapping/. The authors are listed in prov/CP9A01.jsonl.

import math
import random

from cross_lingual_embedding_mapping import (
    apply,
    fit_orthogonal,
    identity,
    least_squares_map,
    loss,
    matmul,
    orthogonality_error,
    polar_newton,
    precision_at_1,
    procrustes_map,
    svd,
    translate,
    transpose,
)


def random_orthogonal(rng, d):
    """Gram-Schmidt on a Gaussian matrix: a random orthogonal matrix (det may be -1)."""
    cols = []
    while len(cols) < d:
        v = [rng.gauss(0, 1) for _ in range(d)]
        for c in cols:
            dot = sum(a * b for a, b in zip(v, c))
            v = [a - dot * b for a, b in zip(v, c)]
        n = math.sqrt(sum(a * a for a in v))
        if n > 1e-3:
            cols.append([a / n for a in v])
    return transpose(cols)


def gaussian_rows(rng, n, d):
    return [[rng.gauss(0, 1) for _ in range(d)] for _ in range(n)]


def max_abs_diff(a, b):
    return max(abs(x - y) for r, s in zip(a, b) for x, y in zip(r, s))


def test_svd_reconstructs():
    rng = random.Random(1)
    for d in (1, 2, 3, 5, 8, 16):
        m = gaussian_rows(rng, d, d)
        u, s, v = svd(m)
        assert orthogonality_error(u) < 1e-9
        assert orthogonality_error(v) < 1e-9
        assert all(s[i] >= s[i + 1] >= 0 for i in range(d - 1))
        us = [[u[i][j] * s[j] for j in range(d)] for i in range(d)]
        assert max_abs_diff(matmul(us, transpose(v)), m) < 1e-9


def test_recovers_planted_rotation():
    rng = random.Random(2)
    for d in (2, 4, 8, 16):
        q = random_orthogonal(rng, d)
        x = gaussian_rows(rng, 3 * d, d)
        y = [apply(q, xi) for xi in x]
        w = procrustes_map(x, y)
        assert orthogonality_error(w) < 1e-9
        assert max_abs_diff(w, q) < 1e-9


def test_planted_rotation_with_noise():
    rng = random.Random(3)
    d = 6
    q = random_orthogonal(rng, d)
    x = gaussian_rows(rng, 200, d)
    y = [[a + rng.gauss(0, 0.05) for a in apply(q, xi)] for xi in x]
    w = procrustes_map(x, y)
    assert orthogonality_error(w) < 1e-9
    assert max_abs_diff(w, q) < 0.05
    assert loss(w, x, y) <= loss(q, x, y) + 1e-9


def test_no_orthogonal_matrix_does_better():
    rng = random.Random(4)
    for d in (2, 3, 4):
        x = gaussian_rows(rng, 10, d)
        y = gaussian_rows(rng, 10, d)
        w = procrustes_map(x, y)
        best = loss(w, x, y)
        for _ in range(300):
            assert loss(random_orthogonal(rng, d), x, y) >= best - 1e-9


def test_brute_force_over_angles_in_two_dimensions():
    rng = random.Random(5)
    x = gaussian_rows(rng, 8, 2)
    y = gaussian_rows(rng, 8, 2)
    best = loss(procrustes_map(x, y), x, y)
    grid = math.inf
    for k in range(20000):
        th = 2 * math.pi * k / 20000
        c, s = math.cos(th), math.sin(th)
        grid = min(grid, loss([[c, -s], [s, c]], x, y), loss([[c, s], [s, -c]], x, y))
    assert best <= grid + 1e-9
    assert grid - best < 1e-3


def test_reflection_case():
    x = [[1.0, 0.0], [0.0, 1.0]]
    y = [[1.0, 0.0], [0.0, -1.0]]
    w = procrustes_map(x, y)
    assert max_abs_diff(w, [[1.0, 0.0], [0.0, -1.0]]) < 1e-12
    assert loss(w, x, y) < 1e-24
    for k in range(360):
        th = math.radians(k)
        c, s = math.cos(th), math.sin(th)
        assert abs(loss([[c, -s], [s, c]], x, y) - 4.0) < 1e-12


def test_polar_newton_agrees():
    rng = random.Random(6)
    for d in (2, 3, 7):
        x = gaussian_rows(rng, 12, d)
        y = gaussian_rows(rng, 12, d)
        m = matmul(transpose(y), x)
        assert max_abs_diff(polar_newton(m), procrustes_map(x, y)) < 1e-9


def test_rank_deficient_dictionary_still_orthogonal():
    rng = random.Random(7)
    d = 5
    q = random_orthogonal(rng, d)
    x = gaussian_rows(rng, 2, d)  # only 2 pairs: M has rank 2
    y = [apply(q, xi) for xi in x]
    w = procrustes_map(x, y)
    assert orthogonality_error(w) < 1e-9
    assert loss(w, x, y) < 1e-18


def test_least_squares_map():
    rng = random.Random(8)
    d = 4
    q = random_orthogonal(rng, d)
    x = gaussian_rows(rng, 30, d)
    y = [apply(q, xi) for xi in x]
    assert max_abs_diff(least_squares_map(x, y), q) < 1e-9
    y_noisy = [[a + rng.gauss(0, 0.3) for a in yi] for yi in y]
    ls = least_squares_map(x, y_noisy)
    orth = procrustes_map(x, y_noisy)
    assert loss(ls, x, y_noisy) <= loss(orth, x, y_noisy) + 1e-9
    assert orthogonality_error(ls) > 1e-3


def test_translation_of_planted_lexicon():
    rng = random.Random(9)
    d, n = 8, 40
    q = random_orthogonal(rng, d)
    src = {f"s{i}": [rng.gauss(0, 1) for _ in range(d)] for i in range(n)}
    tgt = {f"t{i}": [a + rng.gauss(0, 0.01) for a in apply(q, src[f"s{i}"])] for i in range(n)}
    seed = [f"s{i}" for i in range(16)]
    w = fit_orthogonal([src[s] for s in seed], [tgt["t" + s[1:]] for s in seed])
    assert orthogonality_error(w) < 1e-9
    held = {s: src[s] for s in src if s not in seed}
    pred = translate(w, held, tgt)
    gold = {s: {"t" + s[1:]} for s in held}
    assert precision_at_1(pred, gold) == 1.0
    assert precision_at_1(translate(identity(d), held, tgt), gold) < 0.5

History

Mikolov, Le and Sutskever (2013) observed that word vectors of different languages have similar geometric arrangements and fitted a linear map on a few thousand frequent words and their translations. Xing, Wang, Liu and Lin (2015) argued that the map should be orthogonal and the vectors normalized, so that training and retrieval use the same cosine measure. The orthogonal problem had been solved long before in psychometrics: Schönemann (1966) gave the SVD solution of the orthogonal Procrustes problem, and Kabsch (1976) gave the rotation-only version for crystallography. Conneau, Lample, Ranzato, Denoyer and Jégou (2018) combined Procrustes refinement with adversarial training and CSLS retrieval, and reached good precision without any parallel data.

References

  1. Mikolov, Le and Sutskever 2013, the linear map between the two vector spaces, fitted by least squares on a seed dictionary of frequent words, and translation by the nearest neighbour of the mapped vector
  2. Xing, Wang, Liu and Lin 2015, the unit-length normalization of the vectors and the orthogonal constraint on the map
  3. Schönemann 1966, the solution of the orthogonal Procrustes problem from the singular value decomposition
  4. Conneau, Lample, Ranzato, Denoyer and Jégou 2018, Section 2 (equation 1, the linear map; equation 2, the Procrustes solution U V^T from the SVD of Y X^T; the refinement that alternates a new dictionary and Procrustes), Section 3.4 (the dictionary of mutual nearest neighbours under CSLS), Table 1 (the Procrustes baseline on 5,000 source words, with nearest neighbour and with CSLS retrieval)

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