Word2vec from Scratch: A Small Corpus, Weak Analogies

Build word2vec from scratch in NumPy, check its gradients against finite differences, and measure what one epoch on a small corpus can learn.

Cover Image for Word2vec from Scratch: A Small Corpus, Weak Analogies

You search a collection of articles for "monarch". An article about a king could be relevant even if it never uses your search term, so matching words alone would miss it. You need a way to relate the two words. Word2vec approaches that problem by learning a vector for each word from the words that appear nearby. Those vectors give us something we can compare, and a way to inspect the relationships the model has learned.

We test those learned relationships by building NumPy word2vec and comparing it with gensim. After one epoch on the first two million text8 tokens, both reach about 1.4% analogy accuracy. This small run offers little support for the famous king, man, woman and queen arithmetic. Gradient checks and reproducible evaluation leave a saved vector matrix ready for a nearest-neighbour index.

Quick Win

Open In Colab

The notebook contains the NumPy implementation and the full comparison. The following compact example establishes the task with gensim. It downloads the original text8 archive, checks its SHA-256 digest and keeps the specified prefix. The archive contains a cleaned Wikipedia sample described by Matt Mahoney.

A centre word creates pairs with nearby context words as the window moves.

import hashlib
import io
import urllib.request
import zipfile
from gensim.models import Word2Vec

url = "https://mattmahoney.net/dc/text8.zip"
raw = urllib.request.urlopen(url, timeout=60).read()
expected = "a6640522afe85d1963ad56c05b0ede0a0c000dddc9671758a6cc09b7a38e5232"
assert hashlib.sha256(raw).hexdigest() == expected
with zipfile.ZipFile(io.BytesIO(raw)) as archive:
    words = archive.read("text8").decode().split()[:2_000_000]
sentences = [words[i:i + 1000] for i in range(0, len(words), 1000)]
model = Word2Vec(
    sentences, vector_size=100, window=5, min_count=5,
    sg=1, hs=0, negative=5, sample=1e-3, ns_exponent=0.75,
    epochs=1, workers=1, seed=0, alpha=0.025, min_alpha=0.0001,
)
print(model.wv.most_similar("king", topn=5))

Each returned score is a cosine similarity between two input vectors. The model has 21,681 words, after removing words that occur fewer than five times. A neighbour list can look plausible while the model remains poor at a harder task, so we will inspect neighbours and score analogies separately.

The example deliberately uses one epoch and one worker. These choices make the reference run inexpensive and reproducible. A different gensim version, token boundary or training schedule can change the exact output. Our recorded reference uses gensim 4.4.0, and the notebook pins that version.

Word Pairs

Skip-gram constructs a training example from a centre word and one context word. In the sentence “the king and the queen rule”, a radius of two around “king” supplies “the”, “and” and the second “the”, subject to the sentence boundary. Repeated tokens are separate observations. Removing duplicates would change the empirical distribution that the model learns.

The window limits how far apart the two words can be. A narrow window favours local syntactic associations, while a wider window supplies more topical context. Neither setting gives a contextual representation of the centre word. Every occurrence of “bank” updates the same row, whether it appears beside “river” or “mortgage”.

The dynamic window draws an integer radius uniformly between one and five for each centre. A context at distance one always qualifies, while a context at distance five qualifies only one fifth of the time. This creates a distance weighting without adding a separate weight to the loss. The notebook's pairs function samples the radius once per centre and generates both left and right contexts.

The NumPy trainer treats the filtered corpus as one stream. Gensim receives chunks of 1,000 tokens because text8 has no useful sentence punctuation. That small boundary difference, the shuffled NumPy batches and gensim's sequential updates mean the two runs target the same objective with similar settings, rather than reproducing identical optimisation trajectories.

Frequent words dominate the stream. Without a correction, pairs involving “the” and “of” consume much of the training work. Subsampling probabilistically removes tokens before pair construction. The original word2vec implementation uses a keep probability based on the token frequency and a threshold. Our implementation follows the form also used by gensim:

Pkeep(w)=min⁡(1,[f(w)t+1]tf(w)).P_{\mathrm{keep}}(w) =\min\left(1,\left[\sqrt{\frac{f(w)}{t}}+1\right]\frac{t}{f(w)}\right).

