🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Word2Vec: CBOW, Skip-gram, Negative Sampling

Neural NLPWord2VecđŸŸĸ Free Lesson

Two architectures, one shared table

Word2Vec is a shallow network trained on a prediction task nobody cares about, in order to keep the thing the task forces it to learn. The input and output are both embeddings over the vocabulary, and once training finishes the output table is usually discarded — the useful artefact is the hidden layer, whose coordinates organize words by the contexts they predict. That framing explains most of the design choices: the objective is deliberately easy so training is fast, the network is deliberately shallow so it runs on a single machine, and the vocabulary is deliberately subsampled so frequent function words stop dominating the gradient. Because the model never sees a full sentence at once — only a centre word and its immediate neighbours — it learns no long-range structure at all, which is a limitation worth stating plainly before any downstream use.

The two architectures differ only in which direction the prediction runs. Continuous Bag of Words takes a window of context words, averages them, and predicts the single centre word — many to one, which trains quickly and smooths away idiosyncratic detail. Skip-gram takes the centre word and predicts each neighbour independently — one to many, which trains more slowly but devotes proportionally more updates to rare words and therefore represents them better. Choosing between them is a data and budget question rather than a correctness question.

This lesson builds the training pairs, derives why the full softmax is intractable, and implements negative sampling from first principles before using the library version.

The objectives side by side

AspectCBOWSkip-gram
InputContext words, averagedCentre word
TargetCentre wordEach context word
Training speedFasterRoughly 2–3× slower
Rare-word qualityWeakerStronger
Frequent-word qualityStrongerSlightly weaker
Data efficiencyNeeds more textWorks on smaller corpora
Typical windowLarger, 5–10Smaller, 5 or less
Default in gensimsg=0sg=1

The rare-word asymmetry is the one that matters in practice. CBOW averages several context vectors before predicting, so each individual rare word contributes little to the gradient and gets updated weakly. Skip-gram generates a separate training example for every centre-context pair, so a rare word appearing twenty times produces as many updates as a frequent word appearing twenty times — frequency equalisation the averaging step would otherwise destroy.

Building training pairs

Everything else in Word2Vec is bookkeeping around this loop: slide a window over each sentence, emit the pairs, optionally drop frequent tokens with a known probability, and shuffle.

python
from collections import Counter
import random

def build_pairs(sentences, window=4, min_count=2, ns_rate=0.75, discard=1e-3):
    counts = Counter(w for s in sentences for w in s)
    vocab = {w: i for i, (w, c) in enumerate(counts.items()) if c >= min_count}
    inverse = {i: w for w, i in vocab.items()}

    freqs = [counts[w] for w in vocab]
    total = sum(freqs)
    probs = [f / total for f in freqs]

    pairs, negatives = [], []
    for sent in sentences:
        ids = [vocab[w] for w in sent if w in vocab]
        kept = [i for i in ids if random.random() > discard * total / counts[inverse[i]]]
        for pos, center in enumerate(kept):
            lo, hi = max(0, pos - window), min(len(kept), pos + window + 1)
            for offset in range(lo, hi):
                if offset != pos:
                    pairs.append((center, kept[offset]))

    # noise distribution: down-weight frequent words by raising to ns_rate
    noise = [p ** ns_rate for p in probs]
    z = sum(noise)
    noise = [p / z for p in noise]
    return vocab, inverse, pairs, noise

sentences = [["the", "cat", "sat", "on", "the", "mat"],
             ["the", "dog", "sat", "on", "the", "log"]]
vocab, inverse, pairs, noise = build_pairs(sentences, window=3, min_count=1)
print("vocab:", vocab)
print("pairs:", pairs[:6], "... total", len(pairs))

Two details in that loop carry real weight. The subsampling rule removes frequent tokens with probability proportional to the square root of their frequency, which stops the from consuming most of the training budget while still keeping enough of it for grammatical context. The exponent of 0.75 on the noise distribution flattens it just enough that mid-frequency words are drawn often enough to be useful negatives, without making the rarest words dominate.

Why the full softmax does not scale

The straightforward objective is a softmax over the entire vocabulary: compute a dot product with every candidate, exponentiate, and normalise. Correct, differentiable, and hopelessly expensive. With a 50,000-entry vocabulary and a 300-dimensional hidden layer, every single training example costs 15 million multiply-adds just to form the normaliser, and the corpus contains billions of examples. Worse, most of that work scores words that are obviously wrong, and the gradient contributed by an obvious negative is already tiny — the model learns almost nothing from it.

Negative sampling replaces it with binary classification

Instead of ranking the true word against the entire vocabulary, sample a handful of noise words and ask a much simpler question: is this a real context word or a drawn one? Each example becomes a logistic regression with one positive pair and k negative pairs, the normaliser disappears, and the cost per example drops from vocabulary size to k plus one dot products.

python
import numpy as np
import torch
import torch.nn as nn

class SkipGramNeg(nn.Module):
    def __init__(self, vocab_size, dim, noise_p):
        super().__init__()
        self.in_emb = nn.Embedding(vocab_size, dim)
        self.out_emb = nn.Embedding(vocab_size, dim)
        nn.init.uniform_(self.in_emb.weight, -0.5 / dim, 0.5 / dim)
        nn.init.uniform_(self.out_emb.weight, -0.5 / dim, 0.5 / dim)
        self.noise = torch.tensor(noise_p, dtype=torch.float)

    def forward(self, center, context, negatives):
        v_c = self.in_emb(center)                       # (B, D)
        v_o = self.out_emb(context)                     # (B, D)
        v_n = self.out_emb(negatives)                   # (B, k, D)

        pos_score = torch.sum(v_c * v_o, dim=1)         # (B,)
        pos_loss = nn.functional.logsigmoid(pos_score)

        neg_score = torch.bmm(v_n, v_c.unsqueeze(2)).squeeze(2)  # (B, k)
        neg_loss = nn.functional.logsigmoid(-neg_score).sum(1)

        return -(pos_loss + neg_loss).mean()

