Algorithm Search⌘K

Techniquecore

Negative sampling

Also called skip-gram with negative sampling, SGNS.

Train word vectors by logistic loss that tells observed word-context pairs from k random pairs drawn from a smoothed unigram distribution.

Negative sampling trains word vectors without the softmax over the vocabulary. For each observed pair of a word ww and a context word cc, it draws kk noise words from a fixed distribution, and it trains a logistic regression on the dot products to give a high score to the observed pair and a low score to the kk noise pairs. One pair costs k+1k + 1 dot products instead of ∣V∣|V|. Mikolov, Sutskever, Chen, Corrado and Dean (2013) introduced it for the skip-gram model. It is a simplification of noise-contrastive estimation, but it is not an estimator of the softmax model: the trained scores are not normalized probabilities.

In plain words

The full model asks "which word, out of every word in the vocabulary, is the context?" That needs a score for every word, and the vocabulary can have millions of words.

Negative sampling asks an easier question many times. It takes a real pair of words from the text and a few fake pairs, made by putting the same word next to random words. A frequent word is chosen as a fake more often, but less often than its share of the text. The model only has to say "real" or "fake" for each pair.

To do this well, it must pull the vectors of real pairs together and push the vectors of fake pairs apart. Words that occur in the same kinds of places end up with similar vectors. Each step looks at a few words only, so training is fast.

When it applies

Use it when a model scores a pair by a cheap function, here the dot product u⃗c⋅v⃗w\vec u_c \cdot \vec v_w, the output space is large, and you need the vectors, not calibrated probabilities. The signals are a softmax over a large vocabulary in the loss, a training set of observed pairs, and an end use (similarity, analogy, features for another model) that does not need P(c∣w)P(c \mid w). When you need a normalized distribution, for example for perplexity, use noise-contrastive estimation or the hierarchical softmax instead.

The template

The holes are the noise distribution PnP_n, the number kk of noise words and the score s(w,c)=u⃗c⋅v⃗ws(w, c) = \vec u_c \cdot \vec v_w. The loss of one observed pair (w,c)(w, c) with noise words n1,…,nkn_1, \ldots, n_k is

ℓ(w,c)=−log⁡σ(u⃗c⋅v⃗w)−∑i=1klog⁡σ(−u⃗ni⋅v⃗w),\ell(w, c) = -\log \sigma(\vec u_c \cdot \vec v_w) - \sum_{i=1}^{k} \log \sigma(-\vec u_{n_i} \cdot \vec v_w),

where σ(x)=1/(1+e−x)\sigma(x) = 1/(1 + e^{-x}). Mikolov et al. take Pn(u)=#(u)3/4/ZP_n(u) = \#(u)^{3/4} / Z, the unigram distribution raised to the power 3/43/4 and renormalized, a value they chose from their measurements.

  1. NEGATIVE-SAMPLING-STEP(w, c, k, P_n, η)
  2. 1draw n_1, ..., n_k from P_n, and skip a draw equal to c
  3. 2for each (x, y) in (c, 1), (n_1, 0), ..., (n_k, 0) do
  4. 3e ← σ(u_x · v_w) - y ▷ the error of the logistic unit
  5. 4g_v ← g_v + e u_x ▷ the gradient for v_w
  6. 5g_x ← g_x + e v_w ▷ the gradient for u_x
  7. 6u_x ← u_x - η g_x for each x; v_w ← v_w - η g_v

Line L1 draws the noise words. Line L3 is the error of the logistic unit: σ(⋅)−1\sigma(\cdot) - 1 for the observed pair and σ(⋅)\sigma(\cdot) for a noise pair. Lines L4 and L5 are the two halves of the gradient of ℓ\ell, since ddx(−log⁡σ(x))=σ(x)−1\frac{d}{dx}\big(-\log\sigma(x)\big) = \sigma(x) - 1 and ddx(−log⁡σ(−x))=σ(x)\frac{d}{dx}\big(-\log\sigma(-x)\big) = \sigma(x). Line L6 applies the updates after all k+1k + 1 terms are computed, so v⃗w\vec v_w is the same vector in each term. A training pass emits the pairs of the skip-gram model and runs this step on each.

