Algorithm Search⌘K

Algorithmadvanced

Retrofitting

Also called retrofitting word vectors to semantic lexicons.

Post-process word vectors so that words linked in a lexicon such as WordNet move closer, by iterative updates that also keep each near its original.

Time
O(T (V + E) d) worst
Space
O(V d + E) extra
Where
E = the number of neighbour entries in the lexicon; T = the number of sweeps; V = the vocabulary size, the number of types; d = the dimension of the vectors
Properties
deterministicnot exactofflineiterative
Origin
Manaal Faruqui, Jesse Dodge, Sujay Kumar Jauhar, Chris Dyer, Eduard Hovy, Noah A. Smith, 2015

Retrofitting moves a set of trained word vectors so that words linked in a semantic lexicon, such as synonyms in WordNet or paraphrases in PPDB, get closer, while each vector stays near where it started. It needs no corpus and no retraining. Each word in turn is replaced by a weighted mean of its own original vector and the current vectors of its lexicon neighbours, and about 10 sweeps over the vocabulary are enough. Faruqui, Dodge, Jauhar, Dyer, Hovy and Smith (2015) proposed it. The sweep is a Jacobi or Gauss-Seidel iteration for a strictly diagonally dominant linear system, so it converges to one fixed point from any start, with the error at least halved at every sweep under the default weights.

In plain words

Word vectors learned from text put words close together when they appear in similar places. But "good" and "bad" appear in similar places too, and a dictionary of synonyms knows things that the text does not show.

Retrofitting uses such a dictionary to adjust the vectors after training. Each word is pulled toward the words listed as its synonyms, and also held back toward its original vector, so it does not lose what it learned from the text. The new vector of a word is a mix: half from its old self, half from the average of its listed neighbours.

Do this for every word, and repeat a few times. Words connected in the dictionary drift together, and the changes settle quickly. Words not in the dictionary stay as they were.

The problem

The input is a vocabulary VV with original vectors q⃗^i∈Rd\hat{\vec q}_i \in \mathbb{R}^d, a lexicon that gives a set N(i)N(i) of neighbour words for each word ii, positive weights αi\alpha_i and βij\beta_{ij}, and a number of sweeps TT. Only neighbours that are in VV count. Faruqui et al. define the objective

Ψ(Q)=∑i(αi∥q⃗i−q⃗^i∥2+∑j∈N(i)βij∥q⃗i−q⃗j∥2)\Psi(Q) = \sum_{i} \Big(\alpha_i \|\vec q_i - \hat{\vec q}_i\|^2 + \sum_{j \in N(i)} \beta_{ij} \|\vec q_i - \vec q_j\|^2\Big)

and its coordinate update

q⃗i←∑j∈N(i)βijq⃗j+αiq⃗^i∑j∈N(i)βij+αi,\vec q_i \leftarrow \frac{\sum_{j \in N(i)} \beta_{ij} \vec q_j + \alpha_i \hat{\vec q}_i}{\sum_{j \in N(i)} \beta_{ij} + \alpha_i},

with αi=1\alpha_i = 1, βij=1/∣N(i)∣\beta_{ij} = 1/|N(i)| and 10 iterations. The output is the vectors after TT sweeps.

What the iteration computes is the fixed point of the update, the solution of the linear system

(αi+∑j∈N(i)βij)q⃗i−∑j∈N(i)βijq⃗j=αiq⃗^ifor every word i with N(i)≠∅.\Big(\alpha_i + \sum_{j \in N(i)} \beta_{ij}\Big) \vec q_i - \sum_{j \in N(i)} \beta_{ij} \vec q_j = \alpha_i \hat{\vec q}_i \quad \text{for every word } i \text{ with } N(i) \ne \emptyset.

This fixed point minimizes a quadratic objective only when the weights are symmetric. If the lexicon is symmetric, βij=βji\beta_{ij} = \beta_{ji}, and each unordered edge {i,j}\{i, j\} is counted once in the second sum of Ψ\Psi, then the update is the exact minimizer of Ψ\Psi in q⃗i\vec q_i and the fixed point is the minimizer of Ψ\Psi. With βij=1/∣N(i)∣\beta_{ij} = 1/|N(i)| the weights are not symmetric when the degrees differ, and the fixed point is then the solution of the system above, not a minimizer of Ψ\Psi.