# Example usage with 5 negatives per positive pair:
# model = SkipGramNeg(vocab_size=30000, dim=100, noise_p=noise)
# loss = model(center_ids, context_ids, negative_ids)

The sampling count k between 5 and 20 works well across corpora; larger k gives a better approximation of the normaliser at linear cost. Crucially, the objective still yields the same vector geometry as the exact softmax — Mikolov and colleagues showed the noise-scaled objective approximates the shifted pointwise mutual information between words, so what the model converges to is not a hack but a well-defined statistical quantity.

Training with a library and reading its hyperparameters

Production training is a one-liner, and the parameters around it are where the results are actually won or lost.

python
from gensim.models import Word2Vec

sentences = [
    ["natural", "language", "processing", "models", "text"],
    ["language", "models", "predict", "tokens", "from", "context"],
    ["processing", "pipeline", "tokenizes", "raw", "text"],
]

model = Word2Vec(
    sentences,
    vector_size=200,     # dimensionality: 100-300 typical
    window=5,            # context radius
    min_count=5,         # drop rare types (1 on tiny corpora)
    sg=1,                # 0 = CBOW, 1 = Skip-gram
    negative=15,         # noise samples per positive pair
    sample=1e-3,         # subsampling threshold for frequent words
    epochs=20,
    workers=4,
    seed=42,
)

print("vocab size:", len(model.wv))
print("most similar to 'language':",
      model.wv.most_similar("language", topn=3))
print("vector norm:", round(float(np.linalg.norm(model.wv["text"])), 4))
ParameterRangeEffect of raising it
vector_size100–300More capacity, more data needed
window2–10Broader topical context, weaker syntactic signal
min_count5–10Smaller vocab, rarer words dropped
negative5–20Better approximation, slower training
sample1e-4 to 1e-2Aggressively drops frequent words
epochs5–20Better fit, risk of overfitting tiny corpora

Window size quietly controls what the vectors encode. Small windows emphasise syntactic neighbours — with window=2 the closest words to a verb are its subject and object, giving useful part-of-speech structure. Large windows emphasise topical similarity, placing blood near hospital even though the two rarely abut. Most practitioners who want semantic similarity use a moderate window and several epochs rather than pushing either extreme.

What the vectors do and do not encode

The celebrated linear regularities — king - man + woman near queen — are a byproduct of the objective, not a guarantee of it. Relations that occur consistently across many word pairs tend to be encoded as consistent directions; relations that are irregular or rare do not appear at all. The vectors also conflate senses, so stock has one vector regardless of whether the sentence discusses broth or shares, and the location of that vector follows whichever sense dominates the training corpus. Both limitations disappear only when the model stops sharing one vector per word type, which is what contextual encoders do — they produce a vector per occurrence, recomputed from the sentence it appears in.

💡Fix the seed and record min_count

Two runs with different seeds produce vectors that are rotated relative to each other and not directly comparable, and a min_count you did not notice silently removed the rare terms your task needed. Both belong in the training log next to the corpus hash.

Common Mistakes

Using CBOW on a small corpus and blaming the model for poor rare-word vectors

Fix: Switch to Skip-gram, which devotes a separate update to every centre-context pair and treats rare words fairly.

Leaving min_count at 5 on a niche domain corpus

Fix: Rare domain terms are exactly the signal you need; lower it and watch vocabulary size and memory.

Comparing vectors from two training runs directly

Fix: Embedding spaces are identifiable only up to rotation, so compare within one model or evaluate behaviourally.

Ignoring the subsampling threshold

Fix: Without subsampling, function words consume most gradient updates and topical structure weakens.

Best Practices

  • Start with Skip-gram and a moderate window unless the corpus is large enough for CBOW to pay off
  • Tune min_count against downstream recall rather than by convention
  • Log seed, min_count, window, and corpus hash with every saved model
  • Evaluate with nearest neighbours on domain words before trusting analogy scores

Interview Questions

Q1: Why does Skip-gram handle rare words better than CBOW?

CBOW averages the context before predicting, diluting each rare word's contribution to the gradient, while Skip-gram emits one example per pair so updates are proportional to occurrence rather than frequency.

Q2: Why replace the softmax with negative sampling?

The full softmax normaliser costs one dot product per vocabulary entry per example; sampling k negatives reduces that to k plus one while approximating the same pointwise mutual information objective.

Q3: What does the window parameter control semantically?

Small windows emphasise syntactic relations between adjacent words, large windows emphasise topical co-occurrence, so the parameter selects which kind of similarity the vectors encode.

Key Takeaways

  • CBOW predicts the centre from averaged context; Skip-gram predicts each neighbour from the centre
  • Skip-gram's one-pair-per-example structure is what protects rare-word representations
  • Negative sampling turns an intractable normalisation into k plus one binary decisions
  • Subsampling frequent words and the 0.75 noise exponent are both load-bearing, not cosmetic
  • Window size decides whether vectors encode syntax or topic, and one vector per type conflates senses
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert NLP Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement