Word Vectors

Cat and dog never share a sentence in our twelve. Train word2vec to predict each word's neighbours, and their vectors end up pointing the same way: a cosine of 1.00. Car ends up opposite cat, at −0.87. One-hot vectors give 0 for every pair.

Drag the training slider and watch the words sort themselves into two groups. Pick a pair to compare word2vec with raw counts and one-hot vectors. Then we build word2vec from zero: the prediction, the loss, its gradient, and the trick that makes it fast.

You need a little Python, what a probability is and the dot product of two lists of numbers. We build the rest from zero.

Lecture 2, "Word Vectors", of Stanford CS224N, Natural Language Processing with Deep Learning (Winter 2026, Diyi Yang and Yejin Choi; the lecture slides name Diyi Yang). Its readings: Mikolov and colleagues' two word2vec papers (2013), GloVe (Pennington, Socher and Manning, 2014), Levy, Goldberg and Dagan (2015) and Schnabel and colleagues (2015). Before: Lecture 1, History of NLP. Next: Lecture 3, Backpropagation and Neural Network Basics.

Train word vectors here

40

Illustrative toy, trained live in your browser: skip-gram with a full softmax, window 2, two numbers per word, learning rate 0.1, one fixed random seed. Each point is the average of the word's center and outside vectors, as the lecture suggests. The counts bar compares co-occurrence rows (Chapter 1).

Chapter 0

Every Word Is an Island

Store a word as one 1 among 500,000 zeros, and find that no two words are alike

Search for "Seattle motel". A page about a "Seattle hotel" is what you want. To a program that stores words as symbols, "motel" and "hotel" differ as much as "motel" and "fish".

The usual way to store a symbol is a one-hot vector. It is a list as long as the vocabulary: a 1 in the word's own position, 0 everywhere else. The lecture's example vocabulary has 500,000 words or more. So each word is a list of 500,000 numbers, and one of them is 1.

Now compare two words. The dot product of two lists multiplies matching entries and adds the products. For motel and hotel the 1s sit in different places, so every product is 0. That is true for every pair of different words. One-hot vectors hold no idea of "similar".

Search "Seattle motel" three ways

Six pages, four of them places to stay in Seattle. Pick how the program compares words, and watch the ranking change.

Illustrative toy. The pages, the synonym list and the vector cosines (hotel 0.81, inn 0.74, hostel 0.69 to motel) are ours. A page's score adds, for each query word, its best match among the page's words.

Here is the worked number, from the lecture's own example. Motel is [0 0 0 0 0 0 0 0 0 0 1 0 0 0 0]. Hotel is [0 0 0 0 0 0 0 1 0 0 0 0 0 0 0]. Fifteen products, all 0, so the dot product is 0. Each list has length 1, so the cosine is 0 / (1 × 1) = 0. Motel and fish also give 0.

Before word vectors, NLP leaned on resources that people wrote, such as WordNet: a thesaurus of synonym sets and "is a" links. The lecture lists its limits. It lists "proficient" as a synonym of "good", which is right only in some contexts. It misses new senses such as "wicked" or "ninja". It needs people to build and update it, and it gives no number for how similar two words are.

The way out is to put similarity into the vectors themselves. Give each word a short list of real numbers, learned from text, so that words used alike get lists that point alike.

Symptom: the search ranks "Seattle fish market tours" as high as "Seattle hotel near the pier".

Measure: with one-hot words, both pages share exactly one word with the query, "Seattle", so both score 1.

Fix: a synonym list helps only for the pairs someone wrote. Learned vectors give every pair of words a similarity.

The road

  1. Company: count each word's neighbours, compare the rows.
  2. Predict: word2vec scores neighbours with a dot product and a softmax.
  3. Objective: one number for how surprised the model is.
  4. Gradient: derive it by hand, observed minus expected.
  5. SGD: step downhill after every window.
  6. Negatives: k yes-or-no questions instead of a 500,000-way softmax.
  7. GloVe: count first, then fit vectors to the counts.
  8. Evaluate: analogies, human ratings, real tasks, bias.
  9. Showcase: train your own vectors and add your own sentences.
  10. Field guide: the methods, the numbers and the code.