The algorithm

  1. RETROFIT(Q^, N, α, β, T)
  2. 1Q ← Q^ ▷ start at the original vectors
  3. 2for t ← 1 to T do
  4. 3for each word i with at least one neighbour in V do
  5. 4q_i ← (Σ_{j ∈ N(i)} β_ij q_j + α_i q^_i) / (Σ_{j ∈ N(i)} β_ij + α_i)
  6. 5return Q

Line L1 starts at the original vectors. Line L3 skips the words with no neighbour in the vocabulary, so they keep their vectors, and so do words outside the lexicon. Line L4 replaces q⃗i\vec q_i by a weighted mean of its original vector and the current vectors of its neighbours. With the default weights, the original vector has the weight 1 and the neighbours share the weight 1, so the new vector is half the original and half the mean of the neighbours. The released code writes each new vector at once, so the later words of the same sweep see it: a Gauss-Seidel sweep. Using only the vectors of the previous sweep gives a Jacobi sweep. Both converge to the same fixed point.

Example

Take three words in a chain, a - b - c, with one-dimensional original vectors q^=(0,0,4)\hat q = (0, 0, 4), α=1\alpha = 1 and βij=1/∣N(i)∣\beta_{ij} = 1/|N(i)|. The updates are qa←(qb+0)/2q_a \leftarrow (q_b + 0)/2, qb←(qa/2+qc/2+0)/2q_b \leftarrow (q_a/2 + q_c/2 + 0)/2 and qc←(qb+4)/2q_c \leftarrow (q_b + 4)/2. The fixed point is (1/3,2/3,7/3)(1/3, 2/3, 7/3).

sweep Jacobi (qa,qb,qc)(q_a, q_b, q_c) max error Gauss-Seidel (qa,qb,qc)(q_a, q_b, q_c) max error
0 (0, 0, 4) 1.6667 (0, 0, 4) 1.6667
1 (0, 1, 2) 0.3333 (0, 1, 2.5) 0.3333
2 (0.5, 0.5, 2.5) 0.1667 (0.5, 0.75, 2.375) 0.1667
3 (0.25, 0.75, 2.25) 0.0833 (0.375, 0.6875, 2.3438) 0.0417

In Gauss-Seidel sweep 1, qa=(0+0)/2=0q_a = (0 + 0)/2 = 0, then qb=(0/2+4/2)/2=1q_b = (0/2 + 4/2)/2 = 1 uses the new qaq_a, then qc=(1+4)/2=2.5q_c = (1 + 4)/2 = 2.5 uses the new qbq_b. The vector of c moves from 4 toward its neighbour, and a and b move toward c.

With the symmetric weights βij=1\beta_{ij} = 1 instead, the fixed point is (0.5,1,2.5)(0.5, 1, 2.5), which is the minimizer of Ψ\Psi with each edge counted once. The two weightings give different answers.

Correctness

Write the system as AQ=DαQ^A Q = D_\alpha \hat Q over the words with neighbours, where the neighbours without neighbours of their own are constants. Row ii of AA has the diagonal αi+∑jβij\alpha_i + \sum_j \beta_{ij} and off-diagonal entries of total absolute value at most ∑jβij\sum_j \beta_{ij}, so AA is strictly diagonally dominant by rows and the system has one solution. A Jacobi sweep maps the error e⃗\vec e to a vector whose entries are weighted sums of the old entries with nonnegative weights summing to at most

ρ=max⁡i∑jβijαi+∑jβij<1,\rho = \max_i \frac{\sum_j \beta_{ij}}{\alpha_i + \sum_j \beta_{ij}} < 1,

so ∥e⃗∥∞\|\vec e\|_\infty shrinks by the factor ρ\rho per sweep, and a Gauss-Seidel sweep shrinks it by at least the same factor. With the default weights ρ=1/2\rho = 1/2. When the weights are symmetric and the edges are counted once, Ψ\Psi is strictly convex and the fixed point is its unique minimizer. The full proof is in the proof file.

Proof: Retrofitting converges to the unique fixed point of its update, and with symmetric weights that point minimizes the objectivefull

The loop of lines L2 to L4 runs exactly TT sweeps, so it terminates. We prove that the sweeps converge, as TT grows, to one fixed point, with a geometric rate, whatever the order of the words; that words without neighbours never change; and that with symmetric weights the fixed point is the unique minimizer of the objective Ψ\Psi.

