Algorithmadvanced
Smooth inverse frequency embedding
Also called SIF embedding.
A sentence vector as the weighted mean of its word vectors with weights a / (a + p(w)), minus its projection on the first principal component.
- Time
- O(t d + n d^2 + q d^2) worst
- Space
- O(n d + d^2) extra
- Where
- d = the dimension of the word vectors; n = the number of sentences; q = the number of power iteration steps; t = the total number of tokens
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterativenot supervised
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Sanjeev Arora, Yingyu Liang, Tengyu Ma, 2017
Smooth inverse frequency (SIF) embedding turns a sentence into a vector with no training beyond the word vectors. It averages the word vectors of the sentence, each weighted by , where is the frequency of the word in a large corpus and is a small constant such as . Then it removes from every sentence vector its projection on one direction , the first singular vector of the matrix of all sentence vectors. Arora, Liang and Ma 2017 measured that this simple method beats many trained sentence embedding models on textual similarity benchmarks.
In plain words
A plain average of word vectors is pulled toward words like "the", "of" and "and", which appear in almost every sentence and say little. SIF gives each word a weight that is close to 1 for rare words and small for frequent words, so the content words decide where the sentence vector points. Even after the weighting, all sentence vectors still share one common part, which comes from syntax and from frequent words. SIF finds that shared direction from all the sentences together and cuts it away from each sentence. What is left shows how the sentences differ, which is what a similarity score needs.
The problem
The input is a set of tokenized sentences, a word vector for each known word, a unigram probability for each word, estimated on a large corpus, and a parameter . The output is a vector for each sentence. The cosine of two output vectors is used as the similarity of the two sentences.
The algorithm
SIF(S_1 .. S_n, v, p, a)- 1
for each sentence s do - 2
v_s ← (1 / |s|) Σ_{w ∈ s} a / (a + p(w)) · v_w - 3
X ← the n × d matrix with the rows v_s - 4
u ← the first right singular vector of X ▷ no centering - 5
for each sentence s do - 6
v_s ← v_s - u u^T v_s - 7
return v_s for every s, and u
Line L4 needs only the top eigenvector of the matrix , so power iteration is enough, and a truncated singular value decomposition gives the same vector. As in the code of the authors, is not centered, so is not the first principal component in the strict sense of principal component analysis, which centers the data first. To embed new sentences later, keep from the training sentences and apply lines L2 and L6 with it.
The weights come from a model. A latent discourse vector produces each word with probability , where mixes in a common discourse vector . Under approximations, the maximum likelihood estimate of is proportional to the weighted sum of line L2 with , and line L6 estimates by and removes it. The derivation is a heuristic argument; the paper tests it by experiments.
Example
The probabilities and the 3-dimensional vectors are written for this page. With , "the" () gets the weight , "a" () gets 0.0244, "cat" and "dog" () get 0.9091, and "sat" and "ran" () get 0.6667.
| word | vector |
|---|---|
| the | (1, 1, 0) |
| a | (1, 0.8, 0.2) |
| cat | (0.2, 0, 1) |
| dog | (0, 0.2, 1) |
| sat | (0.5, -1, 0) |
| ran | (0.3, -1, 0.3) |
| sentence | line L2 | line L6 |
|---|---|---|
| the cat sat | (0.1783, -0.2157, 0.303) | (0.0495, -0.0326, -0.0364) |
| a dog ran | (0.0748, -0.1551, 0.3713) | (-0.053, 0.0266, 0.0345) |
| the dog sat | (0.1176, -0.1551, 0.303) | (0.0036, 0.007, 0.0024) |
The weighting moves the vectors away from "the": the plain average of "the cat sat" is (0.5667, 0, 0.3333), and the weighted one has its largest entry in the third coordinate, where "cat" points. The first singular vector is with singular value 0.6766, and the projections on it are 0.4066, 0.4035 and 0.3601. Before line L6 the three cosines are 0.9436, 0.9845 and 0.9861, so the vectors hardly differ. After line L6 every vector is orthogonal to , and the cosines are spread from -0.9945 to 0.1435. Three toy sentences cannot show that the new cosines are better; they show only what the steps do.
Correctness
The proof below shows three facts, which are theorems. The weight is 1 at , at , and strictly decreases in . The first right singular vector of maximizes over unit vectors, and power iteration converges to it when the two largest singular values differ. Line L6 gives , and it is the smallest change of along that does so. The tests check these facts and that a common direction planted in the word vectors is found and removed.
That SIF gives good sentence similarities is a measurement, not a theorem. The paper reports that the method, with GloVe or with PARAGRAM-SL999 word vectors, improves on the plain average by about 10% to 30% on textual similarity tasks and beats several trained models, including LSTM encoders.
Proof: The removed direction carries the most energy and the output is orthogonal to itfull
We use the pseudocode of the page. The sentence vectors after line L2 are , and is the matrix with these rows. The claim has three parts: the weights do what the page says, line L4 finds the direction that carries the most energy of the sentence vectors, and line L6 removes exactly that direction.
Lemma 1 (the weights). For , the weight is in , equals 1 at and at , and strictly decreases in .
Proof. and . For the denominator is positive and strictly increases, so is positive and strictly decreases.
So a word with gets about , and a word with gets about 1.
Lemma 2 (the top direction). Let , a symmetric positive semidefinite matrix. For a unit vector , . This is largest when is an eigenvector of for its largest eigenvalue , which is the first right singular vector of , and then .
Proof. Write with orthonormal eigenvectors and . For a unit , , with equality at . The singular value decomposition gives , so is the first right singular vector and .
The matrix is not centered: is the direction with the largest mean squared projection of the sentence vectors, not the largest variance. When all sentence vectors share a large common part, as in the generative model of the paper, this direction points along that part.
Lemma 3 (power iteration). If and the start vector has , the iterates converge to , and the angle to shrinks by a factor of about per step.
Proof. . Divide by : the coefficient of is 1 and every other coefficient is at most , which goes to 0. Normalizing gives the claim (see power iteration). A random Gaussian start has with probability 1.
The code fixes the sign so that the largest entry of is positive. The sign does not matter for line L6, since .
Theorem (removal). For a unit vector , line L6 returns . Then (a) , (b) , (c) removing again changes nothing, and (d) among all vectors of the form , the vector is the shortest.
Proof. (a) . (b) with orthogonal terms, so the Pythagorean theorem applies. (c) By (a), , so . (d) by (b) applied to , which is smallest at .
Corollary. After lines L1 to L7, every output vector is orthogonal to , and is the direction in which the sentence vectors of line L2 have the largest sum of squared projections. If all sentence vectors of line L2 are equal, they all lie on and the output is the zero vector for every sentence.
The proof shows what the steps compute. That this improves the similarity of sentences is a measurement on benchmarks, not a theorem. The paper motivates the weights with a generative model and shows that, in that model, the maximum likelihood estimate of the discourse vector is close to the weighted average; that derivation uses approximations and is a heuristic argument.
Complexity
The model is the real-RAM.
- Weighted averages. Line L2 touches each token once at cost: for tokens.
- First singular vector. Forming costs , and each power iteration step costs , so steps cost . Without forming , each step costs as two products with .
- Removal. Line L6 costs per sentence, in total.
The extra space is for and for . With the whole method is fast enough for millions of sentences.
Properties
- No training of its own. The method needs word vectors and word frequencies. Its only parameters are and the one direction .
- Order is ignored. "dog bites man" and "man bites dog" get the same vector, as with every weighted average.
- Not online. The direction depends on all sentences of the set. A fixed from a training set makes the embedding of new sentences independent of each other.
- Deterministic. With a fixed start vector for the power iteration the output is fixed up to the sign of , and the sign does not change line L6.
Variants and improvements
- Weights only (W) or removal only (R). The paper reports both parts separately; each helps, and the two together help most.
- More directions. Removing the top few singular directions instead of one is a common change. The same idea applied to word vectors is the "all-but-the-top" postprocessing of Mu and Viswanath 2018.
- uSIF. Ethayarajh 2018 derived the weights from a changed random walk model, which removes the need to tune , and removed a few directions with weights.
- Other weights. IDF weights, as in tf-idf, give a similar effect. Both down-weight frequent words, but SIF uses the corpus frequency and IDF uses the share of documents that contain the word.
When to use it
Use SIF as a strong baseline for sentence similarity, clustering and retrieval when no labeled pairs exist, when the cost must be very low, or when a trained encoder is not allowed. Compare a new encoder against it. When labeled pairs or a pretrained transformer are available, trained encoders such as Sentence-BERT and SimCSE usually measure better on the same benchmarks.
Pitfalls
- Frequencies from the wrong corpus. The weights need from a large general corpus. Frequencies from a small task set make rare but common words look important.
- The value of a. The paper measured good results for from about to . Larger values bring back the weight of frequent words, and very small values make most words weigh about .
- Centering. Centering before line L4 gives a different direction. Both are used in practice; state which one you use.
- A new u for every batch. Computing on each small batch at test time makes the vector of a sentence depend on the other sentences of the batch. Fix on a training set.
- Unknown words. Words without a vector are skipped, and a sentence with no known word gives the zero vector, whose cosine is not defined.
Implementations
The code takes the word vectors and the word probabilities as given and implements the weights, the weighted average, the first singular vector by power iteration on the uncentered , and the removal of the projection.
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/smooth-inverse-frequency-embedding/. The authors are listed in prov/V5GPPB.jsonl.
"""Smooth inverse frequency (SIF) sentence vectors of Arora, Liang and Ma 2017.
A sentence vector is the mean of the word vectors of the sentence, each
weighted by a / (a + p(w)), where p(w) is the unigram probability of the word.
Then the projection of every sentence vector on the first singular vector u of
the matrix of all sentence vectors is removed. As in the authors' code, the
matrix is not centered before u is computed. The word vectors and the word
probabilities are given; the code does not train them.
"""
import math
import random
from typing import Dict, Iterable, List, Sequence, Tuple
Vector = List[float]
def dot(a: Sequence[float], b: Sequence[float]) -> float:
return math.fsum(x * y for x, y in zip(a, b))
def norm(a: Sequence[float]) -> float:
return math.sqrt(dot(a, a))
def word_probabilities(corpus: Iterable[Iterable[str]]) -> Dict[str, float]:
"""The unigram probability count(w) / (number of tokens) of each word of a tokenized corpus."""
counts: Dict[str, int] = {}
for sentence in corpus:
for w in sentence:
counts[w] = counts.get(w, 0) + 1
total = sum(counts.values())
if total == 0:
raise ValueError("the corpus is empty")
return {w: c / total for w, c in counts.items()}
def sif_weight(p: float, a: float = 1e-3) -> float:
"""a / (a + p): close to 1 for a rare word and close to a / p for a frequent one."""
if not a > 0 or p < 0:
raise ValueError("a must be positive and p must not be negative")
return a / (a + p)
def weighted_average(
tokens: Sequence[str], vectors: Dict[str, Sequence[float]], p: Dict[str, float], a: float, dim: int
) -> Vector:
"""(1 / |s|) sum over the words of s of a / (a + p(w)) v_w.
Words without a vector are skipped and do not count in |s|. A word with no
probability gets p = 0, the weight of an unseen word. A sentence with no
known word gives the zero vector.
"""
used = [w for w in tokens if w in vectors]
if not used:
return [0.0] * dim
out = [0.0] * dim
for w in used:
c = sif_weight(p.get(w, 0.0), a)
out = [o + c * x for o, x in zip(out, vectors[w])]
return [o / len(used) for o in out]
def first_singular_vector(X: Sequence[Sequence[float]], seed: int = 0, tol: float = 1e-14, max_iter: int = 20000) -> Tuple[Vector, float]:
"""The first right singular vector u of X and the largest singular value.
Power iteration on X^T X, which is not centered. The sign is fixed so that
the largest entry of u is positive. Convergence needs a gap between the
two largest singular values.
"""
d = len(X[0])
G = [[math.fsum(row[i] * row[j] for row in X) for j in range(d)] for i in range(d)]
rng = random.Random(seed)
u = [rng.gauss(0.0, 1.0) for _ in range(d)]
n0 = norm(u)
u = [x / n0 for x in u]
for _ in range(max_iter):
y = [dot(row, u) for row in G]
ny = norm(y)
if ny == 0:
raise ValueError("every sentence vector is zero")
y = [x / ny for x in y]
done = max(abs(a - b) for a, b in zip(u, y)) < tol
u = y
if done:
break
big = max(range(d), key=lambda i: abs(u[i]))
if u[big] < 0:
u = [-x for x in u]
sigma = math.sqrt(max(0.0, dot(u, [dot(row, u) for row in G])))
return u, sigma
def remove_projection(v: Sequence[float], u: Sequence[float]) -> Vector:
"""v - u u^T v for a unit vector u."""
c = dot(u, v)
return [x - c * y for x, y in zip(v, u)]
def sif_embeddings(
sentences: Sequence[Sequence[str]],
vectors: Dict[str, Sequence[float]],
p: Dict[str, float],
a: float = 1e-3,
seed: int = 0,
) -> Tuple[List[Vector], Vector]:
"""Return (the SIF vectors of the sentences, the removed direction u)."""
dim = len(next(iter(vectors.values())))
V = []
for s in sentences: # @line L1
V.append(weighted_average(s, vectors, p, a, dim)) # @line L2
X = V # @line L3
u, _ = first_singular_vector(X, seed) # @line L4
out = []
for v in V: # @line L5
out.append(remove_projection(v, u)) # @line L6
return out, u # @line L7
test_smooth_inverse_frequency_embedding.py 130 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/smooth-inverse-frequency-embedding/. The authors are listed in prov/V5GPPB.jsonl.
import math
import random
import pytest
from smooth_inverse_frequency_embedding import (
dot,
first_singular_vector,
norm,
remove_projection,
sif_embeddings,
sif_weight,
weighted_average,
word_probabilities,
)
P = {"the": 0.05, "a": 0.04, "cat": 1e-4, "dog": 1e-4, "sat": 5e-4, "ran": 5e-4}
V = {
"the": [1.0, 1.0, 0.0],
"a": [1.0, 0.8, 0.2],
"cat": [0.2, 0.0, 1.0],
"dog": [0.0, 0.2, 1.0],
"sat": [0.5, -1.0, 0.0],
"ran": [0.3, -1.0, 0.3],
}
S = ["the cat sat".split(), "a dog ran".split(), "the dog sat".split()]
def rand_vec(rng, d):
return [rng.gauss(0.0, 1.0) for _ in range(d)]
def test_weights():
assert sif_weight(1e-3, 1e-3) == pytest.approx(0.5)
assert sif_weight(0.0, 1e-3) == 1.0
assert sif_weight(0.05) == pytest.approx(1 / 51)
ps = [0.0, 1e-5, 1e-4, 1e-3, 1e-2, 0.1]
ws = [sif_weight(p) for p in ps]
assert all(x > y for x, y in zip(ws, ws[1:]))
with pytest.raises(ValueError):
sif_weight(0.1, 0.0)
def test_word_probabilities():
p = word_probabilities([["a", "b", "a"], ["c", "a"]])
assert p == {"a": 0.6, "b": 0.2, "c": 0.2}
assert math.fsum(p.values()) == pytest.approx(1.0)
def test_page_example():
avg = weighted_average(S[0], V, P, 1e-3, 3)
w_the, w_cat, w_sat = 1 / 51, 1 / 1.1, 1 / 1.5
expected = [(w_the * x + w_cat * y + w_sat * z) / 3 for x, y, z in zip(V["the"], V["cat"], V["sat"])]
assert avg == pytest.approx(expected)
assert avg == pytest.approx([0.1783, -0.2157, 0.3030], abs=1e-4)
out, u = sif_embeddings(S, V, P)
assert u == pytest.approx([0.3168, -0.4503, 0.8348], abs=1e-4)
assert out[0] == pytest.approx([0.0495, -0.0326, -0.0364], abs=1e-4)
for v in out:
assert dot(u, v) == pytest.approx(0.0, abs=1e-12)
def test_unknown_words_are_skipped_and_an_empty_sentence_is_zero():
assert weighted_average(["zzz"], V, P, 1e-3, 3) == [0.0, 0.0, 0.0]
assert weighted_average(["cat", "zzz"], V, P, 1e-3, 3) == pytest.approx([x / 1.1 for x in V["cat"]])
# A word with a vector but no probability gets the weight 1.
assert weighted_average(["new"], {"new": [2.0, 0.0]}, {}, 1e-3, 2) == [2.0, 0.0]
def test_first_singular_vector_is_an_eigenvector_and_maximizes_the_energy():
rng = random.Random(1)
X = [rand_vec(rng, 5) for _ in range(12)]
u, sigma = first_singular_vector(X)
assert norm(u) == pytest.approx(1.0)
G = [[math.fsum(r[i] * r[j] for r in X) for j in range(5)] for i in range(5)]
Gu = [dot(row, u) for row in G]
assert Gu == pytest.approx([sigma**2 * x for x in u], abs=1e-8)
energy = math.fsum(dot(r, u) ** 2 for r in X)
for _ in range(200):
r = rand_vec(rng, 5)
nr = norm(r)
r = [x / nr for x in r]
assert math.fsum(dot(row, r) ** 2 for row in X) <= energy + 1e-9
def test_removal_gives_orthogonal_vectors_and_is_idempotent():
rng = random.Random(2)
u = rand_vec(rng, 4)
nu = norm(u)
u = [x / nu for x in u]
for _ in range(20):
v = rand_vec(rng, 4)
w = remove_projection(v, u)
assert dot(w, u) == pytest.approx(0.0, abs=1e-12)
assert remove_projection(w, u) == pytest.approx(w, abs=1e-12)
assert norm(w) <= norm(v) + 1e-12
def test_planted_common_direction_is_found_and_removed():
rng = random.Random(3)
d = 6
c0 = [1.0, -1.0, 2.0, 0.0, 0.5, 1.0]
n0 = norm(c0)
c0 = [x / n0 for x in c0]
vocab = {f"w{i}": [3.0 * x + 0.3 * y for x, y in zip(c0, rand_vec(rng, d))] for i in range(30)}
sentences = [[f"w{rng.randrange(30)}" for _ in range(5)] for _ in range(40)]
p = word_probabilities(sentences)
out, u = sif_embeddings(sentences, vocab, p)
assert abs(dot(u, c0)) > 0.99
before = [weighted_average(s, vocab, p, 1e-3, d) for s in sentences]
# Before the removal all sentence vectors point the same way; after it they do not.
cos_before = [dot(a, b) / (norm(a) * norm(b)) for a, b in zip(before, before[1:])]
cos_after = [dot(a, b) / (norm(a) * norm(b)) for a, b in zip(out, out[1:])]
assert min(cos_before) > 0.9
assert sum(cos_after) / len(cos_after) < 0.5
def test_identical_sentences_become_zero_without_centering():
vecs = {"x": [1.0, 2.0], "y": [0.5, -1.0]}
out, u = sif_embeddings([["x", "y"], ["x", "y"], ["y", "x"]], vecs, {"x": 0.01, "y": 0.02})
for v in out:
assert v == pytest.approx([0.0, 0.0], abs=1e-12)
def test_all_zero_sentences_raise():
with pytest.raises(ValueError):
sif_embeddings([["zzz"]], V, P)
History
Weighted averages of word vectors, often with IDF weights, were used as sentence vectors well before 2017. Wieting et al. 2016 showed that a plain average of word vectors trained on paraphrase pairs is hard to beat. Arora, Liang and Ma 2017 gave the SIF weights a basis in a random walk model of text, added the removal of the common direction, and titled the paper "a simple but tough-to-beat baseline". Later sentence encoders built on BERT, such as Sentence-BERT, compare against it.
References
- Arora, Liang and Ma 2017, Algorithm 1 (the weighted average and the removal of the common component), the random walk model that gives the weights, and the experiments on the textual similarity tasks
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 V5GPPB Edit this page History Report an error Markdown