Sub topic 4
Context Windows and (Word, Context) Pairs
Assume you know tokenization, vectors, dot products, conditional probability, and the basic idea of gradient descent. This chapter focuses on how a text corpus becomes training data for word2vec and related embedding methods.
What a context window is
A context window is the nearby span of tokens used to describe a target word. With a window size of 2, the model can use up to two tokens on each side of the target.
Consider this sentence:
the cat sits on the matIf sits is the target and the window size is 2, its context is:
cat, on, theThe word the appears twice in the sentence, but each occurrence has a different position and context. Word2vec usually creates training examples from positions, not just from distinct word types.
At the beginning and end of a sentence, the window is truncated. A target near the beginning has fewer available context words.
From windows to training pairs
The skip-gram task uses a target word to predict each nearby context word. For the target sits, the examples are:
| Target word | Context word |
|---|---|
| sits | cat |
| sits | on |
| sits | the |
Each pair becomes a positive training example. The model adjusts vectors so that words appearing in similar contexts receive related representations.
The CBOW task reverses the direction. It combines the context words and predicts the target:
(cat, on, the) -> sitsThus, the same window can produce different training tasks depending on the architecture.
Choosing the window size
A small window captures local, syntactic relationships. For example, words that occur near running may include quickly or is. A larger window captures broader, topic-level relationships, such as words related to sports or politics.
Larger windows create more pairs per token. They also increase computation and may mix several kinds of relationships. The best value depends on the corpus and the task.
This function builds weighted co-occurrence counts. Weighting a nearby word more heavily is useful for count-based methods such as GloVe.
from collections import defaultdict
def cooccurrence(tokens, window=2):
counts = defaultdict(float)
for i, word in enumerate(tokens):
start = max(0, i - window)
stop = min(len(tokens), i + window + 1)
for j in range(start, stop):
if i != j:
counts[(word, tokens[j])] += 1 / abs(i - j)
return counts
tokens = "the cat sits on the mat".split()
print(cooccurrence(tokens)[("sits", "cat")]) # 1.0Exercise
With the sentence birds fly over water and a window size of 1, which skip-gram pairs use fly as the target?
Show answer
(fly, birds) and (fly, over).