Search

Search papers and lessons

Negative Sampling

Level 3 · 10 min read

Negative sampling trains a model to pick out the true partner among a few random decoys, so each update touches a handful of outputs instead of the whole vocabulary.

On this page

  • Colour = topic mix
  • Discrete math
  • Calculus
  • Linear algebra
  • Neural network basics
  • Probability
  • Representation learning
  • ReadReady to readNot yet

TL;DR

Negative sampling is a way to train a model that must choose one correct output from a very large set. Instead of scoring every possible output, it scores the one correct output and a few randomly drawn wrong ones, and it trains the model to separate them. This makes each update cheap, and it is the training trick behind the word vectors of word2vec.

Builds on: Contrastive Learning · Leads to: Efficient Estimation of Word Representations in Vector Space (word2vec)

Where it's used

Word vectors. The word2vec models learn a vector for every word from raw text. The skip-gram version predicts the words near a given word. With a vocabulary of hundreds of thousands of words, scoring every word for every training pair is too slow. Mikolov and colleagues (2013) trained skip-gram with negative sampling, which scores only the true neighbour and a few sampled words. The result is a set of word embeddings that are widely reused as the starting point for language tools.

Graph embeddings. GraphSAGE (Hamilton and colleagues), a graph neural network, learns a vector for each node of a graph. Its unsupervised loss rewards nodes that appear near each other on short random walks and penalises pairs drawn at random. The loss is written with the sigmoid of a dot product, and the random pairs are the negative samples. This lets the method train on large graphs without comparing each node with every other node.

How it works

The idea is a yes-or-no game. For a centre word, the model gets one true partner, the context word, and several random words that are not its partners. The model must answer yes for the true partner and no for each random word. Here is one update with tiny numbers.

  1. Take a training pair from the text. The centre word is "fox" and the true context word is "red", taken from a sentence like "the red fox".
  2. Score the true pair. The score is the dot product of the centre vector and the context vector. Suppose the score is 2. A high score means the model thinks the pair belongs together.
  3. Draw negative words. Pick two words at random that are not usual neighbours of "fox", say "table" and "run". Their scores are -2 and -2. A low score means the model thinks the pair does not belong.
  4. Turn each score into a yes-or-no probability with the sigmoid. The true pair gets σ(2)≈0.88\sigma(2) \approx 0.88, which should be high. Each negative pair gets σ(−2)≈0.12\sigma(-2) \approx 0.12, which should be low. Check: the two numbers add to 1 for each pair, since σ(−s)=1−σ(s)\sigma(-s) = 1 - \sigma(s).
  5. Add up the errors. The error for the true pair is −ln⁡0.88≈0.127-\ln 0.88 \approx 0.127. The error for each negative pair is −ln⁡(1−0.12)=−ln⁡0.88≈0.127-\ln(1 - 0.12) = -\ln 0.88 \approx 0.127. The total is 3×0.127≈0.3813 \times 0.127 \approx 0.381.
  6. Update only the touched vectors. A gradient step changes the centre vector and the three output vectors for "red", "table" and "run". Every other output vector in the vocabulary is left alone. That is the saving.
flowchart LR
  P[Centre and true context word] --> S1[Score true pair]
  N[Draw k random words] --> S2[Score each random pair]
  S1 --> L[Sum of sigmoid errors]
  S2 --> L
  L --> U[Update k plus 1 output vectors]

The math

Definition: Negative sampling loss

For a centre word with vector vc\mathbf{v}_c, a true context word oo with output vector uo\mathbf{u}_o, and kk sampled negative words n1,…,nkn_1, \dots, n_k with output vectors unj\mathbf{u}_{n_j}, the loss is ℓ=−log⁡σ(uo⊤vc)  −  ∑j=1klog⁡σ(−unj⊤vc),\ell = -\log \sigma(\mathbf{u}_o^{\top} \mathbf{v}_c) \;-\; \sum_{j=1}^{k} \log \sigma(-\mathbf{u}_{n_j}^{\top} \mathbf{v}_c), where σ(s)=1/(1+e−s)\sigma(s) = 1/(1 + e^{-s}) is the sigmoid function. The loss is a sum of logarithms of sigmoids, one per pair, so it is a binary cross-entropy over yes-or-no decisions.

Step 2 in symbols: the score

Each pair gets a score s=u⊤vcs = \mathbf{u}^{\top} \mathbf{v}_c, the dot product of two vectors. For the example, so=2s_o = 2 for the true pair and snj=−2s_{n_j} = -2 for each negative pair.

Step 4 in symbols: the sigmoid turns scores into probabilities

The true pair contributes −log⁡σ(so)-\log \sigma(s_o). A negative pair contributes −log⁡σ(−snj)-\log \sigma(-s_{n_j}), which is the same as −log⁡(1−σ(snj))-\log(1 - \sigma(s_{n_j})). With the numbers from the walkthrough, σ(2)≈0.8808\sigma(2) \approx 0.8808 and σ(−(−2))=σ(2)≈0.8808\sigma(-(-2)) = \sigma(2) \approx 0.8808.

Step 5 in symbols: the total error

Plugging in: ℓ=−ln⁡σ(2)−2ln⁡σ(2)=3×0.1269≈0.381\ell = -\ln \sigma(2) - 2 \ln \sigma(2) = 3 \times 0.1269 \approx 0.381.

The gradients have a simple form. The derivative of ℓ\ell with respect to the true pair's score is σ(so)−1\sigma(s_o) - 1, which is negative, so a gradient step raises the true score. The derivative with respect to a negative pair's score is σ(snj)\sigma(s_{n_j}), which is positive, so a step lowers it. For the example, the gradient on the true score is about −0.12-0.12, so a step raises that score by about 0.12, and the gradient on each negative score is about +0.12+0.12, so a step lowers each by about 0.12.

Step 6 in symbols: the cost compared with the full softmax

The full Softmax over a vocabulary of size VV gives the probability of the true word as

P(o∣c)=exp⁡(uo⊤vc)∑w=1Vexp⁡(uw⊤vc).P(o \mid c) = \frac{\exp(\mathbf{u}_o^{\top} \mathbf{v}_c)}{\sum_{w=1}^{V} \exp(\mathbf{u}_w^{\top} \mathbf{v}_c)}.

Its denominator needs VV dot products per training pair. Negative sampling needs k+1k + 1. When VV is 10,000 and kk is 5, that is 10,000 against 6.

Worked examples

Example
1. Tiny case: every score is zero

Use one true pair and two negative pairs, all with score 0.

  1. The sigmoid of 0 is σ(0)=1/2\sigma(0) = 1/2.
  2. Each pair contributes −ln⁡12=ln⁡2≈0.693-\ln \tfrac12 = \ln 2 \approx 0.693.
  3. There are three pairs, so the loss is 3ln⁡2≈2.0793 \ln 2 \approx 2.079.
  4. The gradient on each true or negative score is σ(0)−1=−0.5\sigma(0) - 1 = -0.5 for the true pair and σ(0)=0.5\sigma(0) = 0.5 for each negative pair.

Interpretation: the model knows nothing yet, so every pair is a coin flip. The loss is largest here, and the updates push the true pair up and the negatives down.

Example
2. Standard case: the walkthrough numbers, then a mistake

Start from the walkthrough: true score 2, negative scores -2 and -2.

  1. The true term is −ln⁡σ(2)≈0.127-\ln \sigma(2) \approx 0.127.
  2. Each negative term is −ln⁡σ(2)≈0.127-\ln \sigma(2) \approx 0.127.
  3. The total is 3×0.127≈0.3813 \times 0.127 \approx 0.381.
  4. Now suppose the negatives have crept up to score 0, while the true score stays at 2.
  5. The true term is still 0.127. Each negative term is −ln⁡σ(0)=ln⁡2≈0.693-\ln \sigma(0) = \ln 2 \approx 0.693.
  6. The total is 0.127+2×0.693≈1.5130.127 + 2 \times 0.693 \approx 1.513.

Interpretation: the loss grows when a random word looks like a true partner. That is exactly the error the method is meant to fix.

Example
3. Realistic: the cost of one update in word2vec

Take a vocabulary of 10,000 words and k=5k = 5 negative samples per training pair, a common small setting.

  1. Full softmax: each training pair needs the denominator over all 10,000 words, so 10,000 dot products.
  2. Negative sampling: the true word plus five negatives gives 6 dot products.
  3. The ratio is 10,000/6≈1,66710{,}000 / 6 \approx 1{,}667.
  4. The gradient step touches 6 output vectors instead of 10,000.

Interpretation: a model that would take a long time per pair with a full softmax can run many more pairs in the same time. The saving is the reason negative sampling made word vectors practical at scale.

Try it: a true pair has score 1, and two negative pairs each have score -1. Find the loss ℓ\ell. Use σ(1)≈0.7311\sigma(1) \approx 0.7311.

Answer: The true term is −ln⁡σ(1)≈0.3133-\ln \sigma(1) \approx 0.3133. Each negative term is −ln⁡σ(1)≈0.3133-\ln \sigma(1) \approx 0.3133, because σ(−(−1))=σ(1)\sigma(-(-1)) = \sigma(1). The total is 3×0.3133≈0.9403 \times 0.3133 \approx 0.940.

Common mistakes and tradeoffs

It is tempting to think negative sampling is just a cheap approximation of the softmax, so its probabilities match the softmax's. In fact it solves a different problem: a set of yes-or-no decisions, one per pair, much like Logistic Regression. The word vectors work well, but the numbers it produces are not calibrated probabilities over the vocabulary. If you need those probabilities, use the full softmax or an approximation designed for them.

It is tempting to think the negative words should be picked uniformly at random from the vocabulary. In fact the sampling distribution is a design choice, and the word2vec paper draws negatives from a distribution that favours frequent words over rare ones. Uniform sampling is simpler, but it changes which mistakes the model learns to avoid.

It is tempting to think a negative word is always a wrong answer. In fact a random negative can be a real neighbour by chance. The method accepts this noise, because such collisions are rare and the many other negatives still push the model in the right direction.

Use negative sampling when the output set is very large, when you are learning embeddings, and when cheap updates matter more than calibrated probabilities. Do not use it when the output set is small enough for a full softmax, or when the downstream task needs the full probability distribution. Alternatives include the full softmax, which is exact but costly, and Hierarchical Softmax, which arranges the outputs in a tree so that each prediction follows one path.

History

The idea of separating true data from random noise to fit a model is older than word vectors. Gutmann and Hyvärinen (2010) introduced noise-contrastive estimation, which turns density estimation into a classification of real against noise samples. Mikolov and colleagues (2013) adapted the approach into the negative sampling objective for word2vec, which made it simple to run on very large text corpora. Its use spread quickly because it was cheap, easy to code, and produced vectors that were useful for many tasks. Later graph and retrieval methods, including GraphSAGE, reused the same pattern.

Recap

  • Training a model to choose among all outputs is expensive when the output set is large.
  • Negative sampling scores the true output and a few random ones, and applies a sigmoid to each pair.
  • The loss is a sum of sigmoid errors, with one term for the true pair and one for each negative.
  • Each update touches only k+1k + 1 output vectors, which is the source of the speed.

Read next: Efficient Estimation of Word Representations in Vector Space (word2vec) applies this objective to learn word vectors from raw text, and Word Embedding explains what those vectors are for.

Check yourself

QuestionIn one sentence, what does negative sampling replace the full softmax denominator with?Show answer
A sum over only the true output and a few randomly drawn negative outputs, each scored with a sigmoid, instead of a sum over the entire vocabulary.
QuestionA true pair has score 3, and one negative pair has score -3. Using σ(3)≈0.9526\sigma(3) \approx 0.9526, find the loss ℓ\ell with k=1k = 1.Show answer
The true term is −ln⁡σ(3)≈0.0486-\ln \sigma(3) \approx 0.0486. The negative term is −ln⁡σ(3)≈0.0486-\ln \sigma(3) \approx 0.0486, because σ(−(−3))=σ(3)\sigma(-(-3)) = \sigma(3). The total is about 0.097.
QuestionWhy does a negative pair with a high score increase the loss?Show answer
The negative term is −ln⁡(1−σ(s))-\ln(1 - \sigma(s)), which grows as σ(s)\sigma(s) rises toward 1. A high score on a random pair means the model thinks the random word belongs with the centre word, which is the mistake the objective penalises.
QuestionYou are training a classifier with 50 possible labels and need calibrated probabilities over all 50. Should you use negative sampling? Why or why not?Show answer
Probably not. With only 50 labels the full softmax is cheap, and negative sampling does not produce calibrated probabilities over all labels. It is a good fit for very large output sets when the goal is learned representations rather than full probabilities.

Sources

Negative Sampling — explained simply · ungoon.me