Why can one-hot vectors not tell you that "motel" is closer to "hotel" than to "fish"?

Chapter 1

You Shall Know a Word by the Company It Keeps

Slide a window over the text, count the neighbours, and compare words by their rows of counts

The linguist J. R. Firth wrote in 1957: "You shall know a word by the company it keeps." The lecture calls this distributional semantics: a word's meaning comes from the words that often appear near it. Its example is "banking", seen in "turning into banking crises" and "unified banking regulation". Those neighbours describe banking.

To make "near" exact, fix a window of m words on each side. In "the furry cat slept" with m = 2, the neighbours of "cat" are "the", "furry" and "slept". For every word, count how often each other word falls inside its window, across the whole text. The table of counts is the co-occurrence matrix X. Row "cat" is a list of numbers, one per vocabulary word.

Count the company

Press Scan to slide the window over our twelve sentences. Teal counts fill three rows: cat, dog and car. Change the window size, or drop "the".

Illustrative toy: twelve sentences of ours, 16 words, 44 tokens. The same corpus trains the hero.

Two rows are alike if they point the same way. Call the two rows u and v. Multiply them entry by entry and add: that is the dot product, u · v. Divide by both lengths, ‖u‖ and ‖v‖:

Say it aloud

Cos of u and v equals u dot v, over the length of u times the length of v.

cos(u, v)
cos of u and v the cosine of the angle between two rows: 1 means the same direction, 0 means no overlap.
u · v
u dot v multiply matching counts of the two rows, then add the products.
‖u‖
the length of u the square root of u dot u.
‖v‖
the length of v the square root of v dot v.
In plain words

Multiply the two rows u and v entry by entry and add. Divide by both lengths, so that a frequent word and a rare word can still match.

With numbers

From the device with m = 2: row cat has the 3, fed 1, furry 1, slept 1, purred 1. Row dog is the same with barked for purred. u · v = 3 × 3 + 1 + 1 + 1 = 12. Each length is √13 = 3.61. So cos = 12 / 13 = 0.92: cat and dog keep nearly the same company, though they never meet.

Symptom: cat and car score 0.69, though one purrs and the other honks.

Measure: their rows share only "the", count 3 each. So u · v = 9 and cos = 9 / 13 = 0.69, all of it from one word. Drop "the" and cat and car score 0.

Fix: shrink the counts of frequent words: take logs, cap them, or drop the commonest words (Chapter 7). Word2vec learns its own weighting (Chapter 2).

Cat and dog never appear in the same sentence of the corpus, yet their count rows have a cosine of 0.92. Why?

Chapter 2

Word2vec: Predict the Neighbours

Give each word two vectors, score every outside word with a dot product, and turn the scores into probabilities

Counting stores a long row per word. Word2vec (Tomas Mikolov and colleagues, 2013) learns a short one instead, about 300 numbers, by making it predict the neighbours. It walks through the text. At each position t there is a center word c, and the words inside its window are the outside words o.

Every word gets two vectors. Call the word's vector vw when it is the center word, and uw when it is an outside word. Two vectors per word make the optimization easier; the lecture averages them at the end. To score how well outside word o fits center word c, take the dot product uo · vc. A large dot product means a likely neighbour.

Turn dot products into probabilities

The bold purple arrow is vcat, the center vector. Drag its tip. The blue bars are the probabilities of the three outside words.

Illustrative: three made-up outside vectors in 2 numbers, so you can see them. Real word2vec vectors have about 300 numbers and the softmax runs over the whole vocabulary.

Dot products can be any real number. To get probabilities, make each score positive with exp, then divide by the total over every word w in the vocabulary V. That is the softmax:

Say it aloud

P of o given c equals exp of u-o dot v-c, over the sum over w in V of exp of u-w dot v-c.

