Search

Search papers and lessons

Skip-Gram Model

Level 3 · 11 min read

Skip-gram learns word vectors by asking each word to predict the words near it, so words that share neighbours end up with similar vectors.

On this page

  • Colour = topic mix
  • Calculus
  • Discrete math
  • Probability
  • Representation learning
  • Linear algebra
  • Language & LLMs
  • ReadReady to readNot yet

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 V=3V = 3, and each vector has two numbers.

  1. 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).
  2. Look up the centre vector. Each word has a centre vector vv. For "cat" take vcat=(1,0)v_{\text{cat}} = (1, 0). Check: this is a row from the table of centre vectors, one row per word.
  3. Score every word as a possible context. Each word also has a context vector uu. Take uthe=(1,0)u_{\text{the}} = (1, 0), ucat=(0,1)u_{\text{cat}} = (0, 1) and usat=(1,1)u_{\text{sat}} = (1, 1). The score for a candidate is the dot product with the centre vector: uthe⋅vcat=1u_{\text{the}} \cdot v_{\text{cat}} = 1, ucat⋅vcat=0u_{\text{cat}} \cdot v_{\text{cat}} = 0, usat⋅vcat=1u_{\text{sat}} \cdot v_{\text{cat}} = 1.
  4. Turn scores into probabilities. Apply a softmax over all three words. The exponentials are e1=2.718e^1 = 2.718, e0=1e^0 = 1 and e1=2.718e^1 = 2.718, summing to 6.436. So P(the∣cat)=0.422P(\text{the} | \text{cat}) = 0.422, P(cat∣cat)=0.155P(\text{cat} | \text{cat}) = 0.155 and P(sat∣cat)=0.422P(\text{sat} | \text{cat}) = 0.422. Check: the three add to 1.000.
  5. Measure the error for the true pair. The loss for (cat, the) is the negative log of its probability, −ln⁡0.422=0.862-\ln 0.422 = 0.862. A confident correct guess gives a small loss; a confident wrong guess gives a large one.
  6. Nudge the vectors. The gradient with respect to vcatv_{\text{cat}} is the expected context vector minus the true one, −uthe+∑cP(c∣cat) uc=(−0.155,0.578)-u_{\text{the}} + \sum_c P(c|\text{cat})\, u_c = (-0.155, 0.578). With a learning rate of 0.1, the centre vector moves to (1.016,−0.058)(1.016, -0.058). 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

Definition: Skip-gram model

Each word ww in a vocabulary of size VV has a centre vector vw∈Rdv_w \in \mathbb{R}^d and a context vector uw∈Rdu_w \in \mathbb{R}^d. For a centre word cc and a context word oo, the probability that oo appears in the window of cc is

P(o∣c)=exp⁡(uo⊤vc)∑w=1Vexp⁡(uw⊤vc)P(o \mid c) = \frac{\exp(u_o^\top v_c)}{\sum_{w=1}^{V} \exp(u_w^\top v_c)}

The vectors are learned from a corpus of word sequences w1,…,wTw_1, \ldots, w_T with window size mm.

Step 1 in symbols: the pairs