Setup. Let UU be the set of words with at least one neighbour in the vocabulary (the words line L3 visits), with N(i)⊆V∖{i}N(i) \subseteq V \setminus \{i\} the neighbours of ii. Words in V∖UV \setminus U are never written, so they keep q⃗j=q⃗^j\vec q_j = \hat{\vec q}_j at all times. The update of line L4 acts on each coordinate of the vectors separately and in the same way, so it is enough to prove the claims for one coordinate; write xix_i for that coordinate of q⃗i\vec q_i and x^i\hat x_i for that of q⃗^i\hat{\vec q}_i. For i∈Ui \in U let si=∑j∈N(i)βij>0s_i = \sum_{j \in N(i)} \beta_{ij} > 0 and cij=βij/(αi+si)≥0c_{ij} = \beta_{ij}/(\alpha_i + s_i) \ge 0. Line L4 is

xi←∑j∈N(i)cijxj+αiαi+six^i,∑j∈N(i)cij=siαi+si=:ρi<1,x_i \leftarrow \sum_{j \in N(i)} c_{ij} x_j + \frac{\alpha_i}{\alpha_i + s_i} \hat x_i, \qquad \sum_{j \in N(i)} c_{ij} = \frac{s_i}{\alpha_i + s_i} =: \rho_i < 1,

since αi>0\alpha_i > 0. Let ρ=max⁡i∈Uρi<1\rho = \max_{i \in U} \rho_i < 1. With αi=1\alpha_i = 1 and βij=1/∣N(i)∣\beta_{ij} = 1/|N(i)|, si=1s_i = 1 and ρ=1/2\rho = 1/2.

Step 1. There is exactly one fixed point.

A fixed point is a vector x∗x^* on UU with xi∗=∑jcijxj∗+αiαi+six^ix^*_i = \sum_j c_{ij} x^*_j + \frac{\alpha_i}{\alpha_i + s_i}\hat x_i for all i∈Ui \in U, where xj∗=x^jx^*_j = \hat x_j for j∉Uj \notin U. Multiplying by αi+si\alpha_i + s_i, this is the linear system Ax∗=bA x^* = b with Aii=αi+siA_{ii} = \alpha_i + s_i, Aij=−βijA_{ij} = -\beta_{ij} for j∈N(i)∩Uj \in N(i) \cap U, Aij=0A_{ij} = 0 otherwise, and bi=αix^i+∑j∈N(i)∖Uβijx^jb_i = \alpha_i \hat x_i + \sum_{j \in N(i) \setminus U} \beta_{ij} \hat x_j. In row ii, ∑j≠i∣Aij∣≤si<αi+si=Aii\sum_{j \ne i} |A_{ij}| \le s_i < \alpha_i + s_i = A_{ii}, so AA is strictly diagonally dominant by rows. Such a matrix is nonsingular: if Ay=0A y = 0 with y≠0y \ne 0, pick ii with ∣yi∣=∥y∥∞>0|y_i| = \|y\|_\infty > 0; then Aii∣yi∣=∣∑j≠iAijyj∣≤∑j≠i∣Aij∣ ∣yi∣<Aii∣yi∣A_{ii}|y_i| = |\sum_{j \ne i} A_{ij} y_j| \le \sum_{j \ne i}|A_{ij}|\,|y_i| < A_{ii}|y_i|, a contradiction. So the system has exactly one solution x∗x^*. □\square

Step 2. A Jacobi sweep shrinks the error by the factor ρ\rho.

Let e=x−x∗e = x - x^* on UU, and ej=0e_j = 0 for j∉Uj \notin U (those words are fixed at x^j=xj∗\hat x_j = x^*_j). A Jacobi sweep computes every new xix_i from the old vector. Subtracting the fixed point equation from the update gives ei′=∑j∈N(i)cijeje'_i = \sum_{j \in N(i)} c_{ij} e_j, so

∣ei′∣≤∑jcij∣ej∣≤ρi∥e∥∞≤ρ∥e∥∞.|e'_i| \le \sum_{j} c_{ij} |e_j| \le \rho_i \|e\|_\infty \le \rho \|e\|_\infty.

Hence ∥e′∥∞≤ρ∥e∥∞\|e'\|_\infty \le \rho \|e\|_\infty. □\square