P(o | c)
P of o given c the model's probability that outside word o appears in the window of center word c.
exp(uo · vc)
exp of u-o dot v-c e to the power of the score of o. Any score becomes positive; a higher score becomes much larger.
Σw∈V
the sum over w in V add one term for every word in the vocabulary, so the probabilities add to 1.
uw
u-w the outside vector of word w, learned.
vc
v-c the center vector of word c, learned.
In plain words

Score every word w by u-w dot v-c. Raise e to each score. Divide the exp of o's score by the total of all of them. That fraction is P of o given c.

With numbers

From the device: vcat = (1, 0.5), ufurry = (1.5, 1), uthe = (0.5, 1), udrove = (0.5, −1). The scores are 2, 1 and 0. Their exps are 7.39, 2.72 and 1, total 11.11. So P(furry | cat) = 7.39 / 11.11 = 0.665, P(the | cat) = 0.245 and P(drove | cat) = 0.090.

This is the skip-gram model: predict each outside word from the center word. Word2vec also has CBOW (continuous bag of words), which predicts the center word from the average of its outside vectors. The lecture develops skip-gram, and so does this lesson.

Symptom: after some training, every probability prints as NaN.

Measure: one score reached 710. In 64-bit floats exp(709) is 8.2 × 10307 and exp(710) overflows to infinity; infinity divided by infinity is NaN.

Fix: subtract the largest score from every score before exp. The probabilities do not change, because the same factor cancels above and below.

In the softmax, what is the job of the sum in the denominator?

Chapter 3

The Objective: Average Surprise

Multiply the probabilities of every true neighbour, take logs, and get one number to make small

A good set of vectors gives high probability to the neighbours that occur. The text has T positions. At position t the center word is wt. The window holds the words wt+j, for j from −m to m, skipping 0. The likelihood of all the vectors, written θ, is the product of P(wt+j | wt) over every position and every window slot.

Products of many small numbers are awkward. A log turns the product into a sum. A minus sign turns "make large" into "make small". Dividing by T gives an average per position. The result is the objective, or loss:

Say it aloud

J of theta equals minus one over T, times the sum over t from 1 to T, of the sum over j from minus m to m, j not zero, of log P of w-t-plus-j given w-t.

J(θ)
J of theta the loss for all the vectors θ: every v and every u. Lower is better.
−(1/T)
minus one over T average over the T positions in the text, and flip the sign so the loss is positive.
Σt=1…T
the sum over t from 1 to T visit every position; the word there is the center word w-t.
Σ−m≤j≤m, j≠0
the sum over j from minus m to m, j not zero visit each slot of the window: m words left, m words right.
log P(wt+j | wt)
log P of w-t-plus-j given w-t the natural log of the softmax probability of the true outside word. Near 0 when the model expects it; far below 0 when it does not.
In plain words

Stand on each position t. For each true outside word in the window, look up its softmax probability and take the log. Add all the logs, divide by the number of positions T, and flip the sign. That is J.

With numbers

From the device, "the cat purred" has T = 3 and six window terms. With the random starting vectors every probability is near 1/16, the logs add to −16.2 and J = 16.2 / 3 = 5.39. After 40 training passes the logs add to −12.3 and J = 4.10.

Add up the surprise

Each row is one window term: a center word, a true outside word, its probability (blue) and its surprise, minus log P (pink). Press Step to add the terms one by one.

Illustrative toy: the hero's model, softmax over its 16 words. A loss of 6.55 per position is what a model that guesses every word equally would score on this corpus.

On the whole corpus, J falls from 6.57 to 4.92 in 40 passes. It cannot reach 0. "The" has many different neighbours, so even a perfect model must spread its bets. For this corpus the best possible J is 3.74.

Symptom: the likelihood of a large text prints as exactly 0.

Measure: our toy corpus already multiplies 104 probabilities: about 10−94 after training. A billion window terms would need 10 to the power of minus hundreds of millions, far below the smallest 64-bit float.

Fix: never form the product. Add logs instead, as J does.

Why does word2vec minimize the average negative log probability instead of maximizing the product of probabilities?

Chapter 4

The Gradient: Observed Minus Expected

Differentiate the softmax loss by hand, check it with a finite difference, and see why it pulls toward the true word

To lower J we need the gradient: for each number in vc, the direction that raises the loss fastest. Take the surprise of one true pair, −log P(o | c). Write the softmax inside the log, and the log of a fraction splits in two.

−log P(o | c) = −uo · vc + log Σw exp(uw · vc)

The first part's gradient is the other vector, −uo.

∂/∂vc log Σw exp(uw · vc) = (1 / Σw exp(uw · vc)) × Σx exp(ux · vc) ux

The chain rule gives the second part: 1 over the sum, times the gradient of the sum. The gradient of each exp term is that exp times ux. Each exp over the sum is P(x | c), from Chapter 2.

Put the two parts together:

Say it aloud

The partial of minus log P of o given c, with respect to v-c, equals minus u-o plus the sum over x of P of x given c times u-x.

∂(−log P(o | c)) / ∂vc
the partial with respect to v-c how this pair's surprise changes as each number in v-c changes.
−uo
minus u-o the observed part: the outside vector of the true outside word.
Σx
the sum over x one term for every word x in the vocabulary.
P(x | c)
P of x given c the model's current softmax probability for word x.
ux
u-x the outside vector of word x.
In plain words

Mix every outside vector u-x, each weighted by its probability P of x given c. That mix is the outside vector the model expects. Subtract the observed one, u-o. A step against the gradient moves v-c toward the observed vector and away from the expected one.

With numbers

The Chapter 2 example with o = furry: the expected vector is 0.665 × (1.5, 1) + 0.245 × (0.5, 1) + 0.090 × (0.5, −1) = (1.165, 0.820). Minus ufurry = (1.5, 1) gives the gradient (−0.335, −0.180). A finite difference with step 10−5 agrees to 10−11.

Follow the gradient one step

Pick the true outside word. Purple uo marks the observed vector, the blue ring the expected one, the dashed arrow the step. Press Step, then turn on the check.

Illustrative: the three made-up vectors of Chapter 2. Only vcat moves here; real training also moves every u by its own gradient.

The outside vectors get a gradient too. For the true word o it is (P(o | c) − 1) × vc; for every other word w it is P(w | c) × vc. For furry: (0.665 − 1) × (1, 0.5) = (−0.335, −0.167). Every u moves, so one softmax step costs a pass over the whole vocabulary.

Symptom: the loss goes up after every update.

Measure: a step of α = 0.5 along +gradient takes the surprise from 0.408 to 0.486. Along −gradient it falls to 0.341. A finite difference, (J(v + h) − J(v − h)) / 2h, shows which sign is right.

Fix: subtract the gradient. Check every hand-derived gradient with a finite difference once, on a tiny example.

The gradient of −log P(o | c) with respect to vc is −uo + Σx P(x | c) ux. When is it zero?

Chapter 5

Walking Downhill, One Window at a Time

Step against the gradient after every window, and find the learning rate that blows up

The gradient says which way is uphill. Gradient descent takes a small step the other way, then repeats. The step size is the learning rate, α.

Say it aloud

Theta-new equals theta-old minus alpha times the gradient with respect to theta of J-t of theta.

θnew
theta-new all the vectors after the step.
θold
theta-old all the vectors before it.
α
alpha the learning rate: how far to step. Our toy uses 0.1.
∇θ Jt(θ)
the gradient of J-t the direction that raises the loss of one window, at position t, fastest. Chapter 4 derived it.
In plain words

Pick a window t. Compute the gradient of its loss J-t. Multiply by alpha and subtract it from theta. Pick the next window and repeat.

With numbers

The Chapter 4 example with α = 0.5: vcat = (1, 0.5) − 0.5 × (−0.335, −0.180) = (1.167, 0.590). P(furry | cat) rises from 0.665 to 0.711, and the surprise falls from 0.408 to 0.341.

The full objective J averages over every window in the text: billions of them. Computing its gradient before each step would mean a long wait for one update. Stochastic gradient descent (SGD) updates after each window, with that window's gradient. Each step is noisy, but right on average.

Pick a learning rate

