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 and a context word , it draws 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 noise pairs. One pair costs dot products instead of . 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 , 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 . 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 , the number of noise words and the score . The loss of one observed pair with noise words is
where . Mikolov et al. take , the unigram distribution raised to the power and renormalized, a value they chose from their measurements.
NEGATIVE-SAMPLING-STEP(w, c, k, P_n, η)- 1
draw n_1, ..., n_k from P_n, and skip a draw equal to c - 2
for each (x, y) in (c, 1), (n_1, 0), ..., (n_k, 0) do - 3
e ← σ(u_x · v_w) - y ▷ the error of the logistic unit - 4
g_v ← g_v + e u_x ▷ the gradient for v_w - 5
g_x ← g_x + e v_w ▷ the gradient for u_x - 6
u_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: for the observed pair and for a noise pair. Lines L4 and L5 are the two halves of the gradient of , since and . Line L6 applies the updates after all terms are computed, so 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 , the observed context and two noise words with and . The scores are , and . The loss is
The errors of line L3 are , and , and the gradient for is . A gradient step moves toward and away from , the noise word with the highest score.
The noise distribution. For counts , the unigram distribution is , and the power gives . The power moves mass from frequent words to rare words. A sampler with a cumulative table and binary search draws a word in time; the alias method or the large table of the word2vec tool draws in .
What the optimum is. Let be the number of observed pairs, and the marginal counts and the number of pairs. In expectation over the noise, the terms of the objective that hold the score are . This is concave in , and its maximum is at
with PMI estimated with unigram context counts (for the smoothed noise, with in their place). The SGNS factorization theorem turns this into a statement about .
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 and the center word as the observed output.
- Subword information embeddings. The same loss, with replaced by the sum of the vectors of the character n-grams of . 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 with probability , with (a heuristic). A word with is discarded with probability , and words with 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 from 5 to 20 is useful for small data sets and from 2 to 5 for large ones. Each value of shifts the optimum by .
- The power of the noise. The power gives the unigram distribution and the power the uniform one. The power is a choice from measurements, not a derived value.
- Noise-contrastive estimation. NCE uses the logit in place of . 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 for every , that is uniform noise with .
- 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 as . The scores of one word do not sum to 1 over the contexts, and their optimum depends on and on . Do not report a perplexity from a model trained with negative sampling.
- The sign of the noise term. The noise term is , not or . With the wrong sign, line L3 uses for the noise words and all vectors collapse together.
- Updating inside the loop. If line L6 moves after each term, the later terms see a different vector and the step is not a gradient step of . Accumulate first, as the word2vec code does.
- Normalizing before the power. is divided by the sum of , not the unigram probability raised to without renormalization.
- The true context as noise. For a small vocabulary, a noise draw often equals , and the two terms then pull in opposite directions. The word2vec code skips such a draw (line L1), so a step can have fewer than 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.
# 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
- Show that the cell objective with is strictly concave in and has its maximum at . Use it to get .
- For counts , compute the noise distribution with the power and compare it with the values above.
- Write the NCE logit and show that its optimum is when the model can represent every distribution. Then show that negative sampling gives the same optimum only when for all .
References
- 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
- Dyer 2014, the difference between NCE, which estimates a normalized model, and negative sampling, which trains a binary classifier
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 9W46SG Edit this page History Report an error Markdown