Foundations to Frontier
Tests

word2vec: Skip-Gram, CBOW and Negative Sampling

word2vec (Mikolov and colleagues, 2013) learns word embeddings by prediction. Skip-gram predicts each nearby word from the centre word; CBOW predicts the centre word from its neighbours. Instead of a full softmax over the vocabulary, negative sampling trains a binary classifier to tell the true context word from k random 'noise' words drawn from the unigram distribution raised to the power 0.75. Frequent words are subsampled. The resulting vectors famously capture relations as directions (king − man + woman ≈ queen). This page covers the two architectures, the negative-sampling objective and its gradients, noise distributions, subsampling, hyperparameters and the link to PMI matrix factorisation. In the exercises you derive and check the negative-sampling gradients, then train skip-gram and CBOW in NumPy on a corpus with country/capital structure and test 870 analogies. With 2000 sentences, count-based PPMI + SVD answered 0.85 of analogies against 0.41 for skip-gram. With 8000 sentences skip-gram reached 1.00 and CBOW 0.99, against 0.84 for SVD. One negative sample per pair gave only 0.83.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Learning word vectors by guessing neighbours

word2vec plays a guessing game over millions of sentences: given a word, which words are likely nearby? To get good at it, it must give words with similar neighbours similar vectors. Rather than scoring every word in the dictionary at each step, it just learns to tell the real neighbour from a few random words: “negative sampling”. Afterwards, directions in the vector space often mean something, like “male → female” or “country → capital”. The demo shows a tiny example of such an analogy.

Language lab
cos(king, queen) = 0.874. king − man + woman lands nearest to queen: directions in embedding space can encode relations.
Why engineers care

word2vec-style embeddings are cheap to train on in-house text (maintenance logs, requirements, procedures) and still useful for search, clustering and features when large models are not available.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Skip-gram predicts…
  2. 2. Negative sampling distinguishes the true context word from…
  3. 3. king − man + woman is closest to…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Skip-gram: for each centre word w and context word c within a window, maximise log σ(v_w · u_c) + Σ_(n ~ noise) log σ(−v_w · u_n), with k negatives. Two vector tables: input vectors v (used as embeddings) and output vectors u.
  • CBOW: average the context vectors and predict the centre word; faster, slightly worse on rare words.
  • Cost: (k + 1)·d per pair instead of V·d for a full softmax (1800 vs 15 million for k = 5, d = 300, V = 50k). About 2·window pairs per token.
  • Noise distribution: P_n(w) ∝ count(w)^0.75, which boosts rare words relative to raw frequency.
  • Subsampling: drop a token of frequency f with probability 1 − (√(t/f) + t/f), with t ≈ 10⁻⁵. Words like “the” are mostly dropped, which speeds training and helps rare words.
  • Analogies: answer a : b :: c : ? by the nearest word to v_b − v_a + v_c (excluding a, b, c).
📝 Quick check (Level 1)
0/3 answered
  1. 1. Dot products per pair with k = 5, d = 300:
  2. 2. The noise distribution raises counts to the power…
  3. 3. Subsampling mostly drops…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

word2vec in code

Exercise 1.

  • Implement the negative-sampling loss and its gradients, checked by finite differences.
  • Generate skip-gram (centre, context) pairs from a window.

Practice.

  • Gensim’s Word2Vec trains skip-gram or CBOW with negative sampling efficiently on large corpora.
  • Typical settings: d = 100–300, window 5, k = 5–15 (smaller k for large data), min_count ≥ 5, 5 epochs, subsampling 10⁻⁵.
  • Evaluate with analogy and word-similarity benchmarks and, more importantly, on your downstream task.
  • For rare and misspelt words use fastText (F3-3); for context-dependent meaning use contextual models (F3-4).
from gensim.models import Word2Vec
model = Word2Vec(sentences=token_lists, vector_size=200, window=5, sg=1, negative=10,
                 sample=1e-5, min_count=5, epochs=5, workers=4)
print(model.wv.most_similar(positive=["capital", "france"], negative=["country"], topn=3))
🐍 Exercise 1: negative-sampling gradients
Implement the skip-gram negative-sampling loss with its gradients, and skip-gram pair generation.
📝 Quick check (Level 2)
0/3 answered
  1. 1. A library for training word2vec:
  2. 2. sg=1 in Gensim selects…
  3. 3. Embeddings should finally be judged on…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

