Modelcore
Continuous bag-of-words model
Also called CBOW.
A word2vec model that predicts the center word of a window from the sum or mean of the vectors of the words around it.
The machine
The continuous bag-of-words model (CBOW) is a conditional model of the center word of a window given the words around it. It has these parts.
- Vocabulary. A finite set of word types, fixed before training.
- Parameters. Two tables of real vectors of dimension : an input vector and an output vector for each , that is numbers.
- Context. For position of a corpus , the context is the list of words at distance 1 to on both sides, , cut at the ends of the sentence. Mikolov et al. use four words on each side.
- Hidden vector. The context vectors are averaged (or summed) into one vector, so the order of the context words is lost:
- Conditional distribution. A softmax over the vocabulary:
- Objective. Maximize by stochastic gradient ascent. After training, the rows of the input table are the word embedding.
The word2vec tool draws the radius of each window uniformly from , as for the skip-gram model. The code here uses the fixed radius .
CBOW-LOSS(w_1..w_N, C, W_in, W_out)- 1
for each position t, ctx ← the words at distance 1 to C from t - 2
h ← the mean of v_c over c in ctx ▷ or the sum - 3
s_x ← u_x · h for every x in V ▷ |V| dot products - 4
loss ← loss - (s_{w_t} - log Σ_x exp(s_x)) ▷ -log P(w_t | ctx)
What it counts
The loss of position is , a cross-entropy. With and , the gradient is
where is the number of times occurs in the context. Every context word gets the same share of the error, and a word that occurs twice in the window gets two shares. With the sum in place of the mean, the factor goes away.
Example. Take , , the window "the _ sat" with center "cat", and . The hidden vector is . With , and , the scores are and
The loss is nats. The vector is , and each of the two context vectors gets the gradient . A gradient step moves both toward .
Cost of one evaluation. The mean costs , and the full softmax costs . Mikolov et al. give the training complexity per position as (their equation 4, with the number of context words, and a hierarchical softmax over words). This is one output computation per position, against about for skip-gram. With negative sampling the output term becomes for noise words.
Relation to other models
- Skip-gram model. Skip-gram predicts each context word from the center word. CBOW predicts the center word from the averaged context. CBOW makes one prediction per position, so it trains faster. Averaging smooths over the window, and each context word gets only a share of the error.
- Neural probabilistic language model. Bengio et al. 2003 concatenate the vectors of the previous words, which keeps their order, and pass them through a nonlinear hidden layer. CBOW removes the hidden layer, averages instead of concatenating and uses words on both sides. It is not a language model: it gives no probability to a sentence.
- Softmax regression. For a fixed , the output layer is a multinomial logistic regression whose weight rows are the output vectors.
- Paragraph vector. The distributed memory variant of Le and Mikolov adds a document vector to the CBOW input.
- Training approximations. Hierarchical softmax and negative sampling apply to CBOW unchanged, with in place of the center word vector.
Known results in the model
Free-score optimum. If the scores of each context could be set freely, the objective is maximized when equals the relative frequency of among the positions with that context, by Gibbs' inequality. The proof is the one on the skip-gram model page with the context in place of the center word. CBOW cannot reach this optimum, because depends only on the multiset of context words and lies in a space of dimension .
Mean and sum. With the mean, the scale of does not grow with the size of the window, and windows cut at a sentence end have the same scale as full ones. With a fixed window size , the sum is times the mean, so the two models can represent the same distributions (scale the output vectors by ). With windows of different sizes they are different models. The word2vec tool has an option for each.
Cost. The cost per position is with the full softmax, with a balanced hierarchical softmax and with negative samples. The memory is numbers.
Measurements. These are measurements, not guarantees. Pennington, Socher and Manning report, for 300-dimensional vectors trained on 6 billion tokens with the word2vec tool, an analogy accuracy of 63.6 percent (semantic), 67.4 percent (syntactic) and 65.7 percent (total) for CBOW, against 73.0, 66.0 and 69.1 percent for skip-gram (their Table 2). The comparison depends on the corpus, the window, the number of epochs and the settings.
Code
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/continuous-bag-of-words/. The authors are listed in prov/GERBMV.jsonl.
"""The continuous bag-of-words model (Mikolov, Chen, Corrado and Dean 2013), full softmax.
The context of position t is the words at distance 1 to C on both sides. The
hidden vector h is the mean of their input vectors (rows of vin), and
P(w_t | context) = exp(u_{w_t} . h) / sum_j exp(u_j . h) with the output
vectors u (rows of uout). mean=False uses the sum instead of the mean.
The corpus is a list of lists of word ids.
"""
import math
import random
from typing import Sequence
def log_softmax(scores: Sequence[float]) -> list[float]:
m = max(scores)
z = m + math.log(sum(math.exp(s - m) for s in scores))
return [s - z for s in scores]
def examples(corpus: Sequence[Sequence[int]], c_max: int) -> list[tuple[list[int], int]]:
"""(context ids, center id) for every position with a nonempty context."""
out = []
for sent in corpus:
for t in range(len(sent)):
ctx = [sent[j] for j in range(max(0, t - c_max), min(len(sent), t + c_max + 1)) if j != t] # @line L1
if ctx:
out.append((ctx, sent[t]))
return out
def hidden(vin, ctx: Sequence[int], mean: bool = True) -> list[float]:
d = len(vin[0])
h = [0.0] * d
for j in ctx:
for k in range(d):
h[k] += vin[j][k]
if mean:
h = [x / len(ctx) for x in h]
return h # @line L2
def probabilities(vin, uout, ctx, mean: bool = True) -> list[float]:
h = hidden(vin, ctx, mean)
return [math.exp(x) for x in log_softmax([sum(a * b for a, b in zip(u, h)) for u in uout])]
def loss(vin, uout, ctx, center: int, mean: bool = True) -> float:
"""-log P(center | context)."""
h = hidden(vin, ctx, mean)
scores = [sum(a * b for a, b in zip(u, h)) for u in uout] # @line L3
return -log_softmax(scores)[center] # @line L4
def gradient(vin, uout, ctx, center: int, mean: bool = True):
"""(gradient of each row of vin as a dict, gradient of every row of uout)."""
h = hidden(vin, ctx, mean)
d = len(h)
p = [math.exp(x) for x in log_softmax([sum(a * b for a, b in zip(u, h)) for u in uout])]
gh = [0.0] * d
gu = []
for j, u in enumerate(uout):
e = p[j] - (1.0 if j == center else 0.0)
gu.append([e * a for a in h])
for k in range(d):
gh[k] += e * u[k]
scale = 1.0 / len(ctx) if mean else 1.0
gv: dict[int, list[float]] = {}
for j in ctx: # a word that occurs twice in the context gets two shares
row = gv.setdefault(j, [0.0] * d)
for k in range(d):
row[k] += scale * gh[k]
return gv, gu
def train(corpus, vocab_size: int, d: int = 8, c_max: int = 2, epochs: int = 5,
lr: float = 0.1, seed: int = 0, mean: bool = True):
rng = random.Random(seed)
vin = [[(rng.random() - 0.5) / d for _ in range(d)] for _ in range(vocab_size)]
uout = [[0.0] * d for _ in range(vocab_size)]
data = examples(corpus, c_max)
for _ in range(epochs):
rng.shuffle(data)
for ctx, center in data:
gv, gu = gradient(vin, uout, ctx, center, mean)
for j in range(vocab_size):
for k in range(d):
uout[j][k] -= lr * gu[j][k]
for j, g in gv.items():
for k in range(d):
vin[j][k] -= lr * g[k]
return vin, uout
test_continuous_bag_of_words.py 70 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/continuous-bag-of-words/. The authors are listed in prov/GERBMV.jsonl.
import math
import random
from continuous_bag_of_words import examples, gradient, hidden, loss, probabilities, train
def rand_matrix(rng, n, d, scale=0.5):
return [[rng.uniform(-scale, scale) for _ in range(d)] for _ in range(n)]
def cos(u, v):
return sum(a * b for a, b in zip(u, v)) / math.sqrt(sum(a * a for a in u) * sum(b * b for b in v))
def test_examples_of_a_sentence():
got = examples([[0, 1, 2, 3]], 1)
assert got == [([1], 0), ([0, 2], 1), ([1, 3], 2), ([2], 3)]
assert examples([[5]], 2) == []
def test_hidden_is_mean_or_sum():
vin = [[1.0, 0.0], [0.0, 2.0], [3.0, 3.0]]
assert hidden(vin, [0, 1, 2]) == [4.0 / 3, 5.0 / 3]
assert hidden(vin, [0, 1, 2], mean=False) == [4.0, 5.0]
assert hidden(vin, [1, 2]) == hidden(vin, [2, 1]) # word order does not matter
def test_probabilities_sum_to_one():
rng = random.Random(1)
vin, uout = rand_matrix(rng, 10, 4, 2.0), rand_matrix(rng, 10, 4, 2.0)
for ctx in ([0], [1, 2, 3, 4], [5, 5, 9]):
p = probabilities(vin, uout, ctx)
assert abs(sum(p) - 1.0) < 1e-12
def test_gradient_against_finite_differences():
rng = random.Random(2)
vin, uout = rand_matrix(rng, 6, 3), rand_matrix(rng, 6, 3)
h = 1e-6
for mean in (True, False):
for ctx, center in [([1, 2, 4, 5], 3), ([0, 0, 2], 1)]:
gv, gu = gradient(vin, uout, ctx, center, mean)
for mat, grads in ((vin, gv), (uout, dict(enumerate(gu)))):
for row in range(6):
for k in range(3):
old = mat[row][k]
mat[row][k] = old + h
up = loss(vin, uout, ctx, center, mean)
mat[row][k] = old - h
down = loss(vin, uout, ctx, center, mean)
mat[row][k] = old
ana = grads.get(row, [0.0] * 3)[k]
assert abs((up - down) / (2 * h) - ana) < 1e-5
def test_planted_clusters_come_apart():
rng = random.Random(3)
groups = [(list(range(0, 4)), list(range(8, 11))), (list(range(4, 8)), list(range(11, 14)))]
corpus = []
for _ in range(60):
words, ctx = groups[rng.randrange(2)]
corpus.append([rng.choice(words) if k % 2 == 0 else rng.choice(ctx) for k in range(6)])
vin, _ = train(corpus, 14, d=6, c_max=2, epochs=6, lr=0.2, seed=3)
(a, _), (b, _) = groups
inside = [cos(vin[u], vin[v]) for g in (a, b) for k, u in enumerate(g) for v in g[k + 1:]]
across = [cos(vin[u], vin[v]) for u in a for v in b]
assert min(inside) > max(across)
References
- Mikolov, Chen, Corrado and Dean 2013, Section 3.1 (the continuous bag-of-words model, the averaged projection, four history and four future words, and the training complexity Q = N x D + D x log2(V) of equation 4), Figure 1, Section 4 (the analogy results)
- Mikolov, Sutskever, Chen, Corrado and Dean 2013, hierarchical softmax, negative sampling and subsampling, which the word2vec tool applies to CBOW as well as to skip-gram
- Pennington, Socher and Manning 2014, Table 2 (analogy accuracy of CBOW and skip-gram vectors trained by the authors with the word2vec tool on 6 billion tokens)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W0 stub |
|
Tag GERBMV Edit this page History Report an error Markdown