Sub topic 2
Skip-gram: predicting context from a word
This chapter assumes you know Python and NumPy, can compute dot products and vector norms, understand softmax as a function that turns scores into probabilities, know the idea of gradient descent on a loss, and can split text into tokens.
Skip-gram: predicting context from a word
Skip-gram takes one target word and predicts the words near it. Word2vec builds its training data with a sliding window. Each word in the window becomes a (target, context) pair. The model learns one vector per word, and words that predict similar contexts end up with similar vectors.
CBOW: predicting a word from its context
Continuous bag of words (CBOW) reverses the task. It averages the context vectors and predicts the centre word. CBOW trains faster on large corpora. Skip-gram usually does better on rare words, because each occurrence of a rare word produces several training pairs.
The cost of the full softmax
A full softmax gives a probability for every word in the vocabulary. With a vocabulary of V words and vectors of size d, each training pair costs about O(V·d) work just for the normalizing sum. With V near one million, training becomes too slow.
Negative sampling
Negative sampling replaces the large sum with a yes-or-no task: is this (word, context) pair real or randomly invented? For each real pair, the model draws k random "negative" words. It learns to score real pairs high and random pairs low.
import numpy as np
def sigmoid(x):
return 1.0 / (1.0 + np.exp(-x))
def sgns_loss(w, c_pos, c_negs):
positive = -np.log(sigmoid(w @ c_pos))
negative = -np.sum(np.log(sigmoid(-(c_negs @ w))))
return float(positive + negative)
rng = np.random.default_rng(0)
w = rng.normal(size=4)
c_pos = rng.normal(size=4)
c_negs = rng.normal(size=(5, 4))
print(sgns_loss(w, c_pos, c_negs))Hierarchical softmax
Hierarchical softmax arranges the vocabulary as a binary tree. Predicting a word means choosing a left or right branch at each node, which costs about O(log V) per pair. Modern practice usually prefers negative sampling, so treat hierarchical softmax as an alternative.
Subsampling frequent words
Very frequent words such as "the" add little information. Word2vec discards each occurrence of a word w with probability 1 − sqrt(t / f(w)), where f(w) is the word's frequency and t is a threshold, often 1e-5. This speeds training and improves vectors for rarer words.
Building a co-occurrence matrix
GloVe starts from counts instead of prediction. It scans the corpus with a window and adds 1/distance for each pair, so nearer words count more.
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")])GloVe: fitting log co-occurrence counts
GloVe learns a vector wi and a context vector cj for each pair of words, plus bias terms bi and bj. It fits the dot product so that wi · cj + bi + bj approximates log Xij. The loss is the sum of f(Xij) · (wi · cj + bi + bj − log X_ij)², where f gives less weight to rare pairs and caps the weight of very frequent ones.
Exercise
With window=2, how many (target, context) skip-gram pairs does the word "b" produce in the sentence "a b c d"?
Show answer
Three. The context words are "a" (left), and "c" and "d" (right), which are within two positions of "b".