Here f(w)f(w) is the word's relative frequency and t=10−3t=10^{-3} is the threshold. Tokens with large f(w)f(w) have a lower keep probability. We compute frequency from the retained vocabulary counts, then use the surviving sequence to generate pairs. This matters because removing an intervening token changes which words fall inside a window.

The actual NumPy run generated 8,371,002 positive pairs. That count comes after vocabulary filtering, subsampling and dynamic-window construction. It is the relevant count for training cost, rather than the two-million-token headline alone.

Negative Sampling

Full-softmax skip-gram predicts a probability over every possible context word:

P(c∣w)=exp⁡(uc⊤vw)∑j=1∣V∣exp⁡(uj⊤vw).P(c\mid w)=\frac{\exp(u_c^\top v_w)}{\sum_{j=1}^{|\mathcal V|}\exp(u_j^\top v_w)}.

The denominator touches the entire vocabulary for every observed pair. Negative sampling replaces this prediction problem with a binary classification objective. An observed pair receives label one; several sampled pairs receive label zero. The model learns to assign a larger dot product to observed pairs.

Two matrices hold the parameters. VV contains input vectors vwv_w, and UU contains context vectors ucu_c. Both have one row per vocabulary item, but their roles differ. Exporting VV, exporting UU and averaging the two are separate modelling choices. We export VV for all the neighbour and analogy results here.

Observed and sampled word pairs pass through a scoring objective.

For a positive context cc and KK sampled contexts nkn_k, the loss is:

ℓ(w,c)=−log⁡σ(uc⊤vw)−∑k=1Klog⁡σ(−unk⊤vw).\ell(w,c)=-\log\sigma(u_c^\top v_w) -\sum_{k=1}^{K}\log\sigma(-u_{n_k}^\top v_w).

We use five negatives. Increasing that number gives more noise comparisons per observed pair and increases computation. It also changes the objective's balance, so losses obtained with different negative counts should not be compared directly.

The sampling distribution is proportional to unigram counts raised to a power:

q(w)=count⁡(w)0.75∑jcount⁡(j)0.75.q(w)=\frac{\operatorname{count}(w)^{0.75}} {\sum_j\operatorname{count}(j)^{0.75}}.

The exponent flattens the distribution relative to raw counts. Less frequent words consequently appear as negatives more often than they would under ordinary unigram sampling. We draw with replacement, so the same negative can appear twice. The NumPy objective also allows a sampled context to equal the positive context. Gensim rejects that collision internally, another small implementation difference to record when comparing the runs.

Gradients and Updates

A binary example has a score s=u⊤vs=u^\top v and label yy. Its stable logistic loss and score derivative are:

ℓ(s,y)=log⁡(1+es)−ys,∂ℓ∂s=σ(s)−y.\ell(s,y)=\log(1+e^s)-ys, \qquad \frac{\partial\ell}{\partial s}=\sigma(s)-y.

np.logaddexp evaluates the first term without explicitly computing a potentially overflowing exponential. The score derivative multiplies the other vector to obtain each parameter gradient. This is the same chain rule developed in the backpropagation tutorial.

import numpy as np
from scipy.special import expit

def loss_gradient(v, u, labels):
    scores = u @ v
    loss = np.logaddexp(0, scores) - labels * scores
    error = expit(scores) - labels
    return loss.sum(), error @ u, error[:, None] * v

The finite-difference check perturbs every element of a small input vector and context matrix. The largest absolute discrepancy is 1.37 × 10⁻¹⁰. This verifies the local derivative, but it does not validate pair construction, sampling or the entire training schedule. Those components need their own inspection.

Batch updates introduce an additional indexing detail. If two examples share a centre word, both contributions must reach its row. NumPy's buffered advanced indexing does not guarantee that V[indices] += updates accumulates repeated indices correctly. The trainer uses np.add.at for both matrices:

v = V[centres].copy()
u = U[targets].copy()
scores = np.einsum("bd,bkd->bk", v, u)
error = expit(scores)
error[:, 0] -= 1
np.add.at(V, centres, -learning_rate * np.einsum("bk,bkd->bd", error, u))
np.add.at(
    U, targets.ravel(),
    (-learning_rate * error[:, :, None] * v[:, None, :]).reshape(-1, V.shape[1]),
)