Example. Take v⃗w=(1,0)\vec v_w = (1, 0), the observed context u⃗c=(1,1)\vec u_c = (1, 1) and two noise words with u⃗n1=(0.5,0)\vec u_{n_1} = (0.5, 0) and u⃗n2=(−1,0.5)\vec u_{n_2} = (-1, 0.5). The scores are 11, 0.50.5 and −1-1. The loss is

−log⁡σ(1)−log⁡σ(−0.5)−log⁡σ(1)=0.3133+0.9741+0.3133=1.6006.-\log\sigma(1) - \log\sigma(-0.5) - \log\sigma(1) = 0.3133 + 0.9741 + 0.3133 = 1.6006.

The errors of line L3 are σ(1)−1=−0.2689\sigma(1) - 1 = -0.2689, σ(0.5)=0.6225\sigma(0.5) = 0.6225 and σ(−1)=0.2689\sigma(-1) = 0.2689, and the gradient for v⃗w\vec v_w is −0.2689(1,1)+0.6225(0.5,0)+0.2689(−1,0.5)=(−0.2267,−0.1345)-0.2689(1, 1) + 0.6225(0.5, 0) + 0.2689(-1, 0.5) = (-0.2267, -0.1345). A gradient step moves v⃗w\vec v_w toward u⃗c\vec u_c and away from u⃗n1\vec u_{n_1}, the noise word with the highest score.

The noise distribution. For counts (8,4,2,1,1)(8, 4, 2, 1, 1), the unigram distribution is (0.5,0.25,0.125,0.0625,0.0625)(0.5, 0.25, 0.125, 0.0625, 0.0625), and the power 3/43/4 gives (0.4222,0.2510,0.1493,0.0888,0.0888)(0.4222, 0.2510, 0.1493, 0.0888, 0.0888). The power moves mass from frequent words to rare words. A sampler with a cumulative table and binary search draws a word in O(log⁡V)O(\log V) time; the alias method or the large table of the word2vec tool draws in O(1)O(1).

What the optimum is. Let #(w,c)\#(w, c) be the number of observed pairs, #(w)\#(w) and #(c)\#(c) the marginal counts and ∣D∣|D| the number of pairs. In expectation over the noise, the terms of the objective that hold the score x=u⃗c⋅v⃗wx = \vec u_c \cdot \vec v_w are #(w,c)log⁡σ(x)+k #(w)#(c)/∣D∣⋅log⁡σ(−x)\#(w, c)\log\sigma(x) + k\,\#(w)\#(c)/|D| \cdot \log\sigma(-x). This is concave in xx, and its maximum is at

x∗=log⁡#(w,c) ∣D∣#(w) #(c)−log⁡k=PMI(w,c)−log⁡k,x^* = \log\frac{\#(w, c)\,|D|}{\#(w)\,\#(c)} - \log k = \mathrm{PMI}(w, c) - \log k,

