TL;DR
The skip-gram model learns a vector for every word by playing a prediction game. Take a word from a sentence, the centre word, and try to predict the words within a few positions of it. Each vector is adjusted so that the prediction gets better, and after many such steps, words that appear in similar surroundings have similar vectors. It was the core of word2vec, and it made good word vectors cheap enough to learn from very large text collections.
Builds on: Word Embedding, Dot Product, Softmax · Leads to: Efficient Estimation of Word Representations in Vector Space (word2vec)
Where it's used
Search and recommendation. A search engine that matches "cheap flights" with "low-cost airfare" needs to know that the two phrases mean similar things. Word vectors trained with skip-gram give the words nearby positions in the space, so a query and a document can be compared with a measure such as cosine similarity rather than by exact word match.
Pre-training other models. Before large language models were common, many text classifiers started from pre-trained word vectors. The classifier then only had to learn the task, not the meaning of every word from scratch. Skip-gram vectors were one of the most widely used sources for this.
Analogies and word arithmetic. Because the vectors encode how words are used, simple vector arithmetic often gives sensible results. The classic example is that the vector for "king" minus "man" plus "woman" lands near "queen". The word2vec paper (Efficient Estimation of Word Representations in Vector Space (word2vec)) made this a standard test of embedding quality.
How it works
Skip-gram reads a corpus one centre word at a time. For each centre word it looks at a window of nearby words, say one position on each side, and asks the model to predict each of them. Here is one tiny pass over the sentence "the cat sat" with a window of one. The vocabulary has three words, so , and each vector has two numbers.
- Pick a centre word and its context. The centre word is "cat". Its window contains "the" on the left and "sat" on the right. These two are the pairs the model must learn: (cat, the) and (cat, sat).
- Look up the centre vector. Each word has a centre vector . For "cat" take . Check: this is a row from the table of centre vectors, one row per word.
- Score every word as a possible context. Each word also has a context vector . Take , and . The score for a candidate is the dot product with the centre vector: , , .
- Turn scores into probabilities. Apply a softmax over all three words. The exponentials are , and , summing to 6.436. So , and . Check: the three add to 1.000.
- Measure the error for the true pair. The loss for (cat, the) is the negative log of its probability, . A confident correct guess gives a small loss; a confident wrong guess gives a large one.
- Nudge the vectors. The gradient with respect to is the expected context vector minus the true one, . With a learning rate of 0.1, the centre vector moves to . It has shifted toward the context vectors that the sentence actually supports.
The same update runs for every pair in the corpus, and over many passes the vectors settle. Words used in similar windows get similar centre vectors, because they are pushed toward the same context vectors.
flowchart LR
A["Corpus, one centre word at a time"] --> B["Window of nearby words gives true contexts"]
B --> C["Dot product of centre and context vectors gives scores"]
C --> D["Softmax gives a probability for each word"]
D --> E["Loss is minus log probability of the true context"]
E --> F["Gradient step updates both vector tables"]
F --> C
The math
Each word in a vocabulary of size has a centre vector and a context vector . For a centre word and a context word , the probability that appears in the window of is
The vectors are learned from a corpus of word sequences with window size .
Step 1 in symbols: the pairs
For each position in the corpus, the pairs are for every offset with and inside the text. With and "the cat sat", the centre word "cat" gives the pairs (cat, the) and (cat, sat), as in the walkthrough.
Steps 3 and 4 in symbols: scores and probabilities
The score of context for centre is the dot product (see Dot Product). It is large when the two vectors point the same way. The softmax (see Softmax) divides each exponentiated score by the sum over all words, so the probabilities are positive and add to 1. With the walkthrough numbers, the denominator is .
Step 5 in symbols: the loss
The model maximises the log likelihood of all observed pairs. Equivalently it minimises the loss
The double sum runs over every centre position and every nearby offset , skipping , which is the centre word itself. For the pair (cat, the), the term is .
Step 6 in symbols: the gradient
For one pair with true context , the gradient of with respect to is
It is the difference between the expected context vector and the true one. The walkthrough has , so the gradient is . The step with rate 0.1 subtracts times this, giving .
Negative sampling
The full softmax needs a sum over all words for every pair. Negative sampling replaces it with a set of binary decisions. Let be the sigmoid (see Sigmoid Function). For a true pair and random "negative" words drawn from a noise distribution, the loss is
The first term rewards a high score for the true context. The second rewards low scores for the random words. Each pair now costs dot products instead of .
Worked examples
Vocabulary , so . Suppose the centre vector gives both context vectors a dot product of 0.
- Scores: and .
- Exponentials: each, sum 2.
- Probabilities: and .
- Loss for the true context : .
- Interpretation: with no information, the model splits its probability evenly, and the loss is .
Take the numbers from How it works: , and context vectors , , .
- Scores: , and .
- Softmax: , , .
- Loss for the true pair (cat, the): .
- Gradient with respect to : , as computed in Step 5 above.
- One update with rate 0.1: . The centre vector now leans toward "the" and away from "cat" itself, which is what the sentence supports.
- Interpretation: the model learns from each pair by moving the centre vector toward the words that really occur near it.
Suppose a vocabulary of 50,000 words, which is a common size for word-level models (an illustration, not a figure from a paper). Use negative samples.
- Full softmax per pair: 50,000 dot products to form the denominator.
- Negative sampling per pair: one positive plus 5 negatives, so dot products.
- Ratio: . Each pair is about 8,000 times cheaper to score.
- Interpretation: a corpus of a billion pairs is only feasible if each update touches a handful of output vectors. Negative sampling makes that practical on ordinary hardware.
Try it: the vocabulary has 100,000 words and . How many dot products does a pair need with negative sampling, and how many with the full softmax? Give the ratio. Answer: negative sampling needs dot products; the full softmax needs 100,000. The ratio is .
Common mistakes and tradeoffs
It is tempting to think that the model learns to predict words, so the prediction is the useful output. In fact the prediction is a training device. The vectors that are kept are the centre vectors, and the context vectors are often averaged with them or discarded. The goal is the geometry of the vectors, not the probabilities.
It is tempting to think that words are similar because they appear near each other. In fact they are similar when they appear in similar neighbourhoods. Two words can co-occur often, like "bread" and "butter", and still not be substitutes, and skip-gram alone does not separate those two kinds of closeness.
It is tempting to think that a larger window is always better. In fact the window size shapes what the vectors capture. Small windows tend to capture how a word functions in the sentence, such as its grammatical role. Large windows tend to capture topic. Choose the window to match the use case.
Tradeoffs. Skip-gram needs no hand-built features and learns from raw text. But it treats each window independently, so it does not see the whole sentence at once, and it does not give a different vector to a word with several meanings. CBOW, the other word2vec model, predicts the centre word from the context and trains faster, while skip-gram tends to do better on rare words. Count-based methods such as GloVe use the global co-occurrence table and can do well on the same tasks.
History
The idea that a word's meaning comes from the company it keeps is older than computing. In the 1950s the linguist J. R. Firth gave it its well-known phrasing. Neural language models that learned word vectors as a side effect were proposed in the early 2000s, with the work of Bengio and colleagues as an early landmark. The step that made learning practical at scale came in 2013, when Tomas Mikolov and colleagues released word2vec with the skip-gram and CBOW models, and a follow-up paper that year added the negative sampling trick. The vectors were fast to train and easy to use, and they spread quickly through research and industry.
Recap
- Word embeddings are vectors learned from text; skip-gram is one way to learn them.
- Each word has a centre vector and a context vector, and their dot product scores how likely the context is.
- A softmax over the vocabulary turns scores into probabilities, and the loss is the negative log probability of the true context.
- Gradient steps move each centre vector toward the contexts it actually appears with.
- Negative sampling replaces the full softmax with a few binary decisions, which makes training cheap.
Read next: Efficient Estimation of Word Representations in Vector Space (word2vec) shows the full model, its results, and the analogy tests. Negative Sampling explains the training trick in detail, and Hierarchical Softmax is the other way to avoid the full softmax.
Check yourself
QuestionIn skip-gram, what is the centre word's job, and what does the window size control?Show answer
The centre word is the input: the model takes its centre vector and predicts the words within the window around it. The window size sets how many positions on each side count as context, which changes whether the learned vectors reflect grammatical role (small window) or topic (large window).
QuestionA centre vector is . Two context vectors are and . Using the softmax over just these two words, what is to three decimals?Show answer
Scores: and . Exponentials: and , sum . So .
QuestionWhy does the training loss use the negative log of the probability rather than the probability itself?Show answer
The log turns the product of probabilities over many pairs into a sum, which is easier to compute and differentiate. The negative sign makes the quantity to minimise, so a probability near 1 gives a loss near 0 and a probability near 0 gives a large loss. Minimising the negative log probability is the same as maximising the probability.
QuestionA researcher wants vectors for a domain with many rare technical terms and a large vocabulary, trained on limited hardware. Which ideas from this lesson help, and what is one risk?Show answer
Negative sampling keeps each update cheap, so training fits on limited hardware. Skip-gram gives rare words a training signal from each pair they appear in. The risk is that each word gets one vector regardless of its meaning in context, so a term with several senses will be blurred together.
Sources
- Mikolov, T., Chen, K., Corrado, G., and Dean, J. (2013). Efficient Estimation of Word Representations in Vector Space. arXiv: 1301.3781.
- Wikipedia, "Word2vec": en.wikipedia.org/wiki/Word2vec