Sub topic 6
word2vec: learning embeddings by prediction
Prerequisites and scope
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 met the distributional hypothesis, context windows, and dense embeddings in earlier chapters. Here we cover the overall word2vec design. Skip-gram, CBOW, negative sampling, and hierarchical softmax each get their own chapter, so this one only introduces them.
The core idea: a prediction task as a side effect
word2vec (Mikolov et al., 2013) does not set out to build a dictionary of word meanings. It trains a very small neural network on a fake prediction task: guess a word from its neighbours, or guess the neighbours from a word. The task itself is of no use. The useful part is the set of weights the network has to learn to do it.
The distributional hypothesis explains why this works. If two words appear in similar contexts, the network gets the same kind of prediction problem for both. The cheapest way to solve both problems is to give the two words similar vectors. Similarity of meaning therefore ends up as similarity of vectors, without anyone labelling it.
The architecture
The network has no hidden nonlinearity. It has three parts:
- An input embedding matrix
Wof shapeV x d.Vis the vocabulary size anddis the embedding size, commonly 100 to 300. - An output (context) embedding matrix
C, alsoV x d. - A scoring step that takes dot products and turns them into probabilities.
Looking up row i of W is the same as multiplying a one-hot vector for word i by W. In practice the code just indexes the row.
For a centre word w and a candidate context word c, the model scores the pair with a dot product W[w] · C[c]. A softmax over the whole vocabulary then turns the scores into a probability:
P(c | w) = exp(C[c] · W[w]) / sum over all words c' of exp(C[c'] · W[w])
Training adjusts W and C by gradient descent so that real neighbours get high probability.
Two prediction directions
word2vec comes in two variants that differ only in what is predicted from what.
| Variant | Input | Target | Training examples per window |
|---|---|---|---|
| Skip-gram | Centre word | Each context word, one at a time | One per context word |
| CBOW | Averaged context vectors | Centre word | One |
Take the sentence "the cat sits on the mat" with a window of 2 and centre word "sits". Skip-gram creates the pairs (sits, the), (sits, cat), (sits, on), (sits, the). CBOW creates one example: the average of the vectors for "the", "cat", "on", "the" is used to predict "sits".
Skip-gram produces more training examples and gives rare words more individual updates. It is usually better for small corpora and rare words. CBOW averages its inputs, which smooths noise and makes it faster. It tends to suit large corpora and frequent words.
Generating training pairs
The code below produces skip-gram pairs. It is a plain-Python version of the window logic that gensim runs internally.
def skipgram_pairs(sentence, window=2):
pairs = []
for i, centre in enumerate(sentence):
lo = max(0, i - window)
hi = min(len(sentence), i + window + 1)
for j in range(lo, hi):
if j != i:
pairs.append((centre, sentence[j]))
return pairs
sentence = ["the", "cat", "sits", "on", "the", "mat"]
for pair in skipgram_pairs(sentence, window=2)[:6]:
print(pair)The first pairs printed are ('the', 'cat'), ('the', 'sits'), ('cat', 'the'), ('cat', 'sits'), ('cat', 'on'), ('sits', 'the').
Real implementations also shrink the window at random for each centre word, drawing the effective size between 1 and window. Nearby words are therefore used more often than distant ones, which is a cheap form of distance weighting.
What the loss looks like
For one pair, the loss is the negative log probability of the true context word:
L = -log P(c | w) = -C[c] · W[w] + log sum over c' of exp(C[c'] · W[w])
Summed over all pairs in the corpus, this is the quantity gradient descent minimizes. The second term, the log of a sum over the whole vocabulary, is where the cost lies. With V around a million words, every training pair needs a million dot products. The chapters on the softmax cost, negative sampling, and hierarchical softmax address this.
Two matrices, one set of vectors
Each word has two vectors: a row of W when it is the centre, and a row of C when it is a context word. After training, most users keep only W. Some people average W and C, which GloVe's authors do for their vectors. Gensim exposes the input vectors as model.wv and keeps the output weights separately, in syn1neg when negative sampling is used.
Keeping two matrices avoids a degenerate case. A word is rarely its own neighbour, but the dot product of a vector with itself is always large and positive. With a single shared matrix the model would be pushed against giving any word a high probability of appearing next to itself.
Running it in gensim
Gensim 4 makes the variant a single flag. sg=1 selects skip-gram and sg=0 selects CBOW.
from gensim.models import Word2Vec
sentences = [
["the", "cat", "sits", "on", "the", "mat"],
["the", "dog", "sits", "on", "the", "rug"],
["the", "cat", "chases", "the", "mouse"],
]
model = Word2Vec(
sentences=sentences,
vector_size=50,
window=2,
min_count=1,
sg=1,
negative=5,
epochs=50,
workers=1,
seed=1,
)
print(model.wv["cat"].shape)
print(model.wv.most_similar("cat", topn=3))The shape is (50,). The neighbours are not reliable, because three sentences give the model almost nothing to learn from. Treat this as a check that the code runs, not as a result.
Hyperparameters that matter
- Vector size. More dimensions capture more distinctions but need more data. 100 to 300 is typical.
- Window size. Small windows (2 to 5) favour syntactic similarity, such as "walking" and "running". Large windows (5 to 10 or more) favour topical similarity, such as "walking" and "hiking".
- Minimum count. Words rarer than
min_countare dropped. A very rare word gets too few updates for its vector to mean anything. - Epochs. Small corpora need many passes. Large corpora often need only a few.
Common errors
- Passing raw strings.
Word2Vecexpects a list of token lists. A list of strings is read as lists of characters, and you get character embeddings with no error. - Forgetting preprocessing consistency. If you lowercase when training, you must lowercase when you query.
- Expecting results from tiny data. Word2vec needs millions of tokens to produce stable neighbours.
- Reading meaning into single dimensions. Individual coordinates are not interpretable. Only relative geometry, such as distances and directions, carries information.
- Comparing runs exactly. Initialization and thread scheduling are random, so two runs give different vectors. Only fully fixed seeds with
workers=1repeat exactly. Compare neighbours, not raw numbers.
Exercise
A corpus has 500,000 distinct words and you use skip-gram with a full softmax. Roughly how many dot products does one (centre, context) training pair require, and why is a pair's loss different from a measure of embedding quality?
Show answer
About 500,000 dot products, one per vocabulary word in the softmax denominator. The loss only measures how well the model predicts context words. The prediction task is a means of learning vectors, so a lower loss does not guarantee better similarity judgments or downstream results.
Exercise
For the sentence "a quick brown fox jumps" with window 1, list the skip-gram pairs whose centre word is "brown", and say what single training example CBOW would build for the same centre word.
Show answer
Skip-gram gives (brown, quick) and (brown, fox). CBOW builds one example: it averages the vectors of "quick" and "fox" and uses that average to predict "brown".