Step 3. A Gauss-Seidel sweep, in any order, shrinks the error by at least the factor ρ\rho.

A Gauss-Seidel sweep visits the words of UU in some order i1,i2,…i_1, i_2, \ldots and writes each new value at once. Let E=∥e∥∞E = \|e\|_\infty at the start of the sweep. We show by induction on mm that after the mm-th update every entry of the error is at most EE in absolute value, and the entries already updated in this sweep are at most ρE\rho E.

Base. Before the first update, all entries are at most EE, and no entry is updated.

Step. Assume the hypothesis after m−1m - 1 updates. The update of imi_m gives eim′=∑jcimjeje'_{i_m} = \sum_j c_{i_m j} e_j with the current errors, each at most EE in absolute value by the hypothesis, so ∣eim′∣≤ρimE≤ρE≤E|e'_{i_m}| \le \rho_{i_m} E \le \rho E \le E. The other entries do not change. So the hypothesis holds after mm updates.

At the end of the sweep every word of UU has been updated once, so ∥e′∥∞≤ρE\|e'\|_\infty \le \rho E. □\square

Step 4. Convergence.

By Steps 2 and 3, after TT sweeps of either kind, ∥x(T)−x∗∥∞≤ρT∥x^−x∗∥∞\|x^{(T)} - x^*\|_\infty \le \rho^T \|\hat x - x^*\|_\infty, since the start is x(0)=x^x^{(0)} = \hat x (line L1). As ρ<1\rho < 1, the sweeps converge to x∗x^*, whatever the order of the words, and the limit is the unique fixed point of Step 1. Applying this to every coordinate gives the claim for the vectors, in the max norm over all words and coordinates. Words in V∖UV \setminus U keep their original vectors at every step, by the setup. □\square

Step 5. With symmetric weights the fixed point minimizes Ψ\Psi.

Assume now that the lexicon is symmetric (j∈N(i)j \in N(i) if and only if i∈N(j)i \in N(j)), that βij=βji=wij>0\beta_{ij} = \beta_{ji} = w_{ij} > 0, and that each unordered edge is counted once:

Ψ(Q)=∑i∈Vαi∥q⃗i−q⃗^i∥2+∑{i,j}wij∥q⃗i−q⃗j∥2.\Psi(Q) = \sum_{i \in V} \alpha_i \|\vec q_i - \hat{\vec q}_i\|^2 + \sum_{\{i, j\}} w_{ij} \|\vec q_i - \vec q_j\|^2.

Every word with a neighbour is in UU, and its neighbours are in UU too, so the words outside UU appear only in their own first term, which is minimized by q⃗j=q⃗^j\vec q_j = \hat{\vec q}_j. Ψ\Psi is strictly convex, because the first sum is a strictly convex quadratic (αi>0\alpha_i > 0) and the second is convex. The partial gradient is

∂Ψ∂q⃗i=2αi(q⃗i−q⃗^i)+2∑j∈N(i)wij(q⃗i−q⃗j),\frac{\partial \Psi}{\partial \vec q_i} = 2\alpha_i(\vec q_i - \hat{\vec q}_i) + 2\sum_{j \in N(i)} w_{ij}(\vec q_i - \vec q_j),

because the edge {i,j}\{i, j\} appears once and contains q⃗i\vec q_i once. Setting it to zero gives (αi+si)q⃗i=∑jwijq⃗j+αiq⃗^i(\alpha_i + s_i)\vec q_i = \sum_j w_{ij}\vec q_j + \alpha_i \hat{\vec q}_i, which is exactly line L4. So line L4 sets q⃗i\vec q_i to the exact minimizer of Ψ\Psi in q⃗i\vec q_i with the other vectors fixed, and the stationarity conditions of Ψ\Psi are the fixed point equations of Step 1. A strictly convex function has exactly one stationary point, its global minimizer, so the fixed point x∗x^* is the unique minimizer of Ψ\Psi. In this case a Gauss-Seidel sweep is exact block coordinate descent, and Ψ\Psi does not increase during the sweep. ■\blacksquare

Remark. If each unordered edge were counted twice in Ψ\Psi (once as (i,j)(i, j) and once as (j,i)(j, i)), the gradient would have the factor 4wij4 w_{ij}, and line L4 would no longer be the coordinate minimizer. With βij=1/∣N(i)∣\beta_{ij} = 1/|N(i)| and unequal degrees, βij≠βji\beta_{ij} \ne \beta_{ji}, and Step 5 does not apply: the iteration still converges by Step 4, to the solution of the system of Step 1.