The pink curve is J after each pass over the twelve sentences. Pick a learning rate and a method. Try α = 1.

Illustrative toy: the hero's corpus and seed, softmax loss, 2 numbers per word. Grey lines: 6.55 (guess every word equally) and 3.74 (the best any model can do here).

The worked number for the whole corpus: 40 passes of SGD make 40 × 104 = 4,160 updates, and J falls from 6.57 to 4.92. Full-batch descent with the same α makes 40 updates, and J only reaches 6.52. Each SGD update also touches few rows: the center word's v, and in Chapter 6 only a handful of u's. Real libraries update those rows and leave the rest alone.

Symptom: the loss climbs, then prints as infinite.

Measure: with α = 1, J goes 6.57, 6.33, 7.44, 7.82, and reaches 31.5 by pass 9. With α = 0.3 it falls to 5.25, then bounces back to 5.57.

Fix: lower α until the curve falls smoothly. Many trainers also shrink α as training goes on.

Why does word2vec use stochastic gradient descent instead of computing the full gradient of J before each step?

Chapter 6

Negative Sampling: Real Pair or Noise?

Replace a sum over 500,000 words with a few yes-or-no questions, and draw the noise with a 3/4 power

The softmax's denominator sums over the whole vocabulary: with 500,000 words, 500,000 dot products per window term. So standard word2vec asks a different question: is this pair real, or noise?

For a true pair (c, o), draw k negative samples: random words that stand in for "not a neighbour". The sigmoid σ(x) = 1 / (1 + e−x) squashes a score into a probability. Push σ(uo · vc) toward 1 and each σ(uk · vc) toward 0. The lecture's loss:

Say it aloud

J-neg equals minus log sigma of u-o dot v-c, minus the sum over the sampled k of log sigma of minus u-k dot v-c.

Jneg
J-neg the loss for one true pair and its k noise words.
−log σ(uo · vc)
minus log sigma of u-o dot v-c the surprise at calling the true pair real.
Σk ∈ samples
the sum over the sampled k one term per noise word.
log σ(−uk · vc)
log sigma of minus u-k dot v-c the log chance of calling noise word k fake, since σ(−x) = 1 − σ(x).
In plain words

Take minus log sigma of the true pair's score, u-o dot v-c. For each noise word k, take minus log sigma of minus u-k dot v-c. Add the k + 1 terms.

With numbers

Chapter 2's vectors, with noise words drove (0.5, −1) and honked (−1, 0.5). True pair: σ(2) = 0.881, surprise 0.127. Drove: σ(0) = 0.5, surprise 0.693. Honked: score −0.75, σ(0.75) = 0.679, surprise 0.387. Jneg = 1.207, from three dot products.

Its gradient has Chapter 4's shape, with sigmoids for the softmax:

∂Jneg/∂vc = (σ(uo · vc) − 1) uo + Σk σ(uk · vc) uk = −0.119 × (1.5, 1) + 0.5 × (0.5, −1) + 0.321 × (−1, 0.5) = (−0.250, −0.459)

A finite difference agrees to 10−11. The update touches k + 2 rows, not 500,000.

Which words make good noise? Call U(w) a word's share of all tokens: its unigram probability. Word2vec draws noise from U to the 3/4 power, divided by a total Z:

Say it aloud

P-n of w equals U of w to the three-quarters, over Z.

Pn(w)
P-n of w the chance of drawing w as noise.
U(w)3/4
U of w to the three-quarters the word's share of the text, to the power 0.75. A power below 1 lifts rare words.
Z
Z the total of U to the three-quarters over all words, so the chances add to 1.
In plain words

Raise each word's share U of w to the power 0.75. Divide by the total Z. Draw noise words with those chances.

With numbers

From the device: "the" is 12 of our 44 tokens, U = 0.273, and Pn(the) = 0.198. "Honked" rises from 0.023 to 0.031. "The" was 12 times as likely as "honked"; now it is 6.4 times.

Draw the noise

Teal bars: each word's share of the text. Blue bars: its noise chance. Drag the power, then draw 200 noise words.

