A word is just a label
How could a computer ever know that chai is like coffee?
A new shopkeeper opens a stock register. He gives every item a code number: 1 is chai, 2 is coffee, 3 is a cricket bat.
Is 2 "closer" to 1 than 3 is? No. The numbers are just labels. They say nothing about what the items are. Chai and coffee are both hot drinks, but the register cannot know that.
A computer sees words the same way. To a computer, "chai" is just a label. Our job in this unit is to turn every word into numbers that carry its meaning.
First, what counts as a word? Before a computer can count anything, it cuts the text into pieces called tokens. Often everything is lower-cased first, so that "Chai" and "chai" count as one word. Punctuation becomes a token of its own. And we add two markers to every sentence: at the start and at the end. They mean "a sentence starts here" and "a sentence stops here", and §2 will need them. So I drink chai. becomes
<s> I drink chai . </s>
(We keep "I" as a capital so the examples read naturally.) Modern language models go one step further and cut rare words into smaller pieces; §16 shows how.
Now the simplest way to turn a word into numbers: give each word its own slot. Take a tiny vocabulary of three words — chai, coffee, cricket. Each word becomes a list of three numbers with a single 1 in its own slot:
A list of zeros with a single 1 is called a one-hot vector. With a real vocabulary of 50 000 words, each list is 50 000 numbers long: one 1 and 49 999 zeros.
Now measure how alike two words are, the way Unit 3 taught us: with the dot product. Multiply slot by slot and add:
Chai with cricket? Also 0. Every pair of different one-hot words has dot product 0: they all stand at right angles to each other. And every pair is the same distance apart: . In one-hot land, chai is exactly as far from coffee as it is from cricket.
A phone directory gives every person a line of their own. It tells you who exists, but not who lives near whom. One-hot lists are a directory: every word on its own line, every pair equally far apart, no neighbourhoods.
A city map is different. People who live near each other are drawn near each other, and a neighbourhood has a character — the market, the stadium, the station. We want a map of words: tea words in one neighbourhood, cricket words in another, so that on the map close means similar. This whole unit is about turning the directory into the map.
Why not just number the words 1, 2, 3, like the shopkeeper? Because that is worse than one-hot: it invents an order that isn't there. The computer would believe coffee (2) sits halfway between chai (1) and cricket (3), and that chai + cricket = 2 × coffee. One-hot at least tells no lies — it just tells nothing.
One-hot lists put every word at right angles to every other word, all the same distance apart. They tell words apart, but they cannot say "these two are alike". We want short lists where close means similar. The rest of this unit is about finding them.
With a vocabulary of 10 000 words written one-hot, what is the dot product of "chai" and "coffee", and how far apart are they?
The shopkeeper adds a fourth word, "tea", to the one-hot vocabulary. Which of the old words does tea land closest to?
If you want the algebra · 1 proof, step by step
Claim. For one-hot vectors and with : and , whatever the vocabulary size .
The road ahead. The unit has five acts.
- A word is just a label (§1) — the directory we start from.
- Guessing the next word by counting (§2–§4): a sentence as a chain of guesses, what to do about words never seen, and how to score a guesser by its surprise — its perplexity.
- Meaning from the company a word keeps (§5–§7): count the company, weigh it (TF-IDF and PMI), and squeeze it with the SVD from Unit 5.
- Stop counting, start predicting (§8–§14): word2vec's two games, CBOW and skip-gram; how to make them cheap; why counting and predicting arrive at the same answer; and a small neural language model.
- The geometry of meaning, and its limits (§15–§17): king − man + woman, words with two meanings, words cut into pieces, and the road to Units 17 and 18.
In one sentence: A one-hot list is a phone directory — every word on its own line, every pair at right angles and apart — so it names words but carries no meaning; we want a city map, where close means similar.
A sentence is a chain of guesses
How does your phone's keyboard know what you are about to type?
You type "good" and the keyboard offers "morning". It has seen you — and millions of others — type "good morning" again and again. It simply remembers what usually comes next.
Now play a game with a friend. You say a sentence one word at a time, and before each word she guesses what comes next. "I…" — "drink?" — "drink…" — "chai?" A whole sentence is just a chain of guesses.
That game is exactly how a language model scores a sentence. The chance of the whole sentence is the chance of the first word, times the chance of the second word given the first, times the chance of the third given the first two, and so on. This is the chain rule of probability:
Read it aloud: a sentence is a string of guesses, and each guess is allowed to use everything that came before it. Nothing is approximated yet. The rule is exact.
The trouble is the history. To know the chance of chai after every morning my grandfather drinks a hot cup of, we would need to have seen that exact history many times. Long histories almost never repeat, so we cannot count them.
So we make a bold simplification, called the Markov assumption: the guesser keeps only the last few words and forgets the rest. It is a guesser with a short memory. If it remembers one word, it is a bigram model ("bi" = two words at a time); if it remembers two, a trigram model; in general, remembering words makes an N-gram model:
Now count. Here is a tiny collection of text — people call such a collection a corpus — with the sentence markers added:
<s> I drink chai </s> · <s> I drink coffee </s> · <s> I drink chai </s> · <s> I play cricket </s>
"drink" is followed by chai twice and by coffee once. So the best guess for what follows "drink" is to split the chances the same way:
This "count ÷ total" is not a guess about guessing. It is the maximum-likelihood answer of Unit 14: a coin that showed 7 heads in 10 tosses is best described by , and a word followed by chai 2 times out of 3 is best described by .
Now score a whole sentence by multiplying the guesses along the chain. The start marker gives the first word a history too: its guess is , "how often does a sentence start with I?"
Why the end marker matters. is a word the model must guess, so the model learns when to stop. Without it, the half-sentence "I drink" would score — more than any complete sentence — and the chances of all sentences would add up to more than 1. With it, every sentence must pay for its ending, and the chances of all possible sentences add up to exactly 1.
And the model can write. Start at , roll a loaded die whose faces are the next words and whose weights are their chances, write down the face, and repeat until comes up. Claude Shannon wrote sentences this way, by hand, in 1948.
Because language repeats itself. The same short chains of words — "drink chai", "play cricket", "good morning" — come back again and again, so their counts are reliable even when whole sentences never repeat. Cutting the memory to one or two words trades a little accuracy for counts we can actually trust.
A bigram model has no idea what came two words back. In "The train to Delhi from platform four is ___", it sees only "is" — the train, Delhi and the platform are all forgotten. Every bit of memory you give up is context the model can never use. (Units 17 and 18 are about getting that memory back.)
A sentence is a chain of guesses. The chain rule is exact; the Markov assumption shortens each guess's memory so that we can count; counting is the maximum-likelihood guess; and the markers , let the chain start and stop.
With the four-sentence corpus, what probability does the bigram model give to I play cricket ?
The bigram model reads "you drink" — and "you" never appears in its corpus. What does it guess for the next word?
If you want the algebra · 2 proofs, step by step
Claim. For any three words, — and the same peeling works for any number of words.
Claim. After a word , the next words were seen with counts (total ). The probabilities that make the seen text most likely are .
In one sentence: A sentence is a chain of guesses — the chain rule multiplies them exactly, the Markov assumption gives the guesser a short memory so we can count, and count ÷ total (with <s> and </s>) gives <s> I drink chai </s> the chance 1 · ¾ · ⅔ · 1 = ½.
Never seen is not impossible: smoothing
If two words never appeared side by side in our text, is that pair really impossible?
A new chaiwala opens a stall near your office. You have never bought tea from him. Does that make it impossible that you ever will? Of course not.
"Never seen" is not "impossible". A counting model has to learn that lesson.
The zero problem. What does our bigram model say about "I drink cricket"? The pair "drink cricket" was never counted, so its chance is 0 — and one zero in the chain makes the whole sentence 0. With real text most possible pairs are never seen, so this happens all the time. Worse, in §4 a single zero will make the model's score infinitely bad.
Fix 1 · one free ticket for every pair. Pretend every possible next word was seen one extra time. This is add-one (or Laplace) smoothing. After "drink" the possible next words are the 7 words that can come next — I, drink, chai, coffee, play, cricket and — so the row gains 7 extra counts:
No zeros any more. The price: the words we really saw lost some of their share. Chai fell from 0.667 to 0.3.
With a real vocabulary, add-one gives away almost everything. With possible next words, the row for "drink" gets 50 000 free tickets and only 3 real ones:
The two real sightings are drowned. Almost all the probability now sits on words that never once followed "drink".
Fix 2 · smaller tickets. Give each unseen pair a fraction of a ticket instead of a whole one: , called add-. It helps, but somebody has to choose .
Fix 3 · ask several advisers. Planning a trip, you might ask a friend who went there last month (specific, but little experience) and a travel agent (general, but lots of experience), and blend their advice. Interpolation does the same with a trigram, a bigram and a unigram model (which ignores the history and just knows how common each word is), mixing their guesses with weights that add up to 1.
Worked example: blend the bigram with weight 0.8 and the unigram with weight 0.2. The unigram adviser counts every token that can come next — everything except the markers, 16 tokens in all: I 4, drink 3, chai 2, coffee 1, play 1, cricket 1, 4. So
Cricket is no longer impossible, and chai still leads by far.
Fix 4 · backoff. Ask the specialist first. If the specialist has never seen this history, back off and ask the generalist: use the trigram if it has counts, else the bigram, else the unigram. (The borrowed chances are scaled down a little so that each row still adds up to 1.)
Each fix keeps the row adding up to 1, so probability is never created — only moved. Add-one and add- move it evenly to every unseen word, which is fair only when the vocabulary is small. Interpolation moves it where the general evidence points: an unseen pair gets a share in proportion to how common the word is overall, while the history still decides whenever it has something to say.
Smoothing moves a little probability from what was seen to what was not, so that "never seen" stops meaning "impossible". Add-one is the simplest move and drowns real counts in a big vocabulary; interpolation and backoff move the probability sensibly, by asking a more general adviser.
With add-one smoothing (7 possible next words), what is ?
You keep add-one smoothing, but the vocabulary grows from 7 words to 50 000. What happens to ?
In the interpolation , set . What does the model become?
If you want the algebra · 2 proofs, step by step
Claim. With add-one smoothing, , and these numbers add up to 1.
Claim. If and each add up to 1 over the next words, then so does for any — and if , every word with gets a chance above 0.
In one sentence: Smoothing moves a little probability from pairs we saw to pairs we didn't — add-one does it evenly and drowns real counts in a big vocabulary (3/50 003), while interpolation and backoff ask a more general adviser (0.8 · ⅔ + 0.2 · 2/16 = 0.558).
How surprised is the model? Perplexity
Two keyboards both guess your next word. How do you decide which one is better?
At the railway station the speaker says: "The train to Delhi is running…". Before the next word comes, you already guess "late". If it is "late", you are not surprised at all. If it is "early", you are very surprised.
A good language model is one that is rarely surprised by real text.
In Unit 14 we measured surprise. If the model gave the word that really came next a probability , its surprise is bits. Probability → 1 bit. Probability → 2 bits. Probability 1 → 0 bits: no surprise at all.
Let a model read four words of real text. It gave the words that really came next these probabilities: . The surprises are 1, 2, 1 and 3 bits, and the average surprise is
This average is the cross-entropy of Unit 14. It is hard to feel what "1.75 bits" means, so we turn it back into a number of choices:
This number is the perplexity. Here is the picture to keep: how many sides does the model's die have? On average, this model was as unsure as someone rolling a fair die with about 3.4 faces. Lower is better. A perfect model has perplexity 1 — a die with one face.
Our bigram model scoring I drink chai made four guesses (I, drink, chai and ) whose product was . So its perplexity on that sentence is
That is a die with barely more than one face — no surprise, since the model is being tested on a sentence it was counted from.
A model that knows nothing spreads its guess evenly over a vocabulary of words and gives every word . Its surprise is every time, so its perplexity is exactly : a fair die with faces. That is the worst sensible score, and a useful yardstick. A model with perplexity 120 on a 50 000-word vocabulary has narrowed each guess from 50 000 choices to about 120.
Perplexity averages surprises, which are logs, so it is really a geometric mean of the probabilities, turned upside down. That makes it strict: a word the model thought nearly impossible adds a huge surprise that no number of easy words can cancel. A model with low perplexity has to be reasonable about every word, not just most of them — which is also why smoothing (§3) matters so much.
Perplexities can only be compared on the same test text with the same vocabulary. Children's stories are easier to predict than legal documents, and a model with a 5 000-word vocabulary has a smaller die to begin with than one with 50 000 words. A lower number from a different test is not a better model. And always test on text the model was not counted from — our 1.189 above flatters the model for exactly that reason.
Perplexity is the average surprise turned back into a number of equally likely choices — the number of faces on the model's die. It is 1 for a perfect model and for a model that guesses evenly over words. One word the model thought nearly impossible can ruin it, so a good model never says "impossible".
A model gives each of four real next words probability 0.5. What is its perplexity?
A model with no knowledge guesses evenly over a vocabulary of 10 000 words. What is its perplexity on any text?
Model A scores perplexity 120 on newspaper text. Model B scores 90 on children's stories. Which is the better model?
If you want the algebra · 2 proofs, step by step
Claim. , and the answer is the same if you use natural logs and instead of and 2.
Claim. A model that gives every one of words probability has perplexity exactly on any text.
In one sentence: Perplexity is 2 raised to the average surprise in bits — the number of faces on the model's die — so 1 is perfect, is knowing nothing, 0.5 · 0.25 · 0.5 · 0.125 gives about 3.364, and it only compares models tested on the same text.
You shall know a word by the company it keeps
How can you learn what a word means without ever opening a dictionary?
You hear a word you do not know: "kadak". Then you hear it used: "a cup of kadak chai", "I like my chai kadak", "kadak and sweet, please". You still have no dictionary. But you already know it has something to do with strong tea.
You learned the word from its neighbours. The linguist J. R. Firth put it in one line in 1957: "You shall know a word by the company it keeps."
The counting of Act II only asked "what comes next?". Now we ask a wider question: "what is around?". There are two classic ways to write the company down in a table.
1 · Word × document. Rows are words, columns are documents, and each box counts how often the word appears in that document. A row answers "which documents talk about this word?". This term–document table is how search engines began: to answer the query "chai", look along the row for chai.
2 · Word × word. Rows are the words we want to understand (the targets), columns are neighbour words, and each box counts how often the neighbour appears within a few words of the target. How many words either side count as "near" is the window size. With a window of 2, here is the table from a small made-up corpus (the widget shows its sentences):
| drink | hot | play | match | |
|---|---|---|---|---|
| chai | 5 | 4 | 0 | 1 |
| coffee | 4 | 5 | 0 | 0 |
| cricket | 0 | 0 | 5 | 4 |
| football | 0 | 1 | 4 | 5 |
This is a co-occurrence matrix: "how often do these two words occur together". Read each row as a vector. Chai is , coffee is , cricket is . These are our first real word vectors, and they are no longer one-hot: chai and coffee share neighbours, so their rows look alike.
How alike? Use the angle between the rows, from Unit 3:
For chai and coffee the dot product is , and the lengths are and . So
For chai and cricket the dot product is only , so the cosine is . Cricket and football give again. The tea words point almost the same way, the sport words point almost the same way, and the two groups are nearly at right angles.
Why the angle and not the length? A word used ten times as often has counts ten times as big — a longer arrow — but the same kind of company. The cosine ignores the length and keeps only the direction: which company a word keeps, not how often it talks.
Because words that mean similar things are used in similar places. Chai and coffee both sit after "drink" and "hot"; cricket and football both sit near "play" and "match". Similar use gives similar rows, and similar rows point the same way. And the window size decides the kind of similarity. A small window (one or two words) finds words that can replace each other in a sentence — chai and coffee both fit "a cup of hot ___". A big window, like a whole document, finds words about the same topic — chai, kettle and cup live in the same documents even though "a cup of hot kettle" makes no sense.
"Similar" is not "means the same". Good and bad keep almost identical company ("a ___ day", "a very ___ idea"), so their rows are close — yet they are opposites. Company tells you a word's kind and topic; it cannot always tell you which way round the meaning goes.
A word's row in a company table is a first, honest word vector. Words used in the same places get rows that point the same way. We did not tell the computer that chai and coffee are drinks — the counts told it. Small windows find stand-ins, big windows find topic-mates.
From the table, what is the cosine between coffee and football ?
Suppose chai were twice as common, so its row became . What happens to its cosine with coffee?
You widen the window from two words to a whole paragraph. Which pair becomes more alike?
If you want the algebra · 1 proof, step by step
Claim. For any numbers : .
In one sentence: Count the company a word keeps — by document or by neighbours within a window — and each row becomes a word vector whose angle to another row says how alike their company is: 0.964 for chai and coffee, 0.096 for chai and cricket, stand-ins with small windows, topic-mates with big ones.
Not all company counts: TF-IDF and PMI
"The" sits next to chai more often than any other word. Does that make "the" the best clue to what chai means?
Two people are seen together at the market. If both of them go to the market every single day, meeting there means nothing — they would bump into each other anyway. But if both rarely leave home and yet keep turning up at the same stall, that means a lot.
A meeting only tells you something when it happens more often than chance would explain.
Raw counts reward words that are everywhere. "The", "is" and "a" sit next to every word and appear in every document, so they swamp both of our tables. We need to weigh each count by how surprising it is. There is one standard fix for each table.
For the term–document table: TF-IDF. Give each count a weight
Read it aloud: tf, the term frequency, is how often the word appears in this document. df, the document frequency, is how many of the documents contain the word at all. The log part, the idf, is large for rare words and exactly 0 for a word that is in every document, because .
Take three documents. D1 has "the" 3 times, "chai" twice and "hot" once. D2 has "the" twice and "cricket" three times. D3 has "the", "chai" and "cricket" once each. Then
- "the" is in all 3 documents: idf .
- "chai" and "cricket" are in 2 of 3: idf .
- "hot" is in 1 of 3: idf .
So in D1, chai weighs , hot weighs , and "the" weighs despite being the most frequent word. In D2 cricket weighs ; in D3 chai and cricket weigh 0.176 each. A word that is in every document says nothing about any one of them.
For the word × word table: PMI. Ask how many times more often two words meet than two strangers would by chance. If chai and "hot" had nothing to do with each other, they would meet with probability (independence, Unit 14). So compare the real meetings with that:
This is the pointwise mutual information. Worked example, with counted pairs: chai meets hot 8 times, "the" 10 times and "match" 2 times; cricket meets hot 2 times, "the" 10 times and "match" 8 times. Add up the rows and columns first. Chai and cricket each take part in 20 of the 40 pairs; hot in 10, "the" in 20 and match in 10. So , , , , and :
Raw counts said "the" was chai's biggest neighbour (10 meetings). PMI says it tells us nothing: chai meets "the" exactly as often as chance predicts. Negative values mean "meet less often than chance", and they are noisy with small counts, so people usually keep only the positive part, .
Chance alone would already put common words next to everything. Dividing by what chance would give — for PMI, the share of documents that contain the word for IDF — cancels the part of a count that is just popularity, and leaves the part that is about this pair. What survives is company that is actually informative.
PMI over-rewards rare pairs. In a corpus of a million pairs, two words that each appear once, and appear together, get bits — the biggest number in the table, from a single sighting that may be a typo. That is why people ignore very rare words, or gently raise the counts of the neighbour words to a power below 1, such as 0.75 (the same trick returns in §12).
Not all company counts. Weigh each meeting by how much more often it happens than chance would allow: PMI for pairs of words, TF-IDF for words in documents. A neighbour that is everywhere, like "the", gets weight 0.
A word appears in every one of 1 000 documents — 50 times in one of them. What is its TF-IDF weight in that document?
With the same 40 pairs, cricket meets hot 2 times. What is , and what is its PPMI?
Two rare words each appear once in a million counted pairs — and that one time, they appear together. What does PMI say about them?
If you want the algebra · 2 proofs, step by step
Claim. With meetings out of counted pairs, row total and column total : — the count divided by what chance alone would give, .
Claim. If a word appears in all documents, its TF-IDF weight is 0 in every document, however often it appears.
In one sentence: Weigh company by surprise, not by size — PMI gives chai–hot 0.678 and chai–the exactly 0, and TF-IDF gives any word found in every document the weight 0 — but beware rare pairs, which PMI over-rewards.
Squeeze the table: the SVD finds friends of friends
In our text, chai and tea never share a single neighbour. Can the machine still discover that they are alike?
A school gives a long survey with 100 questions. When the teacher reads the answers, she notices that most of them can be summed up in two scores: "loves sport" and "loves music". Two numbers per student say almost everything the 100 answers say.
A company table is like that survey. It is huge, but most of what it says fits in a few numbers per word.
A real table has one row for every word and one column for every neighbour word: 50 000 × 50 000, mostly zeros. Rows that long are clumsy. We want short rows that keep the pattern and drop the noise.
The tool is the SVD from Unit 5. It writes any matrix as : a turn, a stretch by the singular values , and another turn. Big singular values are the strong patterns; small ones are mostly noise. Keep only the top and you get the best rank- copy of the table (Unit 5's layer cake). Each word's new, short vector is its row of .
For our 4 × 4 table of §5 the singular values are : two big, two small. Measure a table's "energy" as the sum of the squares of all its entries — here , which also equals . The top two keep
of the energy, and rebuilding the table from just those two leaves an error of — small next to entries of 4 and 5. Each word now gets two numbers:
(The SVD may flip the sign of any direction, so another program may print some of these with the opposite sign; the angles do not change.) The first number is about 5 for every word: it says "this word is used a lot". The second is the interesting one: negative for tea, positive for sport. In two numbers, and . The squeeze made the tea words even more alike — it threw away the noise that kept them apart.
Weigh first, then squeeze. On real text, run the SVD on the PPMI table of §6, not on raw counts. Otherwise the loud columns like "the" take over the first direction, and it only says "how common is this word".
Now the surprise: friends of friends. Here is a new table with seven neighbour words:
| drink | hot | cup | kettle | play | match | bat | |
|---|---|---|---|---|---|---|---|
| chai | 4 | 4 | 0 | 0 | 0 | 0 | 0 |
| tea | 0 | 0 | 4 | 4 | 0 | 0 | 0 |
| coffee | 3 | 3 | 3 | 3 | 0 | 0 | 0 |
| cricket | 0 | 0 | 0 | 0 | 4 | 4 | 0 |
| football | 0 | 0 | 0 | 0 | 0 | 4 | 4 |
Chai and tea never share a single neighbour, so their raw cosine is exactly 0. But coffee shares neighbours with both of them. The singular values are , , , and , so the energy kept is 41.5% at , 70.7% at and 90.2% at .
Squeeze to . The words get the coordinates chai , tea , coffee , cricket , football . Chai and tea now sit on the very same line: . Coffee, a friend of both, made them friends. The rebuilt table even fills in the blanks: it gives chai a count of 2 next to cup and next to kettle, words it never met — because coffee meets them.
Keep one more direction, , and the new direction gives chai and tea : it records exactly what makes them different. The cosine drops back to 0. Squeeze enough and hidden friendships appear; keep everything and you keep the differences too. Using the SVD this way on a word–document table is called latent semantic analysis (LSA) — "latent" because it finds similarities that no single count shows.
The squeeze keeps only the few directions that explain the most counts. A direction is shared by groups of words and groups of neighbours, so it cannot fit chai's two neighbours and tea's two neighbours separately — it fits "the drink neighbours" as one block, because coffee connects the two halves. Words that only reach each other through a friend get pulled onto the same direction. The detail that tells them apart lives in a weaker direction, and a small throws it away.
A bigger is not always better. too small, and different topics are squashed together; too large, and you keep the noise and the small differences, so hidden friendships vanish again. For words people usually keep a few hundred directions out of tens of thousands. And the sign of each direction is arbitrary — never read meaning into a minus sign on its own.
The SVD finds the few strong directions hiding in a big table of counts. Keep those, drop the rest, and each word gets a short list of numbers; the energy kept, , tells you how much of the table survived. Because each direction is shared by whole groups of words, the squeeze also finds friends of friends.
A table has singular values . What share of the energy do you keep with ?
A table has singular values . You keep . How big is the rebuild error (Frobenius)?
In the friends-of-friends table, chai and tea have cosine 1 at . What happens to their cosine at ?
If you want the algebra · 3 proofs, step by step
Claim. For any matrix , the sum of the squares of all entries equals .
Claim. Keeping the top terms, , leaves an error of size , and no other rank- matrix does better.
Claim. In the friends table, is the top direction, with ; chai and tea both get the coordinate 4 on it (coffee gets 6). The direction has and gives chai , tea .
In one sentence: The SVD squeezes a company table to its top directions (98.5% of our 4 × 4 table at ), and because each direction is shared by groups of words it finds friends of friends — chai and tea, who never meet, get cosine 1 at through coffee, and 0 again when keeps their difference.
From counting to predicting: the word2vec idea
Counting worked. So why did the people who built word2vec stop counting?
A new teacher joins a school and wants to know which children are friends. She could keep a register: every lunch, for a whole year, write down who sat next to whom. At the end she owns a giant table.
Or she could play a game. Each lunch, before the children sit down, she guesses who will sit next to whom, and she corrects herself whenever she is wrong. After a month she has no register at all — but she knows the friendships. The knowledge lives in her head.
Acts II and III kept the register. The company table of §5 has a row and a column for every word: with 50 000 words that is 2.5 billion boxes, almost all of them zero. New text means counting again, and squeezing such a table with the SVD (§7) is heavy work.
In 2013 Tomas Mikolov and his team at Google played the teacher's game instead. Their method is called word2vec, and its motto could be: don't write down the gossip — train a guesser, then read its mind.
Here is the game. Slide a window along the text, one word at a time. The word in the middle is the centre word. The words up to places on either side are its context. At every stop the machine plays one of two games:
- Fill in the blank. Hide the centre word and guess it from the context. This game is called CBOW (§9).
- Guess the neighbours. Show the centre word and guess each context word. This game is called skip-gram (§10).
Take we drink hot chai every morning with , and stop at "hot". Its context is we, drink, chai, every. CBOW makes one example from this stop: (we, drink, chai, every) → hot. Skip-gram makes four pairs: hot → we, hot → drink, hot → chai, hot → every.
Now count over the whole sentence. CBOW makes one example at each of the 6 stops: 6 examples. Skip-gram makes one pair per neighbour, and the words near the ends have fewer neighbours: pairs. Keep that ratio in mind. It is the whole difference in cost between the two games (§11).
One small network plays both games. It is made of just two tables of numbers, and it works in four moves.
- Look up. Every word owns a row in the input table , which has rows of numbers. The row of word is its input vector . Feeding a one-hot word into the table simply picks out its row (§14 shows why).
- Form one opinion, . CBOW averages the rows of the context words. Skip-gram just takes the centre word's row. Either way is a list of numbers.
- Score every word. Every word also owns a column in the output table , its output vector . Its score is the dot product — how well it lines up with the opinion (Unit 3).
- Turn scores into chances with a softmax over the whole vocabulary (Unit 14), and learn from the surprise at the true word.
Read the shapes along the way: . With words and , every word has to squeeze through a doorway only 300 numbers wide.
Because the doorway is narrow. The network cannot keep a separate answer for each of 50 000 words — it has only numbers per word. So words that must make the same guesses get pushed into nearly the same rows. Chai and coffee are guessed from the same neighbours and guess the same neighbours, so the only way to play well is to give them almost the same vectors. It is the same squeeze as the SVD of §7 — done by a guessing game instead of a formula.
word2vec is not a deep network. There is no bend in the middle: is just a looked-up row, or an average of rows. All the learning lives in the two tables. And only one of them is the prize: after training we throw the game away and keep the input table. Its rows are the word vectors.
word2vec replaces counting with guessing. A window slides along the text. At each stop a tiny two-table network either fills in the centre word from its context (CBOW) or guesses the context from the centre word (skip-gram). The guessing is only a test. What we keep is the input table, whose rows were forced to put words with the same company close together.
A sentence has 5 words and the window is . How many examples does CBOW make, and how many pairs does skip-gram make?
Training is over. Which part of the word2vec network do we keep as the word vectors?
If you want the algebra · 1 proof, step by step
Claim. A sentence of words (with ) and a window of words on each side give CBOW examples and skip-gram pairs.
In one sentence: word2vec slides a window along the text and trains a tiny two-table network to guess each centre word from its neighbours (CBOW) or the neighbours from the centre word (skip-gram), then keeps the input table as the word vectors — don't write down the gossip, train a guesser and read its mind.
CBOW: the committee fills in the blank
How could a game of fill-in-the-blank teach a computer that chai is like coffee?
The teacher writes on the board: "Every morning my grandfather drinks a hot cup of ____." Nobody asks what the missing word is. "Chai," says the whole class.
You did not look anything up. The words around the blank — drinks, hot, cup — each pointed somewhere, and together they pointed at one word. A committee of neighbours voted on the blank.
That game — fill in the blank from the words around it — is the first way word2vec learns. It is called CBOW, the continuous bag of words.
Let us play one round by hand. We use a toy model with a vocabulary of five words and vectors of just numbers, so that every step fits on paper. We chose the starting numbers by hand to keep the arithmetic clean; a real model starts from small random numbers.
| word | input vector | output vector |
|---|---|---|
| we | (0, 1) | (0, 0) |
| drink | (1, 0) | (1, 0) |
| chai | (1, 1) | (1, 1) |
| daily | (0, 1) | (0, 1) |
| cricket | (−1, 0) | (−1, −1) |
Take the tiny sentence we drink chai daily, use a window of one word on each side, and hide the middle word, chai. The committee is drink and daily. The machine plays in four moves.
- Look up the neighbours. Their input vectors are drink = (1, 0) and daily = (0, 1).
- Average them. . This single point is the committee's combined opinion.
- Score every word. Dot each output vector with : we 0, drink 0.5, chai 1, daily 0.5, cricket −1.
- Turn scores into a guess. The softmax gives 0.135, 0.223, 0.368, 0.223, 0.050. The true word is chai, so the surprise is .
Written as formulas, the four moves are:
Read them aloud. The first line asks the committee for its average opinion. The second gives every word in the vocabulary a score: how well its answer-arrow lines up with that opinion. The third turns the scores into chances that add up to 1. The fourth measures how surprised the model was by the truth.
And now the name makes sense. Bag: averaging throws away the order of the neighbours — "drink … daily" and "daily … drink" give the same , like words tipped into a bag. Continuous: the vectors are dense lists of real numbers, not counts.
How it learns. Unit 15 showed that the blame arriving at the scores of a softmax is simply prediction − truth:
Only chai's entry is negative, and negative blame means "raise me". One step (with step size ) now does three things:
- The answers move. Every output vector moves by . Chai's is pulled toward : . Every other word's is pushed away from , each in proportion to the probability it wrongly took.
- The blame reaches the committee. The blame on is . It says: move the opinion toward chai's answer-arrow.
- The blame is shared equally. was an average of two neighbours, so each member moves by half: Drink becomes and daily becomes .
Play the same blank again. The model now gives chai 0.594 instead of 0.368, and the surprise drops from 1.00 to 0.52.
Every time chai is the blank, its answer-arrow is pulled toward the average of the neighbours it had — and those neighbours are pulled toward chai's answer-arrow. Coffee is the blank in the same kinds of sentences (drink, hot, cup, morning), so its arrows receive the same pulls. Two words pulled toward the same places end up in the same place. Nobody told the machine that chai and coffee are drinks. The blanks did.
The vectors we keep are not the answers to the blanks. Each word has two vectors: an input vector , used when it sits on the committee, and an output vector , used when it is the answer. After training we throw the game away and keep the input table — the committee members' vectors. The game was only the test that forced that table to be good.
CBOW averages the context vectors, scores every word against that average, and nudges the vectors until the true centre word wins. With words on each side the committee has members, and each member receives a share of the blame.
In the toy round, swap the two neighbours so the sentence reads we daily chai drink. What happens to the model's chance for chai?
The window grows from one word on each side to two, so the committee has four members. What share of the blame on does each member now receive?
If you want the algebra · 1 proof, step by step
Claim. With , scores and , the gradients are and for every context word , where .
A note on the real program. The lab in §11 follows this exact rule: with words on the committee, each one gets of the blame on , because is their average. The original word2vec program (the C code released with the 2013 papers) takes a shortcut. It also averages the committee to make , but then it hands every member the full blame on , not a share. That is like giving the input vectors a step times bigger. It still learns well; it is simply not the exact slope of the average.
In one sentence: CBOW averages the neighbours' vectors, scores every word against that average, and nudges the vectors until the true middle word wins — a committee of neighbours filling in the blank.
Skip-gram: one word guesses its neighbours
What if we turn the game around, and ask one word to guess the company it keeps?
Show a friend one word cut out of yesterday's newspaper: wicket. Ask her which words were probably printed around it. "Bowler," she says. "Over. Six. Bat."
One word, many guesses. And to make those guesses she had to know what a wicket is.
That is the second game, skip-gram: the centre word throws a guess at each of its neighbours. (The name: a bigram of §2 is two words side by side; a skip-gram is a pair that may skip over the words in between. The centre word is paired with every word in its window.) We use the same toy model and the same sentence, we drink chai daily, with a window of one. This time chai is shown, and it must guess drink and daily.
- Look up the centre word. No committee, no averaging: .
- Score every word. we 0, drink 1, chai 2, daily 1, cricket −2.
- Make one list of chances. The softmax gives 0.072, 0.195, 0.529, 0.195, 0.010. The same list is used for every neighbour slot — the slot on the left and the slot on the right.
- Add up the surprises. The true neighbours, drink and daily, got 0.195 each: .
Read it aloud: the centre word's own vector is the opinion; one list of chances covers the whole vocabulary; each true neighbour adds its own surprise.
Now look at the model's favourite guess: chai itself, with 0.529. Chai's input vector and output vector are both (1, 1), so the word points straight at its own answer-arrow. But a word is almost never its own neighbour. Watch one step fix that.
How it learns. Each neighbour slot sends back prediction − truth, and because both slots used the same list of chances, their errors simply add up:
- The answers move. Drink's and daily's output vectors are pulled toward : they become and . Chai's own output vector took 0.529 in both slots, so it is pushed hard away: .
- The centre word takes all the blame. The blame on is . There is no committee to share it with, so moves by all of it: . Chai stops pointing at itself.
After this one step the chances are 0.092, 0.386, 0.102, 0.386, 0.034. Drink and daily are now the favourites, and the loss has fallen from 3.27 to 1.90.
One list must cover all the company. A single softmax has to spread its chances over all of a word's usual neighbours. The best this model could ever do for chai is 0.5 on drink and 0.5 on daily — a loss of , never 0. So skip-gram literally learns a word's company as a list of chances. Two words that keep the same company must produce the same list, and the only way to do that is to have nearly the same input vector.
The centre word gets every update in full. It receives the sum of all its neighbours' errors. So even a word that appears only a few times gets strong, undiluted updates each time it does appear.
Skip-gram does not make a different guess for each position. The neighbour on the left and the neighbour two places to the right are guessed from the same list of chances. The window says which words count as company; it does not say where they sit.
Skip-gram uses the centre word's own vector as the opinion, makes one softmax over the vocabulary, and checks it against every neighbour. The errors of all the slots add up, and the centre word receives the whole sum. (The lab in §11 plays a cheaper version of this game, with negative sampling in place of the full softmax — see §12.)
In the skip-gram round, chai has two neighbours, drink and daily. How many softmax lists does the model work out for this one position?
Why does a rare word usually end up with a better vector from skip-gram than from CBOW?
In the whole text, chai's only neighbours are drink and daily, equally often. What is the lowest loss skip-gram can ever reach at this position?
If you want the algebra · 2 proofs, step by step
Claim. For , with one list and , the blame on the scores is , and the blame on the centre word is .
Claim. If a centre word's neighbours are two different words and , then , with equality only when .
In one sentence: Skip-gram looks up the centre word's vector, makes one softmax over the whole vocabulary and checks it against every neighbour — so it learns a word's company as a list of chances, and the centre word gets the full sum of its neighbours' blame.
CBOW or skip-gram? Race them
Two games, one goal. Which one should you play?
A coaching class and home tuition. In the coaching class, the teacher asks one question and takes one answer from a room of forty. It is fast, but the quiet student in the back row barely changes the answer. At home tuition, the teacher sits with one student and asks question after question. It is slower and costs more — but the weak student gets full attention.
CBOW is the coaching class. Skip-gram is home tuition. And the rare words are the quiet students.
Both games read the same text through the same window, and both train the same two tables. Put them side by side:
| CBOW · fill in the blank | skip-gram · guess the neighbours | |
|---|---|---|
| what goes in → what comes out | the context (up to words) → the centre word | the centre word → each context word |
| guesses at each stop | 1 | up to |
| what is averaged | the context vectors | nothing |
| a word's share of the blame | of the committee's | the full sum of its neighbours' |
| speed | faster — about times fewer guesses | slower |
| frequent words | slightly better, smoother | good |
| rare words, small collections of text | weaker | better |
The rule of thumb comes from the people who built word2vec (Mikolov and colleagues, 2013): CBOW is several times faster and a little better for frequent words; skip-gram works well with small amounts of text and represents even rare words well. In practice the most popular choice is skip-gram with negative sampling (§12), a window of about 5 words and 100–300 numbers per word.
Why do rare words do better in skip-gram? Follow the blame. In CBOW a rare word is one voice in a committee of , so every update it receives is divided by the size of the committee — and the committee's answer is mostly shaped by the common words around it. In skip-gram the rare word is the centre of up to guesses, and it receives every one of those updates in full.
Below, both games train side by side: the same sentences, in the same order, from the same random start. Watch three things. The cost counters: at each stop skip-gram makes up to guesses where CBOW makes one. The maps: both sort the words into topics they were never told about. And the nearest neighbours of a frequent word and of a rare word, in each model.
Both games are fed by the same thing: which words share a window. Words that keep the same company receive the same pulls in either game, so both tables end up putting them together. The games differ only in how the pulls are packaged — one averaged guess per window, or one guess per neighbour — and that packaging decides the cost and how much attention each word gets.
Faster is not worse, and slower is not better. On a large collection of text both games reach vectors of similar quality; the choice is about time and about rare words. And a toy lab with about a hundred short sentences is noisy: change the random start before you judge a winner.
CBOW buys speed by averaging the committee into one guess. Skip-gram pays about times more to give every word — and especially every rare word — its own full update.
You widen the window from to . In the middle of a long sentence, how many guesses does each game now make at one stop?
You have a small collection of old letters, full of rare village names, and plenty of computer time. Which game is the better bet?
In one sentence: CBOW is the coaching class — one averaged guess per window, fast and smooth — while skip-gram is home tuition — up to guesses per window, slower, but every word, especially every rare one, gets its full share of attention.
Making it cheap: negative sampling, hierarchical softmax, subsampling
Every guess in §9 and §10 scored every word of the vocabulary — in a real model, all 50 000 of them. How could training on billions of words ever finish?
A teacher wants to check whether you know who chai's friends are. She could ask: "Out of all 50 000 students in this city, rank how likely each one is to be chai's friend." That takes all day.
Or she could ask five quick yes-or-no questions: "Is hot a friend? Is football? Is kettle?…" Or she could play twenty questions: "Is the friend a drink word? Yes. A hot one? Yes…" — and find the answer in a handful of steps. Three ways to test the same knowledge. The last two are fast.
The cost of the full softmax. To turn scores into chances, the softmax divides by a sum over the whole vocabulary:
That bottom line needs one dot product and one for every word — 50 000 of them for a single guess. Worse, every word takes a little probability, so every output vector receives a little blame and must be updated. word2vec makes billions of guesses. Something has to give.
Way 1 · Negative sampling — a few yes/no questions. Replace "which one, out of everybody?" by "is this one real, or random?". For each real (centre, neighbour) pair, also pick random words — the negatives — and train the model to say "real" to the true neighbour and "random" to each negative. The score of a pair is a sigmoid of its dot product (Unit 14): .
A worked round, with lists of two numbers. Centre word chai: . Real neighbour hot: . One random negative, football: .
- Real pair: , so : the model is 62% sure hot is real.
- Negative pair: , so the chance it says "random" is .
- The loss is the surprise of both right answers (in nats, as in Unit 14): .
One step downhill (Unit 9) with . Each answer is "wrong by" , and the updates are the same pull-and-push we met in CBOW, now for only three vectors:
- Pull the real neighbour toward chai: .
- Push the random word away: .
- Turn chai toward hot and away from football: .
After this one step the real pair scores , the negative gets "random" with , and the loss has dropped from 0.948 to about 0.505. The cost: dot products instead of . With and , that is times less work.
Which random words? If negatives were picked in proportion to how often words appear, "the" and "is" would be picked all the time and teach little. word2vec picks a word with probability proportional to its count raised to the power . That gently lifts rare words: a word seen 100 times and one seen once would share the picks 99% to 1%; after the power it is against 1, about 96.9% to 3.1%.
Way 2 · Hierarchical softmax — twenty questions down a tree. Put all the words at the leaves of a binary tree. To give a word its chance, walk from the root to its leaf; at every fork, a small sigmoid decides "left or right?", and the word's chance is the product of the decisions along its path. Each fork has its own vector , and the chance of turning left is .
A four-leaf tree, with . The root asks "drink or sport?" with ; the drink fork asks "chai or coffee?" with ; the sport fork asks "cricket or football?" with . Then , and
These four add up to exactly 1 — and nobody ever added up all the words. Each fork splits its share into two parts that add up to what came in, because . With words, a balanced tree needs only decisions per guess instead of 50 000 scores. word2vec even builds the tree so that frequent words sit near the root, with short paths (a Huffman tree).
Way 3 · Subsampling — fewer "the"s. "The" appears millions of times, and after the first thousand it teaches almost nothing about chai. So word2vec simply skips most of them. Each occurrence of a word with frequency (its share of all the words) is kept with probability
and always kept if . A word with is kept half the time ; "the", with , only 1.4% of the time ; rare words are never dropped. Two gains: training is faster, and with the "the"s gone, a window of 2 words reaches further — to words that actually carry meaning.
Side by side:
| full softmax | negative sampling | hierarchical softmax | |
|---|---|---|---|
| the question | which one, out of everybody? | this one — real or random? ( times) | left or right? (down a tree) |
| work per guess | (50 000) | (6) | (16) |
| true chances that add up to 1? | yes | no — a yes/no score per pair | yes |
| tends to suit | small vocabularies | frequent words; the usual default | rare words |
Rule of thumb: negative sampling is the default ( of about 5–20 for small collections of text, 2–5 for huge ones), hierarchical softmax is worth trying when rare words matter most, and subsampling is switched on in both.
The knowledge was never in the sum over 50 000 words. It is in the pulls: toward the true neighbour, away from what is not a neighbour. Negative sampling keeps the pull toward the truth and replaces "away from everybody" by "away from a few random somebodies" — and over millions of steps every word gets its turn to be the random one. The tree keeps exact chances by splitting them fork by fork. And subsampling drops only the repeats that would have taught nothing new.
A model trained with negative sampling no longer gives you "the chance of each next word" — it learned a yes/no detector for pairs. Its vectors are excellent, but its scores are not probabilities that add up to 1. If you need real chances, as a language model does (§14), you need the full softmax or the tree.
Three tricks made word2vec cheap: ask yes/no questions instead of scoring all words (negative sampling), walk forks of a tree (hierarchical softmax), and skip most copies of very common words (subsampling). The cost of a guess stops growing with the vocabulary.
The vocabulary has 100 000 words and you use negatives. About how many times fewer dot products does one guess need?
A hierarchical softmax is built as a balanced tree over a vocabulary of one million words. How many left/right decisions does one guess need?
In the worked round, after one step with , what happens to the score ?
If you want the algebra · 5 proofs, step by step
Claim. and .
Claim. For , with and , a step of size downhill is
Claim. For with scores , the gradient is for every word , where is the softmax and the one-hot truth.
Claim. If every fork sends a share of what reaches it to the left and to the right, the chances of all the leaves add up to 1 — without ever adding over the vocabulary.
Claim. After subsampling, a word that makes up a share of the text makes up about of it. So a word 100 times more common than another keeps only 10 times as many copies.
In one sentence: A full softmax scores all words for every guess; negative sampling asks yes/no questions (50 000 against 6), a tree asks left/right questions (16), and subsampling keeps each "the" with chance only — together they made training on billions of words possible.
Why it works: counting and predicting meet
Counting a table and playing a guessing game look nothing alike. Why do they end up with such similar word vectors?
Two strangers in a new city. They have never met. But they shop at the same kirana store, buy vegetables from the same cart and ride the same bus. After a month, look into their bags: the same brand of tea, the same bread, the same bus pass.
Nobody introduced them. The same places filled their bags with the same things.
That is word2vec in one picture. Every time a word appears, its vector is pulled toward the vectors of its neighbours. Two words that keep the same company — even if they never once appear together — receive the same pulls, step after step. So their vectors are pulled to the same place. Watch it happen: in the demo below, chai and coffee never share a sentence, but they share their neighbours.
The surprise: word2vec is secretly counting. In 2014 Omer Levy and Yoav Goldberg asked what skip-gram with negative sampling is aiming for, if its vectors had room to give every pair exactly the score it wants. The answer: for every word and context word , it wants
The best possible score for a pair is exactly the PMI of §6 (in natural logs), shifted down by . For chai and hot, ; with negatives the best score is . So a table of dot products is a squeezed copy of the PMI table: word2vec is quietly doing what §6 and §7 did by hand — weigh the company, then squeeze it. The counting road and the predicting road arrive at the same city.
GloVe makes the meeting explicit. In 2014 Jeffrey Pennington, Richard Socher and Christopher Manning at Stanford built a method straight on this idea, called GloVe (global vectors). Their insight: meaning lives in ratios of co-occurrence probabilities. Take chai and lassi, with 1 000 context words counted around each:
| probe word | hot | cold | drink | cricket |
|---|---|---|---|---|
| 40/1000 | 2/1000 | 60/1000 | 4/1000 | |
| 2/1000 | 40/1000 | 60/1000 | 4/1000 | |
| ratio | 20 | 0.05 | 1 | 1 |
Words that tell chai and lassi apart give ratios far from 1: "hot" (20) points to chai, "cold" (0.05) to lassi. Words that do not tell them apart give 1, whether they are shared ("drink") or irrelevant to both ("cricket"). The GloVe paper found exactly this pattern for ice and steam with the probes solid and gas, counted over six billion words.
So GloVe asks the vectors to reproduce the log counts directly, for every pair of words seen together times:
Then differences of vectors turn ratios into dot products: . Each pair is weighted by (and 1 above 100), so rare, noisy counts matter less: , .
Counting and predicting read the same thing — which words share windows — and both boil it down to the same kind of number: how much more often than chance a pair meets. Counting writes that number into a table and squeezes it; word2vec discovers it through billions of small pulls; GloVe fits it head-on. Different roads, same city, because the city is the company words keep.
"Predicting is smarter than counting" is a myth. With the same text, the same window and sensible settings (PPMI, a little smoothing, a good ), well-tuned counting methods and word2vec produce vectors of very similar quality. The big wins of word2vec were speed and scale — it never has to build the giant table.
Words that keep the same company receive the same pulls, so their vectors converge. At its best, word2vec's dot products equal the PMI of §6 shifted by — it is squeezing the counting table without ever writing it down — and GloVe fits the log counts directly, so that differences of vectors reproduce ratios of probabilities.
In the demo, chai and coffee never appear in the same sentence. What happens to their cosine as training goes on?
. With only negative per pair, what is the best score skip-gram can aim for?
The probe word "drink" is equally common around chai and around lassi. What does GloVe want the dot product to be?
If you want the algebra · 2 proofs, step by step
Claim. Suppose the score of each pair could be chosen freely. Then the negative-sampling loss is smallest at (natural log), when negatives are drawn in proportion to plain counts.
Claim. If for every pair, then .
In one sentence: Words that keep the same company get the same pulls and converge — strangers who shop at the same stores — and at its best word2vec makes (chai–hot: 0.470 − ln 5 ≈ −1.139), while GloVe fits the log counts so that meaning shows up in ratios like hot's 20 for chai against lassi.
A neural language model
Can we have both — word vectors that share what they learn, and real chances for the next word?
Mumbai's dabbawalas pass a lunch box along a relay. One picks it up, one sorts it, one carries it, one hands it over. Nobody does the whole job, but the box always arrives.
A neural language model is a relay like that. Look up the words, glue them together, mix them in a small network, and hand over a chance for every possible next word.
The count tables of §2 could not share anything between "chai" and "coffee". In 2003 — ten years before word2vec — Yoshua Bengio and his team built a model that could. It works in five steps:
- Look up. Keep a table with one row of numbers for each word — an embedding table. Look up the row of each previous word.
- Glue. Put the rows side by side into one longer list (people say concatenate). Two previous words with give a list of 4.
- Mix. Pass it through a hidden layer, exactly as in Unit 15: .
- Score every word. One more layer gives one score per word, and a softmax (Unit 14) turns the scores into chances.
- Learn. Train with cross-entropy and backprop (Unit 15). The blame flows all the way back into the rows of , so the table is learned too.
The lookup is a matrix multiply. Write a word one-hot and multiply it by the table. With three words and :
The single 1 picks out row 2. So an embedding table is nothing new: it is the first layer's weight matrix, fed with one-hot inputs. Computers skip the multiply and just fetch the row — same answer, far less work. And it is the same object as word2vec's input table (§8): word2vec is this model with the hidden layer removed, trained on a simpler game.
Now the whole relay. We trained a tiny model ourselves, for this page, on just seven sentences: "I drink hot chai .", "we drink hot chai .", "I drink hot coffee .", "we drink hot coffee .", "I play cricket .", "we play cricket .", "we play football .". It has a vocabulary of 10 words, embeddings of numbers and 8 hidden neurons. Its whole brain is 150 numbers.
Notice what it has never seen: "I play football". A count table would give it chance exactly 0. But "I" and "we" were used in the same places, so the model learned almost the same row for both. It gives football after "I play" a chance of about 0.256 — nearly what it gives after "we play" (0.258). That is sharing, and it is the whole point of word vectors.
Because the table is shared by every sentence. When the model learns something after "we play", the blame flows into the row for "we"; since "I" was pushed to nearly the same row by the same kinds of sentences, what was learned about "we" also works for "I". Similar rows make similar guesses — so the model can give a sensible chance to a sentence it has never seen.
The embedding table is not an extra part bolted onto the network — it is the first layer's weights, learned by the same backprop. And this model still has the short memory of §2: it sees exactly two previous words, no more. Removing that fixed window is the job of Unit 17.
A neural language model is a Unit 15 network with a lookup table in front and a softmax at the end. The table is just the first layer's weights, learned by the same backprop — the same kind of table word2vec learns. Because similar words get similar rows, what the model learns about one word helps it with the others.
A vocabulary has 4 words and . What is ?
Our tiny model has words, , two previous words and 8 hidden neurons. How many numbers does it learn? (Table, then hidden weights and biases, then output weights and biases.)
If you want the algebra · 2 proofs, step by step
Claim. If is the one-hot row vector with a 1 in slot , then is row of .
Claim. If and the blame arriving at is , then : the gradient is zero except in row , which gets .
In one sentence: A neural language model looks up each previous word's row in an embedding table (one-hot × matrix = picking a row — the same table word2vec learns), glues the rows, mixes them in a hidden layer and ends with a softmax over the vocabulary, so similar words share what they learn and even unseen sentences get sensible chances.
The geometry of meaning
If every word is a point, what does it mean to walk from "man" to "woman"?
A friend gives you directions: "From the station, walk 2 blocks north and 3 blocks east." Those directions are not tied to the station. Start from the temple and follow the same walk, and you land somewhere new — but in the same position relative to where you started.
In a good word space, the step from "man" to "woman" is a walk like that. Start the same walk from "king".
First, three rulers for "similar". We have met three ways to compare two lists of numbers. Take two tea-stall orders (two cups of chai, one biscuit) and — the same taste, just a bigger order — and a third customer who likes biscuits more, .
- Dot product: , . It mixes taste with size: bigger orders give bigger numbers.
- Distance: but . Distance says is closer to — the size difference beats the taste. (With an office order of (20, 10) it gets worse: about 20.12 against 1.414.)
- Cosine: exactly (the same direction), . The cosine sees only taste.
For word vectors, the length mostly tracks how often a word appears, and the direction tracks what it means — so the cosine is the standard ruler. To make the three rulers agree, normalise: shrink or stretch every vector to length 1. Then the dot product is the cosine, and distance follows from it, , so all three rulers rank neighbours the same way. Real systems normalise once and then use fast dot products.
Now the walk. Here are four hand-made vectors with just two numbers each (we built them for this example; they are not trained):
The step from man to woman is . The step from king to queen is — the same step. The four points make a parallelogram, and that answers the puzzle "man is to woman as king is to ?":
That is exactly queen. With real, trained vectors the answer is never exact; it lands near a word. So we search for the nearest word by cosine. For : queen 1, woman 0.868, king 0.385, man −0.124.
Skip the three words you started with. In trained vectors the step "woman − man" is short next to the words themselves, so the answer usually lies closest to king itself. A search that allowed king would just return king — true, but useless. So the search always leaves out the three input words.
A bigger playground. Below are 60 words. Their vectors are hand-made by us — not trained on text — so that you can check every answer with your own sense of meaning. Each word has 13 numbers: nine meanings we chose (is it a person? royal? female or male? young? a drink? about cricket? an animal? a place? a capital city?), four random "family fingerprint" numbers shared by a family such as king, queen, prince and princess, and a little random noise. The sums and the cosines use all 13 numbers.
To draw them we look through a fixed 3-D window — a projection, like a shadow on a wall (Unit 3). A shadow of a parallelogram is still a parallelogram, so the picture never lies about the arithmetic. But lengths and angles do change in a shadow: two dots that look close may not be, so always read the cosines in the box, never the picture alone.
How do people test real embeddings? Two ways. Similarity: people rate pairs of words — chai and coffee, cup and kettle — and we check whether the cosines put the pairs in the same order. Analogies: thousands of puzzles like "Delhi is to India as Tokyo is to ?", and we count how often the nearest word to is the right one.
Think of what separates "king" from "queen" in text: the same small change of company — "he", "his", "sir" around one; "she", "her", "madam" around the other — while the royal company (crown, palace, throne) stays. Man and woman differ by that same change. If the same change of company always moves a vector the same way, it becomes the same arrow everywhere, and adding it to king swaps king's "he" company for "she" company while keeping the crown.
Analogies are less magical than they look. On real vectors, king − man + woman lands nearest to king itself; many famous analogies only "work" because the three inputs are skipped. And a picture of word vectors is always a shadow: never trust how close two dots look — trust the cosine.
In a good word space, closeness (by cosine) is similarity and a difference of meanings is a direction. The same arrow turns man into woman, king into queen and boy into girl; another turns a country into its capital. "B is to C as A is to ?" becomes arithmetic: , then the nearest word by cosine, leaving out , and .
Toy vectors: Delhi , India , Japan . What is Delhi − India + Japan?
Why does the analogy search leave out the three input words?
Two vectors of length 1 have cosine 0.5. How far apart are their tips?
A word vector is . The same word counted over twice as much text gives . What do the dot product, the cosine and the distance say?
If you want the algebra · 2 proofs, step by step
Claim. If (so make a parallelogram) and is any projection plus shift, then .
Claim. If , then .
In one sentence: Measure "similar" by the cosine (after normalising, all three rulers agree), and a difference of meanings becomes a direction — king − man + woman = (3, −2) = queen in our toy plane, and with real vectors we take the nearest word by cosine, leaving out the three words we started from.
What one vector per word gets wrong — and how pieces help
What should a machine do with a word that means two things — or with a word it has never seen?
"He hit a six with his bat." "A bat flew out of the old fort at dusk." Same word, two completely different things. You never mix them up, because the sentence tells you which one is meant.
And when a shopkeeper says "ask the chaiwala", you understand at once — though you may never have heard that exact word — because you know its pieces.
Problem 1 · one vector must blend every meaning. Everything so far gives each word one vector, whatever the sentence. So what does "bat" get? Training pulls it toward cricket words every time it appears in a cricket sentence and toward animal words every time it appears in an animal sentence. It ends up roughly a blend, weighted by how often each meaning is used.
A tiny example. Let the cricket meaning point along and the animal meaning along . If 80% of the sentences with "bat" are about cricket, the single vector is about
Its cosine with the cricket meaning is , and with the animal meaning only . The rare meaning is almost drowned. A word used half and half sits in the middle, close to neither group.
Problem 2 · vectors copy the text they learn from. The vectors are a mirror of how words are used in the corpus — nothing more. If the training text more often writes "the doctor … he" and "the nurse … she", then "doctor" leans toward the male end of the female–male direction and "nurse" toward the female end. That is a fact about the text, not about doctors or nurses. It matters because a system built on these vectors will repeat the pattern. People measure such leanings with directions like the ones in §15. They can also remove such a direction from every vector, but that hides only part of the pattern, so the text itself still matters.
Problem 3 · words never seen get no vector at all. A table has one row per word it met in training. A new word — a spelling mistake, a new brand, "chaiwala" — has no row, and a plain word2vec model can say nothing about it.
The fix for unseen words: pieces. In 2017 Piotr Bojanowski and colleagues at Facebook built fastText, a word2vec in which a word's vector is the sum of the vectors of its pieces. The pieces are short runs of letters called character n-grams, taken after marking the start and end of the word with < and >. With pieces of 3 letters:
<chai> → <ch cha hai ai>
<chaiwala> → <ch cha hai aiw iwa wal ala la>
"chaiwala" shares 3 pieces with "chai" (<ch, cha, hai) and 3 with "dudhwala" (wal, ala, la>). So even though "chaiwala" was never seen, adding up its pieces gives it a sensible vector — near chai, and near the other -walas. (Real fastText uses pieces of 3 to 6 letters, plus the whole word.)
How modern language models cut text: byte-pair encoding. Big language models go one step further and choose their pieces from data. Start with single characters. Count every pair of neighbouring symbols across the corpus, merge the most frequent pair into one new symbol, and repeat. Take a corpus with the words hug (10 times), pug (5), pun (12), bun (4) and hugs (5):
- u + g appears 10 + 5 + 5 = 20 times → merge into "ug".
- u + n appears 12 + 4 = 16 times → "un".
- h + ug appears 10 + 5 = 15 times → "hug".
- p + un appears 12 times → "pun".
After these four merges, "hugs" is cut as hug · s, and a word never seen, "bug", as b · ug. When two pairs tie, we merge the one met first in reading order. Frequent words become single tokens, and rare words are spelled out of common pieces — so nothing is ever unknown. This is byte-pair encoding (BPE). Most large language models cut their text this way, or with a close cousin of it, and the pieces of Unit 19 are made like this.
Pieces are shared. A rare word is almost always made of common pieces, and a common piece has been seen thousands of times inside other words, so its vector is well trained. Adding up well-trained pieces gives even an unseen word a vector in the right neighbourhood — the way you understood "chaiwala" from "chai" and "-wala".
Pieces are not meanings. "chai" and "chain" share <ch, cha and hai, yet have nothing in common. Pieces help because, over many words, pieces like "wala", "ing" or "un" really do carry meaning — for any single word they can mislead. And pieces do nothing for "bat": both meanings are spelled the same. Only the sentence can tell them apart, which is where Unit 18 goes: every word gets a new vector computed from its sentence, so "bat" in a cricket sentence and "bat" in a fort get different vectors.
One vector per word must blend all its meanings (weighted by use), copies the patterns of its text, and has nothing to say about unseen words. Pieces fix the unseen words — fastText adds up character n-grams, BPE learns a vocabulary of frequent pieces — but only a vector that changes with its sentence can fix "bat".
A word is used in its first meaning half the time and in its second meaning half the time. Its single vector is the blend . What is its cosine with each meaning?
With 3-letter pieces, how many pieces does "<chais>" share with "<chai>"?
After the four BPE merges (u+g, u+n, h+ug, p+un), how is the new word "bug" cut?
If you want the algebra · 2 proofs, step by step
Claim. If the two meanings are unit vectors at right angles, , and a word is used in meaning 1 a share of the time, its blend has .
Claim. With the markers < and > added, a word of letters has exactly character 3-grams.
In one sentence: One vector per word blends every meaning of that word (80% cricket gives cosines 0.970 and 0.243), copies the patterns of its text and knows nothing of unseen words — pieces fix the unseen words (chaiwala shares 3 pieces with chai; BPE cuts bug as b · ug), and Unit 18's vectors that change with the sentence fix the rest.
What to carry forward
The whole unit fits on one wall of cards. Each card is one picture to keep.
A label, then a map
One-hot lists are a phone directory: every pair of words at right angles and apart. We want a map, where close means similar.A chain of guesses
; a short memory (bigram, trigram) and count ÷ total; , start and stop the chain.Never seen ≠ impossible
Smoothing moves a little probability to unseen pairs. Add-one drowns real counts in a big vocabulary; interpolation and backoff ask a more general adviser.Perplexity
: how many faces the model's die has. 1 is perfect, is clueless; compare only on the same test text.The company a word keeps
A row of neighbour counts is a vector; similar = cosine near 1. Small windows find stand-ins, big windows topic-mates.Weigh by surprise
PMI and TF-IDF give "the" the weight 0. Beware rare pairs.Squeeze: friends of friends
Keep the top singular directions (rows of ). Shared directions make chai and tea friends through coffee.CBOW: the committee
Average the context vectors, softmax over the vocabulary, error = prediction − truth, blame shared each.Skip-gram: one word, many guesses
One softmax checked against every neighbour; the centre gets the full sum of the blame — good for rare words.Three ways to make it cheap
Negative sampling ( yes/no questions), hierarchical softmax ( forks), subsampling (keep each copy with ).Counting meets predicting
Same company, same pulls, same place. At best ; GloVe fits log counts so ratios become directions.A neural language model
Look up (one-hot × table = a row), glue, hidden layer, softmax. The table is the first layer — the same kind of table word2vec learns.Meaning is a direction
, then the nearest word by cosine, skipping . Pictures are shadows; trust the cosine.Limits, and pieces
One vector blends every meaning and copies its text. Pieces (fastText, BPE) handle unseen words; context handles "bat".Where this goes next.
- Unit 17 · Machines with Memory. Every model here saw a fixed window of words. A recurrent network reads a sentence one word at a time and carries a running memory along, so it can use everything before — and the fading or exploding of that memory becomes an eigenvalue story (Unit 4).
- Unit 18 · Attention and Transformers. The fix for "bat" and "bank": every word looks at every other word in its sentence, using the very dot products of this unit, and takes on a new vector that fits its context.
- Unit 19 · The Maths Inside an LLM (coming soon). A softmax over a whole vocabulary of BPE pieces, at the scale of billions of words — the cost problem of §12, met head-on.
A word becomes a point in space, placed by the company it keeps — counted, weighed and squeezed, or learned by a guessing game, which turns out to be the same thing. In that space, closeness is similarity and a difference of meaning is a direction. Every language model you will meet from here on starts by turning its words, or pieces of words, into such vectors.
In one sentence: Give each word a short list of numbers learned from the company it keeps — by counting, weighing and the SVD, or by word2vec's two guessing games, which secretly do the same — and meaning becomes geometry: similar words point the same way and differences of meaning are directions.
Practice arena — sixteen problems, solved in full
Sixteen problems, easy to hard, one or more for every idea of the unit: chains of guesses, smoothing, perplexity, TF-IDF, PMI, cosines, the SVD squeeze, counting training examples, a CBOW pass, a skip-gram pass, a negative-sampling step, a path down a tree, subsampling, GloVe ratios, BPE merges and an analogy. Some run forwards, some backwards (find the setting that gives a result), and one asks you to judge two recorded models. Every number was checked by machine.
Three habits do most of the work. Write the counts or vectors in a small table first. Turn probabilities into surprises before you average them. And for "similar", divide by the lengths: use the cosine, not the raw dot product.
The corpus is "we play cricket", "we play football", "we watch cricket", and a bigram model adds and to every sentence. (a) Give , , and . (b) What chance does the model give we play cricket ? (c) And we watch football ? (d) List every sentence the model can produce with a chance above 0, and add up their chances.
What this tests. The chain rule with a one-word memory, count ÷ total, and why the end marker makes the chances of all sentences add up to 1. Plan. Make the table of next-word counts for every history, then multiply along each sentence.
Show the full solution
answers at a glance: (a) 1, , , 1. (b) . (c) 0. (d) three sentences, each, total 1.
With the end marker, a bigram model shares out exactly 1 among all the sentences it can write.
Same corpus as Problem 1. The possible next words are we, play, watch, cricket, football and (). (a) With add-one smoothing, give and . (b) The unigram adviser counts the 12 tokens that follow the markers. With interpolation , give the same two chances. (c) Which weight on the bigram would make exactly 0.05? (d) Show that the interpolated row for "play" adds up to 1 whatever is.
What this tests. Add-one, interpolation, and running interpolation backwards. Plan. Write the "play" row (cricket 1, football 1, total 2) and the unigram counts first.
Show the full solution
answers at a glance: (a) 0.25 and 0.125. (b) 0.4 and 0.025. (c) . (d) .
Interpolation gives an unseen pair the unigram's share, scaled by : more trust in the general adviser, more chance for the unseen.
(a) A model gave five real next words the probabilities . Find the average surprise in bits and the perplexity. (b) What is the perplexity of a model that guesses evenly over 8 words? (c) On a 3-word text a model gave the first two true words 0.5 and 0.25. What must it give the third for the perplexity to be exactly 4? (d) Two models were each scored twice: on their own training text and on new text they had never seen. A scored 45 on its training text and 210 on the new text; B scored 80 and 95. Which would you use, and how many bits per word better is it on the new text?
What this tests. Perplexity as , forwards, backwards, and as a judge (Unit 10's overfitting). Plan. Work in bits: for each word.
Show the full solution
answers at a glance: (a) 1.4 bits; . (b) 8. (c) . (d) B; about 1.144 bits per word.
A model that always gives the truth probability has perplexity ; and only the score on text the model never saw counts.
Four documents. D1: the ×4, chai ×3, milk ×1. D2: the ×3, cricket ×2, bat ×1. D3: the ×2, chai ×1, cricket ×1. D4: the ×1, milk ×1, kadak ×2. (a) Give the document frequency and of the, chai, milk, cricket, bat and kadak. (b) Give the TF-IDF weights of the, chai and milk in D1. (c) Which word is the best keyword for D4? (d) A new word has idf . In how many of the 4 documents does it appear?
What this tests. TF-IDF, and reading idf backwards. Plan. Count documents, not copies, for df; then multiply by the counts.
Show the full solution
answers at a glance: (a) df 4, 2, 2, 2, 1, 1; idf 0, 0.301, 0.301, 0.301, 0.602, 0.602. (b) 0, 0.903, 0.301. (c) kadak (1.204). (d) 3 documents.
A word everywhere has idf 0; a word in one document out of has the biggest idf, .
Counted pairs (): tea meets hot 15, the 12, over 3 times; bat meets hot 3, the 12, over 15 times. (a) Give the row and column totals and the "if strangers" count, row total × column total ÷ , for tea with each word. (b) Give for c = hot, the, over. (c) Give the PPMI of each. (d) Keeping the "if strangers" count for tea–hot fixed, how many tea–hot meetings would make its PMI exactly 1?
What this tests. PMI as the log of count ÷ chance. Plan. Totals first, then one ratio per box.
Show the full solution
answers at a glance: (a) rows 30, 30; columns 18, 24, 18; strangers 9, 12, 9. (b) 0.737, 0, −1.585. (c) 0.737, 0, 0. (d) 18.
PMI counts meetings against chance: 0 means "no more than strangers", and "the" usually scores 0 with everyone.
Count rows over the neighbours (drink, hot, play): tea , coffee , cricket . (a) Compute cos(tea, coffee) and cos(tea, cricket). (b) Compute the straight-line distances tea–coffee and tea–cricket. (c) Which measure clearly says tea is closer to coffee, and why?
What this tests. Cosine against distance on count rows. Plan. Lengths first: .
Show the full solution
answers at a glance: (a) 1 and 0.48. (b) 5 and . (c) the cosine, decisively.
Counts grow with how common a word is; the cosine divides that away.
(a) Find the singular values of and check that equals the sum of the squares of the entries. (b) A company table has singular values . What share of the energy do and keep? (c) What is the smallest that keeps at least 90%? (d) What is the rank-2 rebuild error?
What this tests. Energy , and the error of keeping . Plan. For a symmetric matrix with positive eigenvalues, the singular values are the eigenvalues.
Show the full solution
answers at a glance: (a) ; . (b) 63.2% and 91.2%. (c) . (d) .
Square the singular values before you add them — energy lives in .
(a) A 6-word sentence, window : how many examples does CBOW make, and how many pairs does skip-gram make? (b) Find a formula for the number of skip-gram pairs from a sentence of words (). (c) Apply it to , . (d) With , a sentence gave 34 skip-gram pairs. How many words did it have? (e) In a very long text, about how many times more guesses does skip-gram make than CBOW?
What this tests. The cost difference between the two games, as a general formula. Plan. Count the neighbours of each position, left and right separately.
Show the full solution
answers at a glance: (a) 6 and 18. (b) . (c) 48 (CBOW 10). (d) 10 words. (e) about .
Skip-gram makes about guesses for every one CBOW makes — that is the whole price of home tuition.
A vocabulary of four words with . Input vectors: tea , hot , cup , bat . Output vectors: tea , hot , cup , bat . The sentence is "hot tea cup", window 1, and the blank is tea. (a) Find . (b) Find the four scores and the softmax. (c) Find the loss. (d) Find and the blame on , . (e) With , how far does each context vector move?
What this tests. The whole CBOW round: average, score, softmax, prediction − truth, and the equal share of the blame. Plan. Keep four decimals; do the output side before the input side.
Show the full solution
answers at a glance: (a) . (b) scores 1.5, 1, 0.5, −1.5; softmax 0.4940, 0.2996, 0.1817, 0.0246. (c) 0.7052. (d) ; blame . (e) each.
The committee shares the blame equally: with members, each gets of it.
The same four words and vectors as Problem 9. Now tea is the centre word and must guess its two neighbours, hot and cup. (a) Find and the softmax. (b) Find the loss. (c) Find the summed error and the blame on the centre word. (d) With , what is tea's new input vector? (e) What is the lowest loss skip-gram could ever reach at this position?
What this tests. One softmax checked against two neighbours, errors that add up, and the floor of . Plan. The centre's own input vector is — no averaging.
Show the full solution
answers at a glance: (a) ; 0.3995, 0.1470, 0.3995, 0.0541. (b) 2.8352. (c) ; blame . (d) . (e) .
Skip-gram's centre word takes the full sum of its neighbours' errors — nothing is divided.
, real neighbour , one negative , step size . (a) Find and . (b) Do one step of the pull-and-push rules for all three vectors. (c) Give the new scores and the loss before and after.
What this tests. The rules , , , all using the OLD vectors. Plan. Compute the two "how wrong" numbers once, then update.
Show the full solution
answers at a glance: (a) . (b) , , . (c) scores ; loss 0.6265 → 0.4254.
Use the old vectors on the right-hand side of all three updates — compute first, then overwrite.
A hierarchical softmax with four leaves (LL, LR, RL, RR) and . The root has , the left fork , the right fork ; each fork sends to the left. (a) Find the three fork scores . (b) Find the chance of each leaf. (c) Check that they add up to 1. (d) A balanced tree over 30 000 words: how many decisions per guess, and how many times less work than a full softmax?
What this tests. A leaf's chance as the product of its left/right decisions, and the cost. Plan. Remember .
Show the full solution
answers at a glance: (a) 1, −1, 0. (b) 0.1966, 0.5344, 0.1345, 0.1345. (c) 1. (d) 15 decisions; 2 000 times less.
Every fork splits what it receives into two parts that add up, so the leaves always add up to 1.
Subsampling keeps each copy of a word with frequency with chance (and always if ), with . (a) Give the keep chances for , and . (b) Of 1 000 copies of the word, how many are kept on average? (c) In another model a word with is kept 5% of the time. What was used? (d) A word with is 100 times as common as one with . How many times as common is it after subsampling?
What this tests. The keep rule forwards and backwards, and the square-root flattening. Plan. A kept share is .
Show the full solution
answers at a glance: (a) 0.1, about 0.158, 1. (b) 100. (c) . (d) 10 times.
Subsampling turns a word's share into about : common words shrink the most, rare words are untouched.
Around "ice" and around "steam", 1 000 context words were counted each. The probe solid appears 38 and 2 times, gas 1 and 19, water 60 and 60, fashion 2 and 2. (a) Give for each probe. (b) Give the natural log of each ratio — what GloVe wants to be. (c) Which probe vectors should end up at right angles to ? (d) Give GloVe's weights (1 above 100) for , 2, 60 and 150.
What this tests. Meaning in ratios, and why rare counts get small weights. Plan. Both targets have 1 000 contexts, so the ratio of probabilities is the ratio of counts.
Show the full solution
answers at a glance: (a) 19, 0.0526, 1, 1. (b) 2.944, −2.944, 0, 0. (c) water and fashion. (d) 0.484, 0.0532, 0.682, 1.
A probe that tells two words apart gives a ratio far from 1; one that doesn't gives 1, and its arrow is at right angles to their difference.
A corpus: low ×5, lower ×2, newest ×6, widest ×3. Run byte-pair encoding from single letters; when two pairs tie, merge the one met first reading the corpus in order. (a) Count the neighbouring pairs and find the first merge. (b) Find the next three merges. (c) Cut "lowest" and "slow" with these four merges. (d) How many symbols does the whole corpus have (counting repeats) before any merge, and after the four merges?
What this tests. The BPE loop — count, merge the most frequent pair, repeat — and the tie rule. Plan. Multiply every pair by its word's count; recount after each merge.
Show the full solution
answers at a glance: (a) e+s (9, tie with s+t broken by order). (b) es+t (9), l+o (7), lo+w (7). (c) low · est; s · low. (d) 79 → 47.
BPE turns frequent chunks into single tokens and spells everything else from pieces — so the text gets shorter and no word is ever unknown.
Toy vectors: India , Delhi , Japan , Tokyo , Kyoto . (a) Compute Delhi − India + Japan. (b) Compute the cosine of with Tokyo, Kyoto, Japan and Delhi. (c) Which word does the search return (skipping the inputs)? (d) Would the answer change if the inputs were allowed?
What this tests. Analogy arithmetic and the cosine search. Plan. Add first, then one cosine per candidate.
Show the full solution
answers at a glance: (a) . (b) 0.9984, 0.9640, 0.9349, 0.6503. (c) Tokyo. (d) no.
The answer to is a point, not a word; the nearest word by cosine is the answer.