Algorithm Search⌘K

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 VV of word types, fixed before training.
  • Parameters. Two tables of real vectors of dimension dd: an input vector v⃗w\vec v_w and an output vector u⃗w\vec u_w for each w∈Vw \in V, that is 2∣V∣d2|V|d numbers.
  • Context. For position tt of a corpus w1,…,wNw_1, \ldots, w_N, the context is the list of words at distance 1 to CC on both sides, ctx(t)=(wt−C,…,wt−1,wt+1,…,wt+C)\mathrm{ctx}(t) = (w_{t-C}, \ldots, w_{t-1}, w_{t+1}, \ldots, w_{t+C}), 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:
h⃗t=1∣ctx(t)∣∑c∈ctx(t)v⃗c.\vec h_t = \frac{1}{|\mathrm{ctx}(t)|} \sum_{c \in \mathrm{ctx}(t)} \vec v_c.
  • Conditional distribution. A softmax over the vocabulary:
P(w∣ctx(t))=exp⁡(u⃗w⋅h⃗t)∑j∈Vexp⁡(u⃗j⋅h⃗t).P(w \mid \mathrm{ctx}(t)) = \frac{\exp(\vec u_w \cdot \vec h_t)}{\sum_{j \in V} \exp(\vec u_j \cdot \vec h_t)}.
  • Objective. Maximize ∑tlog⁡P(wt∣ctx(t))\sum_t \log P(w_t \mid \mathrm{ctx}(t)) 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 {1,…,C}\{1, \ldots, C\}, as for the skip-gram model. The code here uses the fixed radius CC.

  1. CBOW-LOSS(w_1..w_N, C, W_in, W_out)
  2. 1for each position t, ctx ← the words at distance 1 to C from t
  3. 2h ← the mean of v_c over c in ctx ▷ or the sum
  4. 3s_x ← u_x · h for every x in V ▷ |V| dot products
  5. 4loss ← loss - (s_{w_t} - log Σ_x exp(s_x)) ▷ -log P(w_t | ctx)

What it counts

The loss of position tt is −log⁡P(wt∣ctx(t))-\log P(w_t \mid \mathrm{ctx}(t)), a cross-entropy. With px=P(x∣ctx(t))p_x = P(x \mid \mathrm{ctx}(t)) and g⃗=∑xpxu⃗x−u⃗wt\vec g = \sum_{x} p_x \vec u_x - \vec u_{w_t}, the gradient is

∂ loss∂u⃗x=(px−[x=wt]) h⃗t,∂ loss∂v⃗c=mc∣ctx(t)∣ g⃗,\frac{\partial\,\text{loss}}{\partial \vec u_x} = \big(p_x - [x = w_t]\big)\,\vec h_t, \qquad \frac{\partial\,\text{loss}}{\partial \vec v_c} = \frac{m_c}{|\mathrm{ctx}(t)|}\,\vec g,

where mcm_c is the number of times cc 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 1/∣ctx(t)∣1/|\mathrm{ctx}(t)| goes away.

Example. Take V={the,cat,sat}V = \{\text{the}, \text{cat}, \text{sat}\}, d=2d = 2, the window "the _ sat" with center "cat", v⃗the=(1,0)\vec v_{\text{the}} = (1, 0) and v⃗sat=(0,1)\vec v_{\text{sat}} = (0, 1). The hidden vector is h⃗=(0.5,0.5)\vec h = (0.5, 0.5). With u⃗the=(0,0)\vec u_{\text{the}} = (0, 0), u⃗cat=(1,1)\vec u_{\text{cat}} = (1, 1) and u⃗sat=(−1,0)\vec u_{\text{sat}} = (-1, 0), the scores are (0,1,−0.5)(0, 1, -0.5) and

P(⋅∣the,sat)=(0.2312,0.6285,0.1402).P(\cdot \mid \text{the}, \text{sat}) = (0.2312, 0.6285, 0.1402).

The loss is −log⁡0.6285=0.4644-\log 0.6285 = 0.4644 nats. The vector g⃗\vec g is 0.6285(1,1)+0.1402(−1,0)−(1,1)=(−0.5117,−0.3715)0.6285(1, 1) + 0.1402(-1, 0) - (1, 1) = (-0.5117, -0.3715), and each of the two context vectors gets the gradient g⃗/2=(−0.2559,−0.1857)\vec g / 2 = (-0.2559, -0.1857). A gradient step moves both toward u⃗cat\vec u_{\text{cat}}.

Cost of one evaluation. The mean costs O(∣ctx∣d)O(|\mathrm{ctx}| d), and the full softmax costs O(∣V∣d)O(|V| d). Mikolov et al. give the training complexity per position as Q=N×D+D×log⁡2VQ = N \times D + D \times \log_2 V (their equation 4, with NN the number of context words, D=dD = d and a hierarchical softmax over VV words). This is one output computation per position, against about CC for skip-gram. With negative sampling the output term becomes (k+1)d(k + 1) d for kk 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 1/∣ctx∣1/|\mathrm{ctx}| 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 h⃗t\vec h_t, 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 h⃗t\vec h_t 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 P(w∣ctx)P(w \mid \mathrm{ctx}) equals the relative frequency of ww 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 h⃗\vec h depends only on the multiset of context words and lies in a space of dimension dd.

Mean and sum. With the mean, the scale of h⃗\vec h 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 mm, the sum is mm times the mean, so the two models can represent the same distributions (scale the output vectors by 1/m1/m). With windows of different sizes they are different models. The word2vec tool has an option for each.

Cost. The cost per position is O(Cd+∣V∣d)O(C d + |V| d) with the full softmax, O(Cd+dlog⁡∣V∣)O(C d + d \log |V|) with a balanced hierarchical softmax and O(Cd+(k+1)d)O(C d + (k + 1) d) with kk negative samples. The memory is 2∣V∣d2|V|d 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.

continuous_bag_of_words.pyI0RawGitHub
# 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

  1. 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)
  2. 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
  3. 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW0 stub
  • the lead paragraph