Complexity

Line L4 for word ii costs O((∣N(i)∣+1)d)O((|N(i)| + 1) d), so a sweep costs O((V+E)d)O((V + E) d), where E=∑i∣N(i)∣E = \sum_i |N(i)|, and TT sweeps cost O(T(V+E)d)O(T(V + E)d). The memory is the VdV d numbers of the new vectors (the original vectors are kept), plus O(E)O(E) for the neighbour lists. With ρ=1/2\rho = 1/2, 10 sweeps reduce the max-norm error to at most 2−10≈0.0012^{-10} \approx 0.001 of its start.

Properties

  • Deterministic. The result depends only on the input and the order of the words in a sweep, and the limit does not depend on the order.
  • Local. A word moves only if it has a neighbour in the vocabulary, and the change spreads along the lexicon edges.
  • Linear. The output is a linear function of the original vectors. Each coordinate of the vectors is solved by the same system, independently.
  • Not exact after TT sweeps. The result approaches the fixed point geometrically. A direct solve of the sparse system gives the fixed point exactly.
  • Any vectors. The input can come from skip-gram, GloVe, an SVD of counts or any other method.

Variants and improvements

  • Weights. Faruqui et al. give each word's neighbours the total weight 1. Equal weights βij=1\beta_{ij} = 1 make the method minimize Ψ\Psi exactly, and words with many neighbours then move more.
  • Direct solve. The system is sparse and diagonally dominant, so conjugate gradients (for symmetric weights) or a sparse direct solver also work. The matrix of the symmetric case is DαD_\alpha plus a weighted graph Laplacian of the lexicon.
  • Relation types. Later work gives different weights to synonyms, hypernyms and antonyms, or pushes antonyms apart.
  • Sense vectors. The same idea applied to sense-level lexicons gives one vector per word sense, linking retrofitting to word sense disambiguation.

When to use it

Use it when you have trained vectors and a reliable lexicon, and you want the vectors to reflect the lexicon relations, for example for word similarity or for tasks where synonyms should behave alike. It is fast, since each sweep is linear in the size of the vocabulary and the lexicon, and it needs no corpus. It does not help words outside the lexicon, and it can hurt when the lexicon relation is not the similarity you need: words linked as related in a broad lexicon are pulled together even when they are not substitutes.

Pitfalls

  • Self loops. A lexicon may list a word as its own neighbour. Line L4 must skip j=ij = i; otherwise the word counts its own current vector as a neighbour, and the fixed point changes.
  • Neighbours outside the vocabulary. Line L4 must use only neighbours that have vectors. Counting the others in ∑jβij\sum_j \beta_{ij} with no vector to add shrinks the vector toward zero.
  • Reading the paper's update as exact minimization. With βij=1/∣N(i)∣\beta_{ij} = 1/|N(i)| the weights are not symmetric, and the result is the fixed point of line L4, not the minimizer of Ψ\Psi. A test that checks the gradient of Ψ\Psi at the result must use symmetric weights.
  • Overwriting Q^\hat Q. Line L4 needs the original vector q⃗^i\hat{\vec q}_i in every sweep. If line L1 aliases QQ and Q^\hat Q instead of copying, each sweep pulls toward the current vector and the method drifts toward the mean of each connected group.

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.

retrofitting_word_vectors.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/retrofitting-word-vectors/. The authors are listed in prov/TKNXEG.jsonl.

"""Retrofitting of word vectors to a semantic lexicon (Faruqui et al. 2015).

The input is a mapping from each word to its original vector q_hat and a
lexicon that maps a word to its neighbours. Only neighbours that have a
vector count. A word with no such neighbour keeps its vector.

The update for a word i with neighbours N(i) is

    q_i <- (sum_j beta_ij q_j + alpha_i q_hat_i) / (sum_j beta_ij + alpha_i)

with alpha_i = 1 and beta_ij = 1 / |N(i)| by default, as in the paper and in
its released code. The default order is Gauss-Seidel (each new vector is used
at once, as the released code does); jacobi=True uses only the vectors of the
previous sweep.

The fixed point of the update is the solution of the linear system
(alpha_i + sum_j beta_ij) q_i - sum_j beta_ij q_j = alpha_i q_hat_i. The
function solve_direct solves it by Gaussian elimination, as a reference.
"""

