Sub topic 6
Skip-gram: predicting context from a word
Prerequisites
This chapter assumes basic Python and NumPy, vectors, dot products, conditional probability, softmax, gradient descent, and tokenization. You should also understand that a word embedding is a dense vector learned from word usage.
The skip-gram task
Skip-gram learns a word vector by using a center word to predict nearby context words. Given a tokenized sentence and a window size, each center word creates several training pairs.
For example, with the sentence:
the cat sits on the mat
and a window size of 2, the center word sits creates pairs such as:
- (
sits,cat) - (
sits,the) - (
sits,on) - (
sits,the)
The first item is the input word. The second item is a target context word. The model sees many such pairs and adjusts vectors so that words appearing in similar contexts receive similar representations.
def skipgram_pairs(tokens, window=2):
pairs = []
for center_index, center in enumerate(tokens):
start = max(0, center_index - window)
stop = min(len(tokens), center_index + window + 1)
for context_index in range(start, stop):
if context_index != center_index:
pairs.append((center, tokens[context_index]))
return pairs
tokens = ["the", "cat", "sits", "on", "the", "mat"]
for pair in skipgram_pairs(tokens, window=2):
print(pair)The window is usually symmetric. A larger window supplies broader topical information, while a smaller window tends to capture grammatical or local relationships.
Model structure
The model has two learned lookup tables:
- An input matrix contains a vector for each possible center word.
- An output matrix contains a vector for each possible context word.
For a training pair (w, c), skip-gram selects the input vector for w. It combines that vector with every output vector to produce scores. A softmax converts the scores into probabilities:
P(c | w) = exp(score(w, c)) / sum(exp(score(w, c'))).
Training increases the probability of the observed context word. Gradient descent updates both lookup tables. After training, practitioners commonly use the input vectors as the word embeddings, although other combinations can be useful.
Why the task works
Words with similar meanings often occur near similar words. Therefore, cat and dog receive related vectors if both occur near words such as pet, food, or runs. Skip-gram does not receive dictionary definitions. It extracts this structure from repeated context-prediction errors.
Exercise
Exercise
What training pairs does the center word "sat" produce in "the cat sat quietly" with a window size of 1?
Show answer
("sat", "cat") and ("sat", "quietly").