Algorithm Search⌘K

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
Properties
deterministicnot exactofflineiterativenot supervised
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 a/(a+p(w))a / (a + p(w)), where p(w)p(w) is the frequency of the word in a large corpus and aa is a small constant such as 10−310^{-3}. Then it removes from every sentence vector its projection on one direction uu, 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 nn tokenized sentences, a word vector vw∈Rdv_w \in \mathbb{R}^d for each known word, a unigram probability p(w)p(w) for each word, estimated on a large corpus, and a parameter a>0a > 0. 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

  1. SIF(S_1 .. S_n, v, p, a)
  2. 1for each sentence s do
  3. 2v_s ← (1 / |s|) Σ_{w ∈ s} a / (a + p(w)) · v_w
  4. 3X ← the n × d matrix with the rows v_s
  5. 4u ← the first right singular vector of X ▷ no centering
  6. 5for each sentence s do
  7. 6v_s ← v_s - u u^T v_s
  8. 7return v_s for every s, and u

Line L4 needs only the top eigenvector of the d×dd \times d matrix XTXX^T X, so power iteration is enough, and a truncated singular value decomposition gives the same vector. As in the code of the authors, XX is not centered, so uu 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 uu from the training sentences and apply lines L2 and L6 with it.

The weights come from a model. A latent discourse vector csc_s produces each word with probability α p(w)+(1−α)exp⁡(vw⋅c~s)/Z\alpha\, p(w) + (1 - \alpha) \exp(v_w \cdot \tilde c_s) / Z, where c~s=βc0+(1−β)cs\tilde c_s = \beta c_0 + (1 - \beta) c_s mixes in a common discourse vector c0c_0. Under approximations, the maximum likelihood estimate of c~s\tilde c_s is proportional to the weighted sum of line L2 with a=(1−α)/(αZ)a = (1 - \alpha) / (\alpha Z), and line L6 estimates c0c_0 by uu 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 a=10−3a = 10^{-3}, "the" (p=0.05p = 0.05) gets the weight 1/51=0.01961/51 = 0.0196, "a" (p=0.04p = 0.04) gets 0.0244, "cat" and "dog" (p=10−4p = 10^{-4}) get 0.9091, and "sat" and "ran" (p=5⋅10−4p = 5 \cdot 10^{-4}) 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 u=(0.3168,−0.4503,0.8348)u = (0.3168, -0.4503, 0.8348) 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 uu, 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 a/(a+p)a / (a + p) is 1 at p=0p = 0, 1/21/2 at p=ap = a, and strictly decreases in pp. The first right singular vector uu of XX maximizes ∑s(vs⋅u)2\sum_s (v_s \cdot u)^2 over unit vectors, and power iteration converges to it when the two largest singular values differ. Line L6 gives vs⋅u=0v_s \cdot u = 0, and it is the smallest change of vsv_s along uu 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 v1,…,vn∈Rdv_1, \ldots, v_n \in \mathbb{R}^d, and XX is the n×dn \times d 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 a>0a > 0, the weight f(p)=a/(a+p)f(p) = a / (a + p) is in (0,1](0, 1], equals 1 at p=0p = 0 and 1/21/2 at p=ap = a, and strictly decreases in p≥0p \ge 0.

Proof. f(0)=a/a=1f(0) = a/a = 1 and f(a)=a/2a=1/2f(a) = a / 2a = 1/2. For p≥0p \ge 0 the denominator a+pa + p is positive and strictly increases, so ff is positive and strictly decreases. □\square

So a word with p(w)≫ap(w) \gg a gets about a/p(w)a / p(w), and a word with p(w)≪ap(w) \ll a gets about 1.

Lemma 2 (the top direction). Let G=XTXG = X^T X, a symmetric positive semidefinite d×dd \times d matrix. For a unit vector rr, ∥Xr∥2=∑i(vi⋅r)2=rTGr\|X r\|^2 = \sum_i (v_i \cdot r)^2 = r^T G r. This is largest when rr is an eigenvector of GG for its largest eigenvalue σ12\sigma_1^2, which is the first right singular vector of XX, and then ∥Xr∥=σ1\|X r\| = \sigma_1.

Proof. Write G=∑jλjqjqjTG = \sum_j \lambda_j q_j q_j^T with orthonormal eigenvectors qjq_j and λ1≥λ2≥⋯≥0\lambda_1 \ge \lambda_2 \ge \cdots \ge 0. For a unit rr, rTGr=∑jλj(qj⋅r)2≤λ1∑j(qj⋅r)2=λ1r^T G r = \sum_j \lambda_j (q_j \cdot r)^2 \le \lambda_1 \sum_j (q_j \cdot r)^2 = \lambda_1, with equality at r=q1r = q_1. The singular value decomposition X=UΣQTX = U \Sigma Q^T gives G=QΣ2QTG = Q \Sigma^2 Q^T, so q1q_1 is the first right singular vector and λ1=σ12\lambda_1 = \sigma_1^2. □\square