from typing import Callable, Mapping, Sequence

Vector = list[float]
Weight = Callable[[str, str, int], float]


def _neighbours(vectors: Mapping[str, Sequence[float]],
                lexicon: Mapping[str, Sequence[str]]) -> dict[str, list[str]]:
    """Neighbours of each word in the vocabulary, restricted to the vocabulary."""
    out: dict[str, list[str]] = {}
    for w in sorted(vectors):
        nb = sorted({u for u in lexicon.get(w, ()) if u in vectors and u != w})
        if nb:
            out[w] = nb
    return out


def default_beta(i: str, j: str, degree: int) -> float:
    """beta_ij = 1 / |N(i)|, the weight of Faruqui et al."""
    return 1.0 / degree


def default_alpha(i: str) -> float:
    return 1.0


def update(i: str, q: Mapping[str, Sequence[float]], q_hat: Mapping[str, Sequence[float]],
           nb: Sequence[str], alpha: Callable[[str], float] = default_alpha,
           beta: Weight = default_beta) -> Vector:
    """One update of the word i: a weighted mean of its neighbours and its original vector."""
    a = alpha(i)
    num = [a * x for x in q_hat[i]]
    den = a
    for j in nb:
        b = beta(i, j, len(nb))
        den += b
        for t, x in enumerate(q[j]):
            num[t] += b * x
    return [x / den for x in num]  # @line L4


def retrofit(vectors: Mapping[str, Sequence[float]], lexicon: Mapping[str, Sequence[str]],
             iterations: int = 10, alpha: Callable[[str], float] = default_alpha,
             beta: Weight = default_beta, jacobi: bool = False) -> dict[str, Vector]:
    """Return the retrofitted vectors after the given number of sweeps."""
    q_hat = {w: list(map(float, v)) for w, v in vectors.items()}
    q = {w: list(v) for w, v in q_hat.items()}  # @line L1
    nbs = _neighbours(vectors, lexicon)
    for _ in range(iterations):  # @line L2
        src = {w: list(v) for w, v in q.items()} if jacobi else q
        new = {}
        for i, nb in nbs.items():  # @line L3
            new[i] = update(i, src, q_hat, nb, alpha, beta)
            if not jacobi:
                q[i] = new[i]
        if jacobi:
            q.update(new)
    return q  # @line L5


def solve_linear(a: list[list[float]], b: list[list[float]]) -> list[list[float]]:
    """Solve A X = B by Gaussian elimination with partial pivoting."""
    n = len(a)
    m = [list(map(float, a[r])) + list(map(float, b[r])) for r in range(n)]
    width = len(m[0])
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(m[r][c]))
        if abs(m[p][c]) < 1e-300:
            raise ValueError("singular matrix")
        m[c], m[p] = m[p], m[c]
        for r in range(n):
            if r != c and m[r][c] != 0.0:
                f = m[r][c] / m[c][c]
                for k in range(c, width):
                    m[r][k] -= f * m[c][k]
    return [[m[r][k] / m[r][r] for k in range(n, width)] for r in range(n)]


def solve_direct(vectors: Mapping[str, Sequence[float]], lexicon: Mapping[str, Sequence[str]],
                 alpha: Callable[[str], float] = default_alpha,
                 beta: Weight = default_beta) -> dict[str, Vector]:
    """The fixed point of the update, found by one linear solve (the reference)."""
    nbs = _neighbours(vectors, lexicon)
    words = sorted(nbs)
    idx = {w: r for r, w in enumerate(words)}
    n = len(words)
    out = {w: list(map(float, v)) for w, v in vectors.items()}
    if n == 0:
        return out
    a = [[0.0] * n for _ in range(n)]
    rhs = []
    for i in words:
        r = idx[i]
        ai = alpha(i)
        a[r][r] += ai
        row = [ai * x for x in vectors[i]]
        for j in nbs[i]:
            b = beta(i, j, len(nbs[i]))
            a[r][r] += b
            if j in idx:
                a[r][idx[j]] -= b
            else:  # a neighbour with no neighbours of its own keeps q_hat_j
                row = [x + b * y for x, y in zip(row, vectors[j])]
        rhs.append(row)
    sol = solve_linear(a, rhs)
    for i in words:
        out[i] = sol[idx[i]]
    return out