For each position tt in the corpus, the pairs are (wt,wt+j)(w_t, w_{t+j}) for every offset jj with 1≤∣j∣≤m1 \le |j| \le m and t+jt + j inside the text. With m=1m = 1 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 oo for centre cc is the dot product uo⊤vcu_o^\top v_c (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 VV words, so the probabilities are positive and add to 1. With the walkthrough numbers, the denominator is e1+e0+e1=6.436e^1 + e^0 + e^1 = 6.436.

Step 5 in symbols: the loss

The model maximises the log likelihood of all observed pairs. Equivalently it minimises the loss

J=−∑t=1T∑−m≤j≤mj≠0ln⁡P(wt+j∣wt)J = -\sum_{t=1}^{T} \sum_{\substack{-m \le j \le m \\ j \neq 0}} \ln P(w_{t+j} \mid w_t)

The double sum runs over every centre position tt and every nearby offset jj, skipping j=0j = 0, which is the centre word itself. For the pair (cat, the), the term is −ln⁡0.422=0.862-\ln 0.422 = 0.862.

Step 6 in symbols: the gradient

For one pair with true context oo, the gradient of −ln⁡P(o∣c)-\ln P(o \mid c) with respect to vcv_c is

∇vc=−uo+∑w=1VP(w∣c) uw\nabla_{v_c} = -u_o + \sum_{w=1}^{V} P(w \mid c)\, u_w

It is the difference between the expected context vector and the true one. The walkthrough has ∑wP(w∣cat) uw=0.422(1,0)+0.155(0,1)+0.422(1,1)=(0.845,0.578)\sum_w P(w|\text{cat})\, u_w = 0.422(1,0) + 0.155(0,1) + 0.422(1,1) = (0.845, 0.578), so the gradient is (0.845,0.578)−(1,0)=(−0.155,0.578)(0.845, 0.578) - (1, 0) = (-0.155, 0.578). The step with rate 0.1 subtracts 0.10.1 times this, giving vcat←(1.016,−0.058)v_{\text{cat}} \leftarrow (1.016, -0.058).

Negative sampling

The full softmax needs a sum over all VV words for every pair. Negative sampling replaces it with a set of binary decisions. Let σ(z)=1/(1+e−z)\sigma(z) = 1 / (1 + e^{-z}) be the sigmoid (see Sigmoid Function). For a true pair (c,o)(c, o) and KK random "negative" words n1,…,nKn_1, \ldots, n_K drawn from a noise distribution, the loss is

−ln⁡σ(uo⊤vc)−∑k=1Kln⁡σ(−unk⊤vc)-\ln \sigma\left(u_o^\top v_c\right) - \sum_{k=1}^{K} \ln \sigma\left(-u_{n_k}^\top v_c\right)

The first term rewards a high score for the true context. The second rewards low scores for the random words. Each pair now costs K+1K + 1 dot products instead of VV.

Worked examples

Example
1. Tiny: a two-word vocabulary with equal scores

Vocabulary {a,b}\{a, b\}, so V=2V = 2. Suppose the centre vector vcv_c gives both context vectors a dot product of 0.

  1. Scores: ua⊤vc=0u_a^\top v_c = 0 and ub⊤vc=0u_b^\top v_c = 0.
  2. Exponentials: e0=1e^0 = 1 each, sum 2.
  3. Probabilities: P(a∣c)=1/2P(a|c) = 1/2 and P(b∣c)=1/2P(b|c) = 1/2.
  4. Loss for the true context aa: −ln⁡(1/2)=0.693-\ln(1/2) = 0.693.
  5. Interpretation: with no information, the model splits its probability evenly, and the loss is ln⁡2\ln 2.
Example
2. Standard: the three-word corpus from the walkthrough

Take the numbers from How it works: vcat=(1,0)v_{\text{cat}} = (1, 0), and context vectors uthe=(1,0)u_{\text{the}} = (1, 0), ucat=(0,1)u_{\text{cat}} = (0, 1), usat=(1,1)u_{\text{sat}} = (1, 1).

  1. Scores: 11, 00 and 11.
  2. Softmax: P(the∣cat)=2.718/6.436=0.422P(\text{the}|\text{cat}) = 2.718 / 6.436 = 0.422, P(cat∣cat)=0.155P(\text{cat}|\text{cat}) = 0.155, P(sat∣cat)=0.422P(\text{sat}|\text{cat}) = 0.422.
  3. Loss for the true pair (cat, the): −ln⁡0.422=0.862-\ln 0.422 = 0.862.
  4. Gradient with respect to vcatv_{\text{cat}}: (−0.155,0.578)(-0.155, 0.578), as computed in Step 5 above.
  5. One update with rate 0.1: vcat←(1.016,−0.058)v_{\text{cat}} \leftarrow (1.016, -0.058). The centre vector now leans toward "the" and away from "cat" itself, which is what the sentence supports.
  6. Interpretation: the model learns from each pair by moving the centre vector toward the words that really occur near it.
Example
3. Realistic: why negative sampling is cheap

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 K=5K = 5 negative samples.

  1. Full softmax per pair: 50,000 dot products to form the denominator.
  2. Negative sampling per pair: one positive plus 5 negatives, so 1+5=61 + 5 = 6 dot products.
  3. Ratio: 50,000/6=8,33350{,}000 / 6 = 8{,}333. Each pair is about 8,000 times cheaper to score.
  4. 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 K=5K = 5. 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 1+5=61 + 5 = 6 dot products; the full softmax needs 100,000. The ratio is 100,000/6=16,667100{,}000 / 6 = 16{,}667.

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 v=(2,0)v = (2, 0). Two context vectors are ua=(1,0)u_a = (1, 0) and ub=(0,1)u_b = (0, 1). Using the softmax over just these two words, what is P(a∣c)P(a \mid c) to three decimals?Show answer

Scores: ua⋅v=2u_a \cdot v = 2 and ub⋅v=0u_b \cdot v = 0. Exponentials: e2=7.389e^2 = 7.389 and e0=1e^0 = 1, sum 8.3898.389. So P(a∣c)=7.389/8.389=0.881P(a|c) = 7.389 / 8.389 = 0.881.

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