The copies freeze the pre-update vectors while forming both gradients. Updating VV first and then using its new values for the UU gradient would produce a different optimisation step. Our batches contain 256 positive pairs, with a linearly declining learning rate from 0.025 to 0.0001 across the epoch.

The following curve uses a fixed probe of pairs from the training distribution. Because the probe uses training pairs, it measures optimisation progress without a held-out generalisation test. The second panel evaluates both trained models on another shared set of 5,000 observed pairs with the same five negatives per pair. This avoids comparing gensim's accumulated training-loss counter with NumPy's average loss.

NumPy's fixed-probe loss falls over one epoch, alongside the two trained models' shared-probe losses.

The NumPy probe loss falls from 4.159 to 2.544. Training takes 106 seconds on the development CPU. Loss reduction confirms that the trainer fits its objective. The analogy test below establishes the practical limit of that fit.

Embedding Geometry

Cosine similarity compares direction after dividing each vector by its norm. We exclude the queried word from its own neighbour list. Euclidean distance on these unit vectors gives the same ranking, since squared distance equals two minus twice the cosine similarity. That identity lets a Euclidean graph index search the saved embeddings later.

Nearest words for six probes, using NumPy and gensim input embeddings.

Some neighbour groups share a recognisable theme, while others mix grammatical or topical associations. Inspect several probes, including rare terms, before concluding that an embedding space is useful. A short hand-picked list cannot measure retrieval quality on a particular application.

PCA provides a two-dimensional projection of the 100-dimensional vectors. The projection makes neighbourhoods visible, but discards most of the dimensions. A vector offset that appears close in the plot can remain far away in the original space. PCA and SVD explains the projection and the information it retains.

A PCA projection of selected words and the computed king minus man plus woman endpoint.

The amber cross marks the actual projected vector arithmetic. It is computed from the trained vectors, without moving the points to form a flattering parallelogram. The proximity of this point to “queen” in a projection is insufficient evidence for analogy performance.

Analogy Evaluation

The original word2vec question file contains semantic and syntactic analogy categories. We retain only questions whose four words occur in our vocabulary, leaving 8,995 questions. Coverage is therefore conditional on the corpus and minimum count. A larger vocabulary can change both the model and the test set.

For each question a:b::c:da:b::c:d, we score candidates by cosine similarity to the offset formed from unit word vectors:

d^=arg⁡max⁡w∉{a,b,c}  cos⁡(vˉw,vˉb−vˉa+vˉc).\hat d=\underset{w\notin\{a,b,c\}}{\arg\max}\; \cos\left(\bar v_w,\bar v_b-\bar v_a+\bar v_c\right).

The standard convention excludes the three supplied words. This makes the task easier because the answer cannot be one of them. NumPy scores 1.423% with this convention and 0.623% when all vocabulary words remain candidates. Both numbers describe the same trained matrix.

The corresponding gensim seed-zero score is 1.434%, a difference of 0.011 percentage points. That passes the planned implementation comparison, but the low absolute scores constrain its interpretation. Matching a weak reference demonstrates similar behaviour at this scale. It does not establish the quality associated with word2vec trained on much larger corpora.

Ablations

The reference ablations use the same corpus, one epoch and three seeds per arm. Turning off subsampling changes the number and distribution of training pairs. Raising the noise exponent to one changes only the noise distribution setting, subject to the trainer's random draws.

Three-seed analogy scores for the baseline, no subsampling and a unigram noise exponent of one.

Reference armMean analogy accuracySeed standard deviation
Baseline1.493%0.112 percentage points
Subsampling off1.764%0.061 percentage points
Noise exponent 1.01.571%0.036 percentage points

Subsampling off raises this particular score by 0.271 percentage points, a larger movement than the exponent change. All three arms remain below 2%. The ablation does not overturn the published motivation for subsampling. It measures a one-epoch, small-prefix regime where keeping more examples can matter, and it does not equalise the arms' number of parameter updates.

Three seeds provide a small view of training variation. The error bars describe the spread among those seeds, rather than confidence intervals over new corpora. Evaluating on multiple corpora or holding compute fixed would answer different questions.

Foundations

Mikolov and colleagues' Efficient Estimation of Word Representations in Vector Space introduces efficient continuous bag-of-words and skip-gram architectures. Skip-gram predicts surrounding words from a centre word. The representation emerges in the input weight matrix, allowing subsequent tasks to use the learned vectors without retaining the original training classifier.