What SGNS optimises. Levy and Goldberg (2014) showed that at the optimum, v_w · u_c = PMI(w, c) − log k. Skip-gram with negative sampling is an implicit, weighted factorisation of a shifted PMI matrix, closely related to PPMI + SVD.

Why analogies appear. If contexts factorise into independent aspects (a country’s own contexts plus role-specific contexts), then log co-occurrence is roughly additive, and so are the vectors. The offset v_capital − v_country is then shared across countries (Arora et al., 2016; Allen and Hospedales, 2019).

Data efficiency. SVD uses exact global counts in one shot and has no optimisation noise, which helps when data is small. SGNS weights frequent pairs more, ignores unobserved pairs and is trained stochastically; with enough data its weighting gives better geometry. Levy, Goldberg and Dagan (2015) found that with matched hyperparameters the methods are close.

📝 Quick check (Level 3)
0/3 answered
  1. 1. At the optimum, SGNS dot products equal…
  2. 2. Analogies arise when log co-occurrence is…
  3. 3. With little data, SVD can win because it uses…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

When does prediction-based word2vec beat count-based SVD?

History.

  • T. Mikolov, K. Chen, G. Corrado and J. Dean, “Efficient estimation of word representations in vector space” (2013).
  • T. Mikolov et al., “Distributed representations of words and phrases and their compositionality” (NeurIPS 2013).
  • O. Levy, Y. Goldberg and I. Dagan, “Improving distributional similarity with lessons learned from word embeddings” (TACL 2015).

Exercise 2.

  • Corpus: 30 countries, each with a “country” word and a “capital” word (Zipfian country frequencies). Each sentence has the target plus 4 context words: two from the country’s own pool and one from a role pool (country-like or city-like contexts), each kept with probability 0.5 (otherwise a general word), plus one general word.
  • Analogies: capital_i − country_i + country_j ≈ capital_j for all 870 ordered pairs.
  • Models (16 dimensions):
    • skip-gram with negative sampling (k = 5 or 1, window 2, 5 epochs, mini-batch SGD);
    • CBOW (k = 5);
    • PPMI + SVD.
  • Corpus sizes: 2000 and 8000 sentences.
model 2000 sentences 8000 sentences
skip-gram, k = 5 0.406 0.999
CBOW, k = 5 — 0.993
skip-gram, k = 1 — 0.826
PPMI + SVD 0.846 0.839
  • With little data, counts win: SVD answers 85% of analogies from 2000 sentences; skip-gram, still noisy after 5 epochs, answers 41%.
  • With more data, prediction wins: skip-gram and CBOW reach about 1.00, while SVD stays at 0.84.
  • One negative sample is too few: 0.83 against 1.00 with five.
  • Seeds: seeds 1 and 2 gave skip-gram 0.415/0.379 against SVD 0.916/0.891 at 2000 sentences, and 0.998/1.000 against 0.840/0.860 at 8000.
  • Dropped variant: uniform noise (power 0) instead of 0.75 made no difference in three seeds (for example 1.00 against 0.999), so I removed it to save time. With a vocabulary of 200 words the noise distribution matters little.
  • Speed work: the first version took 4 s per seed. Replacing np.add.at with a bincount scatter-add and trimming variants gave identical numbers in 2 s; larger batches diverged.
🐍 Exercise 2 (research): when does prediction-based word2vec beat count-based SVD?
Train skip-gram and CBOW with negative sampling and PPMI + SVD embeddings at two corpus sizes; evaluate country–capital analogies.

word2vec in AI, robotics and aerospace

  • Domain vocabularies: embeddings trained on aerospace text place related components and failure terms close together.
  • Lightweight features: compact word vectors for classifiers on embedded or air-gapped systems.
  • Design lesson: count-based methods are strong with little data; prediction-based training shines with more.

References

  1. T. Mikolov, K. Chen, G. Corrado and J. Dean (2013). “Efficient estimation of word representations in vector space.” arXiv:1301.3781.
  2. T. Mikolov, I. Sutskever, K. Chen, G. Corrado and J. Dean (2013). “Distributed representations of words and phrases and their compositionality.” NeurIPS.
  3. O. Levy and Y. Goldberg (2014). “Neural word embedding as implicit matrix factorization.” NeurIPS.
  4. O. Levy, Y. Goldberg and I. Dagan (2015). “Improving distributional similarity with lessons learned from word embeddings.” TACL 3.