with PMI estimated with unigram context counts (for the smoothed noise, with #(c)3/4\#(c)^{3/4} in their place). The SGNS factorization theorem turns this into a statement about WC⊤W C^\top.

Classic examples

  • Skip-gram model. The original use: each (center, context) pair of a window is one observed pair.
  • Continuous bag-of-words. The same step with the mean of the context vectors in place of v⃗w\vec v_w and the center word as the observed output.
  • Subword information embeddings. The same loss, with v⃗w\vec v_w replaced by the sum of the vectors of the character n-grams of ww. The gradient of line L4 goes to every n-gram row.
  • node2vec. Skip-gram on random walks over a graph, trained with negative sampling, so the observed pairs are nodes that occur near each other on a walk.

Variations

  • Subsampling of frequent words. Mikolov et al. discard each token of a word of relative frequency ff with probability 1−t/f1 - \sqrt{t/f}, with t=10−5t = 10^{-5} (a heuristic). A word with f=10−3f = 10^{-3} is discarded with probability 0.90.9, and words with f≤tf \le t are always kept. The released word2vec code uses a slightly different formula. Subsampling speeds up training and also widens the effective window.
  • The number of noise words. Mikolov et al. report that kk from 5 to 20 is useful for small data sets and kk from 2 to 5 for large ones. Each value of kk shifts the optimum by −log⁡k-\log k.
  • The power of the noise. The power 11 gives the unigram distribution and the power 00 the uniform one. The power 3/43/4 is a choice from measurements, not a derived value.
  • Noise-contrastive estimation. NCE uses the logit s(w,c)−log⁡(kPn(c))s(w, c) - \log(k P_n(c)) in place of s(w,c)s(w, c). With this correction the optimum is the normalized conditional distribution. Negative sampling is the case where the correction term is dropped, which is the same as NCE only when kPn(c)=1k P_n(c) = 1 for every cc, that is uniform noise with k=∣V∣k = |V|.
  • Other uses. The same pattern trains embeddings of nodes, items and sentences: any model with a dot-product score over a large set of candidates.

Pitfalls

  • Reading σ(u⃗c⋅v⃗w)\sigma(\vec u_c \cdot \vec v_w) as P(c∣w)P(c \mid w). The scores of one word do not sum to 1 over the contexts, and their optimum depends on kk and on PnP_n. Do not report a perplexity from a model trained with negative sampling.
  • The sign of the noise term. The noise term is log⁡σ(−x)\log\sigma(-x), not log⁡(1−x)\log(1 - x) or −log⁡σ(x)-\log\sigma(x). With the wrong sign, line L3 uses y=1y = 1 for the noise words and all vectors collapse together.
  • Updating v⃗w\vec v_w inside the loop. If line L6 moves v⃗w\vec v_w after each term, the later terms see a different vector and the step is not a gradient step of ℓ\ell. Accumulate gvg_v first, as the word2vec code does.
  • Normalizing before the power. PnP_n is #(u)3/4\#(u)^{3/4} divided by the sum of #(u′)3/4\#(u')^{3/4}, not the unigram probability raised to 3/43/4 without renormalization.
  • The true context as noise. For a small vocabulary, a noise draw often equals cc, and the two terms then pull u⃗c\vec u_c in opposite directions. The word2vec code skips such a draw (line L1), so a step can have fewer than kk noise words.

Code

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.

negative_sampling.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/negative-sampling/. The authors are listed in prov/9W46SG.jsonl.

"""Negative sampling for the skip-gram model (Mikolov, Sutskever et al. 2013).

For an observed pair (w, c) and k noise words n_1 ... n_k drawn from
P_n(u) = count(u)^(3/4) / Z, the loss is

    -log sigma(u_c . v_w) - sum_i log sigma(-u_{n_i} . v_w).

v are the input (word) vectors and u the output (context) vectors. Like the
released word2vec code, the sampler drops a noise word equal to c. The
subsampling rule discards a token of relative frequency f with probability
max(0, 1 - sqrt(t / f)), the formula of the paper (the released code uses a
slightly different one).
"""

import bisect
import math
import random
from typing import Sequence


def sigmoid(x: float) -> float:
    if x >= 0:
        return 1.0 / (1.0 + math.exp(-x))
    e = math.exp(x)
    return e / (1.0 + e)


def log_sigmoid(x: float) -> float:
    return -math.log1p(math.exp(-x)) if x >= 0 else x - math.log1p(math.exp(x))


def noise_distribution(counts: Sequence[int], power: float = 0.75) -> list[float]:
    z = sum(c ** power for c in counts)
    return [c ** power / z for c in counts]


class NoiseSampler:
    def __init__(self, counts: Sequence[int], power: float = 0.75):
        acc, self.cdf = 0.0, []
        for p in noise_distribution(counts, power):
            acc += p
            self.cdf.append(acc)

    def draw(self, rng: random.Random) -> int:
        return min(bisect.bisect_right(self.cdf, rng.random() * self.cdf[-1]), len(self.cdf) - 1)

    def negatives(self, rng: random.Random, k: int, context: int) -> list[int]:
        """k draws; a draw equal to the true context is skipped, as in word2vec."""
        out = []
        for _ in range(k):  # @line L1
            u = self.draw(rng)
            if u != context:
                out.append(u)
        return out


def discard_probability(freq: float, t: float = 1e-5) -> float:
    return max(0.0, 1.0 - math.sqrt(t / freq))


def pair_loss(vin, uout, w: int, c: int, negatives: Sequence[int]) -> float:
    h = vin[w]
    dot = lambda u: sum(a * b for a, b in zip(uout[u], h))  # noqa: E731
    return -log_sigmoid(dot(c)) - sum(log_sigmoid(-dot(u)) for u in negatives)


def pair_gradient(vin, uout, w: int, c: int, negatives: Sequence[int]):
    """(gradient of v_w, dict of gradients of the output rows)."""
    h = vin[w]
    d = len(h)
    gv = [0.0] * d
    gu: dict[int, list[float]] = {}
    for u, label in [(c, 1.0)] + [(u, 0.0) for u in negatives]:  # @line L2
        e = sigmoid(sum(a * b for a, b in zip(uout[u], h))) - label  # @line L3
        row = gu.setdefault(u, [0.0] * d)
        for k in range(d):
            gv[k] += e * uout[u][k]  # @line L4
            row[k] += e * h[k]  # @line L5
    return gv, gu


def sgd_step(vin, uout, w: int, c: int, negatives: Sequence[int], lr: float) -> None:
    gv, gu = pair_gradient(vin, uout, w, c, negatives)
    for u, g in gu.items():
        for k in range(len(g)):
            uout[u][k] -= lr * g[k]
    for k in range(len(gv)):
        vin[w][k] -= lr * gv[k]  # @line L6


def train(corpus, vocab_size: int, d: int = 8, window: int = 2, k: int = 5, epochs: int = 5,
          lr: float = 0.05, seed: int = 0):
    """Skip-gram with negative sampling on a corpus of word ids. Returns (vin, uout)."""
    rng = random.Random(seed)
    counts = [0] * vocab_size
    for sent in corpus:
        for w in sent:
            counts[w] += 1
    sampler = NoiseSampler([max(c, 1) for c in counts])
    vin = [[(rng.random() - 0.5) / d for _ in range(d)] for _ in range(vocab_size)]
    uout = [[0.0] * d for _ in range(vocab_size)]
    for _ in range(epochs):
        for sent in corpus:
            for t, w in enumerate(sent):
                for j in range(max(0, t - window), min(len(sent), t + window + 1)):
                    if j != t:
                        sgd_step(vin, uout, w, sent[j], sampler.negatives(rng, k, sent[j]), lr)
    return vin, uout


def expected_local_objective(x: float, n_wc: float, n_w: float, n_c: float, total: float, k: int) -> float:
    """n(w,c) log sigma(x) + k n(w) n(c) / total * log sigma(-x), the cell objective of Levy and Goldberg."""
    return n_wc * log_sigmoid(x) + k * n_w * n_c / total * log_sigmoid(-x)
test_negative_sampling.py 90 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/negative-sampling/. The authors are listed in prov/9W46SG.jsonl.

import math
import random

from negative_sampling import (
    NoiseSampler,
    discard_probability,
    expected_local_objective,
    noise_distribution,
    pair_gradient,
    pair_loss,
    train,
)


def cos(u, v):
    return sum(a * b for a, b in zip(u, v)) / math.sqrt(sum(a * a for a in u) * sum(b * b for b in v))


def test_noise_distribution_hand_values():
    p = noise_distribution([8, 4, 2, 1, 1])
    assert abs(sum(p) - 1.0) < 1e-12
    assert [round(x, 4) for x in p] == [0.4222, 0.251, 0.1493, 0.0888, 0.0888]
    assert noise_distribution([8, 4, 2, 1, 1], power=1.0) == [0.5, 0.25, 0.125, 0.0625, 0.0625]


def test_sampler_frequencies_and_skip():
    counts = [8, 4, 2, 1, 1]
    s = NoiseSampler(counts)
    rng = random.Random(1)
    n = 20000
    freq = [0] * 5
    for _ in range(n):
        freq[s.draw(rng)] += 1
    assert all(abs(f / n - p) < 0.01 for f, p in zip(freq, noise_distribution(counts)))
    for _ in range(500):
        assert 0 not in s.negatives(rng, 5, 0)


def test_discard_probability():
    assert discard_probability(1e-5) == 0.0
    assert discard_probability(1e-6) == 0.0
    assert abs(discard_probability(1e-3) - 0.9) < 1e-12
    assert abs(discard_probability(0.01) - (1 - math.sqrt(1e-3))) < 1e-12


def test_gradient_against_finite_differences():
    rng = random.Random(2)
    vin = [[rng.uniform(-1, 1) for _ in range(4)] for _ in range(6)]
    uout = [[rng.uniform(-1, 1) for _ in range(4)] for _ in range(6)]
    h = 1e-6
    for w, c, neg in [(0, 1, [2, 3, 3]), (4, 4, [5]), (2, 5, [])]:
        gv, gu = pair_gradient(vin, uout, w, c, neg)
        for mat, row, grad in [(vin, w, gv)] + [(uout, j, gu.get(j, [0.0] * 4)) for j in range(6)]:
            for k in range(4):
                old = mat[row][k]
                mat[row][k] = old + h
                up = pair_loss(vin, uout, w, c, neg)
                mat[row][k] = old - h
                down = pair_loss(vin, uout, w, c, neg)
                mat[row][k] = old
                assert abs((up - down) / (2 * h) - grad[k]) < 1e-5


def test_cell_objective_peaks_at_shifted_pmi():
    for n_wc, n_w, n_c, total, k in [(4, 5, 5, 10, 2), (1, 5, 5, 10, 2), (3, 7, 2, 40, 5), (9, 10, 12, 50, 1)]:
        lo, hi = -20.0, 20.0
        for _ in range(200):  # ternary search on a concave function
            m1, m2 = lo + (hi - lo) / 3, hi - (hi - lo) / 3
            if expected_local_objective(m1, n_wc, n_w, n_c, total, k) < expected_local_objective(m2, n_wc, n_w, n_c, total, k):
                lo = m1
            else:
                hi = m2
        assert abs((lo + hi) / 2 - (math.log(n_wc * total / (n_w * n_c)) - math.log(k))) < 1e-6


def test_planted_clusters_come_apart():
    rng = random.Random(3)
    groups = [(list(range(0, 4)), list(range(8, 11))), (list(range(4, 8)), list(range(11, 14)))]
    corpus = []
    for _ in range(60):
        words, ctx = groups[rng.randrange(2)]
        corpus.append([rng.choice(words) if k % 2 == 0 else rng.choice(ctx) for k in range(6)])
    vin, _ = train(corpus, 14, d=6, window=2, k=3, epochs=5, lr=0.05, seed=3)
    (a, _), (b, _) = groups
    inside = [cos(vin[u], vin[v]) for g in (a, b) for k, u in enumerate(g) for v in g[k + 1:]]
    across = [cos(vin[u], vin[v]) for u in a for v in b]
    assert min(inside) > max(across)

Exercises

  1. Show that the cell objective alog⁡σ(x)+blog⁡σ(−x)a\log\sigma(x) + b\log\sigma(-x) with a,b>0a, b > 0 is strictly concave in xx and has its maximum at x=log⁡(a/b)x = \log(a/b). Use it to get x∗=PMI(w,c)−log⁡kx^* = \mathrm{PMI}(w, c) - \log k.
  2. For counts (8,4,2,1,1)(8, 4, 2, 1, 1), compute the noise distribution with the power 1/21/2 and compare it with the values above.
  3. Write the NCE logit s−log⁡(kPn(c))s - \log(k P_n(c)) and show that its optimum is s=log⁡P(c∣w)s = \log P(c \mid w) when the model can represent every distribution. Then show that negative sampling gives the same optimum only when kPn(c)=1k P_n(c) = 1 for all cc.

References

  1. Mikolov, Sutskever, Chen, Corrado and Dean 2013, the negative sampling objective, the noise distribution U(w)^(3/4)/Z, the range of k, the subsampling of frequent words with t = 1e-5, and the empirical comparison with hierarchical softmax and NCE
  2. Dyer 2014, the difference between NCE, which estimates a normalized model, and negative sampling, which trains a binary classifier
  3. Goldberg and Levy 2014, the negative sampling objective written over the word and context pairs of a corpus, and the remark that it does not model the conditional distribution of contexts
  4. Levy and Goldberg 2014, Section 3.1 (the optimum of each cell of the objective, PMI(w, c) - log k)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
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)
WritingW3 standard
  • five exercises