The later paper, Distributed Representations of Words and Phrases and their Compositionality, develops negative sampling, frequent-word subsampling and phrase representations. Our implementation covers the first two components at word level. It omits phrase detection and trains a single epoch on a prefix, so its scores should not be compared directly with the paper's larger experiments.

The binary objective also has a matrix-factorisation interpretation. Levy and Goldberg's 2014 paper analyses the optimum when word-context dot products can vary independently. Let #(w,c)\#(w,c) be the number of observed pairs, and let q(c)q(c) be the negative-context distribution. The contribution for one pair type is:

Jwc=#(w,c)log⁡σ(x)+K#(w)q(c)log⁡σ(−x),x=vw⊤uc.J_{wc}=\#(w,c)\log\sigma(x) +K\#(w)q(c)\log\sigma(-x),\qquad x=v_w^\top u_c.

Setting the derivative with respect to xx to zero gives:

x∗=log⁡P(w,c)P(w)q(c)−log⁡K.x^* = \log\frac{P(w,c)}{P(w)q(c)}-\log K.

If the noise distribution equals the empirical context unigram distribution, this becomes pointwise mutual information minus log⁡K\log K. PMI measures how much more often two words co-occur than their independent frequencies would predict. The result explains a connection between a predictive neural objective and a co-occurrence matrix.

Our noise distribution uses the 0.75 exponent, so the optimum includes the extra context-dependent adjustment log⁡[P(c)/q(c)]\log[P(c)/q(c)]. Calling the matrix “PMI minus log five” without mentioning the altered noise distribution would omit that term. The finite, 100-dimensional model further couples dot products through shared vectors, while the derivation lets each entry vary independently.

The notebook constructs a sparse positive-PMI matrix for the 5,000 most frequent words using 250,000 tokens and a narrower window. Truncated SVD then supplies a second embedding space. The reduced dataset and window keep this calculation cheap, but prevent a matched accuracy comparison with the SGNS run. Its purpose is to expose the co-occurrence mechanism and compare readable neighbours.

Positive PMI clips negative entries to zero. SVD subsequently approximates that transformed matrix under its own reconstruction criterion. Neither operation reproduces the logistic SGNS loss exactly. Goldberg and Levy's explanation and Levy, Goldberg and Dagan's experiments discuss these distinctions and the effects of preprocessing and hyperparameters.

The trained matrix still gives one vector per word, merges different senses and inherits the corpus's associations. Domain vocabulary, corpus size, repeated training and the evaluation task all affect usefulness. TF-IDF classification remains a useful baseline when explicit word overlap is sufficient, while hybrid retrieval combines lexical and vector signals.

The notebook saves word2vec_vectors.npz, including vocabulary order, counts and the 100-dimensional input matrix. Keeping the word order beside the matrix prevents a downstream index from returning a correct row number with the wrong word label.

The 2013 extensions paper describes subsampling as producing:

“significant speedup”

That claim concerns its training regime. Our ablation keeps epochs fixed, so removing subsampling also increases the number of updates. Comparing those scores with equal update counts would help separate the effect of discarding frequent words from the effect of doing less training.

The full skip-gram conditional distribution uses a softmax over all context rows. Its denominator makes every context compete for probability mass. Negative sampling instead asks whether each selected pair resembles an observed pair, using a small set of contrasts drawn from the noise distribution. Our measured work therefore depends on the number of positive pairs and five sampled contexts per pair, rather than a complete vocabulary scan at every update.

Consider a word that appears in both a geographical and a financial context. Both uses update the same input row. Their gradients can reinforce shared evidence or pull that row towards different context groups. A second row for the word in the output matrix changes its role in the training objective, but still leaves each matrix with one row per word type. Combining the two matrices is an evaluation choice that the exercises make explicit.

The matrix derivation also exposes a boundary case. An unobserved pair has zero positive count and a negative-sampling penalty whenever its context can be drawn. Its unconstrained best score tends towards negative infinity. Finite shared embeddings cannot assign arbitrary values to every pair, so low-rank geometry and training dynamics determine a compromise. Clipping a PMI matrix at zero changes that compromise before SVD starts.

Interactive Tools

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions