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.
- 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".
- 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.
- 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.
- Turn each score into a yes-or-no probability with the sigmoid. The true pair gets , which should be high. Each negative pair gets , which should be low. Check: the two numbers add to 1 for each pair, since .
- Add up the errors. The error for the true pair is . The error for each negative pair is . The total is .
- 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
For a centre word with vector , a true context word with output vector , and sampled negative words with output vectors , the loss is where 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 , the dot product of two vectors. For the example, for the true pair and for each negative pair.
Step 4 in symbols: the sigmoid turns scores into probabilities
The true pair contributes . A negative pair contributes , which is the same as . With the numbers from the walkthrough, and .
Step 5 in symbols: the total error
Plugging in: .
The gradients have a simple form. The derivative of with respect to the true pair's score is , which is negative, so a gradient step raises the true score. The derivative with respect to a negative pair's score is , which is positive, so a step lowers it. For the example, the gradient on the true score is about , so a step raises that score by about 0.12, and the gradient on each negative score is about , 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 gives the probability of the true word as
Its denominator needs dot products per training pair. Negative sampling needs . When is 10,000 and is 5, that is 10,000 against 6.
Worked examples
Use one true pair and two negative pairs, all with score 0.
- The sigmoid of 0 is .
- Each pair contributes .
- There are three pairs, so the loss is .
- The gradient on each true or negative score is for the true pair and 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.
Start from the walkthrough: true score 2, negative scores -2 and -2.
- The true term is .
- Each negative term is .
- The total is .
- Now suppose the negatives have crept up to score 0, while the true score stays at 2.
- The true term is still 0.127. Each negative term is .
- The total is .
Interpretation: the loss grows when a random word looks like a true partner. That is exactly the error the method is meant to fix.
Take a vocabulary of 10,000 words and negative samples per training pair, a common small setting.
- Full softmax: each training pair needs the denominator over all 10,000 words, so 10,000 dot products.
- Negative sampling: the true word plus five negatives gives 6 dot products.
- The ratio is .
- 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 . Use .
Answer: The true term is . Each negative term is , because . The total is .
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 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
QuestionA true pair has score 3, and one negative pair has score -3. Using , find the loss with .Show answer
QuestionWhy does a negative pair with a high score increase the loss?Show answer
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
Sources
- Mikolov, Sutskever, Chen, Corrado and Dean. Distributed Representations of Words and Phrases and their Compositionality. https://arxiv.org/abs/1310.4546
- Word2vec. Wikipedia. https://en.wikipedia.org/wiki/Word2vec