Sub topic 8
CBOW: predicting a word from its context
Continuous bag of words (CBOW) is the second of word2vec's two architectures. Skip-gram predicts each context word from the center word. CBOW reverses this: it predicts the center word from its surrounding words. This chapter assumes you know the skip-gram setup from the previous chapter: (word, context) windows, input and output vectors, and a softmax over the vocabulary. It also assumes basic NumPy.
The training task
Take the sentence "the cat sits on the mat" with a window of 2. At the position of "sits", the context is ["the", "cat", "on", "the"] and the target is "sits". CBOW learns to put high probability on "sits" given those four words.
Each target position gives one training example, not one example per context word. A sentence of n tokens gives about n examples. The model is called a "bag" because it combines the context vectors in a way that ignores their order. Swapping "cat" and "the" in the context changes nothing. The word "continuous" refers to the context being represented by continuous vectors rather than discrete features.
The architecture
Every word has two vectors. The input vector is used when the word appears as context. The output vector is used when the word is the target.
- Look up the input vector of each context word.
- Average those vectors into a single hidden vector
h. - Compute a score for every vocabulary word as the dot product of its output vector with
h. - Apply softmax to turn the scores into probabilities.
- Minimize the negative log probability of the true center word.
Written out, with context words c_1 ... c_m, input vectors v, and output vectors u:
h = (1/m) * sum(v_c)P(w | context) = exp(u_w · h) / sum over all words w' of exp(u_w' · h)loss = -log P(target | context)
The gradient of the loss with respect to the scores is p - y, where p is the predicted distribution and y is the one-hot vector of the true word. This is the same cross-entropy gradient you know from classification.
A minimal implementation
The code below trains CBOW with the full softmax on one sentence. It is too small to give useful vectors. Its purpose is to show every step of the update.
import numpy as np
rng = np.random.default_rng(0)
sentence = ["the", "cat", "sits", "on", "the", "mat"]
vocab = sorted(set(sentence))
idx = {w: i for i, w in enumerate(vocab)}
V, d, window = len(vocab), 8, 2
W_in = rng.normal(0, 0.1, (V, d)) # input vectors, one row per word
W_out = rng.normal(0, 0.1, (V, d)) # output vectors, one row per word
def softmax(z):
z = z - z.max() # subtract the max for numerical stability
e = np.exp(z)
return e / e.sum()
def cbow_step(context, target, lr=0.1):
ctx = [idx[w] for w in context]
t = idx[target]
h = W_in[ctx].mean(axis=0)
p = softmax(W_out @ h)
loss = -np.log(p[t])
grad_scores = p.copy()
grad_scores[t] -= 1.0 # p - y
grad_h = W_out.T @ grad_scores # computed before W_out changes
W_out[:] -= lr * np.outer(grad_scores, h)
for i in ctx: # repeated words get one update per occurrence
W_in[i] -= lr * grad_h / len(ctx)
return loss
for epoch in range(200):
total = 0.0
for i, target in enumerate(sentence):
context = sentence[max(0, i - window):i] + sentence[i + 1:i + 1 + window]
total += cbow_step(context, target)
if epoch % 50 == 0 or epoch == 199:
print(epoch, round(total, 3))The printed loss falls over the epochs. It does not reach zero, because "the" appears twice with different contexts and the model cannot be certain about both.
Dividing grad_h by the number of context words is the exact gradient of the averaged input. Implementations differ on this detail. The original C word2vec code, for example, applies the full hidden gradient to each context word. Both versions train, but they behave like different learning rates.
Why use the full softmax rarely
The score step touches every output vector, so each example costs O(V × d). With a vocabulary of a few hundred thousand words this dominates training time. Production CBOW therefore uses negative sampling or hierarchical softmax, as skip-gram does. With negative sampling, the hidden vector h is scored against the true word and a handful of sampled noise words. Only those few output vectors are updated.
CBOW compared with skip-gram
| Property | CBOW | Skip-gram |
|---|---|---|
| Prediction | Center word from averaged context | Each context word from the center word |
| Examples per position | One | Up to 2 × window |
| Training speed | Faster | Slower |
| Rare words | Weaker: a rare word is only one target among many | Stronger: a rare word gets several updates per occurrence |
| Frequent words | Good | Good |
| Word order | Ignored within the window | Ignored, but each pair is trained separately |
Averaging smooths the context. The update for a rare target is spread across all context words, and each rare word occurs as a target only a few times. Skip-gram gives each rare word more separate updates. This is why skip-gram is usually preferred for small corpora or when rare words matter, and CBOW is chosen when speed on a large corpus matters.
Training CBOW with gensim
In gensim 4, sg=0 selects CBOW. This is also the default if you omit sg.
from gensim.models import Word2Vec
sentences = [
["the", "cat", "sits", "on", "the", "mat"],
["the", "dog", "sits", "on", "the", "rug"],
["the", "cat", "chases", "the", "mouse"],
]
model = Word2Vec(
sentences=sentences,
vector_size=50,
window=2,
min_count=1,
sg=0,
cbow_mean=1,
negative=5,
epochs=50,
workers=1,
seed=1,
)
print(model.wv["cat"].shape)
print(model.wv.most_similar("cat", topn=3))cbow_mean=1 averages the context vectors, as in the code above. Setting cbow_mean=0 sums them instead, which changes the effective step size. The neighbours from a three-sentence corpus are unreliable, so treat them as a check that the code runs.
Edge cases and common errors
- Dynamic window. In word2vec and gensim,
windowis a maximum. For each target, the effective window is sampled between 1 andwindow. Nearby words are therefore used more often than distant ones, and your hand-counted examples will not match exactly. - Sentence boundaries. Targets at the start or end of a sentence have fewer context words. A one-word sentence has no context and yields no CBOW example.
- Duplicate context words. The same word can occur twice in a context. It is averaged twice, so it weighs more in
hand receives two gradient contributions. - Learning rate. The original word2vec recommends a starting rate of 0.05 for CBOW and 0.025 for skip-gram. Gensim's default is 0.025 for both, so CBOW may need
alphatuning. - Too few epochs on small data. CBOW makes fewer updates per epoch than skip-gram. On small corpora it often needs more epochs.
- Two vectors per word. Gensim stores the input vectors in
model.wv. Do not look for the output vectors there. They are inmodel.syn1negwhen negative sampling is on.
Exercise
For the sentence "the cat chases the mouse" and a fixed window of 2 (no dynamic shrinking), how many training examples does CBOW produce, and how many (word, context) pairs does skip-gram produce? Why do they differ?
Show answer
CBOW produces 5 examples, one per target position, because every position has at least two context words. Skip-gram produces 14 pairs. Counting context words per position gives 2, 3, 4, 3 and 2, which sum to 14. The counts differ because CBOW combines all the context words into one averaged prediction, while skip-gram treats each context word as a separate prediction.