Majid Al-RaimiFull guide

ICS 582Lecture 04Full guide

Word embeddings

The whole lecture on one page, taught concept by concept. Work through the parts in order, mark each concept once you understand it, and open the slide chips when you want the original slides.

Parts
10
Concepts
59
Slides
111
Reading
354 min
Understood
0/59 concepts

Part 01: What words mean: lemmas, senses and synonymy

Why treating words as strings or logical symbols is unsatisfying, what lexical semantics asks of a theory of meaning, how lemmas split into senses, and why perfect synonymy probably does not exist.

6 concepts, slides 1-10

Why this part matters

Every vector model in this lecture, from raw counts to word2vec, is graded against the same exam: does it capture the relations between word meanings that linguists named long before anyone trained an embedding? This part writes that exam. It asks what a word means, how one word splits into several senses, and why two words almost never mean exactly the same thing.

The payoff is practical in three directions. Exams ask you to define sense and polysemy and to explain why water and H₂O are not perfect synonyms. In research, a static embedding gives mouse one vector that blends the rodent and the computer device, which is the core motivation for word sense disambiguation and for contextual embeddings. In real systems, a search engine that expands a query with synonyms can silently shift the sense or the register of what the user asked.

By the end you can

  1. Explain why vocabulary indices and logical symbols fail as meaning representations, using the one-hot dot product and the DOG example.
  2. Define lemma, wordform, sense and polysemy using the WordNet entry for mouse.
  3. State the truth-conditional definition of synonymy and test a candidate pair by substitution.
  4. Apply the principle of contrast to water and H₂O and similar pairs, naming the dimension (dialect, register or connotation) on which they differ.
  5. Distinguish synonymy, a relation between senses, from similarity, a graded relation between words, with examples.

Open the vocabulary file of an n-gram model. cat might be entry w_412, dog entry w_977 and spreadsheet entry w_3051. Ask the model which of those three words are alike and it has nothing to say. The numbers are positions in a list, and a list position carries no meaning: 412 is not closer in sense to 977 than to 3051.

Turning each index into a vector does not help. A one-hot vector has a single 1 at the word's index and zeros everywhere else. Two distinct words never share a non-zero position, so their dot product is always 0, whichever pair you pick:

ecat⋅edog=0=ecat⋅espreadsheet\mathbf{e}_{\text{cat}} \cdot \mathbf{e}_{\text{dog}} = 0 = \mathbf{e}_{\text{cat}} \cdot \mathbf{e}_{\text{spreadsheet}}
One-hot vectors make every pair of distinct words equally unlike

Jurafsky and Martin describe exactly this situation: in the n-gram models of Chapter 3 and in classical NLP applications, the only representation of a word is a string of letters or an index in a vocabulary list. A model trained on the cat sat learns nothing about the dog sat, because the two sentences share no symbol in the position that matters.

Four words as one-hot index boxes sit equally far apart; once they become points in a vector space, cat, dog and horse cluster while spreadsheet stays away

The logic class answer, and why it is circular

An introductory logic course offers a different answer: the meaning of dog is the predicate DOG, and the meaning of cat is CAT. Relations between meanings are then stated as axioms written by hand, for instance that every dog is a mammal:

∀x DOG(x)→MAMMAL(x)\forall x\, \mathrm{DOG}(x) \rightarrow \mathrm{MAMMAL}(x)

This is more expressive than an index, because the axioms support inference. But the symbol itself still says nothing; it is the word in capital letters. The old semantics joke makes the point. Q: What is the meaning of life? A: LIFE. Jurafsky and Martin attribute it to the semanticist Barbara Partee and call capitalization a pretty unsatisfactory model of meaning. Every relation you want, from similarity to connotation, has to be typed in by a person, and nothing about DOG tells you that it should sit near CAT.

RepresentationWhat it encodesWhat it misses
String or index w_iWhich word this is: identity, and nothing elseEvery relation. cat is exactly as far from dog as from spreadsheet
Logical symbol DOGWhatever axioms someone writes by hand, such as every dog is a mammalGraded similarity, connotation, and any relation nobody wrote down; the symbol only renames the word
Vector (preview of this lecture)Position in a space learned from how the word is used, so closeness is computableSense distinctions, if one vector must serve every sense of the word
Three ways to represent a word, and what each one leaves out

The rest of the lecture fills the third row. Vector semantics represents a word as a point in a space built from the contexts it appears in, and the resulting Embedding makes closeness a number you can compute instead of an axiom someone must write.

Recall

Why are vocabulary indices and logic symbols like DOG unsatisfying meaning representations?

Indices make every word equally different: distinct one-hot vectors have dot product 0. DOG just renames the word and needs hand-written axioms, so neither yields similarity, antonymy or connotation automatically.

Consider three sentences: Ann bought a car from Bo. Bo sold Ann a car. Ann paid Bo for a car. One event, one car, one transfer of money, described from three positions. Any adequate account of word meaning has to know that buy, sell and pay are tied together this way, and none of the symbol representations from the previous concept does.

Lexical semantics is the linguistic study of word meaning. It is not the study of dictionary definitions one entry at a time; it is the study of how meanings relate to each other. Jurafsky and Martin turn its findings into a list of what a model of word meaning should deliver, and this list is the checklist every later model in the lecture is graded against.

Desiderata from lexical semantics (SLP3 section 5.1)

Similarity
cat is similar to dog, and the model should say so without being told
Antonymy
hot and cold are opposites on one dimension, temperature, and alike on everything else
Connotation
happy carries positive feeling and sad carries negative feeling, beyond what each word refers to
Perspective
buy, sell and pay describe one commercial event from the buyer, the seller and the money
Inference
from 'Ann sold Bo a car' a question answering system should conclude that Bo bought a car

The first three entries get their own treatment in part 02: similarity as a graded human judgment, Antonymy as opposition on a single feature, and Connotation as affective meaning. Perspective and inference are what make the list more than a thesaurus: a question answering system that is asked who bought the car must connect it to a sentence that only says who sold it.

Keep the list in view as the lecture moves on. Sparse count vectors will turn out to be good at similarity and relatedness and weak at antonymy, because hot and cold occur in the same contexts. Word2vec will improve similarity further and add analogies, yet still give one vector to every sense of a word. Each model earns or loses marks on these rows.

Recall

List the five desiderata for a theory of word meaning, with one example each.

Similarity (cat and dog), antonymy (hot and cold), connotation (happy and sad), perspective (buy, sell and pay describe one event) and inference (Ann sold Bo a car, so Bo bought a car).

One lemma, many senses: the mouse entry

Type mouse into WordNet. The slide quotes two of its meanings: any of numerous small rodents, and a hand-operated device that controls a cursor. The full WordNet 3.0 entry has six: four noun senses and two verb senses. Before naming the parts of this entry, look at how much a single spelling has to carry.

from nltk.corpus import wordnet as wn

for synset in wn.synsets("mouse"):
    print(synset.name(), synset.lemma_names())
Listing the WordNet synsets of mouse with NLTK

The six synsets NLTK returns for mouse (WordNet 3.0)