0.75

Illustrative toy: the 16 words of our corpus. Power 0 is a uniform draw, power 1 is raw frequency, 0.75 is word2vec's choice. The draws use a fixed seed per press.

Mikolov and colleagues use k = 5 to 20 for small datasets and 2 to 5 for large ones. With k = 5, a window term costs 6 dot products instead of 500,000.

Symptom: rare words barely move.

Measure: at power 1, "the" is 27% of draws in our toy.

Fix: the 3/4 power cuts "the" to 20% and gives rare words about a third more draws.

What does negative sampling replace, and why does that make word2vec fast?

Chapter 7

Count First, Then Fit: GloVe

Read meaning from ratios of co-occurrence probabilities, and fit word vectors to the log counts

Word2vec walks the text many times. The lecture asks: why not count once? Build the co-occurrence matrix X of Chapter 1. Then squeeze each row with the singular value decomposition (SVD), which keeps the directions that explain most of X. On raw counts this works badly, because "the" dominates. The lecture's fixes: take logs, cap counts near 100, ignore function words.

GloVe (Pennington, Socher and Manning, 2014) starts from ratios. Take "ice", "steam" and a probe word k. Divide the chance of k near ice by the chance of k near steam. "Solid" gives a large ratio and "gas" a small one. "Water" and "fashion" give about 1: they relate to both, or to neither.

Ask a probe word

Pick a probe word. Teal bars: how often it appears near ice and near steam. Blue marker: the ratio, on a log scale where 1 sits in the middle.

Real data: Table 1 of the GloVe paper, counted on a 6 billion token corpus. The paper's ratios come from unrounded probabilities, so 1.9 / 0.22 shows as 8.9, not 8.6.

GloVe asks a dot product of two word vectors, plus two learned offsets, to equal the log of their count. Then a difference of vectors matches a log ratio. Call Xij the count of word j near word i. Call wi and w̃j their vectors, and bi, b̃j their offsets, the biases. A weight f(Xij) stops huge counts from taking over:

Say it aloud

J equals the sum over i and j of f of X-i-j, times the square of w-i dot w-tilde-j, plus b-i plus b-tilde-j, minus log X-i-j.

J
J GloVe's loss: a weighted sum of squared errors.
Σi,j
the sum over i and j one term for each pair of words that co-occur at least once.
f(Xij)
f of X-i-j the weight: (X / 100) to the 0.75 below 100 counts, and 1 above.
wi · w̃j
w-i dot w-tilde-j the dot product of word i's vector and word j's context vector, both learned.
bi + b̃j
b-i plus b-tilde-j two learned offsets that absorb how common each word is.
log Xij
log X-i-j the natural log of how often j appears near i: the target.
In plain words

For every pair i, j with a count, predict log X-i-j as w-i dot w-tilde-j plus the two biases. Square the error and multiply it by the weight f of X-i-j. Add over all pairs, and adjust the vectors to make the total small.

With made-up numbers

A pair seen 20 times: log 20 = 3.00 and f(20) = (20 / 100)0.75 = 0.30. If the prediction is 2.0, the error is −1.0 and the term adds 0.30 × 1.0 = 0.30. A pair seen 1,000 times gets weight 1, not 50 times more.

GloVe trains on the counts, not on every window, so it scales to huge corpora.

Symptom: SVD to 2 numbers puts cat, dog and car at the same point.

Measure: on our corpus's raw counts, the top 2 directions mostly describe "the". Cat and car get identical coordinates, cosine 1.00.

Fix: drop "the" before the SVD: cat and car fall to −0.01, while cat and dog stay at 1.00. The lecture's fixes and GloVe's weight do this job.

Why does GloVe care about the ratio P(k | ice) / P(k | steam) rather than the raw counts?

Chapter 8

Are the Vectors Any Good?

Grade vectors on analogies and on human similarity ratings, then on a real task, and look for bias

The lecture splits evaluation in two. An intrinsic test grades the vectors on a small task of their own. It is fast and helps understanding, but it does not prove they help anywhere else. An extrinsic test plugs them into a real task and measures that task. If swapping in new vectors improves the task, they won.

