Word2vec, step by step
P10.text-representation.07 · Audience: Guest, IT/ML learner, Language professional · Prerequisites: Embeddings
Where next?
Go up a level
P10.text-representation.07 · Audience: Guest, IT/ML learner, Language professional · Prerequisites: Embeddings
Go up a level
The embedding table of P10.text-representation.03 was read straight off the corpus: count which words appear near which, then compress the counts. Word2vec reaches word vectors by the other road. It never counts co-occurrences. It plays a guessing game, given this word, which word is nearby?, and every wrong guess nudges two tables of numbers. This module follows one guess at a time, on a corpus small enough to check by hand, and then shows what thousands of guesses build on a corpus large enough to build something.
"You shall know a word by the company it keeps" (Firth, 1957). Co-occurrence counting reads that company off the text in one pass. Word2vec turns it into a guessing game instead: show the model dough and ask it to guess the words around it. A model that guesses flour and oven well has to give dough a vector close to the vectors of other words found among flour and ovens, such as bread. Nobody tells it that bread and dough are both kitchen words. The guesses do.
A training pair is a centre word c and one word o inside its window: with a window of 2, the two words on each side. The hidden layer h is simply the centre word's row of W_in, a lookup. Multiplying by W_out gives a score for every word in the vocabulary; the softmax turns the scores into probabilities, and the loss is how surprised the model was by the real neighbour.
Why it matters — Two matrices of the same shape, V rows of d numbers: W_in holds each word as a centre, W_out each word as a neighbour. Training only ever asks one question, which neighbour, and the vectors are what it leaves behind.
Reference: Mikolov et al. 2013 — Efficient Estimation of Word Representations in Vector Space
The lab below trains on the eight-sentence demo corpus (56 word types, 328 pairs per epoch with a window of 2), always the same eight: the corpus you chose elsewhere does not drive this module, because what matters here is a step you can follow, not a corpus large enough to learn from. Every press is replayed from the same random start, so the same presses always give the same numbers.
Reads /api/text-representation/word2vec/step — loading
Changing η, the window or the batch size starts a new run from the same seed. Next step trains on one pair alone; Next batch on the next 8 pairs at once, their losses averaged; Next epoch finishes the pass over the corpus a batch at a time.
Reset returns both matrices to their random start and keeps η, the window and the batch size; the defaults are η 0.5, window 2 and batch size 8.
Reads /api/text-representation/word2vec/step — loading
Nothing trained yet: both matrices hold their random start.
Press Next step and the next pair is trained alone. Every number below comes from that one computed step, and the page checks two identities on its own numbers: the loss is −ln p of the context word, and the change to the centre word's row is exactly −η times its gradient.
A gradient has the same shape as the numbers it belongs to (a row for h, a whole table for W_out): for each number, which way moving it makes the loss larger, and how strongly the loss responds. Training moves every number the other way, by the gradient times the learning rate η: that is gradient descent, the step P10.text-representation.06 took for BERT. The symbol ∂L/∂h reads "the gradient of the loss L with respect to h", ᵀ turns a matrix on its side (rows become columns), and Δ means "the change in".
Reads /api/text-representation/word2vec/step — loading
Press Next step, in the controls above: the next pair is trained alone and every quantity of its step appears here.
Only the centre word was looked up, so only its row of W_in receives a gradient: one row per step. But the softmax gives every word some probability, so every word's row of W_out is pushed, the context word's towards h, all the others slightly away. At the default settings the lab counts both after each step: 1 row of W_in, all 56 of W_out.
Why it matters — W_in is updated sparsely and W_out densely: one row against every row, at every step. The two tables are trained very differently. Which one is kept as the word vectors is a separate choice: the original word2vec keeps W_in, some implementations average the two.
Reference: Rong 2014 — word2vec Parameter Learning Explained
The softmax sums over the whole vocabulary at every step. At 56 words that is nothing; at a million it is the whole cost of training. The original papers replace it in one of two ways. The hierarchical softmax arranges the vocabulary as a binary tree, so a probability costs about log₂ V decisions instead of V scores. Negative sampling changes the objective itself: it asks only is this the real neighbour, yes or no? for the true neighbour and a handful of k random words, so each step pushes on k + 1 rows of W_out and the W_out update becomes sparse too. It is a cheaper objective, not an approximation of this gradient. The full softmax is kept here because it is the textbook model, and its dense W_out update is the one worth seeing once.
Eight sentences give most words one or two occurrences: enough to watch the arithmetic, far too few for the vectors to mean anything. The view below was trained once, ahead of time, on the 4096-sentence corpus of the corpus ladder, eight topics of 512 sentences, and the page draws what was stored. Very frequent words such as the were randomly skipped during that run (subsampling), so they do not drown out the topical words.
Closeness between two word vectors is measured by their cosine: 1 when the two point the same way, 0 when they are unrelated, negative when they point apart. The test of whether a structure emerged was written before the run: two pairs of words from the same topic, bread and dough, teacher and lesson, must end at least 0.10 higher in cosine than the two cross-topic pairs made of the same words, and further apart than they started. The page also counts how many epochs meet that bar, because four pairs are a small sample and their cosines move from one epoch to the next.
The scatter flattens each word's 16 numbers onto the two directions along which the final vectors differ most (a principal component analysis), so words drawn close together have similar vectors — roughly: two directions hold only part of the spread, and the caption says how much.
Reads 07-word2vec.structure.json (precomputed on core-4096)
The step trace above is exact on eight sentences, but eight sentences give most words one or two occurrences: nothing to learn a meaning from. This view trained the same skip-gram model on the 4096-sentence corpus of the ladder, once, ahead of time (20 epochs, d = 16, window 4, batches of 64), and stored what it built. Its η = 8 is above the lab's limit, but each update averages the losses of 64 pairs, so each pair's gradient is scaled by η/64 = 0.125: the step one pair alone would take at η = 0.125. Very frequent words were randomly skipped, more often the more frequent they are (subsampling with threshold t = 0.001: a word making up more than about 0.26 % of the tokens is sometimes skipped), so the and a do not drown out the topical words.
Sentences
4096
Word types
6102
Tokens per word type
8.20
Epochs trained
20
8.2 tokens per word type is still little: 62 % of the 6102 types occur once or twice. The words plotted below are the frequent, topical ones, where the evidence is.
epoch 20 · 61 words, coloured by the topic holding at least 75 % of their occurrences · every snapshot is projected on the same two directions, the principal axes of epoch 20, and scaled to fit the box, so compare where words sit, not how spread out a snapshot is · the two directions capture 32.9 % of this snapshot's spread
The four-pair gap is the lowest of the two same-topic cosines minus the highest of the two cross-topic ones: positive only when both kitchen and teaching pairs beat both mixed pairs.
Four-pair gap at epoch 0
0.073
Four-pair gap at the last epoch
0.383
Bar
0.10
Epochs meeting the bar
13 of 20
The structure emerged against the bar set before the run: at epoch 20 both same-topic pairs sit 0.383 in cosine above both cross-topic pairs (the bar was 0.10), against 0.073 at epoch 0. Nothing told the model which words share a topic: it only ever predicted neighbours.
Read the verdict with its sample size. Four pairs are few: their gap moves by up to 0.43 from one epoch to the next and meets the bar at 13 of the 20 trained epochs. Stopped at epoch 19, the run would have read -0.04, short of the bar. The steadier evidence is every plotted word at once, below.
Shuffling the topic labels keeps the vectors and cuts any link between them and the topics; 95 shuffles in 100 give a gap below the dashed line. At epoch 0 the random vectors' gap is 0.035 against a line at 0.032: just above it. Random vectors carry no topic, so this is the one time in twenty or so that chance alone crosses a 95th-percentile line. From epoch 1 on the gap stays between 0.32 and 0.39, about ten times a line that never passes 0.032.
The loss levels off while the gradient norm, measured on each batch of 64 pairs and averaged over the epoch, keeps rising. It rises mostly because the vectors grow from their small random start (in the scatter, the farthest word sits 0.26 from the centre at epoch 0 and 2.05 at epoch 5), and both gradients scale with them. It stops lowering the loss because batches pull in different directions and largely cancel out. A run blowing up looks different: its loss rises.
Skip-gram vs CBOW. Skip-gram predicts each neighbour from the centre word; CBOW (continuous bag of words) predicts the centre word from the average of its neighbours. Skip-gram is slower but better on rare words, because every occurrence of a rare word yields several training pairs. Count-based vs predictive. Levy and Goldberg (2014) showed that skip-gram with negative sampling implicitly factorises a shifted PMI (pointwise mutual information) matrix, a reweighting of the co-occurrence counts P10.text-representation.03 factorises: the two roads are one reweighting apart. Why W_in? Convention: the original implementation keeps W_in, the matrix each word owns as a centre, and some implementations average W_in and W_out. The sparse update does not decide it: under negative sampling W_out is updated sparsely too.
Self-check
After one Next step, how many rows of W_in changed, and how many of W_out? Why?
Self-check
What is p − y at the context word, and what sign does it have?
Self-check
Why does the structure view train on 4096 sentences instead of the eight the trace uses?
Practise this lesson's 3 self-checks
One per screen: you reveal each answer and mark it yourself. Nothing is recorded.
Ask a question about this content. The mentor explains and grounds its answer in what you are studying; asking is recorded as a learning signal, not a grade.
Off by default. The mentor always gets your file; this only decides whether your own copy stays here. Copies live in this browser only - they do not follow you to another device, and clearing site data removes them.
A scratch console for this page's ideas — ungraded, nothing you run here is recorded.
Scratch console
A scratch console with the scientific stack (pandas, numpy, scikit-learn). Runs on the server — no network, resource-limited and measured.
Output appears here.
Loading your notes...