Sub topic 7
Skip-gram: predicting context from a word
This chapter assumes you know basic Python and NumPy, dot products, softmax, and the idea of a loss minimized by gradient descent. It also assumes you have seen how a context window turns text into (word, context) pairs. Here we define the skip-gram objective, look at its two embedding tables, and derive its gradient. We also cover the training pairs it produces, the common mistakes, and a small NumPy implementation.
The prediction task
Skip-gram is the word2vec architecture that takes one word and predicts the words around it. Given a corpus of tokens w1, ..., wT and a window size m, the model maximizes the log-likelihood of every context word given its center word:
J = (1/T) × sum over t of sum over j in [-m, m], j ≠ 0, of log P(w{t+j} | wt)
The model assumes each context word is predicted independently given the center word. This is a naive assumption, because neighbours depend on one another. It is also what makes the objective a sum of simple terms, and it is why word order inside the window does not matter.
The word vectors are a by-product. The model has no interest in predicting context for its own sake. It learns vectors because any model that predicts context well must give similar vectors to words that appear in similar contexts.
Two vectors per word
Each word w has two vectors:
- v_w is the center vector, used when w is the input word.
- u_w is the context vector (also called the output vector), used when w is a candidate context word.
The probability of context word o given center word c is a softmax over the whole vocabulary V:
P(o | c) = exp(uo · vc) / sum over w in V of exp(uw · vc)
The dot product uo · vc is a score. A large score means o is a likely neighbour of c. In matrix form there are two V × d matrices. The first, Win, holds the center vectors, and a row lookup replaces any multiplication by a one-hot vector. The second, Wout, holds the context vectors. After training, most users keep Win as "the embeddings". Some average Win and W_out, which GloVe's authors also do with their two tables.
Training pairs
The window turns each sentence into pairs. For "the cat sits on the mat" with window 2, the center word "sits" produces (sits, the), (sits, cat), (sits, on), (sits, the). Each pair is one training example.
A few details affect real implementations:
- Pairs grow with corpus size times window size. A window of 5 on each side yields up to 10 pairs per token.
- word2vec samples the effective window size uniformly between 1 and m for each center word. Nearby words are therefore used more often than distant ones, which acts like a soft distance weighting.
- Pairs never cross the sentence boundary in gensim, because it receives a list of sentences.
The gradient
For one pair (c, o), the loss is L = -log P(o | c). Let pw be the softmax probability of word w and let yw be 1 for w = o and 0 otherwise. The gradients are:
- dL/dvc = sum over w of (pw − yw) uw
- dL/duw = (pw − yw) vc
The first formula says the center vector moves toward the true context vector and away from the probability-weighted average of all context vectors. The second says that every context vector gets updated, in proportion to its error. Every update touches all V rows of W_out. This is the cost problem the next chapters address: the sum over the vocabulary makes one step cost O(V × d).
A minimal implementation
The following code trains skip-gram with the full softmax on a toy corpus. It is only practical for tiny vocabularies, but it shows the mechanics exactly.
import numpy as np
corpus = [
"the cat sits on the mat".split(),
"the dog sits on the rug".split(),
"the cat chases the mouse".split(),
]
vocab = sorted({w for s in corpus for w in s})
idx = {w: i for i, w in enumerate(vocab)}
V, d, window, lr, epochs = len(vocab), 10, 2, 0.05, 300
rng = np.random.default_rng(0)
W_in = rng.normal(0, 0.1, (V, d))
W_out = rng.normal(0, 0.1, (V, d))
pairs = []
for sent in corpus:
ids = [idx[w] for w in sent]
for i, c in enumerate(ids):
for j in range(max(0, i - window), min(len(ids), i + window + 1)):
if j != i:
pairs.append((c, ids[j]))
def softmax(z):
z = z - z.max()
e = np.exp(z)
return e / e.sum()
for epoch in range(epochs):
loss = 0.0
rng.shuffle(pairs)
for c, o in pairs:
v = W_in[c].copy()
p = softmax(W_out @ v)
loss -= np.log(p[o])
err = p.copy()
err[o] -= 1.0
grad_v = W_out.T @ err
W_out -= lr * np.outer(err, v)
W_in[c] -= lr * grad_v
if epoch % 100 == 0:
print(epoch, round(loss / len(pairs), 3))
def nearest(word, k=3):
v = W_in[idx[word]]
sims = (W_in @ v) / (np.linalg.norm(W_in, axis=1) * np.linalg.norm(v))
order = np.argsort(-sims)
return [(vocab[i], round(float(sims[i]), 3)) for i in order if vocab[i] != word][:k]
print(nearest("cat"))The loss falls steadily because the model can partly memorize this tiny corpus. The neighbours it prints are not reliable evidence of meaning, since the corpus has only a few sentences.
The code copies v before updating W_out, because the gradient for the center vector must use the old context vectors. Updating them in the wrong order is a common bug.
What the model learns, and why
Two words that occur with the same neighbours, such as "cat" and "dog" in the corpus above, receive the same pressure on their center vectors. Each is pushed toward the context vectors of "the", "sits" and "on". After enough updates their center vectors become close, which cosine similarity then shows.
Levy and Goldberg showed that skip-gram with negative sampling implicitly factorizes a shifted pointwise mutual information matrix of word-context pairs. This links word2vec to the co-occurrence methods covered later with GloVe.
Common errors
| Problem | Symptom | Fix |
|---|---|---|
| Corpus too small | Neighbours look random | Use millions of tokens, or use pretrained vectors |
| Learning rate too high | Loss oscillates or becomes NaN | Lower the rate and subtract the maximum before the softmax |
| Using W_out as the embeddings by accident | Weaker similarity results | Take W_in, or deliberately average both |
| Sentences joined into one stream | Pairs span unrelated sentences | Build pairs per sentence |
| Very frequent words dominate | Many pairs with "the" teach little | Apply subsampling (a later chapter) |
Choosing parameters
- A larger window captures topical similarity (a "dog" appears with "leash" and "vet"). A smaller window, around 2, captures more syntactic and functional similarity (a "dog" resembles "cat").
- More dimensions give more capacity. Values from 100 to 300 are typical for corpora of billions of tokens, and smaller values suit small corpora.
- Skip-gram tends to do better than CBOW for rare words, because each occurrence of a rare word creates several training pairs instead of being averaged with its neighbours. The cost is slower training.
Exercise
A sentence has 6 tokens and the window size is 2, with a fixed window (no random shrinking) and no padding. How many (center, context) pairs does skip-gram produce? Then state which matrix of the two (Win or Wout) a center word's vector is read from, and why every row of W_out changes after each pair under the full softmax.
Show answer
Count the context words available at each position: positions 1 and 6 have 2 each, positions 2 and 5 have 3 each, and positions 3 and 4 have 4 each. The total is 2 + 3 + 4 + 4 + 3 + 2 = 18 pairs. The center vector is a row of Win. Under the full softmax every row of Wout changes because the gradient for word w is (pw − yw) vc, and pw is nonzero for every word in the vocabulary.
Exercise
In the NumPy code, what would go wrong if you replaced v = W_in[c].copy() with v = W_in[c] and kept the rest unchanged?
Show answer
Basic slicing of a NumPy row returns a view, not a copy. The line W_in[c] -= lr * grad_v would be computed from grad_v that was already calculated, so in this exact code the result is still the same. The danger is in the ordering: np.outer(err, v) runs after W_out is read but before W_in[c] changes, so the code only stays correct because the update to W_in[c] comes last. Copying makes the code safe against reordering of those lines, which is why the copy is kept.