def objective(q: Mapping[str, Sequence[float]], q_hat: Mapping[str, Sequence[float]],
              lexicon: Mapping[str, Sequence[str]], alpha: Callable[[str], float] = default_alpha,
              weight: Callable[[str, str], float] = lambda i, j: 1.0) -> float:
    """Psi(Q) = sum_i alpha_i |q_i - q_hat_i|^2 + sum over unordered edges w_ij |q_i - q_j|^2.

    Each edge {i, j} of the lexicon is counted once, with a symmetric weight.
    For this objective the update with beta_ij = w_ij is the exact minimizer in q_i.
    """
    nbs = _neighbours(q_hat, lexicon)
    edges = {tuple(sorted((i, j))) for i, nb in nbs.items() for j in nb}
    total = 0.0
    for i in q_hat:
        total += alpha(i) * sum((x - y) ** 2 for x, y in zip(q[i], q_hat[i]))
    for i, j in sorted(edges):
        total += weight(i, j) * sum((x - y) ** 2 for x, y in zip(q[i], q[j]))
    return total
test_retrofitting_word_vectors.py 148 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/retrofitting-word-vectors/. The authors are listed in prov/TKNXEG.jsonl.

import math
import random

from retrofitting_word_vectors import (
    objective,
    retrofit,
    solve_direct,
    solve_linear,
    update,
)

TOL = 1e-9


def max_diff(p, q):
    return max(abs(x - y) for w in p for x, y in zip(p[w], q[w]))


def random_case(rng, n=12, d=4, p=0.3):
    words = [f"w{i:02d}" for i in range(n)]
    vectors = {w: [rng.uniform(-1, 1) for _ in range(d)] for w in words}
    lexicon = {w: [] for w in words}
    for a in range(n):
        for b in range(a + 1, n):
            if rng.random() < p:
                lexicon[words[a]].append(words[b])
                lexicon[words[b]].append(words[a])
    lexicon["w00"].append("not-in-vocabulary")
    return vectors, lexicon


def test_chain_hand_values():
    vectors = {"a": [0.0], "b": [0.0], "c": [4.0]}
    lexicon = {"a": ["b"], "b": ["a", "c"], "c": ["b"]}
    exact = solve_direct(vectors, lexicon)
    assert abs(exact["a"][0] - 1 / 3) < TOL
    assert abs(exact["b"][0] - 2 / 3) < TOL
    assert abs(exact["c"][0] - 7 / 3) < TOL
    one = retrofit(vectors, lexicon, iterations=1, jacobi=True)
    assert [one[w][0] for w in "abc"] == [0.0, 1.0, 2.0]
    two = retrofit(vectors, lexicon, iterations=2, jacobi=True)
    assert [two[w][0] for w in "abc"] == [0.5, 0.5, 2.5]
    gs = retrofit(vectors, lexicon, iterations=1)
    assert [gs[w][0] for w in "abc"] == [0.0, 1.0, 2.5]


def test_iteration_converges_to_direct_solve():
    rng = random.Random(1)
    for _ in range(5):
        vectors, lexicon = random_case(rng)
        exact = solve_direct(vectors, lexicon)
        for jacobi in (False, True):
            got = retrofit(vectors, lexicon, iterations=60, jacobi=jacobi)
            assert max_diff(got, exact) < 1e-12


def test_jacobi_contracts_by_half():
    rng = random.Random(2)
    vectors, lexicon = random_case(rng)
    exact = solve_direct(vectors, lexicon)
    prev = max_diff(vectors, exact)
    q = {w: list(v) for w, v in vectors.items()}
    nbs = {w: sorted({u for u in lexicon[w] if u in vectors}) for w in vectors}
    for _ in range(8):
        q = {w: (update(w, q, vectors, nbs[w]) if nbs[w] else vectors[w]) for w in vectors}
        err = max_diff(q, exact)
        assert err <= 0.5 * prev + 1e-15
        prev = err


def test_gauss_seidel_not_slower_than_bound():
    rng = random.Random(3)
    vectors, lexicon = random_case(rng)
    exact = solve_direct(vectors, lexicon)
    e0 = max_diff(vectors, exact)
    for t in range(1, 8):
        got = retrofit(vectors, lexicon, iterations=t)
        assert max_diff(got, exact) <= 0.5 ** t * e0 + 1e-15


