Sub topic 5
Context windows and (word, context) pairs
What this chapter covers
This chapter assumes you know basic Python and NumPy, can tokenize text, and understand why a word's contexts carry information about its meaning (the distributional hypothesis from the previous chapters). Here we turn that idea into data. We define a context window, generate the (word, context) pairs that both word2vec and GloVe learn from, and look at the choices and edge cases that change the resulting vectors.
From a sentence to training data
Embedding models do not read meaning from text directly. They read pairs. A center word (also called the target) is the word at position i. A context word is any word within a fixed distance of it. The window size m is that maximum distance, counted in tokens on each side.
For the sentence the cat sits on the mat with m = 2 and center word sits (position 2), the context words are the, cat, on, the. Each one gives a pair:
- (sits, the)
- (sits, cat)
- (sits, on)
- (sits, the)
Repeating this for every position gives the full training set. Skip-gram uses each pair as one prediction task: given the center word, predict the context word. CBOW groups the context words for one center word and predicts the center from them. GloVe does not train on single pairs. It first adds them up into a co-occurrence table. All three start from the same windowing step.
Generating pairs in Python
The function below produces every (center, context) pair for a tokenized sentence. It clips the window at the sentence boundaries.
def skipgram_pairs(sentence, window=2):
pairs = []
for i, center 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((center, sentence[j]))
return pairs
sentence = ["the", "cat", "sits", "on", "the", "mat"]
pairs = skipgram_pairs(sentence, window=2)
print(len(pairs))
print([p for p in pairs if p[0] == "sits"])The output has 18 pairs in total, and the pairs for sits match the list above. The count follows from the boundaries. Words near the start or end of a sentence have fewer neighbours, so a sentence of n tokens gives slightly fewer than 2 * m * n pairs.
Symmetry and direction
The window is symmetric: if cat is a context word of sits, then sits is a context word of cat. Skip-gram therefore sees both (sits, cat) and (cat, sits). Because of this, the co-occurrence counts that GloVe builds are symmetric too.
A window does not have to be symmetric. Some work uses only left context or only right context, which captures word order and tends to favour syntactic information. The standard word2vec and GloVe setups use symmetric windows.
How window size changes what you learn
The window size is a hyperparameter with a visible effect on the vectors.
| Window size | Typical effect on neighbours | Typical use |
|---|---|---|
| Small (1–2) | Words that play the same grammatical role and are interchangeable, such as `cat` and `dog` | Syntactic similarity, part-of-speech-like clusters |
| Large (5–10) | Words that appear in the same topic, such as `cat` and `leash` or `hospital` and `nurse` | Topical, associative similarity |
A small window mostly sees the immediate neighbours, which are constrained by grammar. A large window includes words from the whole clause or sentence, which reflects the subject being discussed. Neither is correct in general. Choose by testing on the task you care about, using the methods from the evaluation chapter. Common defaults are 5 for word2vec and 10 for GloVe.
Weighting by distance
Not all context words are equally informative. A word one position away usually has a tighter relation to the center than one ten positions away. Two mechanisms handle this.
Dynamic window in word2vec. For each center word, word2vec samples an effective window size uniformly from 1 to m. A neighbour at distance 1 is always included, while a neighbour at distance m is included only when the sampled size equals m. In expectation, closer words appear in more pairs, so they get more weight, and no extra counting is needed.
Explicit weights in GloVe. GloVe adds 1/d to the count for a pair at distance d. The function from the Topic Spine does this:
from collections import defaultdict
def cooccurrence(sentences, window=2):
counts = defaultdict(float)
for sent in sentences:
for i, w in enumerate(sent):
for j in range(max(0, i - window), i):
c = sent[j]
weight = 1.0 / (i - j)
counts[(w, c)] += weight
counts[(c, w)] += weight
return counts
sentences = [["the", "cat", "sits", "on", "the", "mat"]]
X = cooccurrence(sentences, window=2)
print(X[("cat", "the")])This prints 1.0. In this sentence cat is one step from the first the. The second the is three positions away and falls outside the window. The loop looks only backwards from each position and then writes both orders of the pair, which gives a symmetric table without counting anything twice.
Edge cases to handle
- Sentence boundaries. Pairs are normally built within a sentence or a document, not across them. The last word of one sentence has no real relation to the first word of the next. gensim treats each item in the input list as a separate sentence and never crosses it. If you pass a whole document as one long list, windows will cross sentence breaks.
- Very short sentences. A sentence with one token yields no pairs. Check how many pairs you actually produce before training.
- Stop words and punctuation. If you remove them before windowing, the window spans more content words, so effective context gets wider. If you keep them, many pairs involve
theor,. This is the problem that subsampling addresses in a later chapter. Decide this at the preprocessing stage and apply the same choice consistently. - Rare words. A word that appears once produces only a handful of pairs, which is too little to learn from. Libraries drop words below a minimum count (
min_countin gensim), and the window is then computed over the remaining words. - Duplicates are meaningful. The pair (sits, the) appears twice above because
theoccurs twice nearby. Do not deduplicate pairs. The repeat counts are the signal.
Scale
The number of pairs grows linearly with corpus size and window size. A corpus of one billion tokens with m = 5 yields on the order of ten billion pairs. For this reason word2vec does not store pairs. It slides the window over the text and generates them on the fly. GloVe makes one pass to build a sparse table of counts and then trains from the nonzero entries, which is far fewer than the number of raw pairs, because repeated pairs collapse into a single count.
Exercise
For the sentence ["a", "b", "c", "d"] with window=1, list all (center, context) pairs a symmetric skip-gram model would generate. How many are there, and what does the GloVe-style count for the pair ("b", "c") equal?
Show answer
The pairs are (a,b), (b,a), (b,c), (c,b), (c,d), (d,c), which is 6 pairs. Each adjacent pair is at distance 1, so the GloVe-style count for ("b", "c") is 1/1 = 1.0, and the same value is stored for ("c", "b").
Exercise
You train two models on the same corpus, one with window=2 and one with window=10. Which is more likely to place "doctor" near "nurse" and "hospital", and which near "lawyer" and "engineer"? Explain why.
Show answer
The window=10 model is more likely to place "doctor" near the topically related "nurse" and "hospital", because a wide window captures words from the same subject. The window=2 model is more likely to place it near other professions like "lawyer" and "engineer", because those words appear in the same grammatical slots with the same immediate neighbours.