Sub topic 7
CBOW: predicting a word from its context
Prerequisites and the central idea
Assume you know tokenization, vectors, dot products, softmax, and gradient descent. You should also understand that a word embedding is a learned dense vector.
Continuous bag of words, or CBOW, learns an embedding by predicting a missing target word from nearby context words. For example, given:
> the cat ___ on the mat
the context might be cat, on, and the, while the target is sits.
CBOW uses the distributional hypothesis: words appearing in similar contexts tend to have related meanings.
Creating a training example
Choose a window around each target. With window size 2, the sentence:
the cat sits on the matcan produce this example:
- Context:
the,cat,on,the - Target:
sits
The term bag means that CBOW combines context words without preserving their order. A simple implementation averages their input vectors:
h = \frac{1}{|C|}\sum_{w \in C} v_wHere, \(C\) is the context and \(v_w\) is the vector for context word \(w\). The resulting vector \(h\) represents the local context.
Scoring candidate words
The model has an output vector \(u_w\) for each candidate target word. It scores a candidate using:
s(w) = u_w^\mathsf{T}hThe softmax converts all scores into probabilities:
P(w \mid C) = \frac{\exp(s(w))}{\sum_{x \in V}\exp(s(x))}where \(V\) is the vocabulary. Training minimizes the negative log probability of the correct target:
L = -\log P(\text{target} \mid C)Gradient descent updates both the context-word input vectors and the output vectors. Across many examples, words that occur in similar contexts receive similar representations.
import numpy as np
# Rows are input vectors for: the, cat, on, sits
input_vectors = np.array([
[0.2, 0.1], # the
[0.8, 0.3], # cat
[0.1, 0.4], # on
])
output_vectors = np.array([
[0.1, 0.2], # the
[0.3, 0.1], # cat
[0.2, 0.5], # on
[0.7, 0.6], # sits
])
hidden = input_vectors.mean(axis=0)
scores = output_vectors @ hidden
probabilities = np.exp(scores - scores.max())
probabilities /= probabilities.sum()
target_index = 3 # sits
loss = -np.log(probabilities[target_index])
print("probabilities:", probabilities)
print("loss:", loss)Common errors
- Using only one context vector: CBOW averages all selected context vectors before prediction.
- Confusing input and output embeddings: Training creates two sets of vectors. Libraries usually expose one set, often the input vectors.
- Assuming context order matters: Standard CBOW discards order. Models that use order require a different architecture.
- Expecting a tiny corpus to work: A small dataset cannot provide enough contexts for useful embeddings.
Exercise
For the sentence “birds fly over water” with window size 1 and target “fly”, what is the CBOW context?
Show answer
The context is “birds” and “over”. CBOW combines their vectors, usually by averaging them, to predict “fly”.