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
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 with original vectors , a lexicon that gives a set of neighbour words for each word , positive weights and , and a number of sweeps . Only neighbours that are in count. Faruqui et al. define the objective
and its coordinate update
with , and 10 iterations. The output is the vectors after sweeps.
What the iteration computes is the fixed point of the update, the solution of the linear system
This fixed point minimizes a quadratic objective only when the weights are symmetric. If the lexicon is symmetric, , and each unordered edge is counted once in the second sum of , then the update is the exact minimizer of in and the fixed point is the minimizer of . With 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 .
The algorithm
RETROFIT(Q^, N, α, β, T)- 1
Q ← Q^ ▷ start at the original vectors - 2
for t ← 1 to T do - 3
for each word i with at least one neighbour in V do - 4
q_i ← (Σ_{j ∈ N(i)} β_ij q_j + α_i q^_i) / (Σ_{j ∈ N(i)} β_ij + α_i) - 5
return 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 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 , and . The updates are , and . The fixed point is .
| sweep | Jacobi | max error | Gauss-Seidel | 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, , then uses the new , then uses the new . The vector of c moves from 4 toward its neighbour, and a and b move toward c.
With the symmetric weights instead, the fixed point is , which is the minimizer of with each edge counted once. The two weightings give different answers.
Correctness
Write the system as over the words with neighbours, where the neighbours without neighbours of their own are constants. Row of has the diagonal and off-diagonal entries of total absolute value at most , so is strictly diagonally dominant by rows and the system has one solution. A Jacobi sweep maps the error to a vector whose entries are weighted sums of the old entries with nonnegative weights summing to at most
so shrinks by the factor per sweep, and a Gauss-Seidel sweep shrinks it by at least the same factor. With the default weights . When the weights are symmetric and the edges are counted once, 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 sweeps, so it terminates. We prove that the sweeps converge, as 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 .
Setup. Let be the set of words with at least one neighbour in the vocabulary (the words line L3 visits), with the neighbours of . Words in are never written, so they keep 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 for that coordinate of and for that of . For let and . Line L4 is
since . Let . With and , and .
Step 1. There is exactly one fixed point.
A fixed point is a vector on with for all , where for . Multiplying by , this is the linear system with , for , otherwise, and . In row , , so is strictly diagonally dominant by rows. Such a matrix is nonsingular: if with , pick with ; then , a contradiction. So the system has exactly one solution .
Step 2. A Jacobi sweep shrinks the error by the factor .
Let on , and for (those words are fixed at ). A Jacobi sweep computes every new from the old vector. Subtracting the fixed point equation from the update gives , so
Hence .
Step 3. A Gauss-Seidel sweep, in any order, shrinks the error by at least the factor .
A Gauss-Seidel sweep visits the words of in some order and writes each new value at once. Let at the start of the sweep. We show by induction on that after the -th update every entry of the error is at most in absolute value, and the entries already updated in this sweep are at most .
Base. Before the first update, all entries are at most , and no entry is updated.
Step. Assume the hypothesis after updates. The update of gives with the current errors, each at most in absolute value by the hypothesis, so . The other entries do not change. So the hypothesis holds after updates.
At the end of the sweep every word of has been updated once, so .
Step 4. Convergence.
By Steps 2 and 3, after sweeps of either kind, , since the start is (line L1). As , the sweeps converge to , 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 keep their original vectors at every step, by the setup.
Step 5. With symmetric weights the fixed point minimizes .
Assume now that the lexicon is symmetric ( if and only if ), that , and that each unordered edge is counted once:
Every word with a neighbour is in , and its neighbours are in too, so the words outside appear only in their own first term, which is minimized by . is strictly convex, because the first sum is a strictly convex quadratic () and the second is convex. The partial gradient is
because the edge appears once and contains once. Setting it to zero gives , which is exactly line L4. So line L4 sets to the exact minimizer of in with the other vectors fixed, and the stationarity conditions of are the fixed point equations of Step 1. A strictly convex function has exactly one stationary point, its global minimizer, so the fixed point is the unique minimizer of . In this case a Gauss-Seidel sweep is exact block coordinate descent, and does not increase during the sweep.
Remark. If each unordered edge were counted twice in (once as and once as ), the gradient would have the factor , and line L4 would no longer be the coordinate minimizer. With and unequal degrees, , 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 costs , so a sweep costs , where , and sweeps cost . The memory is the numbers of the new vectors (the original vectors are kept), plus for the neighbour lists. With , 10 sweeps reduce the max-norm error to at most 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 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 make the method minimize 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 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 ; 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 with no vector to add shrinks the vector toward zero.
- Reading the paper's update as exact minimization. With the weights are not symmetric, and the result is the fixed point of line L4, not the minimizer of . A test that checks the gradient of at the result must use symmetric weights.
- Overwriting . Line L4 needs the original vector in every sweep. If line L1 aliases and 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.
# 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag TKNXEG Edit this page History Report an error Markdown