The first intrinsic test is the analogy: man is to woman as king is to what? Take the vector king − man + woman and find the word with the largest cosine to it. The lecture stresses one detail: leave the three input words out of the search, or one of them often wins. Mikolov's 2013 test set holds 8,869 semantic and 10,675 syntactic questions of this kind.

The second test compares cosines with human ratings. In WordSim353, people scored 353 word pairs from 0 to 10: tiger and cat 7.35, stock and jaguar 0.92. A good set of vectors ranks the pairs in the same order. The score is Spearman's ρ, the correlation of the two rankings: 1 when the orders match, 0 when they are unrelated.

Grade vectors against people

Each dot is a word pair: yellow rating from people across, blue cosine up. Pick a vector set, or drag a dot up or down. ρ changes only when a dot passes another.

The nine pairs and their human ratings are the WordSim353 examples shown in the lecture. We made up the three sets of cosines to show the pattern; the page computes ρ live.

The worked number: for the made-up trained vectors, ρ = 0.93. For random vectors ρ = 0.18, and that is only because "tiger, tiger" has cosine 1 and the top rating. Raw counts give 0.48: every pair looks alike, because frequent words fill every row.

For an extrinsic test, the lecture uses named entity recognition: finding the person, organization or place in "Chris Manning lives in Palo Alto." Schnabel and colleagues (2015) found that different evaluations rank embedding methods in different orders. So test on the task you care about.

Symptom: vectors trained on news complete "man is to computer programmer as woman is to" with "homemaker".

Measure: that is the title result of Bolukbasi and colleagues (2016), on word2vec vectors trained on Google News. The vectors copy the text's patterns, biases included.

Fix: measure bias directions and reduce them, and choose training text with care. Neither removes bias fully.

Why do analogy tests leave the three input words out of the search?

Chapter 9

Showcase: Train Your Own Vectors

Choose the loss, the window and the size of each vector, add your own sentences, and watch word2vec learn

This is the hero's trainer, opened up. Every knob is a chapter: the window (Chapter 1), the softmax or negative sampling (Chapters 2 and 6), and the size of each vector. Click a word on the map to see its nearest neighbours by cosine.

Train word2vec on your sentences

Press Train. Click any word on the map to see its nearest neighbours. Then add a sentence of your own and train again.

Illustrative toy, trained live: 40 passes, learning rate 0.1, one fixed seed. With 8 numbers per word the map shows the two directions that hold most of the vectors (an SVD); the neighbour cosines use all 8 numbers.

Things to try. Train with 2 numbers and click "cat": dog ties with "furry" at the top, cosine 1.00. Add "the furry hamster slept" and "i fed the hamster", then train again: hamster lands on dog and cat, 1.00 each. Nobody told the model what a hamster is. Now reset, switch to negative sampling and train: cat's nearest words become car and bus, because two numbers cannot keep every group apart. Switch to 8 numbers and train again: car and bus leave cat's top four.

Check yourself. Why do context words such as "furry" land near "cat"? The plotted vector averages the word's center vector and its outside vector, and cat's outside vector must score high against furry's center vector. Why does the loss stop near 4.9 and never reach 3.74? Two numbers per word cannot hold every word's neighbour list.

Chapter 10

Field Guide

Keep the methods, the numbers, the code, and where the course goes next

One-hot vectors make every word an island. Distributional semantics says a word's meaning lives in its neighbours. Word2vec turns that into a prediction. Each word gets two vectors, a softmax over dot products scores the neighbours, and SGD lowers the average surprise J. The gradient is the expected outside vector minus the observed one.

Negative sampling swaps the vocabulary-wide softmax for k + 1 yes-or-no questions. GloVe fits vectors to log counts instead.