def test_words_outside_lexicon_unchanged():
    vectors = {"x": [1.0, 2.0], "y": [3.0, -1.0], "lonely": [5.0, 5.0], "z": [0.5, 0.5]}
    lexicon = {"x": ["y", "ghost"], "y": ["x"], "z": ["ghost"]}
    got = retrofit(vectors, lexicon)
    assert got["lonely"] == [5.0, 5.0]
    assert got["z"] == [0.5, 0.5]
    assert got["x"] != [1.0, 2.0]


def test_update_matches_released_code_formula():
    # retrofit.py: newVec = (numNeighbours * q_hat + sum of neighbours) / (2 * numNeighbours)
    rng = random.Random(4)
    vectors, lexicon = random_case(rng)
    q = {w: [rng.uniform(-1, 1) for _ in range(4)] for w in vectors}
    for w in vectors:
        nb = sorted({u for u in lexicon[w] if u in vectors})
        if not nb:
            continue
        ref = [(len(nb) * vectors[w][t] + sum(q[u][t] for u in nb)) / (2 * len(nb)) for t in range(4)]
        got = update(w, q, vectors, nb)
        assert max(abs(x - y) for x, y in zip(got, ref)) < 1e-12


def test_symmetric_weights_minimize_objective():
    rng = random.Random(5)
    vectors, lexicon = random_case(rng, n=10, d=3)
    del lexicon["w00"][-1]
    ones = lambda i, j, deg: 1.0  # noqa: E731
    best = solve_direct(vectors, lexicon, beta=ones)
    psi = objective(best, vectors, lexicon)
    h = 1e-6
    for w in vectors:
        for t in range(3):
            plus = {u: list(v) for u, v in best.items()}
            minus = {u: list(v) for u, v in best.items()}
            plus[w][t] += h
            minus[w][t] -= h
            grad = (objective(plus, vectors, lexicon) - objective(minus, vectors, lexicon)) / (2 * h)
            assert abs(grad) < 1e-5
    for _ in range(20):
        other = {u: [x + rng.gauss(0, 0.1) for x in v] for u, v in best.items()}
        assert objective(other, vectors, lexicon) > psi
    got = retrofit(vectors, lexicon, iterations=80, beta=ones)
    assert max_diff(got, best) < 1e-9


def test_lexicon_clusters_move_together():
    rng = random.Random(6)
    a = [f"a{i}" for i in range(6)]
    b = [f"b{i}" for i in range(6)]
    vectors = {w: [rng.gauss(0, 1) for _ in range(8)] for w in a + b}
    lexicon = {w: [u for u in grp if u != w] for grp in (a, b) for w in grp}

    def spread(q, grp):
        pairs = [(u, v) for k, u in enumerate(grp) for v in grp[k + 1:]]
        return sum(math.dist(q[u], q[v]) for u, v in pairs) / len(pairs)

    got = retrofit(vectors, lexicon)
    for grp in (a, b):
        assert spread(got, grp) < 0.6 * spread(vectors, grp)


def test_solve_linear_against_known_system():
    x = solve_linear([[2.0, 1.0], [1.0, 3.0]], [[3.0], [5.0]])
    assert abs(x[0][0] - 0.8) < TOL and abs(x[1][0] - 1.4) < TOL

History

Faruqui, Dodge, Jauhar, Dyer, Hovy and Smith presented retrofitting at NAACL 2015 and released a short Python script. They reported gains on word similarity and other lexical tasks for several kinds of vectors and three lexicons (PPDB, WordNet and FrameNet). The method became a common way to add lexical knowledge to word vectors, and later work extended it to antonyms and to other languages.

References

  1. Faruqui, Dodge, Jauhar, Dyer, Hovy and Smith 2015, Section 2 (the objective Psi(Q), its convexity, the update of q_i, alpha_i = 1, beta_ij = 1/degree(i) and 10 iterations), the experiments with PPDB, WordNet and FrameNet as lexicons, and the released retrofit.py
  2. Gene H. Golub and Charles F. Van Loan, Matrix Computations, fourth edition, Johns Hopkins University Press, 2013, the Jacobi and Gauss-Seidel iterations and their convergence for strictly diagonally dominant matrices

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
  • at least three sources
  • a scene preset for the example