Sub topic 10
Negative sampling
This chapter assumes you know skip-gram, the softmax function, and gradient descent on a loss. It covers the objective that skip-gram with negative sampling (SGNS) optimizes, how noise words are drawn, how the gradient updates work, and the mistakes people make when tuning it.
The problem negative sampling solves
Skip-gram models the probability of a context word c given a center word w with a softmax over the whole vocabulary:
P(c | w) = exp(uc · vw) / Σ{j=1..|V|} exp(uj · v_w)
Here v_w is the center vector of w and u_c is the output (context) vector of c. The denominator sums over every word in the vocabulary. With 500,000 words, each training pair costs 500,000 dot products for the forward pass and the same number of output-vector updates in the backward pass. Negative sampling removes that sum.
From one big classification to many small ones
Instead of asking "which of the |V| words is the context?", the model answers a yes/no question: "Is this (word, context) pair a real pair from the corpus, or noise?"
For each observed pair (w, c), the training procedure does the following:
- It treats (w, c) as a positive example with label 1.
- It draws
kwords c₁…c_k from a noise distribution and treats each (w, cᵢ) as a negative example with label 0. - It minimizes the logistic loss over these k + 1 examples.
The per-pair loss is:
L = −log σ(uc · vw) − Σᵢ log σ(−u{cᵢ} · vw)
Here σ is the sigmoid. Since 1 − σ(x) = σ(−x), the second term is the log-probability that each noise pair is correctly labeled "fake". The cost per pair is now k + 1 dot products, independent of vocabulary size.
The noise distribution
Negatives are not drawn uniformly. Mikolov et al. (2013) sample from the unigram distribution raised to the power 3/4:
Pn(w) = count(w)^0.75 / Σj count(j)^0.75
Sampling by raw frequency would fill the negatives with "the" and "of". Uniform sampling would over-represent rare words. The exponent 0.75 flattens the distribution, so rare words get drawn more often than their frequency implies, and frequent words less often. This value was found empirically. In gensim it is the ns_exponent parameter.
Gradients
Let s₊ = σ(uc · vw) and sᵢ = σ(u{cᵢ} · vw). The gradients of the loss are:
- With respect to the positive output vector: (s₊ − 1) · v_w
- With respect to each negative output vector: sᵢ · v_w
- With respect to the center vector: (s₊ − 1) · uc + Σᵢ sᵢ · u{cᵢ}
A positive pair with a low score pulls u_c and v_w together. A negative pair with a high score pushes them apart. Only k + 2 vectors change per step. The rest of the output matrix is untouched, which is why training is fast.
A runnable NumPy implementation
import numpy as np
def sigmoid(x):
return 1.0 / (1.0 + np.exp(-x))
def sgns_step(V, U, w, c, noise, k, lr, rng):
# Exclude the true context word from the negatives.
p = noise.copy()
p[c] = 0.0
p /= p.sum()
negs = rng.choice(len(p), size=k, p=p)
v = V[w].copy()
u_pos = U[c].copy()
u_neg = U[negs].copy() # shape (k, d)
s_pos = sigmoid(u_pos @ v)
s_neg = sigmoid(u_neg @ v) # shape (k,)
loss = -np.log(s_pos) - np.log(1.0 - s_neg).sum()
V[w] -= lr * ((s_pos - 1.0) * u_pos + s_neg @ u_neg)
U[c] -= lr * (s_pos - 1.0) * v
# np.subtract.at handles a negative that is drawn more than once.
np.subtract.at(U, negs, lr * np.outer(s_neg, v))
return loss
rng = np.random.default_rng(0)
counts = np.array([50, 30, 20, 10, 5, 5], dtype=float)
noise = counts ** 0.75
noise /= noise.sum()
d, k = 8, 5
V = rng.normal(scale=0.5, size=(len(counts), d))
U = np.zeros((len(counts), d)) # word2vec initializes output vectors to zero
losses = [sgns_step(V, U, 0, 1, noise, k, 0.5, rng) for _ in range(1000)]
print(round(losses[0], 4)) # 4.1589, which is (k + 1) * ln 2
print(np.mean(losses[:50]), np.mean(losses[-50:]))The first loss is exactly (k + 1)·ln 2 because the zero-initialized output vectors give every score σ(0) = 0.5. The last 50 steps should average far below the first 50.
Using it in gensim
from gensim.models import Word2Vec
sentences = [["the", "cat", "sits", "on", "the", "mat"],
["the", "dog", "sits", "on", "the", "rug"]]
model = Word2Vec(
sentences,
sg=1,
hs=0, # disable hierarchical softmax
negative=10, # k noise words per positive pair
ns_exponent=0.75, # exponent of the noise distribution
vector_size=50,
window=2,
min_count=1,
workers=1,
seed=1,
)
print(model.wv["cat"].shape)Setting negative=0 with hs=1 switches to hierarchical softmax instead.
Choosing k
| Corpus size | Typical k | Reason |
|---|---|---|
| Small (under a few million tokens) | 5 to 20 | Each positive pair is scarce, so more negatives extract more signal |
| Large (billions of tokens) | 2 to 5 | Data is plentiful, so extra negatives add cost with little benefit |
A larger k costs proportionally more time per pair. It also makes the model's implicit target shift, because the learned dot products absorb a log k term.
Edge cases and common errors
- Negatives that collide with the true context. With a small vocabulary a noise draw often equals
c, which sends contradictory labels for the same pair. The code above masksc. Original word2vec skips such draws. With a large vocabulary the effect is negligible. - Duplicate negatives in a batch. Using
U[negs] -= ...silently applies only one update per repeated index. Usenp.subtract.ator an equivalent scatter-add. - Numerical overflow.
np.exp(-x)overflows for large negativex. Production code clips scores or uses a precomputed sigmoid table, as the original C code does. - Confusing the loss with a probability model. Negative sampling does not estimate P(c | w). It is a simplified relative of noise-contrastive estimation, and its outputs are not normalized probabilities. Do not use the scores as probabilities.
- Evaluating with different noise settings. Changing
ns_exponentornegativechanges the embeddings, so compare models trained with the same settings.
Exercise
With k = 5 negatives and a vocabulary of 200,000 words, how many dot products does one training pair need under negative sampling, and how many under the full softmax? Also, if noise words follow P_n ∝ count^0.75, which gets sampled relatively more often compared with raw frequency: a word occurring 10,000 times or one occurring 100 times?
Show answer
Negative sampling needs k + 1 = 6 dot products, and the full softmax needs 200,000. The word occurring 100 times is sampled relatively more often than its raw frequency implies, because the 0.75 exponent flattens the distribution. The ratio of probabilities is (10,000/100)^0.75 ≈ 31.6, not 100.