MethodWhat it fitsCost per window termWhere it breaks
One-hotnothing: one 1 per wordnoneno similarity at all
Count rows (+ SVD)co-occurrence counts Xone pass to count; SVD is costly for big Xfrequent words dominate raw counts
Skip-gram, softmaxP(o | c) for every true pairV dot products (500,000)too slow for a real vocabulary
Skip-gram, negative samplingreal pair or noise, by sigmoidk + 1 dot products (6 for k = 5)one vector per word, whatever its sense
CBOWcenter word from averaged outside wordsas skip-gram, one prediction per windowsame as skip-gram
GloVelog Xij, weighted least squaresone term per nonzero countone vector per word, whatever its sense
NumberValueWhere it came from
cos(cat, dog), count rows12 / 13 = 0.92Chapter 1, window 2
P(furry | cat)7.39 / 11.11 = 0.665Chapter 2, scores 2, 1, 0
J on the toy corpus6.57 to 4.92 in 40 passes; best 3.74Chapter 3
Gradient for vcat(−0.335, −0.180)Chapter 4, checked by finite difference
One SGD step, α = 0.5P(furry | cat) 0.665 to 0.711Chapter 5
Jneg, k = 21.207Chapter 6
Noise share of "the"0.273 at power 1, 0.198 at 3/4Chapter 6
Solid ice/steam ratio8.9GloVe paper, Table 1

The core of word2vec as code: skip-gram with negative sampling, using the gradients of Chapter 6. We ran it on the twelve sentences.

python
import numpy as np
rng = np.random.default_rng(0)

sents = ["i fed the cat", "i fed the dog", "the furry cat slept", "the furry dog slept",
         "the cat purred", "the dog barked", "i drove the car", "i drove the bus",
         "the fast car stopped", "the fast bus stopped", "the car honked", "the bus braked"]
vocab = sorted({w for s in sents for w in s.split()})
idx = {w: i for i, w in enumerate(vocab)}
pairs = [(idx[ws[i]], idx[ws[j]]) for s in sents for ws in [s.split()]
         for i in range(len(ws)) for j in range(len(ws)) if i != j and abs(i - j) <= 2]

counts = np.bincount([idx[w] for s in sents for w in s.split()])
noise = counts ** 0.75; noise /= noise.sum()     # P_n(w) = U(w)^(3/4) / Z
sig = lambda x: 1 / (1 + np.exp(-x))

d, k, lr = 8, 3, 0.1
V = rng.normal(0, 0.3, (len(vocab), d))           # center vectors v
U = rng.normal(0, 0.3, (len(vocab), d))           # outside vectors u
for epoch in range(200):
    for n in rng.permutation(len(pairs)):
        c, o = pairs[n]
        negs = rng.choice(len(vocab), size=k, p=noise)
        vc = V[c].copy()
        g_pos = sig(U[o] @ vc) - 1                    # sigma(u_o.v_c) - 1
        g_neg = sig(U[negs] @ vc)                        # sigma(u_k.v_c), one per noise word
        V[c] -= lr * (g_pos * U[o] + g_neg @ U[negs])     # dJ/dv_c from Chapter 6
        U[o] -= lr * g_pos * vc
        np.subtract.at(U, negs, lr * np.outer(g_neg, vc))

cos = lambda a, b: a @ b / np.linalg.norm(a) / np.linalg.norm(b)
print(round(cos(V[idx["cat"]], V[idx["dog"]]), 2), round(cos(V[idx["cat"]], V[idx["car"]]), 2))   # 0.77 0.29

Where the course goes next. Lecture 3 builds neural networks and backpropagation: the chain rule of Chapter 4, applied to many layers. Later lectures give each word a different vector in each sentence, which fixes the one-vector-per-word limit of the table.

Keep going

Read next

The habit. For any word vector, ask which neighbours it was trained to predict. Two words that keep the same company will end up alike, whether or not they mean the same thing.
Which sentence best sums up how word2vec learns word vectors?

Now teach it: press Present or Teach. Derive the softmax gradient on a whiteboard and say why it equals expected minus observed. Then go back to the training slider, pick cat and car, and predict where the cosine ends before you drag.

Word Vectors · Stanford CS224N, Lecture 2
Before: History of NLP · Next: Neural Networks · Course site · Back to Gleams