mouse.n.01
Any of numerous small rodents (the slide's first sense)
shiner.n.01
A swollen bruise around the eye; the synset is shiner, black_eye, mouse
mouse.n.03
A person who is quiet or timid
mouse.n.04
A hand-operated device that controls a cursor (the slide's second sense)
sneak.v.01
To go stealthily or furtively
mouse.v.02
To manipulate the mouse of a computer
The lemma mouse (N) branches into four noun senses: the two on the slide in the main accent, the black eye and timid person senses in teal, with a note on the verb's two senses below

Lemma and wordform

The headword mouse is a Lemma, also called the citation form: the form under which a dictionary lists the word. The plural mice has no entry of its own; it is a wordform of the same lemma. A wordform is any inflected form a lemma takes in running text. The same split holds across verbs and languages, and it is the same lemma idea you met in tokenization and morphology.

WordformLemmaInflection
micemousePlural noun
sang, sungsingPast tense and past participle
duermesdormirSpanish, second person singular present: you sleep
Wordforms grouped under their lemma

Sense and polysemy

Each numbered meaning in the entry is a sense: a discrete aspect of the word's meaning. A lemma with several senses is polysemous, and the phenomenon is called Polysemy. WordNet groups senses into synsets, sets of near-synonymous senses that share one gloss and express one concept. That is why the black eye sense appears under the name shiner.n.01: its synset is {shiner, black_eye, mouse}, and WordNet names a synset after its first member.

How do you know two meanings really are separate senses? One practical test is the zeugma. In ?Does Air France serve breakfast and Philadelphia? the two uses of serve (providing food and flying to a city) are forced to share one verb, and the sentence sounds like a pun. That oddness is the evidence for two senses. With one sense, coordination is fine: Air France serves breakfast and lunch.

Why the split matters for systems

Jurafsky and Martin point out that a search for mouse info is ambiguous between a pet owner and a shopper. Deciding which sense a given occurrence uses is the task of word sense disambiguation. And the split sets up a limitation you will meet at the end of this lecture: a Static embedding gives each word type one vector, so the vector for mouse must blend the rodent and the device. A Contextual embedding computes a different vector for each occurrence, which is how modern models separate senses.

Recall

Using mouse and mice, define lemma, wordform, sense and polysemy.

mouse is the lemma (citation form). mouse and mice are wordforms. The rodent and the cursor device are two senses. A lemma having several senses is polysemy.

Quick check

Which statement correctly relates a lemma to its senses?

couch and sofa. filbert and hazelnut. car and automobile. vomit and throw up. big and large. Each pair can be swapped in some sentence without anyone noticing a change in what is claimed. That intuition has a precise form.

Two words are synonymous if they can be substituted for each other in any sentence without changing the truth conditions of the sentence, that is, the situations in which the sentence would be true. This is Synonymy in its truth-conditional definition. I sat on the couch and I sat on the sofa are true in exactly the same situations. WordNet even files car and automobile in the same synset, car.n.01.

The slide states the same idea more loosely: synonyms have the same meaning in some or all contexts. All contexts is the strict truth-conditional ideal. Some contexts is what real pairs such as big and large achieve, and that gap is exactly why synonymy is stated between senses rather than words.

The twist: the relation is between senses

Try the substitution with big and large. In Would I be flying on a large or small plane? the swap to big is harmless. In Miss Nelson became a kind of big sister to Benjamin it is not: a large sister is a different claim. The textbook draws the conclusion directly. Synonymy is a relationship between senses rather than words. WordNet makes this visible: big has 17 synsets and large has 11. They share some, such as large.a.01, above average in size, and not others, such as big.s.01, significant. A claim that two words are synonyms is really a claim about one of their senses.

Two regions of contexts for big and large: a large plane lights in the overlap where they share the size sense, while big sister glows only in the region that belongs to big

Worked example

Testing a candidate synonym pair

  1. Substitute in several sentences

    Take big and large. Swap them in a large plane, a big house, a big decision and my big sister.
  2. Check the truth conditions

    A large plane and a big plane are true of the same planes. A big decision is an important one, and a large decision is at best odd. My large sister makes a claim about her size, not her age.
  3. Find the sense in play

    The swaps that succeed all use the size sense (large.a.01). The swaps that fail use senses only big has: significant, and older or grown up.
  4. Check register and genre

    Even in the size sense, check whether one word belongs to a different style. Here neither is marked, so the pair survives.
  5. Result

    Of the sentences tested, big and large swap only in the size sense, so they are near-synonyms in that sense, not as words.

Recall

Give the truth-conditional definition of synonymy, and say why it is a relation between senses.

Two words are synonymous if they can be swapped in any sentence without changing the truth conditions. The swap works only when both words are used in a shared sense: big and large swap in a large plane (size) but not in my big sister (older), so the relation holds between particular senses. The slide's version, same meaning in some or all contexts, allows the partial case.

Quick check

Why does 'my large sister' sound wrong while 'a large plane' is fine?

water and H₂O refer to the same substance. Swap them in the glass contains water and the sentence stays true in exactly the same situations. Now imagine a hiking guide that says to carry two litres of H₂O per person. Nothing false was said, and yet the sentence is wrong for its setting. That wrongness is part of what the words mean.

The same thing happens with big and large: even setting aside the older-sibling sense, the pairs that pass the truth test still differ somewhere. Jurafsky and Martin put it carefully: while substitutions between some pairs of words like car and automobile or water and H₂O are truth preserving, the words are still not identical in meaning, and probably no two words are absolutely identical in meaning.

The principle of contrast

The generalization behind this is the Principle of contrast: a difference in linguistic form is always associated with some difference in meaning. The idea has a long history, from Girard in 1718 and Bréal in 1897 to Eve Clark in 1987, who stated it as: every two forms contrast in meaning. Clark used it to explain language acquisition: a child who already knows one word for a thing assumes a new word for the same thing must mean something different. In her words, there are no true synonyms.

Where do apparent synonyms differ, if not in truth? Clark names three dimensions, and the slide's list of politeness, slang, register and genre maps onto them.

  • Dialect. autumn and fall, truck and lorry, tap and faucet: the choice tells the listener where the speaker is from.
  • Register. die, pass away and pop off; attempt and try. A register is a speech style such as formal, colloquial or technical. Politeness and slang sit here, and so does genre: H₂O is the technical register of a chemistry text.
  • Connotation. politician and statesman, skinny and slim: the referent can be the same while the attitude differs. This is Connotation, which part 02 measures.
water slides to the casual end of a genre axis and H₂O to the technical end, while both stay linked to the same referent: same truth conditions, different meaning
PairSame truth?Where they differDimension
water and H₂OYesH₂O belongs to scientific writing; it is odd in a hiking or surfing guideGenre and register
big and large (sister)Nobig has an older or grown-up sense that large lacksNot a contrast case: a different sense (see concept 4)
die and pass awayYespass away is the polite, euphemistic choice; pop off is slangRegister (politeness)
politician and statesmanMostlystatesman praises, politician often does notConnotation
truck and lorryYesAmerican versus British EnglishDialect
Apparent synonym pairs and where they part ways

The consequence for the rest of the course is terminological: when NLP papers say synonym, they mean approximate synonymy, two senses close enough to substitute in most contexts. It also has an engineering consequence. Query expansion in search, paraphrase generation and data augmentation by synonym replacement all assume substitutability, and the principle of contrast predicts they will shift register, sense or tone some of the time. A paraphraser that rewrites passed away as died has kept the truth and changed the message.

Recall

State the principle of contrast and name the three dimensions along which apparent synonyms usually differ, per Clark.

Every difference in form marks some difference in meaning. The dimensions are dialect (truck and lorry), register (die and pass away) and connotation (politician and statesman).

Recall

Why is water and H₂O not a perfect synonym pair, even though substitution preserves truth?

The swap keeps the truth conditions, but H₂O belongs to a scientific genre and is odd in a hiking guide. By the principle of contrast that genre difference is part of its meaning.

Quick check

In a hiking guide, what best describes replacing water with H₂O?

car and bicycle are not synonyms. Neither are cow and horse. Yet everyone feels they belong together: both pairs share an element of meaning, a vehicle you ride on a road, a large farm animal. Swap them, though, and the truth changes. I took my car to work describes a different morning from I took my bicycle to work.

This relation is Word similarity. Jurafsky and Martin give the reason it matters: while words don't have many synonyms, most words do have lots of similar words. A model that only knew synonymy would have almost nothing to say about most of the vocabulary; a model of similarity has something to say about every word.

There is a second, quieter shift. Synonymy was a relation between senses, which requires deciding first what the senses of every word are. Similarity is usually stated between words, which avoids committing to a sense inventory at all. That is exactly the quantity vector models compute: one number for a pair of words, later the cosine of the angle between their vectors. Part 02 shows how humans rate it, on datasets such as SimLex-999, and how it differs from relatedness.

RelationHolds betweenExampleSubstitutable?
SynonymySensescouch and sofaMostly yes, in the shared sense
SimilarityWordscar and bicycleNo, the truth of the sentence changes
Synonymy versus similarity

Recall

How does similarity differ from synonymy, and why is it the better target for vector models?

Synonymy holds between senses and requires substitutability with the same truth conditions. Similarity is a graded relation between words that share elements of meaning (car and bicycle), without substitutability. Most words have few synonyms but many similar words, and similarity needs no sense inventory, so it is what a vector model can measure for every word.

Quick check

Which pair is similar but not synonymous?

Recap

If you remember nothing else

  • Treating a word as an index or as a symbol like DOG gives identity, not meaning. Every pair of distinct one-hot words has dot product 0.
  • Lexical semantics wants a model that captures similarity, antonymy, connotation, perspective (buy, sell, pay) and inference.
  • A lemma (citation form) groups wordforms such as mouse and mice. Its senses are discrete aspects of meaning. Several senses means polysemy.
  • WordNet 3.0 lists 4 noun senses and 2 verb senses for mouse. The slide shows only the rodent and the cursor device.
  • Synonyms can be substituted without changing truth conditions, and synonymy holds between senses: big and large share size but not older sibling.
  • Principle of contrast: every difference in form marks a difference in meaning, so perfect synonyms probably do not exist.
  • Apparent synonyms differ in dialect, register or connotation. H₂O belongs to a scientific genre, so it is odd in a hiking guide.
  • Similarity (car and bicycle, cow and horse) is a graded relation between words. It is what vector models measure next.

Sources

Part 02: Similarity, relatedness, antonymy and connotation

The graded relations between word senses (similarity rated by humans, relatedness through semantic fields, antonymy as opposition on one feature) and the affective meaning captured by valence, arousal and dominance.

6 concepts, slides 11-17

Why this part matters

Before we build a single vector, we need to know what a good vector is supposed to capture. This part names the meaning relations that every embedding model in the rest of the lecture is judged against.

Similarity is the target of SimLex-style intrinsic evaluation. Relatedness is what co-occurrence counts actually pick up, whether you wanted it or not. Antonymy is the classic failure case of distributional models. Connotation is the raw material of sentiment and affect lexicons. Exams like to hand you a list of word pairs and ask which relation each one shows, and a research project that reports a score on a word benchmark must know which of these relations that benchmark measures. Part 01 gave us lemmas, senses and synonymy. Here we add the graded, messier relations that sit around them.

By the end you can

  1. Explain word similarity as a graded, human-rated relation and read SimLex-999 scores.
  2. Distinguish similarity from relatedness, and identify a semantic field from examples.
  3. Define antonymy, tell scale or binary opposites from reversives, and explain why antonyms look similar to distributional models.
  4. Describe connotation and evaluation, and give word sets that differ only in connotation.
  5. Define valence, arousal and dominance, and interpret NRC VAD scores.
  6. Label a word pair with the right relation: synonym, similar, related, antonym, or a connotation contrast.

Read these pairs and give each one a number from 0 to 10 for how alike the two meanings are: vanish and disappear, behave and obey, belief and impression, muscle and bone, modest and flexible, hole and agreement. You probably gave the first pair close to 10, the last close to 0, and found the middle harder but not impossible. Hundreds of people did exactly this, and their averages are the numbers below.

PairSimLex similarity (0 to 10)USF associationPOS
vanish / disappear9.82.76verb
behave / obey7.30.21verb
belief / impression5.950.10noun
muscle / bone3.650.13noun
modest / flexible0.980adjective
hole / agreement0.30noun
Slide 11 pairs with their SimLex-999 similarity, plus the USF free-association strength recorded in the same file

The association column comes from the University of South Florida free-association norms: how often people answer the second word when given the first as a cue. It measures connection, not shared features.

The scores fall away smoothly. There is no point where the pairs stop being similar and start being dissimilar, which is the first thing to notice. Synonymy, from part 01, is close to a yes or no question about two senses. Word similarity is a matter of degree: two words are similar when their meanings share features, and they can share many features, a few, or none. vanish and disappear share nearly all of them. muscle and bone share a few (body tissue, anatomy) and differ on the rest. hole and agreement share essentially nothing.

The second thing to notice is that similarity is a relation between words, not senses. This is the car and bicycle idea from the end of part 01. To say whether two senses are synonyms you need a sense inventory; to ask a person how similar two words feel, you do not. That makes word similarity cheap to collect and directly comparable to anything that produces one number per word pair, which is exactly what a vector model does.

Where the numbers come from

The table is SimLex-999 (Hill, Reichart and Korhonen 2015). It contains 999 pairs: 666 noun pairs, 222 verb pairs and 111 adjective pairs, mixing concrete and abstract words. About 500 Mechanical Turk workers rated them on an integer slider from 0 to 6, and the mean ratings were then linearly rescaled to 0 to 10. The slide shows the rescaled values, which match the released data file exactly. Individual raters disagree a fair amount: the average Spearman correlation between two raters is 0.67, and between one rater and the mean of the others it is 0.78. The average is what is stable.

Why should you care about these particular numbers? Because later in this lecture they become the gold standard for intrinsic evaluation. You compute the cosine between the two vectors of every SimLex pair, rank the pairs by cosine, and report the Spearman rank correlation with the human ranking. A model that agrees with people about which pairs are more alike scores high.

Recall

What scale does SimLex-999 use, and what does 0.3 mean for hole and agreement?

0 to 10, rescaled from a 0 to 6 slider. A score of 0.3 means raters judged the pair to share almost no meaning.

Quick check

Which pair would SimLex-999 annotators rate as most similar?

Relatedness: words that belong to the same scene

Compare two pairs: coffee and tea, then coffee and cup. Coffee and tea are both hot drinks made by steeping or brewing a plant, both contain caffeine, both are served in the morning. They share features, so they aresimilar. Coffee and cup share practically no features: one is a drink from a plant, the other is a manufactured container. Yet nobody would call them unconnected. They take part together in one everyday event, drinking coffee from a cup.

That second kind of connection is word relatedness, also called association. Two words are related when they are connected in any way at all: by shared features, by a shared event, by part and whole (car and wheel), by function (pencil and paper), even by opposition (hot and cold). Budanitsky and Hirst put the hierarchy plainly: similarity is a special case of relatedness. Every similar pair is related, but many related pairs are not similar. They quote Resnik's example: cars and gasoline are more closely related than cars and bicycles, but the latter pair are certainly more similar.

coffee at the centre. tea sits close on a short solid edge because the two share features. cup sits far away on a long dashed edge: it shares almost no features with coffee, but the two belong to the same scene.
PairShares features?Same scene?Label
coffee / teaYes: both are hot drinksOftenSimilar (and related)
coffee / cupAlmost none: drink against objectYes: drinking coffeeRelated, not similar
surgeon / scalpelNo: person against toolYes: an operationRelated, not similar
car / bicycleSome: wheeled vehiclesRarelySimilar, weakly related
car / gasolineNo: vehicle against fuelYes: driving, refuellingRelated, not similar
hole / agreementNoNoNeither
Two separate questions: do the words share features, and do they appear in the same scene?

The SimLex file records both quantities, so you can see the split in real numbers. clothes and closet have similarity 3.27 but association 4.83: related more than they are alike. car and bicycle have similarity 3.47 and association only 0.41: alike more than they are associated.

Semantic fields

When you collect all the words that keep turning up in the same scene, you get a semantic field: a set of words that cover one domain and bear structured relations to each other. The hospital field holds surgeon, scalpel, nurse, anaesthetic and hospital. The restaurant field holds waiter, menu, plate, food and chef. The house field holds door, roof, kitchen, family and bed. Inside a field the relations are varied: a surgeon uses a scalpel, a nurse assists a surgeon, the anaesthetic is given in the hospital. What unites them is the domain, not shared features.

Three fields, five words each. Each field lights in turn and its words join up: the edges inside a field are relatedness, not similarity.

Fields are not only a linguist's classification. Topic models such as Latent Dirichlet Allocation read a large collection of documents with no labels and discover clusters of words that tend to occur together, and the clusters they find look very much like semantic fields. That is a first hint of the theme of this whole lecture: the company a word keeps carries information about its meaning.

Recall

Why are coffee and tea similar, but coffee and cup only related?

Tea shares features with coffee: both are hot, caffeinated drinks. A cup shares almost none, but it takes part in the same event, drinking coffee, so the pair is connected through a scene or semantic field rather than through shared meaning.

Recall

Which semantic field do waiter, menu, plate and chef belong to, and what holds them together?

The restaurant field. They share almost no features of meaning; what unites them is the domain, and the varied relations inside it (a waiter brings the menu, a chef prepares the food on the plate).

Quick check

A model gives coffee and cup a high score. What has it most likely captured?

Take hot and cold. Both are adjectives. Both describe temperature. Both slot into the same frames: hot coffee and cold coffee, hot weather and cold weather, it is too hot today and it is too cold today. Line up everything you know about the two words and they agree on almost every point. They disagree on exactly one: which end of the temperature scale they name.

That is the definition of antonymy. Antonyms are senses that are opposite with respect to only one feature of meaning and otherwise very similar. It sounds paradoxical that opposites are mostly alike, but you cannot be opposite to something unless you are first comparable to it. Hot is not the opposite of Tuesday.

hot and cold share their part of speech, their dimension and the nouns they modify, so the first three rows light identically. Only the scale position flips to opposite ends. Below, a reversive pair: rise and fall move in opposite directions.

Kinds of opposition

The single opposed feature can be of different types. In the first group the two words name the two values of a binary choice or the two ends of a scale: long and short, fast and slow, big and little. In the second group, the reversives, the two words describe change or movement in opposite directions: rise and fall, up and down. Mohammad, Dorr, Hirst and Turney refine this further (antipodals, complementaries, gradable opposites) and note that many contrasting pairs, such as warm and cold, are not strict opposites at all.

KindPairsWhat is opposed
Opposite ends of a scalelong / short, fast / slow, hot / coldA position on one graded dimension (length, speed, temperature)
Binary oppositionin / outTwo values with no middle ground
Reversiverise / fall, up / downThe direction of a change or movement
The two families on slide 14, with the scale case split from the binary one

What humans say, and why models struggle

Because antonyms differ on a feature people care about, human raters call them dissimilar. Because they share everything else, they are among the most strongly associated pairs in the language. SimLex records both, and the gap is striking. Hill and colleagues conclude that antonyms are the most strongly associated word pairs among the finer-grained relations they examined.

PairSimLex similarityUSF association
night / day1.888.19
old / new1.587.25
short / long1.235.36
bottom / top0.706.96
large / big (synonyms, for contrast)9.550.68
SimLex-999 similarity against USF association for antonym pairs, with a synonym pair for contrast

Now look ahead. The distributional hypothesis that drives the rest of this lecture says that words in similar contexts have similar meanings. hot and cold occur in almost identical contexts, so a model built on contexts will put them close together. Opposites even co-occur in the same sentence more often than chance would predict (Charles and Miller, cited by Mohammad and colleagues), which pulls them closer still. SLP3 is blunt about the result: automatically distinguishing synonyms from antonyms can be difficult.

Recall

What do antonyms have in common, and why does that matter for distributional models?

They are opposite on one feature only and alike on everything else, so they occur in the same contexts and end up close together in a distributional space. Synonyms and antonyms are therefore hard to separate.

Recall

Name the two kinds of antonymy on slide 14, with an example of each.

Binary opposition or opposite ends of a scale (long/short, fast/slow), and reversives, which describe change or movement in opposite directions (rise/fall, up/down).

Quick check

Why do distributional models often place hot close to cold?

Connotation: the feeling a word carries

A museum shop sells a replica of an ancient vase. A street stall sells a knockoff. Both objects are copies of a real thing, and a description of either would read much the same. But the first word is close to praise and the second is an accusation.

The part of meaning that differs here is connotation: the aspects of a word's meaning tied to a writer's or reader's emotions, sentiment, opinions or evaluations. Some words exist mainly to evaluate: great and love are positive, terrible and hate are negative. Others, like replica and knockoff, describe the same thing while carrying different attitudes toward it. Positive or negative evaluation in language is called sentiment, and connotation is what sentiment analysis, stance detection, and NLP work on political language and consumer reviews all exploit.

Connotation can be measured. Affect lexicons give each word a score, and the one we meet in the next concept, the NRC VAD Lexicon, gives a valence (pleasantness) between 0 and 1. Here is the SLP3 example worked through with its real numbers.

Worked example

Two sets of copies, one difference in feeling

  1. Look up each word's valence

    Negative set: fake 0.073, knockoff 0.350, forgery 0.235. Positive set: copy 0.460, replica 0.480, reproduction 0.800.
  2. Average each set

    Negative mean: (0.073 + 0.350 + 0.235) / 3 ≈ 0.219. Positive mean: (0.460 + 0.480 + 0.800) / 3 = 0.580.
  3. Compare, and read the numbers critically

    The positive set is about 0.36 higher. But positive is relative here: copy, at 0.460, sits just below the neutral midpoint. And reproduction scores high partly because it is polysemous: its biological sense (having children) is pleasant, and a lexicon with one score per word averages over all senses.
  4. Result

    Words that refer to nearly the same thing can sit far apart on valence. Other pairs show the same pattern: innocent 0.729 against naive 0.406, great 0.958 against terrible 0.061, love 1.000 against hate 0.031.

Recall

Give two words with nearly the same reference but different connotation, and say how you would measure the difference.

replica and fake (or knockoff). Look up their valence in the NRC VAD Lexicon: replica 0.480, fake 0.073.

Compare napping and toxic. napping is pleasant and calm, and it puts you in no particular position of control. toxic is unpleasant and agitating. A single positive or negative score would capture the first difference, but not the second, and not the question of who has the power.

Osgood and colleagues (1957) found that people's ratings of words consistently varied along three affective dimensions, now called valence, arousal and dominance:

  • Valence is the pleasantness of the stimulus. napping 0.765, toxic 0.008.
  • Arousal is the intensity of emotion the stimulus provokes. napping 0.046, toxic 0.885.
  • Dominance is the degree of control the stimulus exerts. napping 0.306, toxic 0.492.

Three numbers per word means each word becomes a point in a three-dimensional space. SLP3 calls this the first expression of the idea behind vector semantics: on the 1 to 9 scales of Warriner and colleagues (2013), heartbreak sits at [2.45, 5.65, 3.58]. Part 03 takes that idea and scales it from three hand-chosen dimensions to hundreds learned from text.

A V, A, D frame. love, toxic, napping and powerful start bunched at the centre, then slide to their real NRC VAD coordinates, with droplines to the valence-dominance floor showing how high each sits on arousal.

How the NRC VAD Lexicon was built

The numbers come from the NRC VAD Lexicon (Mohammad 2018). Version 1 covers about 20,000 English words; the released file has 19,971 entries. Asking people to rate a word on a slider is unreliable, because everyone uses the slider differently. Instead Mohammad used best-worst scaling. An annotator sees four words and picks the one highest on the dimension (say, most pleasant) and the one lowest. Over many such four-word sets, each word is scored by how often it won minus how often it lost.

score(w)=#best(w)#seen(w)−#worst(w)#seen(w)\text{score}(w) = \frac{\#\text{best}(w)}{\#\text{seen}(w)} - \frac{\#\text{worst}(w)}{\#\text{seen}(w)}
Best-worst score, which runs from -1 to 1 before rescaling to 0 to 1 in v1

Comparative judgements are much more consistent than absolute ones. Splitting the annotators into two random halves and correlating the scores each half produces gives split-half reliability of r = 0.95 for valence, 0.90 for arousal and 0.91 for dominance. Version 2, released in March 2025, extends the lexicon to over 55,000 terms (about 10,000 of them multiword phrases) on a -1 to 1 scale, with split-half Spearman of 0.98, 0.97 and 0.96.

WordValenceArousalDominance
love1.0000.5190.673
happy1.0000.7350.772
toxic0.0080.8850.492
nightmare0.0050.8100.436
elated0.7920.9600.725
frenzy0.6100.9650.682
mellow0.6330.0690.265
napping0.7650.0460.306
calm0.8750.1000.282
excited0.9080.9310.709
powerful0.8650.8300.991
leadership0.8700.6900.983
controlling0.4900.4410.885
weak0.1800.2410.045
empty0.1880.1830.081
NRC VAD v1 scores (0 to 1). Sort mentally by each column and the order changes: the dimensions are independent.

Recall

Define valence, arousal and dominance, and place napping on each.

Valence is pleasantness, arousal is intensity of emotion, dominance is degree of control. napping has valence 0.765 (pleasant), arousal 0.046 (very calm) and dominance 0.306 (low control).

Recall

How is an NRC VAD score produced, and how reliable is it?

Best-worst scaling over four-word sets: the proportion of times a word is chosen best minus the proportion chosen worst, rescaled to 0 to 1 in v1. Split-half reliability is r = 0.95, 0.90 and 0.91 for valence, arousal and dominance.

Quick check

In NRC VAD v1, napping scores 0.046 on arousal. What does that tell you?

Step back and look at what we now have. One word can map to many senses: mouse is a rodent or a pointing device. One sense can map to many words: couch and sofa. The mapping between words and concepts is many to many, and on top of it sits a set of relations, some between senses and some between whole words.

RelationLevelGraded?ExampleTypical evidence
SynonymySenseRarely exactcouch / sofaThesaurus or WordNet synsets
AntonymySenseComes in kindshot / coldWordNet antonym links
SimilarityWordGradedvanish / disappearSimLex-999 ratings
RelatednessWordGradedcoffee / cupAssociation norms or WordSim-353
ConnotationWordGradedreplica / knockoffNRC VAD Lexicon
The five relations that a representation of word meaning should reproduce

A lemma groups its senses, and polysemy is the fact that it has several. Synonymy and antonymy are relations between senses. Similarity, relatedness and connotation are graded and can be asked of whole words, which is what makes them measurable with ratings and lexicons.

This table is a list of desiderata. Any representation of word meaning we build next should put similar words near each other, keep related words in recognisable neighbourhoods, encode affect in some consistent direction, and ideally tell synonyms from antonyms. Part 03 introduces vectors as that representation. A vector space captures relatedness readily and affect reasonably well; separating true similarity from relatedness is harder, and telling synonyms from antonyms is where it struggles most, as concepts 2 and 3 warned.

Quick check

replica and knockoff differ mainly in which relation?

Recap

If you remember nothing else

  • Similarity is graded and word level. SimLex-999 (999 pairs, 0 to 10) runs from vanish/disappear 9.8 down to hole/agreement 0.3.
  • Relatedness (association) is broader: coffee/cup are related through a shared event but not similar. Similarity is a special case of relatedness.
  • A semantic field is a set of words covering one domain with structured relations: the hospital, restaurant and house fields. Topic models induce fields from text.
  • Antonyms are opposite on one feature and alike on the rest. The kinds are binary or scalar opposites (long/short) and reversives (rise/fall).
  • Antonyms score low on SimLex similarity but high on association (night/day 1.88 against 8.19), so distributional models tend to put them close together.
  • Connotation is affective meaning. Near-synonyms can differ sharply: replica 0.480 against fake 0.073 valence.
  • Osgood's three affective dimensions are valence (pleasantness), arousal (intensity) and dominance (control).
  • NRC VAD v1 has about 20k words scored 0 to 1 by best-worst scaling. v2 (2025) has over 55k terms on -1 to 1.
  • Every relation here is a test that later vector representations must pass.

Sources

Part 03: Vector semantics and the distributional hypothesis

Defining a word by its contexts (Wittgenstein, Harris, the ongchoi example), combining that with Osgood's meaning as a point in space, and arriving at embeddings, plus why vectors generalize better than word identities and the two kinds (sparse tf-idf, dense word2vec).

6 concepts, slides 18-30

Why this part matters

Every model in this course from here on, word2vec now and BERT and large language models later, begins by turning words into vectors. This part explains why that works at all. Words that keep similar company mean similar things, and once words are points in a space, "similar" becomes something you can measure.

Parts 1 and 2 listed what a model of word meaning should capture: synonymy, similarity, relatedness and connotation. This part introduces the model that meets many of those wishes. It is a core exam topic (state the hypothesis, compare sparse and dense vectors), the basis of retrieval and semantic search in real systems, and the representation behind most NLP research projects you are likely to start.

By the end you can

  1. State the distributional hypothesis and attribute it to Harris, Firth and Joos, with Wittgenstein's "meaning is use" as its philosophical root.
  2. Infer the category of an unknown word (ongchoi) from the contexts it shares with known words.
  3. Represent a word as a point in a space of affective dimensions and compute the distance between two words.
  4. Define an embedding and read a 2D t-SNE word map without over-reading global distances.
  5. Explain why vector features generalize to similar unseen words when identity features cannot.
  6. Compare sparse (tf-idf, PPMI) and dense (word2vec) embeddings on length, sparsity, construction and use.

Meaning from the company a word keeps

Take two words, "oculist" and "eye-doctor". Collect every sentence each appears in, and look at the neighbors: eye, examined, prescription, glasses, appointment. The two lists are almost the same. Now compare "oculist" with "lawyer". Some neighbors still overlap (appointment, fee, office), but far fewer. Without a dictionary, the overlap of environments already tells you which pair is closer in meaning.

That observation is the distributional hypothesis. Zellig Harris put it in 1954 using exactly this example: if two words have almost identical environments, meaning neighboring words or the grammatical frames they occur in, we call them synonyms. He then made the claim graded. The difference in meaning between two words corresponds roughly to the amount of difference in their environments. That second sentence matters more than the first, because it turns meaning into a quantity you can estimate by counting.

The idea was in the air in the 1950s. Wittgenstein had argued that, for a large class of cases, the meaning of a word is its use in the language. Joos (1950) described the meaning of a morpheme as the set of conditional probabilities of its occurrence alongside every other morpheme, which is almost a definition of a language model. Firth (1957) gave the line everyone quotes: "You shall know a word by the company it keeps." Firth and Harris are often merged, but they meant different things. Firth cared about situational and cultural context; Harris cared about the formal distribution of words inside text. NLP took Harris's version, because it can be computed from a corpus alone.

ThinkerYearClaimWhat it contributes
Ludwig Wittgenstein1953For a large class of cases, the meaning of a word is its use in the languageThe philosophical license: stop looking for meaning behind the word and look at how it is used
Martin Joos1950The meaning of a morpheme is the set of conditional probabilities of its occurrence with all other morphemesA probabilistic statement, decades before anyone could count at scale
Zellig Harris1954Words with almost identical environments are synonyms; the difference in meaning roughly matches the difference in environmentsThe operational, graded form that NLP actually implements
J. R. Firth1957You shall know a word by the company it keepsThe slogan, from a theory of meaning in situational and cultural context
Four roots of one idea

This is why the lecture moves to vector semantics. Earlier, lexical semantics gave us a list of relations a good model should respect: synonymy, similarity, relatedness, connotation. Writing those relations down by hand for every pair of words is impossible. The distributional hypothesis says you do not have to: read enough text, record each word's environments, and the relations fall out of the overlaps. Vector semantics is the standard way NLP does this today.

Recall

State the distributional hypothesis, and say who formulated it in the 1950s.

Words that occur in similar environments (neighboring words or grammatical contexts) have similar meanings, and the difference in meaning roughly matches the difference in environments. Harris (1954), Joos (1950) and Firth (1957, "You shall know a word by the company it keeps"), with philosophical roots in Wittgenstein's "meaning is use" (1953).

Quick check

Harris (1954) wrote about two words A and B that have almost identical environments. What did he conclude about them?

Guessing ongchoi from the words around it

Suppose you have never seen the word "ongchoi", a recent borrowing into English from Cantonese, and you meet it three times: ongchoi is delicious sauteed with garlic; ongchoi is superb over rice; ongchoi leaves with salty sauces. You do not know what it is yet. But you have read plenty of other sentences: spinach sauteed with garlic over rice, chard stems and leaves are delicious, collard greens and other salty leafy greens.

Put the contexts side by side and the answer is hard to miss. Sauteed, garlic, rice, leaves, delicious and salty all show up around ongchoi and around the leafy greens you already know. Nothing about laptops, contracts or weather. So ongchoi is very likely a leafy green that people cook and eat. It is: the plant is Ipomoea aquatica, a relative of morning glory sometimes called water spinach, and it has other names in Chinese, Malay and Vietnamese.

Contexts that ongchoi shares with known words

ongchoi
delicious, sauteed, garlic, superb, rice, leaves, salty, sauces
spinach
sauteed, garlic, rice
chard
stems, leaves, delicious
collard greens
salty, leafy, greens
Two rows of context words, ongchoi above and the known greens spinach, chard and collards below. The six shared words (sauteed, garlic, rice, leaves, delicious, salty) light up and link across; superb and stems stay dim because only one row has them.

Worked example

Inferring ongchoi

  1. List the contexts of the unknown word

    Around ongchoi: delicious, sauteed, garlic, superb, rice, leaves, salty, sauces.
  2. List the contexts of candidate known words

    Spinach: sauteed, garlic, rice. Chard: stems, leaves, delicious. Collard greens: salty, leafy, greens. A distractor such as laptop: screen, battery, keyboard.
  3. Mark what is shared

    Spinach shares 3 context words with ongchoi, chard shares 2, collard greens share 1, and laptop shares 0. Together the greens cover sauteed, garlic, rice, leaves, delicious and salty.
  4. Result

    Ongchoi sits with the leafy greens and nowhere near laptop. The prediction is "a cooked leafy green", which is right.

This is the computational form of the distributional hypothesis. Define the meaning of a word by its distribution, the neighboring words or grammatical environments it appears in, and then do the obvious thing: count the words in the context of ongchoi and compare those counts with the counts for every other word. A table of such counts, one row per word and one column per context word, is the term-context matrix of part 4, and each row is a word's vector.

Recall

What exactly would a program count to carry out the ongchoi inference?

For each word, how often every other word appears within a small window around it. Comparing ongchoi's counts with those of spinach, chard and collards shows heavy overlap on sauteed, garlic, rice, leaves, delicious and salty. That count table is the term-context matrix, and each row is the word's vector.

Here are two words with three numbers each. Heartbreak is [2.45, 5.65, 3.58] and courageous is [8.05, 5.5, 7.38]. The first number is valence (how pleasant), the second is arousal (how intense the emotion), the third is dominance (how much control is exerted). Plot both as points. They sit far apart on valence and dominance, and almost level on arousal: both words are emotionally charged, one pleasantly and with control, the other unpleasantly and with loss of control.

Valence, arousal and dominance ratings on a 1 to 9 scale (Warriner et al. 2013)

courageous
[8.05, 5.5, 7.38]
music
[7.67, 5.57, 6.5]
heartbreak
[2.45, 5.65, 3.58]
cub
[6.71, 3.95, 4.24]

The idea of placing a word at a point goes back to Charles Osgood and colleagues in 1957. Osgood asked people to rate words on many bipolar scales, such as good to bad, strong to weak, active to passive, a method he called the semantic differential. Factor analysis showed that most of the variation came from three factors, which he named evaluation, potency and activity. Today the same three are usually called valence, dominance and arousal, the VAD dimensions of a word's connotation from part 2. Osgood noticed that three numbers per word make each word a point in a three-dimensional space, and he proposed that similarity of meaning is nearness in that space. That is the first appearance of vector semantics.

d(u,v)=∑i(ui−vi)2d(\mathbf{u},\mathbf{v})=\sqrt{\sum_i (u_i-v_i)^2}
Euclidean distance between two points

Worked example

How far is courageous from heartbreak?

  1. Subtract coordinate by coordinate

    Valence 8.05 − 2.45 = 5.60, arousal 5.5 − 5.65 = −0.15, dominance 7.38 − 3.58 = 3.80.
  2. Square and add

    5.60² + 0.15² + 3.80² = 31.36 + 0.02 + 14.44 = 45.82.
  3. Take the square root

    √45.82 ≈ 6.77.
  4. Result

    For comparison, courageous is 0.96 from music and 3.75 from cub. Heartbreak is the far outlier, and almost all of the gap comes from valence and dominance.
Four words placed by their valence (V), arousal (A) and dominance (D) ratings. Drop lines show each word's height on the arousal axis; courageous and heartbreak light up and the long segment between them is their distance, about 6.77.

Put the two threads together. Idea 1 is that meaning can be defined by linguistic distribution. Idea 2, from Osgood, is that meaning can be a point in a multidimensional space. Vector semantics joins them: represent each word as a point, but let the word's distribution, not a panel of human raters, decide where the point goes.

Recall

What two 1950s ideas does vector semantics combine?

(1) Meaning defined by linguistic distribution (Harris, Firth, Joos). (2) Meaning as a point in a multidimensional space (Osgood et al. 1957). An embedding is a point in space whose position is derived from the word's distribution.

Recall

Where do the slide 25 numbers really come from, and on what scale?

From Warriner, Kuperman and Brysbaert (2013), human ratings of about 14,000 lemmas on a 1 to 9 scale. The VAD dimensions trace back to Osgood's semantic differential (evaluation, potency, activity).

Quick check

Using the slide 25 ratings and Euclidean distance, which word is farthest from courageous in VAD space?

Embeddings: points placed by distribution

Look at a map of word vectors squashed onto a page. Good, nice, wonderful, fantastic, amazing and very good huddle in one region. Bad, worst, worse, dislike and not good gather in another. Function words such as to, by, that, is and with sit off by themselves. Nobody placed these words by hand. Their positions came from training on text.

Twenty-four words as dots. They start loosely spread, then tighten into three groups: positive words, negative words and function words, each outlined once it forms.

This is vector semantics in its working form. Each word is a vector, a list of numbers, rather than an arbitrary symbol such as the string "good" or the index w45. Similar words end up nearby in what is called semantic space. And the space is built automatically, by seeing which words are nearby in text, so the distributional hypothesis does the placing that Osgood's raters used to do.

Such a vector is called an embedding, because the word is embedded into a space. The term began in the latent semantic analysis community in the late 1990s, where it named the mapping from sparse count space into a smaller dense space, and it later shifted to mean the resulting vector itself. Embeddings are now the standard way to represent word meaning in NLP: practically every modern system, from classifiers to large language models, starts by looking up or computing them. They give a fine-grained model of similarity, a number for every pair of words instead of a yes or no.

Recall

What can and cannot be read from a 2D t-SNE map of word embeddings?

Local neighborhoods (which words are near each other) are roughly preserved. Distances between clusters and absolute positions are distorted by the projection from 60 dimensions, so do not read them as real distances.

Why vectors beat word identities

Build a sentiment classifier the traditional way. Feature 5 is "the previous word was terrible", and training learns that it signals a negative review. At test time a review says "awful acting". If awful never appeared in the labeled training data, feature 5 does not fire, no other feature knows about awful, and the classifier has nothing to go on.

Now replace the identity feature with the previous word's embedding. During training the input was terrible's vector, say [35, 22, 17, ...], and the classifier learned weights on those coordinates. At test time awful arrives as [34, 21, 14, ...]. The weights do not care whether the word is the same string; they act on the numbers, and these numbers are nearly the same. The classifier treats awful almost exactly as it treated terrible. It has generalized to a similar but unseen word.

Left: an identity feature for terrible rejects the key awful, because only an exact match fires. Right: the vector for awful swings in beside the vector for terrible, separated by an angle of about 3 degrees (cosine about 0.999).
cos⁡(u,v)=u⋅v∣u∣ ∣v∣\cos(\mathbf{u},\mathbf{v})=\frac{\mathbf{u}\cdot\mathbf{v}}{|\mathbf{u}|\,|\mathbf{v}|}
Cosine similarity, developed fully in part 4

Worked example

How close are terrible and awful?

  1. Dot product

    Using only the three coordinates the slide shows: 35×34 + 22×21 + 17×14 = 1190 + 462 + 238 = 1890.
  2. Lengths

    √(35² + 22² + 17²) = √1998 ≈ 44.70 and √(34² + 21² + 14²) = √1793 ≈ 42.34.
  3. Divide

    1890 / (44.70 × 42.34) ≈ 0.9986.
  4. Result

    On these three coordinates the vectors point in almost the same direction, giving a cosine similarity near 1 and an angle of about 3°. Their Euclidean distance is √11 ≈ 3.32, small next to their lengths. Anything the classifier learned about terrible transfers.
PropertyIdentity featureVector feature
What is storedA yes or no: was the previous word exactly terribleThe previous word's vector, for example [35, 22, 17, ...]
Test-time matchString equalityGeometry: weights act on every coordinate, so nearby vectors produce nearby scores
Unseen similar word (awful)Feature never fires; the learned weight is wasted[34, 21, 14] lands almost where terrible did, so the classifier reacts in nearly the same way
Number of weightsOne per vocabulary word, often 50,000 or moreOne per dimension, often 300
Identity features against vector features

This matters because of what lecture 2 showed about vocabularies. Zipf's law means most word types are rare, and about half of them appear only once. A classifier trained on a few thousand labeled reviews will meet many words at test time that it never saw with a label. Embeddings, learned from billions of unlabeled words, carry knowledge about those words into the classifier. Dense vectors also need far fewer weights, around 300 per input position instead of one per vocabulary word, and they can place car and automobile close together, which separate identity features never can.

Recall

Why does a word-identity feature fail on an unseen synonym when an embedding feature does not?

The identity feature fires only if the exact same word appeared in training. An embedding feature compares vectors, so a test word whose vector is close to a trained word's vector (for example [34, 21, 14] against [35, 22, 17], cosine ≈ 0.999) gets similar treatment.

Quick check

A sentiment classifier learned that the previous word 'terrible' signals negativity. At test time it meets 'awful', which never appeared in its labeled training data. Why can an embedding-based classifier still handle it?

Picture two vectors for ongchoi. The first has one slot per vocabulary word, tens of thousands of them, and stores how often each word appeared near ongchoi. Garlic, rice and leaves have counts; nearly every other slot is 0. The second has about 300 real numbers, almost none of them zero, some negative, and none of them labeled with a word. Both are embeddings. This lecture covers both families.

Sparse vectors: weighted counts

A sparse vector is built from a simple function of counts. With tf-idf, the classic weighting from information retrieval, the counts come from documents. With PPMI, they come from nearby words, re-weighted so that informative co-occurrences stand out. These vectors are the workhorse of search engines and a strong, cheap baseline in almost any text task. Their dimensions are interpretable, because each one is a specific word or document.

Dense vectors: learned by prediction

A dense vector such as one from word2vec is learned instead of counted. Word2vec trains a simple classifier to predict whether a word is likely to appear near a target word, and keeps the classifier's weights as the embedding. The labels come free from running text, which is self-supervision. Both families give one fixed vector per word type, a static embedding. Later in the course, contextual embeddings such as BERT compute a different vector for each occurrence of a word.

PropertySparse (tf-idf, PPMI)Dense (word2vec)
Length|V|, tens of thousands50 to 1000
ZerosMostly zeroMostly non-zero, can be negative
How builtWeighted co-occurrence countsA classifier trained to predict whether a word appears near the target
What one dimension meansA specific context word or documentNothing individually
Typical useInformation retrieval, a strong baselineInput features for neural NLP
Synonyms such as car and automobileSeparate, unrelated dimensionsCan end up with similar coordinates
The two families of embeddings in this lecture

Recall

Contrast sparse and dense embeddings on length, content and construction.

Sparse vectors (tf-idf, PPMI) are |V|-long, mostly zero, and built from weighted co-occurrence counts. Dense vectors (word2vec) have 50 to 1000 real-valued, mostly non-zero entries, and are learned by training a classifier to predict whether a word appears near the target.

Quick check

Which statement correctly contrasts the two kinds of embeddings on slide 30?

Recap

If you remember nothing else

  • Distributional hypothesis: words in similar environments have similar meanings, roughly in proportion to how similar the environments are (Harris 1954, Firth 1957, Joos 1950; Wittgenstein 1953: meaning is use).
  • Ongchoi shares sauteed, garlic, rice, leaves, delicious and salty with spinach, chard and collards, so it is a leafy green. It is Ipomoea aquatica, water spinach.
  • Osgood (1957) treated a word's connotation as a point in a space of a few rated dimensions, and similarity as distance. The slide 25 numbers are Warriner et al. (2013) ratings on a 1 to 9 scale.
  • Vector semantics combines both ideas: a word is a point in a multidimensional space built from its distribution. That vector is an embedding.
  • The slide 27 map is a 2D t-SNE projection of 60-dimensional sentiment-trained embeddings (Li et al. 2015), not the embedding itself.
  • Vector features generalize: [34, 21, 14] is almost parallel to [35, 22, 17] (cosine ≈ 0.999), while an identity feature needs the exact word.
  • Sparse vectors (tf-idf, PPMI) are |V| long, mostly zero, and built from counts. Dense vectors (word2vec) have 50 to 1000 non-zero entries learned by a classifier predicting neighbors. Contextual embeddings come later.

Sources

Part 04: Term matrices and cosine similarity

Building term-document and word-word (term-context) co-occurrence matrices, reading rows and columns as vectors, and measuring similarity with the dot product and its length-normalized form, the cosine.

5 concepts, slides 31-44

Why this part matters

The previous part said a word is known by the company it keeps. This part turns that slogan into arithmetic: count tables, row and column vectors, and one number, the cosine, that says how alike two vectors are. Every later topic in the lecture stands on it. tf-idf and PPMI reweight these same matrices, word2vec vectors are compared with this same cosine, and the retrievers behind RAG systems and vector databases rank by cosine or by a dot product on normalized vectors.

The argument runs in five steps. First a table of counts over Shakespeare plays, read by columns as documents. Then the same kind of table read by rows as words, and a second table that counts neighbors instead of documents. Then the dot product, the obvious way to compare two rows, and the flaw that makes it reward frequent words. Then the cosine, which removes length and keeps only direction. Finally the full computation for cherry, digital and information by hand, with the slide's one rounding slip flagged.

By the end you can

  1. Build and read a term-document matrix and say what its rows and columns represent.
  2. Explain how a word-word (term-context) matrix is filled from a context window and why it is sparse.
  3. Compute a dot product and a vector length, and explain why the raw dot product favors frequent words.
  4. Derive cosine as the normalized dot product and state its range, including why counts give 0 to 1.
  5. Compute cos(cherry, information) and cos(digital, information) by hand and interpret them as angles.

Documents as columns of counts

Take four Shakespeare plays and four words, and count. As You Like It uses battle once, good 114 times, fool 36 times and wit 20 times. Twelfth Night has no battle at all but 58 fools. Julius Caesar and Henry V, the two histories, have almost no fools and plenty of battles. Put the counts in a grid with one row per word and one column per play, and you already have a usable representation of each play.

WordAs You Like ItTwelfth NightJulius CaesarHenry V
battle10713
good114806289
fool365814
wit201523
Counts of four words in four plays (SLP ch 11, figure 11.4). Read each column as one document.

This grid is a Term-document matrix. In general it has |V| rows, one per word in the vocabulary, and |D| columns, one per document, and the cell in row w and column d counts how often w occurs in d. Each column is then a list of |V| numbers: a vector. As You Like It becomes [1, 114, 36, 20], a point in a 4-dimensional space whose axes are the words. This is the basic move of Vector semantics, applied first to documents rather than words.

Each play as a column vector over (battle, good, fool, wit)

As You Like It (comedy)
[1, 114, 36, 20]
Twelfth Night (comedy)
[0, 80, 58, 15]
Julius Caesar (history)
[7, 62, 1, 2]
Henry V (history)
[13, 89, 4, 3]

Notice what was thrown away. The counts do not record where in the play a word appeared, or what came before it. A document reduced to word frequencies with order discarded is a bag of words, and it is the oldest representation in information retrieval. It sounds crude, but for the question "what is this document about?" it is surprisingly strong, because topic is carried mostly by which words occur and how often.

Seeing the vectors

Four dimensions cannot be drawn, so pick two: fool on the horizontal axis and battle on the vertical one. The comedies become long arrows lying almost flat along fool (As You Like It at [36, 1], Twelfth Night at [58, 0]), while the histories become short arrows pointing up along battle (Julius Caesar at [1, 7], Henry V at [4, 13]). Comedies point one way, histories another. That is the whole promise of the vector view: similar documents have similar columns, so they point in similar directions.

Gerard Salton turned this picture into the vector space model of information retrieval: represent every document and every query as a vector of term weights, measure how close the query vector is to each document vector, and return the closest documents first (Salton, Wong and Yang 1975). A web search for "battle" is, in this model, a vector with a single non-zero entry, and Henry V wins because its column leans hardest in that direction. The measure of closeness is the cosine you will meet in concept 4. Here is a preview of what it says about the plays, computed once on the two plotted dimensions and once on all four.

Pairfool and battle onlyAll four words
As You Like It and Twelfth Night0.99960.95
Julius Caesar and Henry V0.9880.999
As You Like It and Julius Caesar0.1690.945
Twelfth Night and Julius Caesar0.1410.809
Cosine between plays: on the fool and battle plane, and on all four word dimensions

On the plane, the pattern is crisp: comedies with comedies near 1, comedy with history near 0.15. On all four dimensions every pair lands between about 0.81 and 0.999, and As You Like It looks 0.945 similar to Julius Caesar. The culprit is good: it is frequent in every play, so it dominates every vector and makes all of them point roughly the same way. A word that occurs everywhere carries no information about which document you are in, and the next part's tf-idf exists precisely to turn its weight down.

Recall

Why does As You Like It look 0.945 similar to Julius Caesar on all four words, but only 0.169 on fool and battle?

good is frequent in every play, so it dominates all four vectors and points them the same way. Keeping only fool and battle removes good (and wit) and exposes the comedy and history split (0.169 against 0.945); tf-idf down-weights such words instead of dropping them.

Turn the same Shakespeare table sideways and read it by rows. battle becomes [1, 0, 7, 13]: a word that shows up a little in the comedies and a lot in Julius Caesar and Henry V. fool becomes [36, 58, 1, 4], the opposite profile. Without any dictionary, the rows already say that battle is a history word and fool is a comedy word, and two words with similar rows occur in similar documents.

One table, two kinds of vector. The Julius Caesar column lights up as a document vector, then the fool row as a word vector.

Counting neighbors instead of documents

Documents are a coarse unit of context. A play contains thousands of words, so two words sharing a play says little more than that they share a topic. The finer alternative is to count, for each target word, which words appear right next to it. Slide the target through a large corpus, and every time it occurs, look at the words within a fixed window on each side (SLP uses ±4) and add 1 to the cell for each of them.

A ±4 window around cherry. Every word inside the bracket is a context, and each one adds 1 to its cell in cherry's row.

The result is a Term-context matrix, also called a word-word or word-context matrix. It is square, |V| x |V|: rows are target words, columns are context words, and the cell (w, c) counts how often c appeared inside the window around w. Here are four rows from Wikipedia counts, restricted to five of the context columns.

Targetcomputerdataresultpiesugar
cherry28944225
strawberry0016019
digital167016838554
information33253982378513
Co-occurrence counts from Wikipedia (SLP ch 5, figure 5.3), five context columns out of |V|

The rows sort themselves into two families. cherry and strawberry have their mass in pie and sugar; digital and information have theirs in computer and data. Plot digital at [1683, 1670] and information at [3982, 3325] on the data and computer axes and the two arrows point almost the same way, about 5° apart, even though information is more than twice as long. That is the Distributional hypothesis made concrete: two words are similar when their context vectors are similar. Each row is an Embedding of its word, a sparse one built by counting, which later parts will reweight and then replace with short dense vectors.

Ahead of concept 4, here is what the cosine, a 0 to 1 score of how closely two rows point the same way, says about these rows.

PairCosineWhy
cherry and strawberry0.969Both live in the pie and sugar columns
digital and information0.996Both live in the computer and data columns
cherry and digital0.019Almost no shared mass
strawberry and information0.003Almost no shared mass
Cosines on all five context columns (computed for this page; concept 5 uses only pie, data and computer, so its values differ slightly, for example 0.018 instead of 0.019 for cherry and digital)

Two practical facts follow from the shape. First, almost every cell is zero: most of the |V| words never appear within four words of cherry. These are sparse vectors, and real systems store only the non-zero entries (a compressed sparse row format in SciPy, for example). Second, |V| is not the full vocabulary of the corpus. SLP notes that it is usually the 10,000 to 50,000 most frequent words, and that keeping more than about 50,000 rarely helps (SLP 5.3).

MatrixShapeCellSimilarity it captures
Term-document|V| x |D|Count of the word in the documentTopical: which texts a word appears in
Word-word (term-context)|V| x |V|Count of the context word in a window around the targetCloser, more substitutable similarity
The two count matrices of this part

Recall

What are the rows and columns of a term-document matrix, and of a term-context matrix?

Term-document: |V| word rows by |D| document columns, each cell the count of the word in the document. Term-context: |V| x |V|, each cell the count of the context word inside the target's window.

Quick check

A term-document matrix over 37 plays and 20,000 word types has which shape?

Which word is closer to fool: good or wit? Multiply the Shakespeare rows entry by entry and add. For good and fool that gives 9162; for fool and wit only 1604. By this measure good is almost six times closer to fool than wit is, which is clearly wrong: wit and fool are both comedy words, while good is just everywhere.

The measure is the Dot product, the most natural way to compare two vectors:

v⋅w=∑i=1Nviwi=v1w1+v2w2+⋯+vNwN\begin{aligned} \mathbf{v}\cdot\mathbf{w} &= \sum_{i=1}^{N} v_i w_i \\ &= v_1 w_1 + v_2 w_2 + \dots + v_N w_N \end{aligned}
Dot product (SLP eq 5.7)

It is large when both vectors have large values in the same dimensions, so it does behave like a similarity measure. Vectors whose non-zero entries sit in different dimensions get 0: they are orthogonal, which for count vectors means the two words never share a context. The trouble is that a product of two numbers grows with either number. The dot product therefore depends on how big the vectors are, and the size of a vector is its Vector length:

∣v∣=∑i=1Nvi2|\mathbf{v}| = \sqrt{\sum_{i=1}^{N} v_i^2}
Vector length, the Euclidean norm (SLP eq 5.8)

Worked example

Why good beats wit as fool's neighbor

  1. The rows

    good [114, 80, 62, 89], fool [36, 58, 1, 4], wit [20, 15, 2, 3] over (As You Like It, Twelfth Night, Julius Caesar, Henry V).
  2. Dot products

    good · fool = 114×36 + 80×58 + 62×1 + 89×4 = 4104 + 4640 + 62 + 356 = 9162. fool · wit = 36×20 + 58×15 + 1×2 + 4×3 = 720 + 870 + 2 + 12 = 1604.
  3. Lengths

    |good| = √31161 ≈ 176.5, |fool| = √4677 ≈ 68.4, |wit| = √638 ≈ 25.3. good is seven times longer than wit simply because it is a more frequent word.
  4. Divide out the lengths

    9162 / (176.5 × 68.4) ≈ 0.759 and 1604 / (68.4 × 25.3) ≈ 0.929.
  5. Result

    The raw dot product ranks good first, only because good is long. Once length is divided out, wit is the closer neighbor (0.929 against 0.759), which matches intuition. That division is the cosine of the next concept.

The general lesson is SLP's: the dot product favors long vectors, and more frequent words have longer vectors, because they co-occur with many words and do so many times. Words such as of, the and you would therefore come out as the nearest neighbor of almost everything. Information retrieval met the same problem with documents: a long document has larger counts everywhere, and a raw dot product with a query rewards it for being long rather than for being on topic (Manning, Raghavan and Schütze, "Dot products").

Recall

Why does the raw dot product favor frequent words?

Frequent words co-occur with many words at high counts, which makes their vectors long. The dot product grows with the lengths of the vectors, so long vectors score high against almost everything.

Cosine: the length-normalized dot product

Run an experiment on digital. Suppose the corpus were twice as large, so every count in its row doubles, from [5, 1683, 1670] to [10, 3366, 3340] over (pie, data, computer). Its dot product with information doubles too, from 12,254,481 to 24,508,962. Nothing about the meaning of digital changed, yet the similarity score did. The cure is to measure the angle between the vectors rather than their overlap, and the angle does not move at all.

Geometry supplies the formula. For any two vectors, the dot product equals the product of their lengths times the cosine of the angle θ between them. Solve for the cosine and you get Cosine similarity:

a⋅b=∣a∣ ∣b∣cos⁡θ⟹cos⁡(v,w)=v⋅w∣v∣ ∣w∣=v∣v∣⋅w∣w∣=∑i=1Nviwi∑i=1Nvi2 ∑i=1Nwi2\begin{aligned} \mathbf{a}\cdot\mathbf{b} &= |\mathbf{a}|\,|\mathbf{b}|\cos\theta \\ \Longrightarrow\quad \cos(\mathbf{v},\mathbf{w}) &= \frac{\mathbf{v}\cdot\mathbf{w}}{|\mathbf{v}|\,|\mathbf{w}|} \\ &= \frac{\mathbf{v}}{|\mathbf{v}|}\cdot\frac{\mathbf{w}}{|\mathbf{w}|} \\ &= \frac{\sum_{i=1}^{N} v_i w_i}{\sqrt{\sum_{i=1}^{N} v_i^2}\,\sqrt{\sum_{i=1}^{N} w_i^2}} \end{aligned}
Cosine similarity in three equivalent forms (SLP eqs 5.9 and 5.10)

The middle form is the useful one to remember. Dividing a vector by its own length gives a unit vector, a vector of length 1 pointing the same way: [3, 4] has length 5, so its unit vector is [0.6, 0.8], and 0.6² + 0.8² = 1. The cosine is simply the dot product of the two unit vectors. Length has been removed before the comparison, so only direction is left.

Stretch v to 2v along the same ray: the dot product doubles, the cosine stays where it was.

Three properties follow. The range is -1 to 1: 1 for vectors pointing the same way, 0 for orthogonal vectors, -1 for opposite directions. Scaling is invisible: for any c > 0, cos(cv, w) = cos(v, w), because the c appears once in the numerator and once in |cv| = c|v| and cancels (SLP exercise 5.2). And for raw counts the range shrinks to 0 to 1, because no count is negative.

This is also why real systems often skip the division at query time. If every stored vector is normalized to length 1 once, in advance, then a plain dot product is the cosine. scikit-learn documents exactly this: cosine_similarity is the normalized dot product, and on L2-normalized data it is equivalent to linear_kernel. Vector databases that offer an "inner product" metric rely on the same identity, and it is why the embedding vectors of many retrieval models come out already normalized.

Recall

Compute cos([1, 0], [1, 1]).

Numerator 1×1 + 0×1 = 1. Lengths 1 and √2. Cosine 1 / √2 ≈ 0.707, an angle of 45°.

Recall

What happens to cos(v, w) if v is multiplied by 3? And for unit vectors, how do the dot product and the cosine relate?

Nothing happens: the 3 multiplies the numerator and |v| equally and cancels. For unit vectors the denominator is 1 × 1, so the dot product and the cosine are equal.

Quick check

Why do we divide the dot product by the two vector lengths?

Quick check

For raw co-occurrence count vectors, what range can the cosine take?

Now do the whole computation once by hand, on three words and three context dimensions (pie, data, computer): cherry [442, 8, 2], digital [5, 1683, 1670] and information [5, 3982, 3325]. The question is which of cherry and digital is closer to information under the cosine.

Worked example

cos(cherry, information) and cos(digital, information)

  1. Lengths

    |cherry| ≈ 442.08, |digital| ≈ 2370.95, |information| ≈ 5187.68. Each is the length, the square root of the sum of squared counts.
  2. cherry and information

    Dot product (numerator) 442×5 + 8×3982 + 2×3325 = 2210 + 31856 + 6650 = 40716. Cosine 40716 / (442.08 × 5187.68) ≈ 0.0178, an angle of about 89.0°.
  3. digital and information

    Numerator 5×5 + 1683×3982 + 1670×3325 = 25 + 6701706 + 5552750 = 12254481. Cosine 12254481 / (2370.95 × 5187.68) ≈ 0.9963, an angle of about 4.9°.
  4. Result

    cos(digital, information) ≈ 0.996 and cos(cherry, information) ≈ 0.018. digital is almost exactly aligned with information; cherry is nearly at a right angle to it. For completeness, cos(cherry, digital) ≈ 0.018 as well.

Every intermediate quantity, for checking your own arithmetic

|cherry|
√(442² + 8² + 2²) = √195432 ≈ 442.08
|digital|
√(5² + 1683² + 1670²) = √5621414 ≈ 2370.95
|information|
√(5² + 3982² + 3325²) = √26911974 ≈ 5187.68
cherry · information
442×5 + 8×3982 + 2×3325 = 2210 + 31856 + 6650 = 40716
digital · information
5×5 + 1683×3982 + 1670×3325 = 25 + 6701706 + 5552750 = 12254481
cos(cherry, digital)
≈ 0.018

The picture makes the numbers obvious. Plot the words on two of the dimensions, pie upward and computer to the right. cherry stands nearly upright, because nearly all of its mass is in pie. digital and information both lie almost flat along computer. The angle between cherry and information is close to a right angle, so its cosine is close to 0; the angle between digital and information is a sliver, so its cosine is close to 1.

Schematic of slide 44 (angles widened so the small one is visible): a wide arc between cherry and information, a sliver between digital and information. Small angle, large cosine.

Recall

Without a calculator, why must cos(cherry, information) be small?

cherry's mass is in pie and information's is in data and computer. The large counts never meet in the same dimension, so the numerator is tiny compared with the product of the lengths.

Quick check

Using counts over (pie, data, computer), which word is closest to information?

Recap

If you remember nothing else

  • A term-document matrix is |V| x |D|: columns are document vectors, and rows are word vectors over documents.
  • A word-word (term-context) matrix is |V| x |V| and counts context words in a window such as ±4. Its rows are sparse word vectors.
  • The dot product Σ v_i w_i is high when both vectors are large in the same dimensions, but it grows with vector length, so frequent words win.
  • Cosine = v·w / (|v||w|) is the dot product of unit vectors. It ignores length and measures only the angle.
  • Cosine runs from -1 to 1 in general and from 0 to 1 for counts. It is unchanged by scaling a vector by a positive number.
  • Worked example: cos(digital, information) ≈ 0.996 and cos(cherry, information) ≈ 0.018 (the slide's .017 is a rounding slip).

Sources

Part 05: Weighting with tf-idf

Why raw frequency is a poor representation, how log-scaled term frequency and inverse document frequency combine into tf-idf, and a full worked tf-idf table for the Shakespeare example.

5 concepts, slides 45-52

Why this part matters

Part 04 built count vectors and compared them with cosine. Those vectors have a flaw you can see the moment you look at real counts: the words with the biggest numbers are the, it and good, words that sit near everything and therefore say nothing. Any similarity computed from raw counts is dominated by them.

This part fixes the term-document side of that problem with tf-idf, the weighting that has been the baseline of information retrieval since the 1970s and still ships as the default sparse retriever and text feature extractor. Its descendant BM25 is the keyword half of most retrieval-augmented generation pipelines you will meet in research. Exams like this material because it is computable by hand: the difference between document frequency and collection frequency, and a tf-idf cell worked out from a count, are classic questions. The next part does the same job for term-term matrices with PPMI.

By the end you can

  1. Explain why raw co-occurrence counts over-weight frequent, uninformative words.
  2. Compute log-scaled term frequency and contrast the log10(count + 1) and 1 + log10(count) variants.
  3. Distinguish document frequency from collection frequency using Romeo and action.
  4. Compute idf with N = 37 and explain why a word in every document gets weight zero.
  5. Reproduce any cell of the slide 52 tf-idf table and explain how the choice of document changes the weights.

Build a Term-context matrix from a large corpus and look at the row for apricot. The context sugar has a healthy count there, and that is genuinely useful: apricots are sweet things you cook with sugar, and a word whose row also has a high sugar count, such as peach, is probably similar. Now look further along the same row. The contexts the, it and they have counts many times larger than sugar. They have similarly huge counts in the row for digital, for information, for every word in the vocabulary.

That is the paradox. Frequency is clearly informative, since co-occurring often is exactly how sugar earns its place. But frequency is not proportional to information. A Dot product sums products dimension by dimension, so a dimension where both vectors carry a count in the thousands swamps a dimension where both carry a count of twenty. Even after normalising by length, Cosine similarity on raw counts mostly measures how much two words share the ubiquitous dimensions, and every word shares those. What we want instead is a weight with two pressures in it: reward a term that is frequent here, and penalise a term that is frequent everywhere.

Two classic reweightings

Which reweighting you pick depends on which matrix you have. For a Term-document matrix, where columns are documents, the standard answer is tf-idf. Jurafsky and Martin describe it as "the product of two terms, the term frequency tf and the inverse document frequency idf", and note that the "-" is a hyphen, not a minus sign. The first factor rewards local frequency; the second penalises spread across the collection.

wt,d=tft,d×idftw_{t,d} = \mathrm{tf}_{t,d} \times \mathrm{idf}_t
tf-idf weight of term t in document d

For a term-term matrix, where both rows and columns are words, the standard answer is Pointwise mutual information. It compares how often two words actually appear together with how often they would if they were independent. Words like good and great earn a high PMI only if they meet more often than their individual frequencies predict, so a context like the that meets everything at the expected rate scores near zero. Part 06 develops PMI in full.

PMI(w1,w2)=log⁡2P(w1,w2)P(w1) P(w2)\mathrm{PMI}(w_1, w_2) = \log_2 \frac{P(w_1, w_2)}{P(w_1)\,P(w_2)}
Pointwise mutual information, written with the base 2 used from slide 54 onward
SchemeMatrix it suitsQuestion it answers
tf-idfTerm-documentIs this term distinctive for this document?
PMITerm-term (word-context)Do these two words co-occur more than chance would predict?
Two reweightings for two kinds of matrix

The idea behind the idf half is older than vector semantics. Karen Sparck Jones argued in 1972 that "matches on less frequent, more specific, terms are of greater value than matches on frequent terms", and proposed weighting each term by how few documents it appears in. Every term-weighting scheme in this lecture, PPMI included, is a variation on her insight.

Recall

Why does a cosine between two raw count vectors tend to be high for almost any pair of words?

Both vectors have their largest entries in the same ubiquitous dimensions (the, it, they, good). Those products dominate the dot product, so the cosine mostly reflects shared function-word contexts rather than meaning. Reweighting with tf-idf or PMI shrinks those dimensions.

Squashing term frequency with a logarithm

Suppose a word appears 0, 1, 9, 99 or 999 times in a document. Under the slides' formula those counts become a term frequency of 0, 0.301, 1, 2 and 3. A hundredfold increase in occurrences, from 9 to 999, adds only 2 to the weight.

Raw count to log-scaled term frequency, tf = log10(count + 1)

count 0
tf = log10(1) = 0
count 1
tf = log10(2) = 0.301
count 9
tf = log10(10) = 1
count 99
tf = log10(100) = 2
count 999
tf = log10(1000) = 3

The simplest term frequency would be the raw count itself, tf = count(t, d). The trouble is that significance does not grow linearly with repetition. Manning, Raghavan and Schütze put it plainly: "It seems unlikely that twenty occurrences of a term in a document truly carry twenty times the significance of a single occurrence." The second mention of battle in a play tells you a lot (this play has a battle in it); the hundredth mention adds far less. So we squash the count with a logarithm.

tft,d=log⁡10(count(t,d)+1)\mathrm{tf}_{t,d} = \log_{10}\big(\mathrm{count}(t,d) + 1\big)
Log-scaled term frequency used on the slides

The +1 is there because log 0 is undefined. Adding one before taking the log sends a count of zero to log10(1) = 0, which is exactly the weight an absent term should have, while barely changing large counts.

Grey ghosts show raw counts of 0, 9, 99 and 999 on a linear scale, where the first two are almost invisible. When active, the log-scaled tf bars rise to 0, 1, 2 and 3: each tenfold increase in count + 1 adds one equal step.

The other formula you will meet

The current SLP3 draft (now Chapter 11, on retrieval and RAG) and the IR book both use a slightly different squash. SLP3 notes in a footnote that log10(count + 1) is "this alternative formulation" used in its earlier editions, which is where the slides come from. Neither is an error; they are two members of the same sublinear family.

tft,d={1+log⁡10count(t,d)if count(t,d)>00otherwise\mathrm{tf}_{t,d} = \begin{cases} 1 + \log_{10} \mathrm{count}(t,d) & \text{if } \mathrm{count}(t,d) > 0 \\ 0 & \text{otherwise} \end{cases}
The variant in the current SLP3 draft and in IIR section 6.4.1

The two agree on the shape but not the numbers. Under the variant, a count of 1 gives 1 + log10 1 = 1 rather than 0.301, a count of 10 gives 2 rather than 1.041, and a count of 7 gives 1.845 rather than 0.903. scikit-learn offers a third version through sublinear_tf=True, which uses 1 + ln(tf) with the natural log.

Recall

Compute tf = log10(count + 1) for counts 0, 9 and 99.

0, 1 and 2. The +1 keeps a count of zero at a tf of zero, since log10 1 = 0.

Across the complete works of Shakespeare, the words Romeo and action each occur exactly 113 times. By raw volume they are identical. Yet every occurrence of Romeo sits in one play, Romeo and Juliet, while action is spread across 31 different plays. If you are handed a document and told it contains Romeo, you know which play it is. If you are told it contains action, you have learned almost nothing.

The two numbers in that story have names. The total number of times a term occurs across the whole collection is its Collection frequency, cf. The number of documents that contain the term at least once is its Document frequency, df_t. The IR book defines them exactly that way and concludes that for discriminating between documents it is "better to use a document-level statistic ... than to use a collection-wide statistic". SLP3 gives the reason: "Terms that occur in only a few documents are useful for discriminating those documents from the rest of the collection."

Wordcfdfidf
Romeo1131log10(37 / 1) = 1.57
action11331log10(37 / 31) = 0.077
Equal collection frequency, very different document frequency (idf computed with N = 37 plays)
A grid of 37 plays with 113 faint tokens scattered over it. When active, Romeo's 113 tokens collapse into a single play while action's 113 tokens spread across 31 plays: the same collection frequency, document frequencies of 1 and 31.

The Shakespeare pair is not a curiosity. The IR book finds the same pattern in the Reuters newswire collection, where try and insurance have almost the same collection frequency but very different document frequencies. Insurance clusters in the articles that are actually about insurance; try is sprinkled through everything.

Wordcfdf
try10,4228,760
insurance10,4403,997
Reuters RCV1, from IIR section 6.2.1

Recall

Romeo and action both have collection frequency 113. Give their df values and say which gets the larger idf with N = 37.

Romeo has df = 1 and action has df = 31. Romeo's idf is log10 37 = 1.57; action's is log10(37 / 31) = 0.077, about twenty times smaller.

Quick check

Romeo and action both occur 113 times across Shakespeare. Why does Romeo receive a much higher idf?

Treat each of Shakespeare's 37 plays as a document and walk down a ladder of words ordered by how many plays they appear in. Romeo is in one play, salad in two, Falstaff in four, forest in twelve, battle in twenty-one, wit in thirty-four, fool in thirty-six, and good and sweet in all thirty-seven. We want a weight that is large at the top of the ladder and vanishes at the bottom.

The ratio N / df_t of collection size to Document frequency does that: it is 37 for Romeo and 1 for good. Raw ratios grow too fast, though (a word in one document out of a million would get a ratio of a million), so we take the logarithm, exactly as we did for tf. The result is the inverse document frequency.

idft=log⁡10 ⁣(Ndft)\mathrm{idf}_t = \log_{10}\!\left(\frac{N}{\mathrm{df}_t}\right)
N is the number of documents in the collection
Worddfidf
Romeo11.57
salad21.27
Falstaff40.966 (slide prints 0.967)
forest120.489
battle210.246
wit340.037
fool360.012
good, sweet370
The idf ladder for Shakespeare, N = 37 plays (as in SLP3 section 11.1.2)

Two boundary values are worth memorising. The largest possible idf is log10 N, reached when a term occurs in a single document: log10 37 = 1.57 here. The smallest is 0, reached when a term occurs in every document, since log10(N / N) = log10 1 = 0. SLP3 says it directly: the lowest weight, 0, is "assigned to terms that occur in every document", words "like good or sweet". Notice that idf is not linear in df. Going from df = 1 to df = 2 costs 0.30, the same as going from df = 12 to df = 24: halving the spread always buys the same amount of weight.

Horizontal bars for idf = log10(37 / df), ordered by df. When active they draw in one after another, from 1.57 for Romeo down to almost nothing for fool and a bare dot at zero for good and sweet, which occur in all 37 plays.

Worked example

Checking the two ends of the ladder

  1. Romeo, df = 1

    idf = log10(37 / 1) = log10 37 = 1.568, which rounds to the slide's 1.57.
  2. fool, df = 36

    37 / 36 = 1.0278, so idf = log10 1.0278 = 0.0119, which rounds to 0.012.
  3. good, df = 37

    idf = log10(37 / 37) = log10 1 = 0.
  4. Result

    A word in one play is worth 1.57; a word missing from just one play is worth about 0.012, over a hundred times less; a word in every play is worth nothing.

What counts as a document?

Nothing in the formula says a document must be a play. SLP3 defines a document as "whatever unit of text the system indexes and retrieves (web pages, scientific papers, news articles, or even shorter passages like paragraphs)". It could be a Wikipedia article, a tweet, a paragraph, or a 300-token chunk in a RAG index. The choice is a modelling decision, and it changes everything downstream: N changes, every df changes, and so every idf changes.

Switch Shakespeare from plays to paragraphs and N grows into the thousands. good is no longer in every document, because most paragraphs do not contain it, so it gets a positive idf. A word like battle that clusters in a few scenes now looks rarer relative to the collection, and its weight rises. The right unit is the one that matches what you retrieve or compare: if your system returns passages, compute df over passages.

Recall

What happens to the idf values if you treat each paragraph as a document instead of each play?

N and every df change, so every idf changes. Words concentrated in a few passages gain relative weight, and a word like good that is in every play but not in every paragraph stops getting zero. The unit should match what you retrieve or compare.

Take battle in Julius Caesar. The play uses the word 7 times, so its term frequency is log10(7 + 1) = log10 8 = 0.903. battle appears in 21 of the 37 plays, so its idf is 0.246. Multiply: 0.903 × 0.246 = 0.222, which the slide prints as 0.22. That is one cell of the tf-idf matrix, and every other cell is computed the same way.

The rule is just the definition applied cell by cell: squash the count into Term frequency, look up the word's Inverse document frequency, multiply. The table below combines the raw counts on slide 52 with the idf column of slide 50 and shows the intermediate tf values the slide skips. All sixteen weights agree with the slide.

WordRaw countstf = log10(count + 1)idftf-idf
battle1, 0, 7, 130.301, 0, 0.903, 1.1460.2460.074, 0, 0.22, 0.28
good114, 80, 62, 892.061, 1.908, 1.799, 1.95400, 0, 0, 0
fool36, 58, 1, 41.568, 1.771, 0.301, 0.6990.01190.019, 0.021, 0.0036, 0.0083
wit20, 15, 2, 31.322, 1.204, 0.477, 0.6020.03670.049, 0.044, 0.018, 0.022
Four words in As You Like It, Twelfth Night, Julius Caesar and Henry V (values listed in that order)

Worked example

Two cells from the slide 52 table

  1. battle in Julius Caesar

    tf = log10 8 = 0.903, idf = log10(37 / 21) = 0.246, so w = 0.903 × 0.246 = 0.222 ≈ 0.22.
  2. fool in Henry V

    The count is 4, so tf = log10 5 = 0.699. fool is in 36 plays, so idf = 0.0119, and w = 0.699 × 0.0119 = 0.0083.
  3. Result

    battle in Julius Caesar outweighs fool in Henry V by a factor of about 27, although the raw counts differ only by 7 against 4. The difference comes almost entirely from idf.

What the table teaches

Look at the good row. It has the largest counts in the table, from 62 to 114, and its tf values are all around 2. Yet every tf-idf cell is 0, because good occurs in all 37 plays and its idf is log10 1 = 0. The word that dominated the raw vectors has been removed from the comparison without anyone writing a stop list.

Now look at battle. In raw counts it was a minor dimension, dwarfed by good in every play and by fool in the comedies. After weighting it is the largest value in every column where it appears, and it cleanly separates Julius Caesar (0.22) and Henry V (0.28), plays full of war, from the comedies As You Like It (0.074) and Twelfth Night (0). The IR book summarises the pattern: a weight is highest when a term occurs many times in a small number of documents, lower when it occurs fewer times or in many documents, and lowest when it occurs in virtually all documents.

A 4 by 4 grid of plays and words. Grey bars are raw counts, with the good row tallest. When active, the good row's tf-idf collapses to nothing while the battle cells for Julius Caesar and Henry V light up as the strongest weights.

The resulting document vectors are still sparse vectors of vocabulary length, mostly zeros, and you compare them with Cosine similarity exactly as in part 04. The difference is that the dimensions now carry information in proportion to how distinctive they are.

tf-idf in real systems

The formula is the same everywhere, but the details are not, and the differences matter when you reproduce a paper or debug a pipeline. scikit-learn's TfidfVectorizer by default uses raw counts for tf, a smoothed natural-log idf, ln((1 + n) / (1 + df)) + 1, and then L2-normalises each document vector. Because of the +1, a term in every document gets idf 1, not 0, so good would survive. The documentation's own example turns the vector [3, 0, 1.8473] into [0.8515, 0, 0.5243] after normalisation.

Sourcetfidfidf of a term in every document
Slides (SLP3 earlier editions)log10(count + 1)log10(N / df)0
SLP3 current draft, IIR1 + log10(count), or 0log10(N / df)0
scikit-learn defaultraw count (sublinear_tf=False)ln((1 + n) / (1 + df)) + 11
Three formulations you will meet

BM25 is the modern member of the family and the standard keyword retriever in search engines and hybrid RAG systems. It keeps idf but replaces log tf with a saturating function controlled by a parameter k, usually between 1.2 and 2, and normalises for document length with b = 0.75. Salton and Buckley's 1988 comparison of term-weighting schemes is the classic study of why these choices matter.

Recall

Compute the tf-idf of battle in Henry V (count 13, df 21, N 37).

tf = log10 14 = 1.146, idf = 0.246, so w = 1.146 × 0.246 = 0.282 ≈ 0.28.

Recall

Why does every cell in the good row of slide 52 become 0?

good occurs in all 37 plays, so df = N and idf = log10 1 = 0. Anything multiplied by zero is zero, however large its counts.

Quick check

With N = 37 and tf = log10(count + 1), what is the tf-idf of battle in Julius Caesar (count 7, df 21)?

Quick check

Why is every entry in the good row of the slide 52 tf-idf table equal to zero?

Quick check

In scikit-learn's default TfidfVectorizer, what idf does a term that appears in every document receive?

Recap

If you remember nothing else

  • Raw frequency is informative but dominated by ubiquitous words. tf-idf (term-document) and PMI (term-term) reweight counts.
  • The slides use tf = log10(count + 1), so 0 → 0, 9 → 1, 99 → 2. The current SLP3 draft and IIR use 1 + log10(count) for count > 0.
  • df counts documents, cf counts tokens. Romeo and action share cf 113 but have df 1 versus 31.
  • idf = log10(N / df). With N = 37 plays it ranges from 1.57 (Romeo) to 0 (good, sweet). The slides never state N.
  • w = tf × idf. Battle in Julius Caesar is log10 8 × 0.246 = 0.22, and the whole good row becomes 0.
  • A document is any unit you choose. Changing it changes N, df and every weight.
  • Libraries differ: scikit-learn uses ln((1 + n) / (1 + df)) + 1 with L2 normalization, so a term in every document keeps idf 1 instead of 0. BM25 adds tf saturation and length normalization.

Sources

Part 06: Pointwise mutual information and PPMI

Measuring whether two words co-occur more than chance with PMI, clipping negatives to get PPMI, computing it step by step on a term-context matrix, and correcting PMI's bias toward rare words with alpha-weighted context probabilities.

6 concepts, slides 53-60

Why this part matters

Part 05 fixed raw counts on the term-document side with tf-idf. Term-context matrices have the same disease: the biggest numbers belong to frequent words such as information and data, which sit next to almost everything. A raw count cannot tell you whether two words genuinely belong together or merely happen to be common.

Positive pointwise mutual information is the standard cure. It rescales every cell of a term-context matrix by what chance alone would predict, keeping only above-chance association, and it turns that matrix into meaningful sparse word vectors. It is also the bridge to the rest of this lecture: skip-gram with negative sampling turns out to factorize a shifted PMI matrix, and the magic number 0.75 you will meet in word2vec first appears here. Outside embeddings, PMI drives collocation extraction, lexicography and feature selection, so it will show up in your research. Exams almost always ask for one PPMI cell by hand.

By the end you can

  1. Explain PMI as observed versus chance co-occurrence, measured in bits.
  2. Justify clipping negative PMI to zero to obtain PPMI.
  3. Compute joint and marginal probabilities from a term-context count matrix.
  4. Compute any single PPMI cell by hand from counts.
  5. Explain PMI's bias toward rare contexts and two standard fixes.
  6. Apply alpha = 0.75 context smoothing and predict its effect on each cell.

Start with numbers. In the small Term-context matrix used throughout this part, the word information accounts for 7703 of the N = 11716 counted word-context pairs, and the context data for 5673 of them. If the two words had nothing to do with each other, how often would you expect to see them together? The full table, with every row and column sum, is in the counts-to-probabilities section below.

Independence answers that. If knowing one word tells you nothing about the other, the probability of the pair is just the product of the separate probabilities: P(information) × P(data) = .6575 × .4842 = .3184. So about 31.8% of all pairs should be (information, data) by chance alone. The observed share is 3982 / 11716 = .3399. The ratio of observed to expected is 1.0676: the pair occurs only 6.8% more often than chance, and log2 1.0676 = .0944 bits. Compare cherry and pie: there the ratio is 20.8, and the log is 4.38 bits. That number is pointwise mutual information.

PMI⁡(x,y)=log⁡2P(x,y)P(x) P(y)\operatorname{PMI}(x, y) = \log_2 \frac{P(x, y)}{P(x)\,P(y)}
Generic form, for any two events x and y
PMI⁡(w,c)=log⁡2P(w,c)P(w) P(c)\operatorname{PMI}(w, c) = \log_2 \frac{P(w, c)}{P(w)\,P(c)}
Word form: target word w and context word c

Read the fraction one piece at a time. The numerator is what actually happened: how often the pair appeared together. The denominator is what independence predicts, because under independence P(x, y) = P(x) P(y). The ratio therefore says how many times more often the pair occurs than chance, and the base-2 logarithm turns that ratio into bits. A ratio of 1 gives 0 bits (independent), a ratio above 1 gives a positive score (attraction), and a ratio below 1 gives a negative score (avoidance). Each extra bit means the pair is twice as over-represented.

Two circles stand for P(x) and P(y). The dashed ring marks where the second circle would sit if the words were independent, so their overlap equals P(x)P(y). When active, the second circle slides in, the overlap grows past the chance amount, and the PMI turns positive.

Where the measure comes from

Church and Hanks (1989, journal version 1990) brought the measure to lexicography. They estimated P(x, y) by counting how often x is followed by y within a window of w = 5 words, and they read the score exactly as above: well above zero for genuine association, near zero for no relation, well below zero for words in complementary distribution. Their rough rule of thumb was that pairs with a score above 3 tend to be interesting, and they ignored pairs seen 5 times or fewer because the ratio was unstable, an early sign of the rare-event problem later in this part. One subtlety a PhD reader should notice: because their count encoded word order (x before y), their association ratio was not symmetric. The term-context version on these slides counts a symmetric window, so PMI(w, c) depends only on which pair you pick.

Recall

In one sentence, what does PMI(w, c) = 0 mean?

The pair co-occurs exactly as often as independence predicts, P(w, c) = P(w) P(c), so the ratio is 1 and log2 1 = 0.

Suppose two words each have probability 10^-6, which is typical of most of the vocabulary. Independence predicts that they appear together with probability 10^-12. To say with confidence that they appear together less than that, you must be able to estimate probabilities well below 10^-12, which takes a corpus on the order of trillions of pairs. With a corpus of a few million tokens you will simply never see them together, and you cannot tell "these words avoid each other" apart from "these words never happened to meet".

That is the first reason negative PMI is unreliable: the evidence needed to estimate below-chance co-occurrence grows with the rarity of the words, and for most word pairs it is never available. The second reason is about evaluation: it is not clear that people can even judge "unrelatedness" reliably, so there is no good gold standard to check negative scores against. The practical answer, used since Church and Hanks and later Dagan and colleagues (1993) and Niwa and Nitta (1994), is to keep only the positive side.

PPMI⁡(w,c)=max⁡ ⁣(log⁡2P(w,c)P(w) P(c), 0)\operatorname{PPMI}(w, c) = \max\!\left(\log_2 \frac{P(w, c)}{P(w)\,P(c)},\ 0\right)
Positive PMI: negative and undefined values become 0

Positive PMI keeps the attraction signal and floors everything else at zero. It has a welcome side effect. A pair that never co-occurs has P(w, c) = 0, so its Pointwise mutual information is log2 0 = -∞, a value that would wreck any later arithmetic. Clipping maps it cleanly to 0. In the slide table this is exactly what happens to strawberry/computer and strawberry/data, both with count 0. The result is a sparse vector per word: long, mostly zero, with a few positive entries for the contexts that really characterise it.

PMI bars for the cherry and information rows sit around a zero baseline, several of them far below it. When active, the negative bars collapse onto the baseline and the positive bars stay, in teal: PPMI is max(PMI, 0).
PMIPPMI
Range-∞ to +∞ (asymptotically)0 to +∞
Unseen pair (count 0)log2 0 = -∞0
What a value saysAttraction (positive) or avoidance (negative)Strength of attraction only; 0 means no evidence of it
ReliabilityNegative side needs enormous corporaKeeps only the side small corpora can estimate
Matrix shapeDense, with many large negative entriesSparse: most entries are exactly 0
PMI and PPMI side by side

Empirically the choice pays off. Levy, Goldberg and Dagan (2015) report that Bullinaria and Levy (2007) found PPMI outperforms plain PMI on semantic similarity tasks, and PPMI became the default count-based baseline against which neural embeddings were later compared.

Recall

Give two reasons PPMI discards negative PMI.

First, negative estimates need enormous corpora: for words with P = 10^-6 each you must resolve P(w, c) well below 10^-12. Second, humans cannot reliably judge "unrelatedness", so negative scores have no gold standard. As a bonus, zero counts give log 0 = -∞, which clipping turns into 0.

Quick check

Why does PPMI replace negative PMI values with zero?

Everything so far needs three probabilities per cell: the joint P(w, c) and the two marginals P(w) and P(c). All three come from one count matrix F. Here is the matrix the slides use, taken from SLP3, whose counts come from Wikipedia: four target words as rows, five context words as columns, with the row and column sums added.

computerdataresultpiesugarrow sum
cherry28944225486
strawberry001601980
digital1670168385543447
information332539823785137703
column sum4997567347351261N = 11716
p(c).4265.4842.0404.0437.00521
Co-occurrence counts f_ij with margins (SLP3 Fig. 6.10)

Add every cell and you get the grand total N = 11716. Each probability is then a share of that one total. The joint probability of a cell is the cell divided by N. The marginal probability of a target word is its row sum divided by N, and the marginal probability of a context is its column sum divided by N.

pij=fijN,pi∗=∑jfijN,p∗j=∑ifijN,N=∑i∑jfij\begin{gathered} p_{ij} = \frac{f_{ij}}{N}, \qquad p_{i*} = \frac{\sum_j f_{ij}}{N}, \\ p_{*j} = \frac{\sum_i f_{ij}}{N}, \qquad N = \sum_i \sum_j f_{ij} \end{gathered}
Joint, row marginal and column marginal, all over the same N

Worked example

Three probabilities for (information, data)

  1. Find the total

    Sum all twenty cells, or equivalently the four row sums: 486 + 80 + 3447 + 7703 = 11716.
  2. Joint

    The cell count is 3982, so p(information, data) = 3982 / 11716 = .3399.
  3. Row marginal

    The information row sums to 7703, so p(information) = 7703 / 11716 = .6575.
  4. Column marginal

    The data column sums to 5673, so p(data) = 5673 / 11716 = .4842.
  5. Result

    Joint p(information, data)
    3982 / 11716 = .3399
    Marginal p(information)
    7703 / 11716 = .6575
    Marginal p(data)
    5673 / 11716 = .4842
    Chance prediction p(information) p(data)
    .6575 × .4842 = .3184

Because the joint and both marginals come from the same matrix and the same N, they are consistent: each row of joint probabilities sums to its row marginal, each column to its column marginal, and everything sums to 1. SLP3 is candid that this "pretends" the five listed contexts are the only ones in the world. In a real system the matrix has tens of thousands of columns and the same recipe applies unchanged.

Recall

From the count table, compute p(strawberry) and p(sugar).

p(strawberry) = 80 / 11716 = .0068 and p(sugar) = 61 / 11716 = .0052, both over the same matrix total N.

With the three probabilities in hand, one cell of the Pointwise mutual information matrix is a division and a log. Work it once by hand for information/data, then notice a shortcut that skips the rounding entirely.

Worked example

PPMI(information, data) by hand

  1. Ratio of observed to expected

    .3399 / (.6575 × .4842) = .3399 / .3184 = 1.0675.
  2. Same ratio straight from counts

    The Ns cancel into one: f × N / (row × col) = 3982 × 11716 / (7703 × 5673) = 1.0676. This route avoids rounding the probabilities first.
  3. Take log base 2

    Most calculators lack log2, so use log2 x = ln x / ln 2: ln 1.0676 / 0.6931 = 0.0654 / 0.6931 = .0944.
  4. Clip

    .0944 > 0, so the clip changes nothing.
  5. Result

    PPMI(information, data) = .09, matching the slide.
PMI⁡ij=log⁡2fij Nfi∗ f∗j\operatorname{PMI}_{ij} = \log_2 \frac{f_{ij}\, N}{f_{i*}\, f_{*j}}
Shortcut from raw counts: cell times total over row sum times column sum

Repeat for every cell and you get the full PMI matrix below. Every Positive PMI value on slide 58 is this matrix after clipping; SLP3 quotes PMI(cherry, computer) = -6.7 in its figure caption as an example of a large negative value that PPMI discards.

computerdataresultpiesugar
cherry-6.70-4.88-1.124.383.30
strawberry-∞-∞-1.694.105.51
digital0.180.01-0.71-4.91-2.17
information0.020.090.28-6.07-1.63
Full PMI matrix before clipping
computerdataresultpiesugar
cherry0004.383.30
strawberry0004.105.51
digital0.180.01000
information0.020.090.2800
PPMI matrix after clipping (slide 58, SLP3 Fig. 6.12)

Now read the PPMI matrix as a set of word vectors. The fruit rows light up only on pie and sugar; the technology rows only on computer, data and result. The two groups share no non-zero dimension, so the cosine similarity between cherry and digital is exactly 0, while cherry and strawberry have a cosine of about 0.96. The raw counts were noisier: cherry co-occurs with computer and data a few times, and in a full-size matrix such incidental counts, scaled by frequent contexts, blur every row. PPMI vectors are still long and sparse; the second half of this lecture learns short dense vectors instead.

The 4 by 5 grid of PPMI values, dim at rest. When active, only the nine non-zero cells fill, with strength proportional to their PPMI, and the fruit block and technology block appear as two separate islands.

Recall

Compute PPMI(cherry, pie) from count 442, row sum 486, column sum 512 and N = 11716.

442 × 11716 / (486 × 512) = 20.81, and log2 20.81 = 4.38. It is positive, so PPMI = 4.38.

Quick check

Using the slide counts, what is PMI(information, data)?

PMI's bias toward rare events

Add one more row and one more column to the slide table: a word w and a context c, each seen exactly once, and that once together. The shortcut gives PMI = log2(1 × 11716 / (1 × 1)) = log2 11716 = 13.5 bits. That is more than double strawberry/sugar (5.51), from a single observation that may be a typo or a coincidence. One accident beats thousands of genuine co-occurrences.

The mechanism is the denominator. When a context is rare, P(c) is tiny, so even one co-occurrence produces a large ratio. Levy, Goldberg and Dagan (2015) call this Pointwise mutual information's Achilles' heel, citing Turney and Pantel (2010): a word's highest-scoring dimensions become obscure contexts it met once or twice, and since similar words rarely share those accidents, their vectors look less alike under cosine than they should. Clipping does not help, because Positive PMI only touches negative values and this bias inflates positive ones.

Two fixes

  1. Give rare contexts a little more probability. If P(c) for a rare context is nudged upward, its PMI falls. This is the alpha weighting of the next concept.
  2. Add-k smoothing. Add a small constant k to every count before computing probabilities, exactly as in the n-gram language models of Lecture 03. Slide 59 names the simplest case, add-one smoothing, which is k = 1 and lowers strawberry/sugar from 5.51 to 5.41. SLP3 gives k = 0.1 to 3 as common choices, and notes that the larger the k, the more the non-zero counts are discounted. A count of 1 becomes 3 with k = 2, tripling, while a count of 442 barely moves. On the slide table, add-2 lowers strawberry/sugar from 5.51 to 5.31 and leaves the overall pattern intact.

The oldest fix is the bluntest. Church and Hanks simply discarded pairs seen 5 times or fewer. Frequency cut-offs of that kind are still common in collocation tools.

Add-k smoothingContext alpha
What changesEvery count gets + k before probabilities are computedOnly the context distribution P(c) is reshaped
Which counts move mostSmall counts, proportionally (1 becomes 3 with k = 2)Rare contexts gain probability, frequent ones lose a little
Typical valuek from 0.1 to 3alpha = 0.75
strawberry/sugar5.51 → 5.31 (k = 2)5.51 → 4.01
OriginLaplace smoothing, as in n-gram language modelsword2vec negative sampling, carried over by Levy et al. (2015)
The two smoothing fixes for rare-event bias

Recall

Why does clipping to PPMI not remove PMI's bias toward rare contexts?

The bias inflates positive values through a tiny P(c) in the denominator, and clipping only touches negative values, so the inflated scores pass through unchanged.

Raising context counts to alpha = 0.75

Take two contexts with P(a) = .99 and P(b) = .01. Raising both to 0.75 and renormalising roughly triples the rare one, so every Pointwise mutual information involving b falls by about 1.6 bits. The worked example below shows each step.

PPMI⁡α(w,c)=max⁡ ⁣(log⁡2P(w,c)P(w) Pα(c), 0),Pα(c)=count⁡(c)α∑c′count⁡(c′)α\begin{aligned} &\operatorname{PPMI}_\alpha(w, c) \\ &\quad = \max\!\left(\log_2 \frac{P(w, c)}{P(w)\,P_\alpha(c)},\ 0\right), \\ &P_\alpha(c) = \frac{\operatorname{count}(c)^\alpha}{\sum_{c'} \operatorname{count}(c')^\alpha} \end{aligned}
Alpha-weighted PPMI; the slides and SLP3 use alpha = 0.75

The exponent Alpha-weighted context probability flattens the context distribution. Because 0 < α < 1 shrinks large counts proportionally more than small ones, after renormalising P_alpha(c) > P(c) for rare contexts and P_alpha(c) < P(c) for frequent ones. A larger denominator means a lower PMI, so rare contexts lose exactly the inflated advantage the previous concept described, and Positive PMI computed with P_alpha(c) keeps fewer spurious rare dimensions. Only P(c) changes; P(w, c) and P(w) stay as before.

The five context probabilities on a log scale, with dashed outlines at the original P(c). When active, the bars morph to their alpha = 0.75 values: computer and data dip slightly, while sugar, the rarest context with 61 counts, rises to almost three times its old probability.

On the slide table the effect is easy to predict. Sugar, with only 61 counts, goes from P = .0052 to .0148, so strawberry/sugar drops from 5.51 to 4.01 and cherry/sugar from 3.30 to 1.80. The frequent context computer goes from .4265 to .4019, so digital/computer actually rises from 0.18 to 0.27. Result goes from .0404 to .0686, which pushes information/result from 0.28 to a PMI of -0.48, so its PPMI becomes 0.

computerpiesugar
P(c).4265 → .4019.0437 → .0728.0052 → .0148
cherry-6.70 → -6.614.38 → 3.643.30 → 1.80
strawberry-∞ → -∞4.10 → 3.375.51 → 4.01
digital0.18 → 0.27-4.91 → -5.65-2.17 → -3.67
information0.02 → 0.10-6.07 → -6.81-1.63 → -3.13
PMI before and after alpha = 0.75 for three contexts (alpha = 1 → alpha = 0.75)

Worked example

Slide 60's two-context example

  1. Raise to alpha

    .99^.75 = .9925 and .01^.75 = .0316.
  2. Find the shared normaliser

    .9925 + .0316 = 1.0241. Both contexts are divided by this same sum.
  3. Renormalise

    P_alpha(a) = .9925 / 1.0241 = .97 and P_alpha(b) = .0316 / 1.0241 = .03.
  4. Result

    The rare context's probability rises from .01 to .03; the frequent one falls from .99 to .97.

Why 0.75, and the road to word2vec

The number is borrowed. Mikolov and colleagues (2013) found that drawing negative samples for word2vec from the unigram distribution raised to the 3/4 power, U(w)^(3/4) / Z, worked significantly better than either the plain unigram or the uniform distribution. Levy, Goldberg and Dagan (2015) carried the trick over to count-based PMI as "context distribution smoothing", tested α ∈ {1, 0.75}, and found that it alleviates PMI's bias toward rare words and consistently improves performance across tasks, methods and configurations.

The connection runs deeper than a shared constant. Levy and Goldberg (2014) showed that Skip-gram with negative sampling with k negative samples implicitly factorizes a word-context matrix whose cells are PMI(w, c) - log k. The sparse analogue is shifted PPMI, max(PMI(w, c) - log k, 0), which they found competitive on word similarity. So PPMI and word2vec are close relatives: Negative sampling is, in a precise sense, a smoothed and compressed way of estimating the same quantity you just computed by hand. Keep this in mind for the skip-gram parts that follow.

Recall

Why does raising context counts to 0.75 lower the PMI of rare contexts?

It flattens the context distribution, so after renormalising a rare context gets P_alpha(c) > P(c). A bigger denominator means a smaller ratio and a lower PMI.

Recall

Why is "raise the probabilities" the same as "raise the counts" to alpha?

P(c)^α = count(c)^α / N^α, and the N^α cancels when you renormalise.

Quick check

With P(a) = .99, P(b) = .01 and alpha = 0.75, what is P_alpha(b)?

Quick check

Applying alpha = 0.75 to the slide's context counts does what to PPMI(strawberry, sugar)?

Recap

If you remember nothing else

  • PMI(w, c) = log2 P(w, c) / (P(w)P(c)) measures how far a pair sits above or below chance, in bits. Zero means independent.
  • Negative PMI is unreliable without enormous corpora, so PPMI = max(PMI, 0). Clipping also maps unseen pairs from minus infinity to 0.
  • All probabilities come from one matrix total N: the joint is the cell over N, the marginals are the row and column sums over N.
  • Shortcut: PMI = log2(f_ij × N / (row_i × col_j)). In the slide example, information/data = 0.09 and strawberry/sugar = 5.51.
  • PMI favours rare events: one co-occurrence with a rare context can outscore thousands of genuine ones. PPMI does not fix this.
  • Fixes: add-k smoothing (add-one on slide 59 is k = 1; SLP3 uses k from 0.1 to 3), or P_alpha(c) with alpha = 0.75, which raises rare-context probabilities and lowers their PMI.
  • alpha = 0.75 comes from word2vec negative sampling, and SGNS itself approximates a PMI matrix shifted by log k.

Sources

Part 07: Dense vectors and the skip-gram classifier

Why short dense vectors beat long sparse ones, the main ways to get them, and how word2vec turns embedding learning into a self-supervised binary task scored by the sigmoid of a dot product.

6 concepts, slides 61-74

Why this part matters

This is where the lecture switches from counting to learning. Until now every vector was a row of a count table, reweighted by tf-idf or PPMI. From here on the vectors are parameters that a small classifier learns, and the classifier is trained on a task that running text answers for free. Skip-gram with negative sampling is an early, influential template for the pretext tasks that followed in NLP, including the masked-word objective of BERT, and it is a staple exam item: explain self-supervision, compute σ(c·w).

It also matters for research and real systems. The downloadable static vectors you will reach for (GoogleNews 300-d, GloVe 6B) and the gensim switches you will set (sg=1, negative=5, window=5) all come from the ideas below. The argument runs in six steps: why short dense vectors beat long sparse ones, where dense vectors come from, the idea of predicting instead of counting, how a window turns text into pairs, how a dot product becomes a probability, and how one window is scored as a whole. How the vectors are actually learned is the next part.

By the end you can

  1. Contrast sparse and dense vectors by length, zeros and value range, and give three reasons dense vectors help, including the car and automobile argument.
  2. Name the main sources of dense vectors (word2vec, GloVe, SVD/LSA, contextual models) and distinguish static from contextual embeddings.
  3. Explain self-supervision and the four-step skip-gram recipe, and say why the classifier is discarded while its weights are kept.
  4. Generate the positive (target, context) pairs for a ±m window, and relate m to the slides' L = 2m context words per target.
  5. Compute P(+|w,c) = σ(c·w) and P(-|w,c) = σ(-c·w) for given vectors.
  6. Score a whole window with the product of sigmoids and its log sum, and state the independence assumption behind it.

Short dense vectors versus long sparse ones

One sentence says "she drove the car to work"; another says "he parked the automobile outside". In a count space, drove collects weight on the car dimension and parked collects weight on the automobile dimension. Those are two different coordinates. If those are their only informative neighbors, the dot product of the two verbs is exactly 0, so their cosine is 0 too, even though any reader sees that the two sentences describe the same kind of event.

Worked example

Two verbs, two synonyms, zero similarity

  1. Keep only the two relevant dimensions

    Use the axes (car, automobile). drove = [1, 0] and parked = [0, 1].
  2. Dot product

    1×0 + 0×1 = 0.
  3. Cosine

    0 / (1 × 1) = 0. The vectors are orthogonal: as far as the space can tell, the two verbs share nothing.
  4. Result

    Sparse vectors treat car and automobile as unrelated axes, so words that differ only in which synonym they co-occur with look completely dissimilar.

Part 03 previewed this contrast on slide 30; here it gets its full argument. The vectors of the last three parts were sparse vectors. Built from a tf-idf or Pointwise mutual information weighting, they have one dimension per vocabulary word, so their length is |V|, typically 20,000 to 50,000, and nearly every entry is zero. A Dense vector is the opposite on every count. It has a small fixed number of dimensions d, usually between 50 and 1000; almost all of its entries are non-zero; and they are real numbers that can be negative. The price is interpretability: the d dimensions do not correspond to context words or to anything else nameable (SLP 5.5). Such a vector is still an Embedding, just a learned one rather than a counted one.

Car and automobile light up separate cells of a forty-cell sparse row. In a dense space both words land on the same few dimensions, so their cosine is high.
PropertySparse (tf-idf, PPMI)Dense (word2vec)
Length|V| ≈ 20,000 to 50,000d ≈ 50 to 1000
ZerosAlmost every entryAlmost none
ValuesCounts or non-negative weightsReal numbers, positive or negative
Dimension meaningEach axis is one context wordNo clear interpretation
Weights a one-word classifier needs50,000300
SynonymsSeparate, orthogonal axesCan share the same directions
Sparse count vectors and dense learned vectors side by side (SLP 5.5)

Three reasons dense vectors win

  1. Fewer weights to learn. A classifier that uses one word as a feature needs one weight per dimension: 300 weights for a dense vector instead of 50,000 for a sparse one. Fewer parameters may generalize better and overfit less.
  2. Better Synonymy. In a dense space, car and automobile can occupy nearby directions, so a word whose neighbors include car is automatically close to a word whose neighbors include automobile. The Cosine similarity of drove and parked is no longer forced to zero.
  3. Empirically better. SLP states it bluntly: dense vectors work better in every NLP task than sparse vectors. The slide says the same more cautiously: in practice, they work better.

Recall

Why do sparse vectors fail on car and automobile, and give two other reasons dense vectors help.

Car and automobile are separate, orthogonal dimensions, so two words whose neighbors differ only in which synonym they use share nothing and get cosine 0. Dense vectors also need fewer weights (300 vs 50,000), which may generalize better, and they work better in practice.

Quick check

One word occurs only near car, another only near automobile. What cosine do their sparse count vectors give?

Suppose you need word vectors for a project tomorrow. You do not have to train anything. You can download the word2vec GoogleNews vectors, or one of the GloVe sets from Stanford, and have a dense vector for millions of words in a few minutes. Knowing where each set comes from tells you what it can and cannot do.

Pretrained static vectors you can download today

word2vec GoogleNews
300-d vectors for 3,000,000 words and phrases, trained on part of Google News (about 100 billion words); 1,662 MB as word2vec-google-news-300 in gensim-data
GloVe 6B
Wikipedia 2014 plus Gigaword 5, 400K vocabulary, in 50, 100, 200 and 300 dimensions
GloVe, larger sets
Common Crawl (42B and 840B tokens), Twitter (27B), and newer 2024 Dolma and Wikipedia plus Gigaword releases

The lecture sorts dense vectors into three families. The first is inspired by neural language models: learn vectors by predicting words from their neighbors. Word2vec is the flagship, and it is a toolkit with two algorithms, Skip-gram (predict the neighbors from the word) and Continuous bag of words (predict the word from its neighbors). The slide also places GloVe here, which is a simplification noted below. The second family is factorization: take a count matrix and compress it with singular value decomposition. Latent semantic analysis (LSA) is SVD applied to a term-document matrix with the first 300 or so dimensions kept (Deerwester et al. 1990, in SLP's history section). The slide then presents contextual models such as ELMo and BERT as an alternative to these static embeddings. Both the SVD bullet and the contextual bullet are greyed out, because this lecture concentrates on word2vec.

FamilyExampleLearns fromOne vector per
Prediction (neural-LM inspired)word2vec SGNS, CBOWLocal windows, by predicting neighborsWord type
Global co-occurrence regressionGloVeGlobal co-occurrence countsWord type
Matrix factorizationSVD, LSATerm-document (or PPMI) matrixWord type
ContextualELMo, BERTThe whole sentence, at run timeToken in context
Where dense vectors come from, and what each one is a vector of

The last column is the line that matters most. Word2vec, GloVe and LSA all produce a Static embedding: one fixed vector per word type, looked up from a table. The word bank gets the same vector in "river bank" and "bank loan", so Polysemy is averaged into a single point. A Contextual embedding is computed by running the whole sentence through a network, so each token occurrence gets its own vector (Peters et al. 2018; Devlin et al. 2019). Those models come later in the course; this lecture is about static vectors.

In practice you train your own vectors with gensim. Its defaults are worth memorizing because they bite: vector_size=100, window=5, negative=5 (the docs say usually between 5 and 20), ns_exponent=0.75, min_count=5, and sg=0, which means CBOW.

from gensim.models import Word2Vec
import gensim.downloader as api

model = Word2Vec(
    sentences=corpus,
    vector_size=300,
    window=5,
    sg=1,
    negative=5,
    min_count=5,
)

google_news = api.load("word2vec-google-news-300")
google_news.most_similar("automobile", topn=3)
Training skip-gram with gensim, and loading the GoogleNews vectors from gensim-data

Recall

Static versus contextual embeddings: give one example of each.

Static means one vector per word type, looked up from a table (word2vec, GloVe). Contextual means one vector per token, computed from its sentence (ELMo, BERT).

Read the phrase "...a tablespoon of apricot jam...". Without anyone annotating anything, it hands you a labeled fact: (apricot, jam) is a yes, these two words occur near each other. Now pick a random word from the lexicon, say aardvark. (apricot, aardvark) is almost certainly a no. Every sentence of every book and web page produces such facts by the dozen.

That is the whole idea behind Skip-gram with negative sampling. Instead of counting how often a word c occurs near apricot, train a binary classifier on the question "is c likely to show up near apricot?" Nobody actually cares about that question. What we keep are the weights the classifier learns in order to answer it, and those weights are the embeddings. Because the gold answers come from running text rather than from people, this is Self-supervision.

The four-step recipe

  1. Treat the target word and each neighboring context word as a positive example.
  2. Randomly sample other words from the lexicon to make negative examples.
  3. Train logistic regression to tell the two kinds of pair apart.
  4. Throw the classifier away and use its learned weights as the embeddings.

The idea has a lineage. Bengio et al. (2003) and Collobert et al. (2011) had already shown that the next word in running text is a free supervision signal for learning word vectors, and Collobert et al. stressed the "vast amounts of mostly unlabeled training data" this unlocks. Word2vec simplifies their neural language models in two ways (SLP 5.5). It replaces the hard task of predicting the next word over the whole vocabulary with a yes-or-no question about a single pair, and it replaces a multi-layer network with plain logistic regression. The payoff was speed: Mikolov et al. (2013a) learned high quality vectors from a 1.6 billion word data set in less than a day.

The binary framing is also what keeps training cheap. The basic skip-gram formulation defines its probability with a softmax over the whole vocabulary, whose cost grows with W, "often large (10^5 to 10^7 terms)" (Mikolov et al. 2013b). Negative sampling replaces that sum with a handful of k sampled noise words, 5 to 20 for small data sets and 2 to 5 for large ones. How those negatives are drawn and how the weights are updated is the subject of the next part.

Recall

What is self-supervision in word2vec, and why does it need no human labels?

Words that actually occur near the target in running text serve as gold positive answers to "is c a neighbor of w?", and randomly sampled words serve as negatives. The corpus supplies the labels; we keep the classifier's learned weights as the embeddings.

Recall

List the four steps of the skip-gram intuition.

(1) Target and neighbor pairs are positives. (2) Random lexicon samples are negatives. (3) Train logistic regression to separate them. (4) Use the learned weights as embeddings.

Quick check

In skip-gram training, where do the gold labels come from?

From a context window to (target, context) pairs

Take the running text "...lemon, a tablespoon of apricot jam, a pinch..." and put a window of two words on each side of apricot. The target is w = apricot, and the four context words are c1 = tablespoon, c2 = of, c3 = jam and c4 = a. Each one forms a positive training pair with the target.

A ±2 window around apricot: four arcs to real neighbors become positive pairs, while a randomly sampled word such as aardvark becomes a negative one.

Worked example

Positive pairs from a ±2 window

  1. Target apricot

    (apricot, tablespoon), (apricot, of), (apricot, jam), (apricot, a).
  2. Slide one word to the right: target jam

    (jam, of), (jam, apricot), (jam, a), (jam, pinch).
  3. Result

    Every token takes a turn as the target. A window of ±2 gives up to 4 positive pairs per target, and in general a half-width of m gives up to 2m. Fewer appear only at the edges of a text.

A note on letters: the slides and SLP write L for the number of context words being scored, so a ±2 window has L = 4. Keep that in mind when you meet c_1:L in the last concept of this part. The half-width is written m throughout this lecture, so L = 2m. Try the window yourself: click any word to make it the target and change the half-width.

SimulatorWindow to (target, context) pairs
Click any word to make it the target.
......
  • (apricot, tablespoon)
  • (apricot, of)
  • (apricot, jam)
  • (apricot, a)
Positive pairs4of up to 4A full window gives 2 pairs per unit of half-width.
Target wapricotEvery token takes this role in turn during training.

Once the pairs exist, the classifier's job is simple to state. Given a candidate pair (w, c), return the probability that c is a real context word of w. For (apricot, jam) that probability should be high; for (apricot, aardvark) it should be low. Since there are only two outcomes, the probability of the negative answer is whatever is left over:

P(+∣w,c)P(−∣w,c)=1−P(+∣w,c)\begin{gathered} P(+\mid w,c) \\ P(-\mid w,c)=1-P(+\mid w,c) \end{gathered}
The two outputs of the skip-gram classifier (SLP eqs 5.11 and 5.12)

Recall

How many positive pairs does a ±3 window give for a target in mid-sentence, and what is the slides' L for it?

6 pairs, so L = 6 (in general 2m).

Quick check

With a ±1 window over '...tablespoon of apricot jam, a pinch...', which positive pairs does target jam produce?

Give apricot a toy three-dimensional vector w = (1, 0.5, -1). Give jam the context vector c = (2, 1, -0.5) and aardvark c = (-1, 0.5, 1). Multiply apricot by jam elementwise and add: 2 + 0.5 + 0.5 = 3. Do the same with aardvark: -1 + 0.25 - 1 = -1.75. The real neighbor scores high, the random word scores low. The question is how to turn those two scores into probabilities.

The intuition the classifier uses is the one from the cosine parts: two vectors are similar when their Dot product is high, and the Cosine similarity is just a dot product divided by the two vector lengths. So skip-gram takes the dot product c·w as its similarity score. But neither a dot product nor a cosine is a probability. Because embedding entries can be negative, the dot product can be anything from -∞ to ∞ (SLP 5.5.1).

Logistic regression already has the fix. The sigmoid function maps any real number into the open interval (0, 1), so the classifier passes the dot product through it:

σ(x)=11+exp⁡(−x)\sigma(x)=\frac{1}{1+\exp(-x)}
The logistic sigmoid (SLP eq 5.14)
P(+∣w,c)=σ(c⋅w)=11+exp⁡(−c⋅w)\begin{aligned} P(+\mid w,c)&=\sigma(\mathbf{c}\cdot\mathbf{w}) \\ &=\frac{1}{1+\exp(-\mathbf{c}\cdot\mathbf{w})} \end{aligned}
Probability that c is a real context word of w (SLP eq 5.15)
P(−∣w,c)=1−P(+∣w,c)=σ(−c⋅w)=11+exp⁡(c⋅w)\begin{aligned} P(-\mid w,c)&=1-P(+\mid w,c) \\ &=\sigma(-\mathbf{c}\cdot\mathbf{w}) \\ &=\frac{1}{1+\exp(\mathbf{c}\cdot\mathbf{w})} \end{aligned}
Probability that c is not a context word of w (SLP eq 5.16)

The identity 1 - σ(x) = σ(-x) is worth checking once, because it is used constantly: the two cases always sum to 1, and flipping the sign of the score swaps them. A few anchor values make hand computation quick: σ(0) = 0.5, σ(2) = 0.8808, σ(-2) = 0.1192, σ(5) = 0.9933, σ(-5) = 0.0067.

The sigmoid squashes any dot product into (0, 1). Jam's score of 3 maps to 0.95; aardvark's -1.75 maps to 0.15.

Worked example

P(+) for jam and for aardvark, with w = (1, 0.5, -1)

  1. Multiply elementwise

    jam: (1×2, 0.5×1, -1×-0.5) = (2, 0.5, 0.5). aardvark: (1×-1, 0.5×0.5, -1×1) = (-1, 0.25, -1).
  2. Sum

    c·w = 3 for jam and c·w = -1.75 for aardvark.
  3. Exponentiate the negated score

    e^-3 = 0.0498 and e^1.75 = 5.7546.
  4. Invert one plus that

    jam: 1 / 1.0498 = 0.9526. aardvark: 1 / 6.7546 = 0.1480.
  5. Result

    P(+ | apricot, jam) = 0.9526 and P(+ | apricot, aardvark) = 0.1480, so P(- | apricot, aardvark) = 0.8520.
SimulatorFrom dot product to probability
c · w3.0000Any real number, not a probability.
P(+ | w, c)0.9526σ(c · w) = 1 / (1 + e-c·w)
P(- | w, c)0.0474σ(-c · w), so the two sum to 1.

Recall

Compute P(+|w,c) for w = (1, 0.5, -1) and c = (2, 1, -0.5).

The dot product is 2 + 0.5 + 0.5 = 3, so σ(3) = 1 / (1 + e^-3) = 0.9526.

Quick check

With w = (1, 0.5, -1) and c = (2, 1, -0.5), what is P(+|w,c)?

One pair at a time is not enough: apricot has four neighbors in its ±2 window, and the classifier should score the whole window. Keep w = (1, 0.5, -1) and give each of the four context words a toy vector.

Contextcc·wσ(c·w)log σ
tablespoon(0.5, 0, -0.5)1.00.7311-0.3133
of(0.2, -0.4, 0.1)-0.10.4750-0.7444
jam(2, 1, -0.5)3.00.9526-0.0486
a(0, 0.2, 0)0.10.5250-0.6444
Scoring apricot's ±2 window, one context word at a time (natural logs)

Skip-gram makes one simplifying move: it assumes the context words are independent of each other given the target. Under that assumption the probability that all of them are real neighbors is the product of the individual sigmoid probabilities, and its logarithm is a sum.

P(+∣w,c1:L)=∏i=1Lσ(ci⋅w)P(+\mid w,c_{1:L})=\prod_{i=1}^{L}\sigma(\mathbf{c}_i\cdot\mathbf{w})
Window probability under independence (SLP eq 5.17)
log⁡P(+∣w,c1:L)=∑i=1Llog⁡σ(ci⋅w)\log P(+\mid w,c_{1:L})=\sum_{i=1}^{L}\log\sigma(\mathbf{c}_i\cdot\mathbf{w})
The same quantity in log space (SLP eq 5.18)

Worked example

Product and log sum for the apricot window

  1. Multiply the four sigmoids

    0.7311 × 0.4750 × 0.9526 × 0.5250 = 0.1737.
  2. Add the four logs

    -0.3133 - 0.7444 - 0.0486 - 0.6444 ≈ -1.7507.
  3. Check they agree

    e^-1.7507 ≈ 0.1737. The log sum is the log of the product.
  4. Result

    Four true neighbors give a joint probability of only 0.1737, dragged down by the weakly scored function words of and a. With hundreds of factors the product would underflow, which is why training works in log space.

That last sentence hides a detail that sets up the next part. SLP's figure 5.6 shows that skip-gram stores two embeddings per word: one for when the word is a target and one for when it is a context. They live in a target matrix W and a context matrix C, the Target and context matrices, so the parameters are 2|V| vectors of dimension d. Learning those two matrices from positive and negative pairs is what part 8 is about.

Recall

Write P(+|w,c_1:L), say which assumption it relies on, and why we take logs.

P(+|w,c_1:L) = ∏ σ(c_i·w). It assumes the context words are independent given the target. Taking logs turns the product into a sum of log σ terms, which avoids underflow and does not change which window scores higher.

Quick check

Why does skip-gram multiply the sigmoid scores of the context words?

Recap

If you remember nothing else

  • Sparse tf-idf and PPMI vectors have length |V| (20,000 to 50,000) and are mostly zeros. Dense embeddings have 50 to 1000 dimensions with real values that can be negative.
  • Dense vectors need far fewer classifier weights (300 vs 50,000), capture synonymy that separate dimensions miss (car and automobile), and work better in practice.
  • The dense families are word2vec (skip-gram, CBOW), GloVe (global co-occurrence), SVD/LSA, and contextual models (ELMo, BERT). The first three are static: one vector per word type.
  • Word2vec predicts rather than counts. A binary classifier asks "is c near w?", and its learned weights become the embeddings.
  • Self-supervision: neighbors in running text are the gold positives and random lexicon words are the negatives, so no human labels are needed.
  • A ±2 window around apricot gives four positives: tablespoon, of, jam, a.
  • P(+|w,c) = σ(c·w) = 1/(1 + e^(-c·w)) and P(-|w,c) = σ(-c·w). σ(0) = 0.5.
  • Assuming independent context words, P(+|w,c_1:L) = ∏σ(c_i·w) and log P = Σ log σ(c_i·w).
  • SGNS stores two vectors per word: a target matrix W and a context matrix C.

Sources

Part 08: Learning skip-gram embeddings with negative sampling

The two embedding matrices W and C, how positive and k negative training pairs are built, the cross-entropy loss for SGNS, its gradients, and the SGD updates that pull true neighbors together and push sampled noise apart.

6 concepts, slides 75-88

Why this part matters

Part 07 built a classifier, P(+ | w, c) = σ(c · w), that scores whether c is a real neighbor of w. It assumed the vectors already existed. This part is where they come from: the Skip-gram with negative sampling training loop that starts from random numbers and, one window at a time, turns them into embeddings in which apricot sits near jam.

Three reasons to know this cold. The Stochastic gradient descent update for skip-gram is a standard exam derivation (it is SLP3 Exercise 5.3). The same pattern of positive and noise pairs, dot-product scores and a cross-entropy loss is the backbone of contrastive learning in modern retrieval and sentence embedding models, so it shows up in research papers well beyond word2vec. And when you train or debug real embeddings, the defaults matter: k = 5 negatives, a 0.75 exponent on the noise distribution, and a learning rate that starts at 0.025 and decays.

By the end you can

  1. Describe θ as W stacked over C, with 2|V| rows of dimension d, and say what each matrix is for.
  2. Build positive pairs from a ±2 window and draw k noise words from the α = 0.75 weighted unigram.
  3. Derive the SGNS cross-entropy loss from the independence assumption and σ(−x) = 1 − σ(x).
  4. Derive the three gradients and apply one SGD update by hand.
  5. Explain why W and C are trained separately and then summed or reduced to W alone.

Take a vocabulary of 10,000 words and embeddings of dimension d = 300. How many numbers does Skip-gram learn? The natural guess is one vector per word, so 3,000,000. The real answer is twice that, 6,000,000, because every word owns two rows.

The parameters θ are two matrices stacked on top of each other. The top block W has one row per vocabulary word, indexed 1 to |V|; these are the target embeddings, used when a word sits at the center of a window. The bottom block C has another row per word, indexed |V| + 1 to 2|V|; these are the context embeddings, used when a word appears as a neighbor or is drawn as a noise word. So apricot has a row w_apricot in W and a separate row c_apricot in C, and together these are the Target and context matrices. SLP3 (Fig. 5.6) calls the W rows the input embeddings and the C rows the output embeddings, which is also the vocabulary of Mikolov et al. and of Rong's derivation notes.

θ=[WC]∈R2∣V∣×d\theta=\begin{bmatrix}W\\C\end{bmatrix}\in\mathbb{R}^{2|V|\times d}
All SGNS parameters: 2|V| dense vectors of dimension d

What each block of θ holds

W, rows 1 to |V|
Target embeddings (also called input embeddings). Row w_i is used when word i sits at the center of a window.
C, rows |V| + 1 to 2|V|
Context embeddings (also called output embeddings). Row c_i is used when word i is a neighbor or a sampled noise word.
Shape of θ
2|V| × d
Size for |V| = 10,000, d = 300
2 × 10,000 × 300 = 6,000,000 parameters
What the classifier reads
Only dot products c · w, with c taken from C and w taken from W. A row of W is never dotted with another row of W.

The reason for two tables becomes clear once you look at what the classifier from part 07 actually computes. It only ever takes a Dot product between a context row and a target row, c · w. A target never meets another target, and a context never meets another context. W and C are therefore two different roles, and the model is free to learn different coordinates for each role. Every row is a Dense vector of length d; nothing here is sparse or counted.

θ as one tall column: W (targets) over C (contexts). apricot owns a row in each band, and after training the two rows are usually added into one vector.

Recall

How many vectors does θ hold, and how many parameters is that for |V| = 10,000 and d = 300?

2|V| vectors of size d, so 2 × 10,000 × 300 = 6,000,000.

Take the sentence fragment "lemon, a tablespoon of apricot jam, a pinch" with apricot as the target and a ±2 window. The four words inside the window give four positive pairs: (apricot, tablespoon), (apricot, of), (apricot, jam) and (apricot, a). No human labeled them; the corpus did, which is the Self-supervision idea from part 07.

A classifier trained only on positives would learn to say "yes" to everything. So each positive pair is matched with k negative pairs, built by keeping the target and replacing the context with a noise word drawn at random from the lexicon. With k = 2 the four positives above get eight negatives, for example aardvark, my, where, coaxial, seven, forever, dear and if. The slide lists these eight as one pool, so the way the table below assigns two to each positive is only illustrative. This is Negative sampling: the model learns to tell real neighbors from random words, rather than to predict the exact neighbor out of all |V| words.

Positive context (label 1)Two noise words drawn for it (label 0, illustrative)
tablespoonaardvark, my
ofwhere, coaxial
jamseven, forever
adear, if
Training pairs for target apricot, window ±2, k = 2

Which random words? The flattened unigram

Noise words are not drawn uniformly, and not quite in proportion to frequency either. They are drawn from the unigram distribution raised to the power α = 0.75 and renormalized, the same Alpha-weighted context probability trick part 06 used to stop Pointwise mutual information from overrating rare contexts. The only constraint SLP3 imposes is that the noise word is not the target itself.

Pα(w)=count(w)α∑w′count(w′)α,α=0.75P_\alpha(w)=\frac{\mathrm{count}(w)^{\alpha}}{\sum_{w'}\mathrm{count}(w')^{\alpha}},\qquad \alpha=0.75
SLP3 eq. 5.19: the weighted unigram used to draw noise words

Raising probabilities to a power below one compresses their range. Frequent words lose a little mass, rare words gain proportionally much more, so the model sees rare words as negatives often enough to learn something about them, while frequent function words still dominate. The two-word example from part 06 (slide 60, SLP3 eq. 5.20) applies unchanged: with P(a) = 0.99 and P(b) = 0.01, the rare word roughly triples its chance of being drawn, to about 0.03, while a drops only to 0.97. The arithmetic is identical; what changes is the role. In part 06 the flattened distribution sat in a PMI denominator, here it decides which words are sampled as noise.

Five words from a Zipf-like unigram. Raising to the power 0.75 and renormalizing shrinks the head (0.60 to 0.51) and lifts the tail (0.01 to 0.024).

Mikolov et al. (2013) report that U(w)^{3/4} / Z "outperformed significantly" both the raw unigram and the uniform distribution. They recommend k between 5 and 20 for small datasets and 2 to 5 for large ones. The reference C code and gensim both default to negative = 5 and an exponent of 0.75 (gensim calls it ns_exponent). Levy, Goldberg and Dagan (2015) named the same move context distribution smoothing and showed it consistently improves count-based PMI vectors too, not just word2vec.

Recall

How are noise words chosen, and what does α = 0.75 do?

They are drawn from count(w)^0.75, normalized, and never the target itself. Rare words gain probability (0.01 becomes about 0.03) and frequent ones lose a little.

Quick check

Why does SGNS draw noise words from the unigram raised to 0.75?

Fix one training instance: target w = apricot, positive context c_pos = jam, and k = 2 noise words matrix and Tolstoy. The loss for this instance is

L=−[log⁡σ(cjam⋅w)+log⁡σ(−cmatrix⋅w)+log⁡σ(−cTolstoy⋅w)]\begin{aligned} L=-\Big[&\log\sigma(\mathbf{c}_{jam}\cdot\mathbf{w}) \\ &+\log\sigma(-\mathbf{c}_{matrix}\cdot\mathbf{w}) \\ &+\log\sigma(-\mathbf{c}_{Tolstoy}\cdot\mathbf{w})\Big] \end{aligned}

The first term is small when the classifier is confident that jam is a neighbor. Each of the other two is small when the classifier is confident that the noise word is not. Where does this shape come from? We want the classifier to give high probability to the correct label of every pair in the instance: label + for the positive and label − for each noise word. Treating the k + 1 decisions as independent, and minimizing the negative log of their joint probability, gives the cross-entropy loss in four short steps.

LCE=−log⁡[P(+∣w,cpos)×∏i=1kP(−∣w,cnegi)]=−[log⁡P(+∣w,cpos)+∑i=1klog⁡P(−∣w,cnegi)]=−[log⁡P(+∣w,cpos)+∑i=1klog⁡(1−P(+∣w,cnegi))]=−[log⁡σ(cpos⋅w)+∑i=1klog⁡σ(−cnegi⋅w)]\begin{aligned} L_{CE}&=-\log\Big[P(+\mid w,c_{pos})\\&\qquad\times\prod_{i=1}^{k}P(-\mid w,c_{neg_i})\Big]\\ &=-\Big[\log P(+\mid w,c_{pos})\\&\qquad+\sum_{i=1}^{k}\log P(-\mid w,c_{neg_i})\Big]\\ &=-\Big[\log P(+\mid w,c_{pos})\\&\qquad+\sum_{i=1}^{k}\log\big(1-P(+\mid w,c_{neg_i})\big)\Big]\\ &=-\Big[\log\sigma(\mathbf{c}_{pos}\cdot\mathbf{w})\\&\qquad+\sum_{i=1}^{k}\log\sigma(-\mathbf{c}_{neg_i}\cdot\mathbf{w})\Big] \end{aligned}
SLP3 eq. 5.21: independence, log of a product, P(−) = 1 − P(+), and 1 − σ(x) = σ(−x)
  1. Independence turns the joint probability of the k + 1 labels into a product, and the minus log turns maximizing probability into minimizing a loss.
  2. The log of a product is a sum of logs.
  3. A pair is either a neighbor or not, so P(− | w, c) = 1 − P(+ | w, c).
  4. Plug in P(+ | w, c) = σ(c · w) from part 07 and use the Sigmoid identity 1 − σ(x) = σ(−x).

The negative terms are not decoration. Goldberg and Levy (2014) point out that with positives alone the objective has a trivial solution: make every vector the same, with a large enough norm that every dot product is huge, and every positive gets probability 1 (they note this happens once the dot product reaches about 40). Such vectors are useless, since every word looks like every other. The noise terms make that collapse expensive, because identical vectors would also give every noise pair probability 1.

Recall

Write the SGNS loss for one target w with one positive and k negatives.

L = −[log σ(c_pos · w) + Σ_{i=1..k} log σ(−c_neg_i · w)], which is minimized.

Take the instance from the previous concept, "...apricot jam..." with k = 2 noise words matrix and Tolstoy. One learning step does three things at once. It moves apricot's target vector w and jam's context vector c_jam toward each other, so c_pos · w rises. It moves w and c_matrix apart, and w and c_Tolstoy apart, so both c_neg · w values fall. Every other row of θ, including aardvark and zebra in both W and C, is left exactly as it was.

One SGD step for apricot with k = 2: w and jam's context vector move toward each other (c·w rises) while matrix and Tolstoy drift away (c·w falls).

The rule behind the picture is gradient descent. The gradient ∇_θ L is the vector of partial derivatives of the loss with respect to every parameter; it points in the direction in which the loss grows fastest. To reduce the loss, step the opposite way, by an amount scaled by the Learning rate η.

θt+1=θt−η ∇θL(θt)\theta^{t+1}=\theta^{t}-\eta\,\nabla_{\theta}L(\theta^{t})
One gradient descent step. SLP3: we minimize the loss using stochastic gradient descent.

"Stochastic" means the gradient is computed from one training instance (or a small batch) at a time, not from the whole corpus. The training loop walks through the corpus, takes each target and each of its window positives, samples k noise words, computes the loss for that small instance, and steps. Because the loss of one instance involves only w, c_pos and the k noise contexts, the gradient is zero for every other row, and the update touches just 2 + k rows out of 2|V|. That sparsity is what makes word2vec fast enough to train on billions of tokens.

Recall

Which rows of θ change after one (w, c_pos) step with k = 2?

Four: w in W, and c_pos, c_neg1 and c_neg2 in C.

Quick check

For one positive pair with k = 2, which vectors does a single SGD step change?

The fastest way to trust the update equations is to run one by hand. Use tiny vectors so every number is visible, then read the general rule off the arithmetic.

Worked example

One SGD step in two dimensions

  1. Setup

    d = 2, η = 0.5, w = (1, 0), c_pos = (0, 1) for jam, c_neg1 = (1, 1) for matrix, c_neg2 = (0.5, −1) for Tolstoy.
  2. Dot products and sigmoids

    c_pos · w = 0, c_neg1 · w = 1, c_neg2 · w = 0.5. So σ(0) = 0.5, σ(1) = 0.731, σ(0.5) = 0.622. The classifier is unsure about jam and wrongly leans toward calling both noise words neighbors.
  3. Loss before the step

    L = −[log 0.5 + log(1 − 0.731) + log(1 − 0.622)] = 0.693 + 1.313 + 0.974 ≈ 2.980.
  4. Gradients (all at time t)

    Each gradient is (σ(c · w) − y) times the partner vector, with y = 1 for jam and y = 0 for noise words; the derivation follows below. ∂L/∂c_pos = (0.5 − 1) w = (−0.5, 0); ∂L/∂c_neg1 = 0.731 w = (0.731, 0); ∂L/∂c_neg2 = 0.622 w = (0.622, 0); ∂L/∂w = −0.5 c_pos + 0.731 c_neg1 + 0.622 c_neg2 = (1.042, −0.391).
  5. Apply θ − η ∇L

    c_pos = (0.25, 1.0), c_neg1 = (0.634, 1.0), c_neg2 = (0.189, −1.0), w = (0.479, 0.196).
  6. Check the effect

    New dot products: c_pos · w = 0.315 (up from 0), c_neg1 · w = 0.500 (down from 1), c_neg2 · w = −0.105 (down from 0.5).
  7. Result

    The loss falls from 2.980 to 2.163 in one step. The positive was pulled up and both negatives were pushed down, exactly the picture in the previous concept.

Where the gradients come from

Two derivative facts do all the work, both about the Sigmoid derivative. From dσ/dz = σ(z)(1 − σ(z)) it follows that d/dz log σ(z) = 1 − σ(z) and d/dz log σ(−z) = −σ(z). Apply them with the chain rule, remembering that z = c · w has derivative w with respect to c and c with respect to w, and the minus sign in front of the loss flips the signs.

∂LCE∂cpos=[σ(cpos⋅w)−1]w∂LCE∂cnegi=[σ(cnegi⋅w)]w∂LCE∂w=[σ(cpos⋅w)−1]cpos+∑i=1k[σ(cnegi⋅w)]cnegi\begin{aligned} \frac{\partial L_{CE}}{\partial \mathbf{c}_{pos}}&=\big[\sigma(\mathbf{c}_{pos}\cdot\mathbf{w})-1\big]\mathbf{w}\\ \frac{\partial L_{CE}}{\partial \mathbf{c}_{neg_i}}&=\big[\sigma(\mathbf{c}_{neg_i}\cdot\mathbf{w})\big]\mathbf{w}\\ \frac{\partial L_{CE}}{\partial \mathbf{w}}&=\big[\sigma(\mathbf{c}_{pos}\cdot\mathbf{w})-1\big]\mathbf{c}_{pos}\\&\quad+\sum_{i=1}^{k}\big[\sigma(\mathbf{c}_{neg_i}\cdot\mathbf{w})\big]\mathbf{c}_{neg_i} \end{aligned}
SLP3 eqs. 5.22 to 5.24

All three have the same shape: (prediction minus label) times the other vector. Write y = 1 for a positive pair and y = 0 for a noise pair; each gradient is (σ(c · w) − y) times the partner vector. The reference word2vec.c computes exactly this as g = (label − sigmoid) * alpha, folding the learning rate and the sign into one number. Plugging the gradients into θ^{t+1} = θ^t − η ∇L gives the three update rules.

cpost+1=cpost−η[σ(cpost⋅wt)−1]wtcnegit+1=cnegit−η[σ(cnegit⋅wt)]wtwt+1=wt−η[[σ(cpost⋅wt)−1]cpost+∑i=1k[σ(cnegit⋅wt)]cnegit]\begin{aligned} \mathbf{c}_{pos}^{t+1}&=\mathbf{c}_{pos}^{t}-\eta\big[\sigma(\mathbf{c}_{pos}^{t}\cdot\mathbf{w}^{t})-1\big]\mathbf{w}^{t}\\ \mathbf{c}_{neg_i}^{t+1}&=\mathbf{c}_{neg_i}^{t}-\eta\big[\sigma(\mathbf{c}_{neg_i}^{t}\cdot\mathbf{w}^{t})\big]\mathbf{w}^{t}\\ \mathbf{w}^{t+1}&=\mathbf{w}^{t}-\eta\Big[\big[\sigma(\mathbf{c}_{pos}^{t}\cdot\mathbf{w}^{t})-1\big]\mathbf{c}_{pos}^{t}\\&\qquad+\sum_{i=1}^{k}\big[\sigma(\mathbf{c}_{neg_i}^{t}\cdot\mathbf{w}^{t})\big]\mathbf{c}_{neg_i}^{t}\Big] \end{aligned}
SLP3 eqs. 5.25 to 5.27, with every right-hand side at time t
ParameterLabel yGradientDirection of the update
c_pos1[σ(c_pos·w) − 1] wToward w (the factor is negative)
c_neg_i0σ(c_neg_i·w) wAway from w
wboth[σ(c_pos·w) − 1] c_pos + Σ σ(c_neg_i·w) c_neg_iToward c_pos, away from each c_neg_i
The three gradients as (σ − y) times the partner vector
Step size equals error. jam (label 1) at σ = 0.50 has an error bar of 0.50 up to 1; matrix (label 0) at σ = 0.73 has a long bar down to 0; a noise word already at σ = 0.02 barely moves.

Recall

Derive ∂L/∂c_pos.

d/dc [−log σ(c · w)] = −(1 − σ(c · w)) w = [σ(c_pos · w) − 1] w.

Quick check

The update for a negative context is η·σ(c_neg·w)·w. When is it nearly zero?

When training ends, apricot still has two rows, w_apricot and c_apricot. SLP3 says the common choice is to add them and represent apricot by w_apricot + c_apricot; the alternative is to keep only w_apricot and throw C away. Either way the result is a Static embedding: one fixed vector per word type, compared with Cosine similarity.

Why keep the tables apart during training at all? Goldberg and Levy (2014) give the argument. Suppose dog had a single vector v used in both roles. Then the score for the pair (dog, dog) would be v · v = |v|², which is large for any vector with a large norm, so the model would believe dog is its own most likely neighbor. Real text rarely says "dog dog", so the model would have to keep word norms small to avoid that, fighting its own objective. Two tables remove the conflict.

Why does adding them afterwards help? Levy, Goldberg and Dagan (2015) show that the cosine of two summed vectors includes terms like w_x · c_y, which measure whether x and y appear in each other's contexts. Adding context vectors therefore adds first-order similarity (co-occurrence) to the second-order similarity (shared neighbors) that W alone captures. The trick comes from GloVe, whose authors summed the two sets of vectors as a cheap way of combining two models, much like an ensemble.

OptionVector for word iWhat it capturesIn practice
Keep W onlyw_iSecond-order similarity: two words are close when they have similar neighborsSmallest vectors; the default in gensim's wv
Sumw_i + c_iAdds first-order similarity terms: words that co-occur also get closerSLP3's common choice; behaves like an ensemble
Concatenate[w_i ; c_i]Keeps both views separately, doubling the dimensionRarely used; costs 2d per word
Turning the two trained tables into one vector per word

The whole recipe

  1. Initialize W and C randomly: 2|V| vectors of dimension d. (word2vec.c draws W uniformly in ±0.5 / d and starts C at zeros.)
  2. Slide a window over the corpus. Each (target, neighbor) pair is a positive; for each, draw k noise words from P_α as negatives.
  3. Train the logistic classifier σ(c · w) to separate positives from negatives, minimizing L_CE with SGD.
  4. Throw the classifier away and keep the learned rows as the embeddings, summed or W only.

Step 4 is the heart of Self-supervision: the yes-or-no prediction task was never the goal. It was a pretext that forced the model to place words with similar contexts close together, and the Embedding is the by-product we wanted.

The same θ column at the end of training: the apricot row in W and the apricot row in C are drawn out and merged into one w + c vector.

Recall

Why keep W and C separate during training, then sum them?

One shared vector would force a high v · v, so a word would look like its own neighbor. Summing afterwards adds first-order similarity and works like an ensemble.

Quick check

Why does SGNS train separate W and C tables instead of one vector per word?

Recap

If you remember nothing else

  • θ = [W; C]: 2|V| vectors of size d. W holds targets and C holds contexts and noise words.
  • Each window positive gets k noise words from P_α(w) ∝ count(w)^0.75, never the target itself.
  • L_CE = −[log σ(c_pos·w) + Σ log σ(−c_neg_i·w)], minimized with SGD.
  • The gradients are (σ − y) times the other vector: [σ(c_pos·w) − 1]w, σ(c_neg·w)w, and the combined sum for w.
  • Updates take the form θ^{t+1} = θ^t − η∇L. Use time-t values throughout. Only 2 + k rows change per pair.
  • After training, discard the classifier and keep w_i + c_i, or w_i alone.

Sources

Part 09: Hyperparameters, word2vec variants and window size

Standard SGNS settings, the CBOW, GloVe, FastText and skip-thought alternatives, and how the context window size decides whether neighbors are syntactic or topical.

6 concepts, slides 89-97

Why this part matters

Picking k, d and the window size is the first thing you do when you train embeddings on a thesis corpus or an Arabic system, and the defaults you inherit from a library are not always the ones the papers recommend. CBOW, GloVe, FastText and skip-thought are the standard comparisons on an exam, and the window size quietly decides whether your vectors find synonyms or topics.

The part opens with the settings that make skip-gram work in practice and what each one trades. It then walks through four relatives of skip-gram, each changing one design decision: CBOW flips the prediction direction, GloVe replaces the sliding window with a global count matrix, FastText breaks words into character pieces, and skip-thought moves the whole idea from words to sentences. It closes with the one hyperparameter that changes not how good the vectors are but what kind of similarity they encode.

By the end you can

  1. State the standard SGNS hyperparameters and explain what raising k, d or the window costs and buys.
  2. Contrast CBOW with skip-gram by input, output, speed and rare-word quality.
  3. Write the GloVe objective and explain each part of its weighting function f.
  4. Decompose a word into FastText n-grams and explain how unseen words get vectors.
  5. Explain skip-thought vectors as skip-gram lifted to sentences.
  6. Predict whether a small or large window yields functional or topical neighbors.

Two students train skip-gram on the same afternoon. One has a clinical corpus of 5 million tokens; the other has 6 billion tokens of web text. Should they use the same number of negative samples? No. The small corpus gives each word only a few true context pairs, so each of those precious pairs has to do more work: contrasting it against many noise words, k = 15 to 20 (the paper allows 5 to 20), squeezes more signal out of it. On the huge corpus every word already sees thousands of real contexts, and k = 2 to 5 is enough while costing a fraction of the compute.

That is the pattern for every knob in skip-gram with negative sampling: each one trades quality against compute or memory, and the right value depends on how much data you have. The lecture gives a "somewhat standard" setting: the model is SGNS, 15 to 20 negative samples for smaller datasets and 2 to 5 for the huge datasets that are usually used, a dense vector of 300 dimensions (100 or 50 also work), and a sliding context window of 5 to 10.

The SGNS knobs, their usual values, and what raising each one buys and costs

Model
Skip-gram with negative sampling (SGNS). The alternatives in this part (CBOW, GloVe, FastText) are judged against it.
Negatives k
15 to 20 on small corpora per the slide (5 to 20 per Mikolov et al.), 2 to 5 on very large corpora. Raising k sharpens the contrast for each true pair and costs one more dot product per positive.
Dimension d
300 is the common choice; 100 or 50 also work. Raising d gives room for more distinctions but grows memory and every dot product linearly, with small gains past 300.
Window half-width m
5 to 10 on the slide, read as words per side, matching word2vec's and Gensim's window parameter (SLP3 says 1 to 10 per side). A ±m window gives 2m context words, which is part 07's L. Raising it adds more pairs per position and shifts neighbors from functional to topical (last concept of this part).
Noise distribution
Unigram counts raised to 3/4, the α of weighted PPMI, so rare words are drawn as negatives a little more often than their raw frequency.
Subsampling threshold t
Around 10^-5 in Mikolov et al.: very frequent words such as the are randomly dropped, which speeds training and helps rare words.

What each knob costs

The cost of negatives is easy to count. For every true (target, context) pair, the skip-gram classifier computes one dot product for the positive and one for each of the k noise words, and each dot product sends a gradient into one row of the context matrix:

dot products per positive pair=1+k\text{dot products per positive pair} = 1 + k

Going from k = 5 to k = 20 therefore makes training about 3.5 times slower (21 / 6). The dimension sets the memory. The model holds two matrices, the target and context matrices W and C, each with one row of length d per vocabulary word:

parameters=2 ∣V∣ d\text{parameters} = 2\,|V|\,d
A 100,000-word vocabulary at d = 300 needs 60 million parameters

Two smaller settings travel with these. Negatives are not drawn by raw frequency but from the unigram distribution raised to 3/4, the same α = 0.75 trick that weighted PPMI uses, which gives rare words a slightly better chance of being picked as noise. And very frequent words are randomly discarded with a threshold around 10^-5, so that the model does not spend most of its updates on pairs like (cat, the) (Mikolov et al. 2013b).

The defaults you meet in practice differ from the slide, which matters when you compare your results to a paper. Gensim, the usual Python library, defaults to CBOW (the variant explained in the next concept), not skip-gram, with 100 dimensions.

SettingdWindowkModel
Mikolov et al. 2013b experiments30055 to 20 (small data)skip-gram
Gensim Word2Vec10055CBOW (sg=0)
fastText10055skip-gram
This slide300 (or 100, 50)5 to 1015 to 20 (small), 2 to 5 (huge)SGNS
Where the numbers come from

Quick check

According to the lecture, which range of k suits a small training corpus?

Recall

State the standard SGNS hyperparameters from the lecture.

Model SGNS. Negatives 15 to 20 on small data (Mikolov says 5 to 20) and 2 to 5 on huge data. Dimension 300, with 100 or 50 also possible. Window 5 to 10.

Take the sentence "I saw a cute grey cat playing in the garden" with a ±2 window around cat. Skip-gram, the model of the last two parts, turns this position into four separate training pairs: (cat, cute), (cat, grey), (cat, playing), (cat, in). The continuous bag of words model, the other half of word2vec, runs the arrow the other way. It looks up the four context vectors for cute, grey, playing and in, combines them into a single hidden vector h, scores every vocabulary word against h, and is trained so that the highest score goes to cat. One position, one prediction.

Same five words, opposite arrows. CBOW draws the four context words into one prediction of cat; skip-gram sends cat out to predict each of the four context words separately.

The combination step is what gives CBOW its name. The context vectors are pooled into one, which throws away their order (a bag), and they are dense real-valued vectors rather than counts (continuous). In Mikolov et al.'s original description the projection layer is shared so that "all words get projected into the same position (their vectors are averaged)", and "the order of words in the history does not influence the projection":

h=12m∑−m≤j≤m, j≠0wt+j\mathbf{h}=\tfrac{1}{2m}\sum_{-m\le j\le m,\,j\ne 0}\mathbf{w}_{t+j}
The CBOW hidden vector: the mean of the 2m context vectors around position t, for a ±m window

Worked example

One sentence, two models

  1. Pick the window

    Target position: cat. With m = 2, the context words are cute, grey (left) and playing, in (right).

  2. CBOW builds one training instance

    h = (w_cute + w_grey + w_playing + w_in) / 4. The model scores h against the output vectors and the loss pushes the score of cat up. Four vectors go in, one gradient signal comes out, and it is shared equally by the four context words.

  3. Skip-gram builds four

    The pairs (cat, cute), (cat, grey), (cat, playing) and (cat, in) are each scored and updated separately, each with its own k negatives. The center vector of cat receives four updates.

  4. Result

    CBOW does one prediction per position; skip-gram does 2m = 4. That factor is why CBOW trains faster and why skip-gram gives each word, including rare ones, more direct updates.

The consequences follow from that count. With negative sampling, CBOW does 1 + k dot products per position and skip-gram 2m × (1 + k), so skip-gram is about 2m times slower (Mikolov et al. 2013a report the same gap with hierarchical softmax). CBOW's averaging also smooths: a rare word that appears as context is blended with its frequent neighbors before any prediction is made, so its own vector gets a diluted signal. Skip-gram gives every occurrence of a rare word its own pairs, which is why it handles rare words better and in Mikolov et al.'s experiments did better on semantic analogies. The fastText tutorial adds a practical note: skip-gram "works better with subword information than cbow".

CBOWSkip-gram
InputThe bag of 2m context vectors, averaged into one hOne center vector
OutputA score for the center wordA score for each context word, one pair at a time
Predictions per position12m
Dot products per position (SGNS)1 + k2m × (1 + k)
Word order inside the windowIgnoredIgnored (each pair is independent)
Rare wordsSmoothed away by averaging with frequent neighborsEach occurrence gives its own updates; better
StrengthSpeed on large corpora, frequent wordsRare words, semantic analogies, subword extensions
CBOW against skip-gram

Quick check

In CBOW, what is the input and what is the prediction target?

Recall

In one sentence each, what do CBOW and skip-gram predict, and which is better for rare words?

CBOW predicts the center word from the averaged (or summed) bag of context vectors. Skip-gram predicts each context word from the center word. Skip-gram is better for rare words, because each occurrence gets its own updates instead of being averaged with frequent neighbors.

Consider three cells of a word-word co-occurrence matrix. The pair (ice, solid) was seen 10 times, (the, of) 1000 times, and (ice, fashion) never. GloVe wants a dot product for each pair that matches the log of its count: about log 10 ≈ 2.30 for (ice, solid) and log 1000 ≈ 6.91 for (the, of). It does not trust every cell equally. With the published settings, the ice and solid pair gets weight 0.178, the pair the and of gets the maximum weight 1 and no more, and the ice and fashion pair gets weight 0, so its undefined log 0 never enters the loss.

That is the whole method. GloVe, Global Vectors (Pennington, Socher and Manning 2014), first counts the term-context matrix N(w, c) over the corpus, the same matrix that PPMI reweights. It then fits a Dot product of a word vector and a context vector, plus two learned biases, to the log count in every cell, as a weighted least-squares regression:

J(θ)=∑w,cf(N(w,c)) (uc⊤vw+bc+bˉw−log⁡N(w,c))2\begin{aligned} J(\theta)=\sum_{w,c} f\big(N(w,c)\big)\,\big(&\mathbf{u}_c^\top\mathbf{v}_w \\ &+b_c+\bar b_w \\ &-\log N(w,c)\big)^2 \end{aligned}
The GloVe objective as on the slide: context vector u_c, word vector v_w, biases b_c and b̄_w

The weighting function f is where the design lives. Pennington et al. ask three things of it. It must vanish at zero, because log 0 is undefined and because zero cells are 75 to 95 percent of the matrix. It must not decrease, "so that rare co-occurrences are not overweighted", since a pair seen once is mostly noise. And it must stay "relatively small for large values of x, so that frequent co-occurrences are not overweighted". Their choice is a power curve that flattens into a cap:

f(x)={(x/xmax⁡)αx<xmax⁡1otherwisexmax⁡=100, α=34\begin{gathered} f(x)=\begin{cases}(x/x_{\max})^{\alpha} & x<x_{\max}\\ 1 & \text{otherwise}\end{cases} \\ x_{\max}=100,\ \alpha=\tfrac{3}{4} \end{gathered}
f(x) = (x/100)^0.75 rises to the dashed x_max marker and stays flat at 1. The bars show the weights of pairs seen 1, 10, 50 and 1000 times: 0.03, 0.18, 0.59 and 1.
Count xWeight f(x)Example
10.0316A single co-occurrence: barely trusted
50.1057
100.1778(ice, solid)
500.5946
1001x = x_max: full weight reached
10001(the, of): capped, cannot dominate
f(x) at the published settings

Worked example

Three pairs through the loss

  1. (ice, solid), 10 co-occurrences

    Target log 10 ≈ 2.30. Weight (10/100)^0.75 ≈ 0.178. If the current prediction u·v + b + b̄ is 1.30, the term contributes 0.178 × 1.0² = 0.178.

  2. (the, of), 1000 co-occurrences

    Target log 1000 ≈ 6.91. The count is above x_max, so the weight is capped at 1. Without the cap, the same curve would give (1000/100)^0.75 ≈ 5.6, and this one function-word pair would count as much as about 32 pairs like (ice, solid).

  3. (ice, fashion), 0 co-occurrences

    Weight f(0) = 0. The term vanishes, so the undefined log 0 is never evaluated and the optimizer only visits the nonzero cells.

  4. Result

    Rare pairs count a little, mid-frequency pairs count a lot, and very frequent pairs are capped. The slide's sum over all w, c ∈ V silently relies on f(0) = 0 to skip the empty cells.

GloVe sits between the two families in this lecture. Like PPMI it is built on global matrix statistics collected once, and like word2vec it learns dense vectors whose dot products carry the meaning. Jurafsky and Martin describe it as "based on ratios of probabilities from the word-word co-occurrence matrix", capturing global corpus statistics as count methods do while learning dense vectors as word2vec does. Like SGNS it ends with two vectors per word, and the authors use the sum W + W̃ as the final embedding, the same trick as adding w and c in skip-gram. The slide's b̄_w is just the second bias set, written b̃_j in the paper. Pennington et al. also chose 300 dimensions for their main results, and they report that α = 3/4 gave "a modest improvement over a linear version with α = 1".

SGNSGloVe
Data it readsA stream of (target, context) pairs from sliding windowsThe global co-occurrence matrix, counted once
ObjectiveLogistic loss: true pairs up, sampled noise pairs downWeighted squared error between u·v + biases and log N(w,c)
Negativesk sampled per positive pairNone: zero cells get weight f(0) = 0 and drop out
Frequency controlNoise drawn from U(w)^(3/4), subsampling of frequent wordsWeight f(x) = (x/x_max)^(3/4), capped at 1
Final vectorsTarget matrix W, or W + CW + W̃ (target plus context)
SGNS against GloVe

Recall

Why does GloVe's weighting function need f(0) = 0, and what does capping f at 1 above x_max do?

log 0 is undefined, and zero cells are 75 to 95 percent of the matrix, so f(0) = 0 drops them. The cap stops very frequent pairs such as (the, of) from dominating the loss. Below x_max, rare noisy pairs get small weights.

Take the word where. FastText first wraps it in boundary symbols, <where>, so that prefixes and suffixes can be told apart from the middle of a word. With n = 3 it then slides a three-character window across: <wh, whe, her, ere, re>. It also keeps the whole word <where> as one more unit. Each of those six units has its own vector, and the vector of where is their sum.

A three-character window slides across <where>, emitting <wh, whe, her, ere and re>; the whole-word unit <where> joins them, and the six vectors sum into one word vector.

Bojanowski et al. 2017 built this on the skip-gram model. Write 𝒢_w for the set of n-grams of word w, including the word itself, and z_g for the vector of n-gram g. The word's vector and its skip-gram score with a context word c become:

uw=∑g∈Gwzg\mathbf{u}_w=\sum_{g\in\mathcal{G}_w}\mathbf{z}_g
s(w,c)=∑g∈Gwzg⊤vcs(w,c)=\sum_{g\in\mathcal{G}_w}\mathbf{z}_g^\top\mathbf{v}_c
The skip-gram score with subword information: every n-gram of the target takes part in every dot product

Worked example

All the n-grams of where at the real settings

  1. Pad

    where becomes <where>, 7 characters.

  2. n = 3 (5 n-grams)

    <wh whe her ere re>

  3. n = 4, 5 and 6 (4 + 3 + 2 n-grams)

    <whe wher here ere>, then <wher where here>, then <where where>.

  4. Add the special whole-word sequence

    <where> is added as its own unit, distinct from the n-gram where found inside it.

  5. Result

    The paper extracts "all the n-grams for n greater or equal to 3 and smaller or equal to 6", which gives 14 n-grams here, plus the whole word: 15 vectors summed into one.

The boundary symbols matter more than they look. The paper's own example: "the sequence <her>, corresponding to the word her, is different from the tri-gram her from the word where". So the pronoun and the piece of where get separate vectors, while the prefix <wh is shared by where, when, what and which.

What the pieces buy

Plain word2vec gives each word type its own row, so a word missing from training has no vector at all. FastText builds a vector for an unseen word such as wherever by summing the vectors of its n-grams, most of which (<wh, whe, her, ere) were learned from other words. The same sharing helps rare inflections in morphologically rich languages such as Arabic, Turkish and German: a rarely seen form borrows statistics from frequent forms that share its stem and affixes. Pretrained FastText vectors exist for 157 languages.

The price is computation, which the slide calls "a lot of additional computation": every update now touches about fifteen vectors for the target instead of one. Memory is kept bounded by hashing all n-grams into a fixed table of 2,000,000 buckets (the bucket default), so collisions are allowed rather than storing every possible substring.

Quick check

FastText meets the unseen word 'wherever' at test time. Which vector does it return?

Recall

List the FastText 3-gram units for 'where' and explain how FastText builds a vector for an unseen word.

<wh, whe, her, ere, re>, plus the whole-word token <where>. In practice n runs from 3 to 6. An unseen word gets the sum of the vectors of its known n-grams. The word <her> differs from the trigram her inside where.

Take three consecutive sentences from a novel: "I got back home. I could see the cat on the steps. This was strange." A skip-thought model reads the middle sentence and compresses it into one vector. Two decoders then have to regenerate the neighbors from that vector alone, word by word: one writes "I got back home", the other writes "This was strange".

Prev decoder

Generates the previous sentence, "I got back home <eos>", conditioned on the vector.

sentence vector
Encoder (GRU)

Reads "I could see the cat on the steps" and outputs one sentence vector.

sentence vector
Next decoder

Generates the next sentence, "This was strange <eos>", conditioned on the vector.

Skip-thought on the triplet from Kiros et al. 2015: one encoder, two decoders, the previous and next sentences as targets; both decoders read the same vector in parallel

The idea is skip-gram moved up one level. Skip-gram uses a word to predict its neighboring words; Kiros et al. 2015 use a sentence to predict its neighboring sentences. The distributional hypothesis carries over: sentences that appear in similar discourse surroundings, with similar sentences before and after them, are pushed toward similar vectors. In the paper's words, "the sentence s_i is encoded and tries to reconstruct the previous sentences_i−1 and next sentence s_i+1".

Three things change on the way up. A sentence is not one vocabulary item that can be looked up, so the encoder is a recurrent network with GRU units that reads the words in order, which makes the vector order-sensitive. The targets are whole sentences, so the decoders generate text instead of classifying pairs, and there is no negative sampling. And the vectors are big: the model was trained on the BookCorpus (11,038 books, 74,004,228 sentences), the unidirectional encoder gives 2400 dimensions and the combined model 4800. The authors froze these vectors and trained only linear classifiers on top of them for 8 evaluation tasks.

Skip-gramSkip-thought
UnitA wordA sentence
ContextWords within ±mThe previous and the next sentence
EncoderA lookup in W (one row per word)A GRU recurrent network over the words, order-sensitive
ObjectiveClassify (target, context) pairs as real or noiseGenerate each neighbor sentence word by word
Negativesk sampled per positiveNone: decoders use a softmax over the vocabulary
Output sized, typically 100 to 3002400 (uni-skip), 4800 (combine-skip)
Skip-gram against skip-thought

Recall

What does a skip-thought model encode and what does it predict?

A GRU encoder turns a sentence into one vector. Two decoders regenerate the previous and the next sentence from that vector. The result is a 2400-dimensional sentence vector, used as frozen features.

Properties of embeddings start with the window. Levy and Goldberg 2014 trained skip-gram on English Wikipedia twice, changing only the window, and looked up the nearest neighbors of Hogwarts. With a ±2 window they were evernight, sunnydale, garderobe, blandings and collinwood: other fictional schools and houses, words that fill the same slot in a sentence. With a ±5 window they were dumbledore, hallows, half-blood, malfoy and snape: the world of Harry Potter. Same corpus, same model, a different idea of what "similar" means.

Two models trained with different windows. With ±2 Hogwarts' nearest neighbors are Sunnydale, Evernight, Garderobe and Blandings; retrained with ±5 they become Dumbledore, Malfoy, half-blood and Snape. The frames stand for the training window, not distance in the vector space.

The reason is what each window can see. Two words on each side of a noun are mostly its syntactic frame: the determiner before it, the preposition, the verb that takes it as an object ("students at Hogwarts", "returned to Sunnydale"). Words that share those frames are words of the same type and function, so a short window rewards similarity. Linguists call this a paradigmatic, or second-order, association: the two words rarely appear together but appear in the same surroundings. Five words on each side reach past the frame into the topic of the passage, so a long window rewards relatedness, words from the same semantic field. That is a syntagmatic, or first-order, association: the words appear near each other.

The slides show the same split with Voita's examples. With larger windows, dog groups with bark and leash, and walking with walked and run: words about the same activity. With smaller windows, Poodle groups with Pitbull and Rottweiler, and walking with running and approaching: words that could replace one another. Jurafsky and Martin summarize it as shorter windows giving representations that are "a bit more syntactic", with neighbors that are "semantically similar words with the same parts of speech", while longer windows give words that are "topically related but not similar".

Small windowLarge window
Window±2 (small)±5 or more (large)
What the window seesThe syntactic frame: determiners, prepositions, the verb that takes the wordThe whole topic of the passage
Neighbor kindFunctional similarity: same slot, same part of speechTopical relatedness: same semantic field
Hogwarts (Levy and Goldberg)sunnydale, evernight, garderobe, blandings, collinwooddumbledore, hallows, half-blood, malfoy, snape
Dog example (Voita)Poodle, Pitbull, Rottweilerdog, bark, leash
Verb example (Voita)walking, running, approachingwalking, walked, run
Good forSynonym finding, POS-like features, slot fillingTopic modelling, retrieval, query expansion
Small against large windows

The same logic explains the window in the term-context matrix of the count methods: it is one hyperparameter shared by PPMI, SGNS and GloVe, and it changes what all of them learn. Levy and Goldberg push it one step further by replacing the window with syntactic dependency contexts. Hogwarts' neighbors then become sunnydale, collinwood, calarts, greendale and millfield: even more purely functional, all schools and fictional places.

Quick check

Skip-gram is trained with a context window of plus or minus 2. Which neighbors does Hogwarts get?

Recall

With a ±2 versus a ±5 window, what are Hogwarts' nearest neighbors, and why?

±2 gives other fictional schools (Sunnydale, Evernight, Blandings), because narrow windows capture syntactic slot or function. ±5 gives the Harry Potter world (Dumbledore, half-blood, Malfoy), because wide windows capture topic.

Recap

If you remember nothing else

  • Standard SGNS: k = 15 to 20 on small data (5 to 20 in Mikolov), 2 to 5 on huge data, d = 300 (or 100, 50), window 5 to 10.
  • Each extra negative adds one dot product per positive pair; d sets the 2|V|d parameter count.
  • CBOW predicts the center from the averaged context bag: faster, smoother. Skip-gram predicts the context from the center: better for rare words.
  • GloVe fits u_c·v_w + b_c + b_w to log N(w,c) by weighted least squares; f(x) = (x/100)^0.75 below 100, then 1, and f(0) = 0 skips zero cells.
  • FastText adds < and > boundaries, n-grams of 3 to 6 characters and the whole word; a word is the sum of its n-gram vectors, so unseen words still get vectors.
  • Skip-thought encodes a sentence with a GRU and decodes the previous and next sentences, giving 2400-dimensional sentence vectors.
  • A ±2 window yields functional look-alikes (Hogwarts near Sunnydale); a ±5 window yields topic-mates (Hogwarts near Dumbledore).

Sources

Part 10: Analogies, bias and evaluating embeddings

The parallelogram method for analogies and its limits, embeddings as a lens on historical meaning change and cultural bias, visualizing and evaluating embeddings intrinsically and extrinsically, and when to use pretrained embeddings.

7 concepts, slides 98-111

Why this part matters

You have trained an embedding. Four questions follow immediately, and this part answers each. What has the space learned? Relations such as male to female or country to capital show up as directions you can probe with one subtraction and one addition. Can you trust it? Analogy scores flatter it, and it carries the biases of its corpus, which matters for any hiring, search or Arabic NLP system built on top of it. How do you measure it? Intrinsic tests against human judgments, or extrinsic tests inside a real task. And should you train it yourself at all, or take vectors someone else trained?

For exams, the parallelogram formula, the intrinsic versus extrinsic split and allocational versus representational harm are standard items. For research, diachronic embeddings and bias measurement are live tools: the same machinery that tracks how awful changed meaning also measures a century of gender stereotypes.

By the end you can

  1. Compute an analogy answer with the parallelogram method, using argmin distance or argmax cosine, and exclude the input words.
  2. Explain why analogy accuracy overstates relational knowledge, citing the exclusion effect and relation-dependence.
  3. Describe how aligned decade embeddings reveal semantic change, and state the laws of conformity and innovation.
  4. Explain how embeddings encode and amplify cultural bias, distinguish allocational from representational harm, and describe Garg's relative norm measure.
  5. Classify evaluations as intrinsic or extrinsic, and compute a Spearman correlation against human ratings.
  6. Choose between frozen, fine-tuned and jointly trained embeddings given data size and task difficulty.

Apple is to tree as grape is to what? Picture the arrow that starts at apple and ends at tree. It means something like "fruit to the plant it grows on". Now pick that same arrow up, keep its length and direction, and set its tail down on grape. Its head lands near vine. That is the whole method.

The apple to tree arrow is copied to start at grape; its tip lands beside vine, and the dashed edges close the parallelogram.

The same move works on the famous examples. Take king, subtract man, add woman, and the point you reach is close to queen. Take Paris, subtract France, add Italy, and you land close to Rome. In each case the subtraction isolates a relation (royalty without the maleness, the capital-of relation without the particular country) and the addition applies it to a new word. Because the four points form a parallelogram when it works, this is called the Parallelogram method.

The rule, in two equivalent forms

The slides write an analogy as a : a* :: b : b*, read "a is to a* as b is to b*". The relation is the offset from a to a*, so the point to search around is t = a* − a + b. No vocabulary word sits exactly at t, so the answer is the word nearest to it, and the three question words themselves are taken out of the candidate pool (the next concepts show why that matters so much). With Euclidean distance, nearest means smallest distance, so the operator is an argmin:

b^∗=argmin⁡x∈V∖{a,a∗,b}∥x−(a∗−a+b)∥\hat{b}^{*}=\operatorname*{argmin}_{x\in V\setminus\{a,a^{*},b\}} \lVert \mathbf{x}-(\mathbf{a}^{*}-\mathbf{a}+\mathbf{b})\rVert
Parallelogram method with Euclidean distance (SLP3 eq. 5.28, in the slide's a : a* :: b : b* order)

Mikolov, Yih and Zweig, who made the method famous for dense vectors, wrote it the other way round. They normalize every vector to unit length, compute the same target, and return the word with the largest Cosine similarity to it. Nearest by distance and most similar by cosine are the same idea, one written as a minimization and the other as a maximization. When the candidate vectors have unit length, the two rankings are identical, because ‖x − t‖² = 1 + ‖t‖² − 2 x·t.

b^∗=argmax⁡x∈V∖{a,a∗,b}cos⁡(x, a∗−a+b)\hat{b}^{*}=\operatorname*{argmax}_{x\in V\setminus\{a,a^{*},b\}} \cos(\mathbf{x},\ \mathbf{a}^{*}-\mathbf{a}+\mathbf{b})
The cosine form used by Mikolov, Yih and Zweig (2013), with all vectors normalized to unit length

Worked example

man : woman :: king : ? in two dimensions

  1. Place the words

    man (1, 1), woman (1, 3), king (4, 1), queen (4.2, 3.1), princess (3, 3.5).
  2. Build the target

    a = man, a* = woman, b = king, so t = (1, 3) − (1, 1) + (4, 1) = (4, 3). The offset (0, 2) is the "male to female" arrow.
  3. Measure every candidate

    Distances to t: queen 0.224, princess 1.118, king 2.0, woman 3.0, man 3.606.
  4. Result

    The nearest allowed word is queen. Note that it is near t, not on it: the method always ends in a nearest-neighbour search.
SimulatorParallelogram playground: a is to a* as b is to ?
Target t(4.00, 3.00)t = a* − a + b, the point the method searches around.
AnswerqueenNearest remaining word to t.
  1. 1. queen0.224
  2. 2. princess1.118
  3. 3. prince1.803
  4. 4. crown2.28
  5. 5. throne2.786

Try it above. Pick any three words, watch the a to a* arrow get copied onto b, and read the ranking. Switch the space to the small offset and the candidate pool to "allow input words" and keep the playground in mind for the third concept of this part.

Where the idea came from

The parallelogram is older than embeddings. Rumelhart and Abrahamson proposed it in 1973 as a model of how people solve analogies, working in a space of mammal names built from human similarity judgments (apple : tree :: grape : vine is the illustration SLP3 uses for it). Turney and Littman showed in 2005 that sparse count vectors could solve SAT-style analogies, and Mikolov and colleagues brought it to dense neural embeddings in 2013. Their NAACL paper, titled Linguistic Regularities in Continuous Space Word Representations, built a syntactic test set of 8,000 questions and found its recurrent network vectors answered almost 40% correctly. The slide labels it "Mikolov et al. 2013b" and SLP3's bibliography labels the same paper 2013c, so cite it by title.

Recall

Write the parallelogram method for a : a* :: b : b*, and state the two things you must change on slide 99's version.

b̂* = argmin over x ∉ {a, a*, b} of distance(x, a* − a + b). Change argmax to argmin (or switch to cosine and keep argmax), and exclude the three input words.

Quick check

For man : woman :: king : ?, which point does the parallelogram method search around?

Plot man, woman, uncle, aunt, king and queen from Mikolov, Yih and Zweig's recurrent-network language model (the precursor of Word2vec) in two dimensions and draw an arrow from each male word to its female partner. The three arrows come out roughly parallel and roughly the same length. In a second projection of the same space, king to kings and queen to queens are parallel to each other too, and that plural direction cuts across the gender direction.

This is what it means for a relation to be linear in an Embedding space: the offset vector between the two words of a pair is nearly the same for every pair that stands in that relation. Mikolov and colleagues found such offsets for gender (man to woman), verb tense (walking to walked) and country to capital (Spain to Madrid), and their larger 2013 test set organized analogy questions by exactly these semantic and syntactic families. The same picture holds for GloVe: the GloVe project page shows man to woman, sir to madam, heir to heiress, king to queen, uncle to aunt, nephew to niece, brother to sister, earl to countess, duke to duchess and emperor to empress as ten segments that all tilt the same way, and Pennington and colleagues report that offsets also capture comparative and superlative forms.

RelationExample pairWhat the offset meansSlides
Genderman → womanMale form to female form100 to 102
Numberking → kingsSingular to plural100
Tensewalking → walkedProgressive to past101
CapitalSpain → MadridCountry to its capital city101
Titleearl → countessMale noble title to female counterpart102
Relation families that show up as consistent offsets

One word can take part in many relations at once. King is the male member of a gender pair, the singular of a number pair, and a royal term next to throne and crown. A 300-dimensional space has room for all of these as different directions, and that is the sentence Mikolov and colleagues put under their figure: in high-dimensional space, multiple relations can be embedded for a single word. Any 2D picture is one projection chosen to show one of those directions, which is why the slides need two panels to show gender and number for the same words.

Recall

How can king lie on a gender direction and a number direction at the same time?

They are different directions in a high-dimensional space; any 2D plot is one projection chosen to show one of them.

Change the toy space from the first concept so the gender offset is small: man (1, 1), woman (1.4, 1.3), king (4, 1), queen (4.6, 1.9). Now ask man : woman :: king : ?and let every word compete.

Worked example

The exclusion trap

  1. Build the target

    t = (1.4, 1.3) − (1, 1) + (4, 1) = (4.4, 1.3).
  2. Rank with input words allowed

    Distance to king is 0.5, distance to queen is 0.632. The method answers king, the word you gave it.
  3. Exclude a, a* and b

    Remove man, woman and king from the pool. The nearest remaining word is queen at 0.632.
  4. Result

    The right answer appears only after exclusion. With a small offset the target barely moves away from b, so b itself is the nearest point.

This is not a toy artefact. Linzen (2016) ran the standard Word2vec analogy benchmark without excluding the inputs: the nearest neighbour of a* − a + b was b in 93% of cases, a* in 5%, and never a. SLP3 makes the same point with cherry : red :: potato : x, which returns potato or potatoes instead of brown unless those are forbidden. Every published analogy accuracy therefore depends on the exclusion rule, and part of the credit belongs to b*'s simply being b's nearest neighbour. Linzen's baselines make this concrete: a method that ignores a, or even both a and a*, and just returns the neighbour of b, scores very high on plurals.

Where the method works and where it does not

  • It works for frequent words, for pairs where b* already sits close to b (SLP3's "small distances", which is also why b wins unless it is excluded), and for certain relations (SLP3): country to capital, and inflections such as plural and tense.
  • It does poorly on many lexicographic and derivational relations. The BATS set of Gladkova and colleagues has 99,200 questions in 40 categories, against only 15 relations in the Google set, and accuracy varies widely across them.
  • Reversing an analogy uses the same offset with the sign flipped, yet Linzen found accuracy dropped in most categories (mean −0.11): US cities fell from .69 to .17 and common capitals from .9 to .53.
  • As a model of human analogy making, the parallelogram is too simple: Peterson, Chen and Griffiths (2020) show it cannot account for how people form even simple analogies.

3CosAdd versus 3CosMul

Levy and Goldberg (2014) rewrote the cosine objective with unit vectors and saw it as a balance: two attractors (b* should resemble b and a*) and one repeller (b* should not resemble a). Added together, one large similarity can swamp the others. Their multiplicative version keeps each term in check and generally does better.

3CosAdd: argmax⁡b∗∈V(cos⁡(b∗,b)−cos⁡(b∗,a)+cos⁡(b∗,a∗))\begin{aligned} \text{3CosAdd: }\operatorname*{argmax}_{b^{*}\in V}\big(&\cos(b^{*},b) \\ &-\cos(b^{*},a) \\ &+\cos(b^{*},a^{*})\big) \end{aligned}
The additive objective, equivalent to the cosine parallelogram method for unit vectors
3CosMul: argmax⁡b∗∈Vcos⁡(b∗,b) cos⁡(b∗,a∗)cos⁡(b∗,a)+ε,ε=0.001\begin{gathered} \text{3CosMul: }\operatorname*{argmax}_{b^{*}\in V}\frac{\cos(b^{*},b)\,\cos(b^{*},a^{*})}{\cos(b^{*},a)+\varepsilon}, \\ \varepsilon=0.001 \end{gathered}
Levy and Goldberg's multiplicative objective, in the slide's a : a* :: b : b* order; for dense embeddings each cosine is first mapped to [0, 1] by (cos + 1)/2

Recall

What does the offset method return most often if a, a* and b are allowed as answers?

b itself, 93% of the time in Linzen (2016); a* 5%, never a. A small offset leaves the target closest to b.

Quick check

If the input words stay in the candidate pool, what does the offset method usually return?

Follow three words through two centuries of books. In the 1900s gay sits near daft, flaunting, sweet and cheerful; by the 1990s its neighbours are homosexual and lesbian. In the 1850s broadcast sits near sow and seed, a farmer scattering grain; by the 1990s it sits near newspapers, radio and bbc. In the 1850s awful sits near majestic, awe and solemn, full of awe; by the 1900s it sits near terrible and appalling, and by the 1990s near weird and wonderful. That slide from praise to blame is called pejoration.

awful drifts from majestic and awe (1850s) through terrible and appalling (1900s) to weird and wonderful (1990s).

Hamilton, Leskovec and Jurafsky (2016) produced these pictures with diachronic embeddings. The recipe has three steps. First, train a separate embedding for each decade of text. They compared Positive PMI, SVD and Skip-gram with negative sampling on six historical corpora in four languages, with a window of 4 and 300 dimensions; the English Google Books corpus alone has 8.5 × 1011 tokens covering 1800 to 1999, and COHA has 4.1 × 108 tokens covering 1810 to 2009. Second, align the decades so their axes mean the same thing. Third, measure how far each word moved between aligned decades, and read its old and new neighbours.

Why alignment is needed

SVD and SGNS only care about dot products between vectors, and any rotation of the whole space preserves every dot product. So the 1900 run and the 1990 run can come out rotated relative to each other for no linguistic reason, and comparing the raw coordinates of gay in the two runs measures that arbitrary rotation. Hamilton and colleagues fix this with orthogonal Procrustes: find the orthogonal matrix that best maps one decade's matrix onto the next. Because the matrix is orthogonal it is a rotation (possibly with a reflection), so cosines within each decade are unchanged. PPMI vectors need no alignment, since their dimensions are context words that mean the same thing in every decade.

R(t)=argmin⁡Q⊤Q=I∥W(t)Q−W(t+1)∥FR^{(t)}=\operatorname*{argmin}_{Q^{\top}Q=I}\lVert W^{(t)}Q-W^{(t+1)}\rVert_F
Orthogonal Procrustes alignment between decade t and decade t + 1 (Hamilton et al. 2016, eq. 4)

Two statistical laws

Measuring displacement for thousands of words let Hamilton and colleagues state two laws. The law of conformity: the rate of semantic change scales with an inverse power of word frequency, so frequent words change slowly. The law of innovation: holding frequency fixed, words with more senses (higher Polysemy) change faster.

Recall

Why must decade-specific embeddings be aligned before you measure semantic change, and how?

SVD and SGNS spaces can be arbitrarily rotated, so coordinates are not comparable across decades. Orthogonal Procrustes finds the rotation that best maps one decade onto the next while keeping within-decade cosines unchanged.

Recall

State the law of conformity and the law of innovation.

Frequent words change meaning more slowly (the rate scales with an inverse power of frequency). Controlling for frequency, more polysemous words change faster.

Embeddings inherit and amplify cultural bias

Bolukbasi and colleagues ran the Parallelogram method on Word2vec trained on Google News (3 million words and phrases, 300 dimensions). Asked Paris : France :: Tokyo : x, it answers Japan. Asked father : doctor :: mother : x, it answers nurse. Asked man : computer programmer :: woman : x, it answers homemaker. The same machinery that captured capitals captured stereotypes.

The reason is unsurprising once said aloud. An Embedding is a compressed summary of co-occurrence statistics, so if the training text talks about women and men in different contexts, that difference becomes geometry. Bolukbasi and colleagues found that gender bias is largely captured by a single direction, roughly the she minus he offset, onto which occupation words project unevenly.

Occupations drop onto a she to he axis and land at uneven offsets; neutralizing pulls them to the midpoint, yet a small residue stays split.

Two kinds of harm

HarmDefinitionExample
AllocationalA system distributes a resource or opportunity (jobs, loans, search exposure) unfairly across groups.A resume search that ranks documents by embedding similarity to programmer pushes women's resumes down.
RepresentationalA system demeans, stereotypes or erases a group, whether or not any resource is at stake.Caliskan et al. find African American names closer to unpleasant words than European American names.
Harm types (SLP3 section 5.8)

Embeddings do not just mirror the bias in their text; they can amplify it, exaggerating an association beyond its strength in the corpus or in the world (Zhao et al. 2017, Ethayarajh et al. 2019, Jia et al. 2020, as summarized in SLP3). Caliskan, Bryson and Narayanan (2017) built the Word Embedding Association Test (WEAT) and reproduced classic Implicit Association Test results with GloVe, including the finding that African American names sit closer to unpleasant words. Debiasing methods such as Bolukbasi's neutralize and equalize steps remove the component of gender-neutral words along the gender direction. They reduce measured bias, but Gonen and Goldberg (2019) show that the stereotyped words still cluster together afterwards: the bias is hidden, not removed.

Measuring a century of stereotypes

Garg, Schiebinger, Jurafsky and Zou (2018) turned diachronic embeddings into a tool for social history. Using the decade embeddings from Hamilton and colleagues, they built a group vector for women (the average of words like she, her, woman) and one for men, and scored each neutral word (an adjective or an occupation) by its relative norm difference: its average distance to the men vector minus its average distance to the women vector. A negative score means the word sits closer to men.

bias(w)=∥w−vmen∥−∥w−vwomen∥\text{bias}(w)=\lVert \mathbf{w}-\mathbf{v}_{\text{men}}\rVert-\lVert \mathbf{w}-\mathbf{v}_{\text{women}}\rVert
Relative norm difference for one neutral word, averaged over a word list in Garg et al. (positive means closer to women, negative closer to men)

Worked example

Relative norm difference in 2D

  1. Place the vectors

    Women group vector (0, 2), men group vector (2, 0), adjective smart (1.6, 0.6).
  2. Measure both distances

    ‖smart − men‖ = √(0.4² + 0.6²) = 0.721 and ‖smart − women‖ = √(1.6² + 1.4²) = 2.126.
  3. Result

    0.721 − 2.126 = −1.405. A negative value means smart is closer to the men vector.

Run over each decade, the measure tells a story. Competence and intelligence adjectives (smart, wise, thoughtful, logical) were biased toward men, and that bias has been decreasing since the 1960s. Words used to describe outsiders (barbaric, monstrous, hateful, bizarre) were most associated with Asian last names before 1950 and declined steadily afterwards. The embeddings reproduce a 1933 survey of ethnic stereotypes. Occupation bias in the Google News embeddings tracks the 2015 share of women in each occupation (r² = .46), and the decade-by-decade trend in the historical embeddings follows US Census data. Embeddings, in other words, are a usable instrument for measuring culture.

QueryConstrained answerUnconstrained answer
man : doctor :: woman : xgynecologistdoctor
man : computer programmer :: woman : xhomemakercomputer programmer
3CosAdd with and without the input-exclusion constraint (Nissim et al. 2020, Table 1)

Recall

Give one allocational harm and one representational harm caused by embeddings.

Allocational: a hiring search built on embeddings ranks documents with women's names lower. Representational: African American names sit closer to unpleasant words (Caliskan et al. 2017).

Recall

Compute Garg's relative norm difference for w = (1, 1), women = (0, 2), men = (2, 0), and interpret it.

√2 − √2 = 0: equally close to both groups, no gender lean.

Before testing an embedding, look at it. Slide 107 shows a hierarchical clustering of noun embeddings (from Rohde et al., reproduced in SLP3). Read it bottom-up. Body parts merge early: wrist with ankle, then shoulder, arm and leg. Animals form their own branch: dog with cat, then puppy and kitten. Places split off near the top. And look closely at the places: Tokyo sits with Chicago and the other US cities, while Moscow and Hawaii sit with countries and continents.

Leaves join bottom-up in order of merge height: wrist and ankle, dog and cat, Chicago and Tokyo, China and Russia, then the branches.

The height of each join is the dissimilarity at the moment the two clusters merged, so low joins mean close vectors. The odd placements are a lesson in what an embedding encodes: the tree reflects the contexts words appear in, not a geography ontology. Other ways to look include the nearest-neighbour lists you saw for awful, and 2D projections such as t-SNE (van der Maaten and Hinton 2008), which keep local neighbourhoods but distort global distances.

Intrinsic evaluation: test the vectors directly

Intrinsic evaluation scores the vectors on a small task designed to probe them, without building a full system. The most common form compares model similarity with human judgments.

  • WordSim-353 (Finkelstein et al. 2002) asks people to rate 353 word pairs from 0 (totally unrelated) to 10 (very much related or identical); plane and car get 5.77. Because the instruction is about relatedness, cup and coffee can score as high as cup and mug. That is Word relatedness, not Word similarity.
  • SimLex-999 (Hill, Reichart and Korhonen 2015) was built to fix that: 999 adjective, noun and verb pairs rated for genuine similarity, so cup and mug score high and cup and coffee score low.
  • The TOEFL synonym test has 80 questions with 4 choices each: which word is closest to levied? The model picks the choice with the highest cosine. Latent semantic analysis scored 64.4% (Landauer and Dumais 1997), almost exactly the 64.5% average of non-native college applicants in the US.
  • Analogy sets, with all the caveats of the earlier concept.

For a similarity dataset the score is the Spearman rank correlation between the model's cosines and the human ratings. Spearman compares orders, not values, so it does not matter that cosines live in [−1, 1] and ratings in [0, 10].

ρ=1−6∑idi2n(n2−1)\rho = 1-\frac{6\sum_i d_i^{2}}{n(n^{2}-1)}
Spearman's rank correlation without ties, where d_i is the difference between the two ranks of pair i

Worked example

Spearman correlation on four WordSim pairs

  1. Rank both columns

    Human ratings are the real WordSim-353 values; the model cosines are illustrative.
    PairHuman ratingModel cosineHuman rankModel rankd
    drink, ear1.310.08110
    plane, car5.770.42220
    drink, eat6.870.61341
    planet, star8.450.55431
  2. Sum the squared rank differences

    Σd² = 0 + 0 + 1 + 1 = 2, with n = 4.
  3. Result

    ρ = 1 − (6 · 2) / (4 · 15) = 1 − 0.2 = 0.8. The model orders the pairs almost like people do; it only swaps drink-eat and planet-star.

Worked example

Answering a TOEFL item

  1. The question

    Which word is closest in meaning to levied: imposed, believed, requested or correlated?
  2. Score each choice

    Compute cos(levied, choice) for all four choices.
  3. Result

    Return the argmax. A good space puts imposed first, because both words appear around taxes, fines and duties.

Extrinsic evaluation: test inside a real task

Extrinsic evaluation plugs each candidate embedding into an actual system (named entity recognition, machine translation, coreference), trains it, and compares the task metric. SLP3 calls this the most important evaluation for vector models, because the task is what you care about. It is also slow and noisy, which is why intrinsic tests remain popular for quick comparisons.

EvaluationTypeDataScore
WordSim-353Intrinsic353 pairs, 0 to 10, relatednessSpearman ρ between cosine and human ratings
SimLex-999Intrinsic999 pairs, similarity onlySpearman ρ; penalizes cup and coffee scoring like cup and mug
TOEFL synonymsIntrinsic80 items, 4 choices eachAccuracy of argmax cosine over the choices
Analogy sets (Google, BATS)Intrinsica : a* :: b : ? questionsAccuracy of the parallelogram method
NER, MT, coreferenceExtrinsicA full task with its own labelled dataTask metric (F1, BLEU) with each embedding plugged in
Common evaluations and what they measure

Recall

Intrinsic or extrinsic: (a) Spearman ρ with SimLex-999, (b) NER F1 with GloVe versus word2vec inputs, (c) TOEFL synonym accuracy.

(a) intrinsic, (b) extrinsic, (c) intrinsic.

Quick check

A team reports Spearman correlation with SimLex-999 ratings for new embeddings. What evaluation is this?

Feed "I saw a cat." into a neural network. Each token passes through an Embedding layer, a lookup table from word to vector, and the network sits on top. Where should that table come from? There are three answers: copy it from Word2vec or GloVe and freeze it; copy it and keep updating it on your task; or start it from random numbers and learn it together with the network.

The slides give the rule. When there is not enough labelled data, or the task is simple, use embeddings pretrained on another task. Pretrained vectors bring knowledge distilled by Self-supervision from billions of unlabelled tokens, which your few thousand labelled examples could never teach. When there is enough data and the task is hard, such as language modelling or machine translation, train the embeddings with the model, because the task itself supplies the signal and task-specific vectors fit it better. Fine-tuning pretrained vectors is the middle path.

OptionWhere vectors come fromUpdated during training?When to useExample
Frozen pretrainedword2vec or GloVe trained on another corpusNoLittle labelled data, simple taskKim's CNN-static
Fine-tuned pretrainedCopied from word2vec or GloVeYes, starting from the pretrained valuesModerate data, want task-specific nuanceKim's CNN-non-static
Joint from randomLearned from scratch with the networkYes, from random valuesLarge data and a hard task (LM, MT)Kim's CNN-rand; large LMs and MT systems
Three ways to obtain the embedding layer

Two studies give the evidence. Kim (2014) trained a CNN sentence classifier on small benchmarks three ways. CNN-rand, with random embeddings learned jointly, did poorly. CNN-static, with frozen word2vec vectors, "performs remarkably well", and CNN-non-static, which fine-tunes them, improves further; Kim concludes that pretrained vectors are good, universal feature extractors. Qi and colleagues (2018) asked the same question for neural machine translation and found gains of up to 20 BLEU in the most favourable setting. The gains have a sweet spot: they are largest when training data is scarce, but not so scarce that the system cannot be trained at all (baseline BLEU around 3 to 4), and they shrink as parallel data grows.

Everything in this lecture has been a Static embedding: one fixed vector per word type, whatever the sentence. Later lectures replace it with a Contextual embedding, where the vector for bank depends on its sentence. In those language models the embedding layer is trained jointly with the network, exactly the right-hand side of slide 110.

Recall

You have 500k parallel sentences for a hard MT task. Pretrained or joint, and why?

Joint training, possibly initialized from pretrained vectors. Enough data and a hard task let the model learn task-specific embeddings, and Qi et al. found pretrained gains largest in low-resource settings.

Quick check

You build a dialect sentiment classifier from 2,000 labeled tweets. How should its embeddings start?

Recap

If you remember nothing else

  • Parallelogram method: b̂* = argmin over x of distance(x, a* − a + b), or argmax of cosine, with a, a* and b excluded. Slide 99's argmax of distance is a typo.
  • Relations such as gender, number, tense and country to capital appear as roughly constant offsets; one word can sit on several such directions at once.
  • Without exclusion the method returns b 93% of the time. It works best for frequent words, answers that already sit near b, and inflectional or capital relations; 3CosMul improves on 3CosAdd.
  • Decade-specific embeddings, aligned by orthogonal Procrustes, show gay, broadcast and awful shifting. Frequent words change slowly; polysemous words change fast.
  • Embeddings reproduce and amplify stereotypes (father : doctor :: mother : nurse), causing allocational and representational harms. Debiasing hides more than it removes.
  • Garg et al. track bias over a century with relative norm differences: competence adjectives lean male (weakening since the 1960s), outsider words were tied to Asian names before 1950, and occupation bias tracks census data.
  • Visualize with dendrograms, nearest-neighbour lists or t-SNE; all of them show usage, not an ontology.
  • Intrinsic evaluation: WordSim-353, SimLex-999, TOEFL, analogies. Extrinsic evaluation is a downstream task and the more important one.
  • Use pretrained vectors with little data or a simple task; train embeddings jointly with a large dataset and a hard task; fine-tuning sits between.

Sources