The matrix GG is not centered: uu 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 λ1>λ2\lambda_1 > \lambda_2 and the start vector u0u_0 has q1⋅u0≠0q_1 \cdot u_0 \ne 0, the iterates ut+1=Gut/∥Gut∥u_{t+1} = G u_t / \|G u_t\| converge to ±q1\pm q_1, and the angle to q1q_1 shrinks by a factor of about λ2/λ1\lambda_2 / \lambda_1 per step.

Proof. Gtu0=∑jλjt(qj⋅u0)qjG^t u_0 = \sum_j \lambda_j^t (q_j \cdot u_0) q_j. Divide by λ1t(q1⋅u0)\lambda_1^t (q_1 \cdot u_0): the coefficient of q1q_1 is 1 and every other coefficient is at most ∣qj⋅u0∣/∣q1⋅u0∣⋅(λ2/λ1)t|q_j \cdot u_0| / |q_1 \cdot u_0| \cdot (\lambda_2/\lambda_1)^t, which goes to 0. Normalizing gives the claim (see power iteration). A random Gaussian start has q1⋅u0≠0q_1 \cdot u_0 \ne 0 with probability 1. □\square

The code fixes the sign so that the largest entry of uu is positive. The sign does not matter for line L6, since uuT=(−u)(−u)Tu u^T = (-u)(-u)^T.

Theorem (removal). For a unit vector uu, line L6 returns wi=vi−(u⋅vi)uw_i = v_i - (u \cdot v_i) u. Then (a) wi⋅u=0w_i \cdot u = 0, (b) ∥vi∥2=(u⋅vi)2+∥wi∥2\|v_i\|^2 = (u \cdot v_i)^2 + \|w_i\|^2, (c) removing again changes nothing, and (d) among all vectors of the form vi−c uv_i - c\, u, the vector wiw_i is the shortest.

Proof. (a) wi⋅u=vi⋅u−(u⋅vi)(u⋅u)=0w_i \cdot u = v_i \cdot u - (u \cdot v_i)(u \cdot u) = 0. (b) vi=(u⋅vi)u+wiv_i = (u \cdot v_i) u + w_i with orthogonal terms, so the Pythagorean theorem applies. (c) By (a), (u⋅wi)=0(u \cdot w_i) = 0, so wi−0⋅u=wiw_i - 0 \cdot u = w_i. (d) ∥vi−cu∥2=∥wi∥2+((u⋅vi)−c)2\|v_i - c u\|^2 = \|w_i\|^2 + ((u \cdot v_i) - c)^2 by (b) applied to vi−cuv_i - c u, which is smallest at c=u⋅vic = u \cdot v_i. □\square

Corollary. After lines L1 to L7, every output vector is orthogonal to uu, and uu 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 uu and the output is the zero vector for every sentence. ■\blacksquare

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 O(d)O(d) cost: O(td)O(t d) for tt tokens.
  • First singular vector. Forming XTXX^T X costs O(nd2)O(n d^2), and each power iteration step costs O(d2)O(d^2), so qq steps cost O(qd2)O(q d^2). Without forming XTXX^T X, each step costs O(nd)O(n d) as two products with XX.
  • Removal. Line L6 costs O(d)O(d) per sentence, O(nd)O(n d) in total.

The extra space is O(nd)O(n d) for XX and O(d2)O(d^2) for XTXX^T X. With d=300d = 300 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 aa and the one direction uu.
  • Order is ignored. "dog bites man" and "man bites dog" get the same vector, as with every weighted average.
  • Not online. The direction uu depends on all sentences of the set. A fixed uu 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 uu, 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 aa, 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 p(w)p(w) 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 aa from about 10−410^{-4} to 10−310^{-3}. Larger values bring back the weight of frequent words, and very small values make most words weigh about a/p(w)a / p(w).
  • Centering. Centering XX before line L4 gives a different direction. Both are used in practice; state which one you use.
  • A new u for every batch. Computing uu on each small batch at test time makes the vector of a sentence depend on the other sentences of the batch. Fix uu 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 XTXX^T X, 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.

smooth_inverse_frequency_embedding.pyI0RawGitHub
# 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

  1. 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.

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