Chapter 6 left us with a working idea and two complaints about it.
The idea is this. Represent a word by a row of a co-occurrence matrix . Read similarity of meaning as the cosine between rows.
The complaints are these. The raw counts in measure frequency more than association. And the matrix is impossibly wide, with one column per vocabulary word and almost all entries zero.
This chapter is the classical repair of both. It is the pipeline that carried distributional semantics for two decades before neural embeddings. Reweight the counts so they measure genuine association. Then factor the matrix, so tens of thousands of sparse dimensions collapse into a few hundred dense ones.
Why are raw counts misleading? Because the most frequent words co-occur with everything.
The word the sits next to dog, car, idea and every other noun, thousands of times. A raw count credits the with enormous association to words it is merely adjacent to by grammatical accident.
What we want is a different quantity. Not how often two words co-occur, but how much more often than we would expect if they were independent.
That ratio is pointwise mutual information:
where is the probability that and co-occur, and and are their individual probabilities, all estimated by counting.
The denominator is what we would expect under independence. The numerator is what we observe. PMI takes the logarithm of their ratio, in bits.
The interpretation is clean. A PMI of means the words are exactly independent, since . A positive value means they co-occur more than chance. A negative value means less than chance.
One number will fix the scale in your mind. Two words that co-occur twice as often as independence predicts have a PMI of bit. Ten times as often gives bits.
The estimate is a pure count computation. With a corpus of tokens,
Take a pair seen together times in a corpus of tokens. Each word occurs times on its own. The score is bits. That is a strong, above chance association.
The word the never contaminated the answer. Its large marginal sits in the denominator and cancels its large joint count.
Try it yourself.
code/worked_examples/weighting.py pmitabulates five pairs against what independence predicts. One is above chance, one is exactly at chance and scores zero, and one is below chance and gets clipped by PPMI.
PMI has a weakness at the other end. A negative PMI claims that two words co-occur less than chance.
To trust such a claim you need to have seen the pair often enough to trust its rarity. In a sparse matrix, most pairs are seen never or once. So negative values are mostly noise.
The standard remedy is to clip them:
which is positive pointwise mutual information.
A PPMI weighted matrix keeps only the above chance associations and sets everything else to zero. That has a happy side effect. The matrix stays sparse, and so storable, while now measuring association rather than frequency.
One bias survives the clipping. It is worth naming, because it returns in the next chapter in disguise.
PMI is inflated for rare words. A word seen only a handful of times has a tiny marginal in the denominator. So any co-occurrence at all produces a large PMI.
The common fix is to smooth the context distribution. Raise its counts to a power less than one, with . This lifts the probability of rare contexts and so lowers their PMI.
Remember that exponent, . Chapter 9 introduces word2vec’s negative sampling. It draws negative examples from a distribution smoothed by exactly the same power. That is not a coincidence. It is a sign that the two methods compute closely related things.
Before neural embeddings, several complete systems were built on the ideas of this chapter. Two are worth knowing properly. Their design choices are the choices anyone building a count model has to make. And the second was the strongest count based model of its era.
Hyperspace Analogue to Language makes three decisions that set it apart.
Plain counting treats every word in the window alike. A neighbour ten words away then counts as much as the word next door. HAL weights by closeness instead.
Slide a window of width along the corpus. For a target at position and a context word at position , the weight is
The adjacent word scores the full , and the weight ramps down to at the edge of the window. Lund and Burgess used , so the neighbour scored 10 and the tenth word away scored 1.
HAL passes over the corpus twice, in opposite directions, and keeps the two results apart.
The left to right scan takes each word as the key and ramps weights onto the words that follow it. The right to left scan reverses the corpus and does the same, which ramps weights onto the words that precede it.
Both passes write into one matrix, under the convention that holds the weight of occurring before :
Now read that definition carefully. counts before . But counts before . Those are different events, so in general
The matrix is asymmetric, and deliberately so. Here is the same pair read in both directions, taken from the worked matrix below:
| pair | what each cell counts | ||
|---|---|---|---|
| raced, horse | horse before raced, and the reverse | 5 | 0 |
| barn, the | the before barn, and the reverse | 6 | 0 |
| the, horse | horse before the, and the reverse | 3 | 5 |
The first two pairs are lopsided to the point of being one sided. Horse precedes raced in this corpus and never follows it, so one cell holds 5 and its mirror holds 0. The third pair is nonzero both ways and still unequal, because the and horse occur near each other at different distances depending on which comes first.
A symmetric matrix could not record any of that. It would average the two directions away and report only that the words occur near each other.
Word order carries grammar. Dog bites and bites dog are different facts, and a symmetric window throws the difference away. HAL keeps it, which is what the two scans are for.
Take the corpus used in the lectures,
the horse raced past the barn fell
with . The scan is a ramp descending from each key word:
| the | horse | raced | past | the | barn | fell | |
|---|---|---|---|---|---|---|---|
| weight from the | K | 5 | 4 | 3 | 2 | 1 | 0 |
| weight from horse | K | 5 | 4 | 3 | 2 | 1 |
Apply Equation (7.4) everywhere and the full matrix is:
| the | horse | raced | past | barn | fell | |
|---|---|---|---|---|---|---|
| the | 2 | 3 | 4 | 5 | 0 | 0 |
| horse | 5 | 0 | 0 | 0 | 0 | 0 |
| raced | 4 | 5 | 0 | 0 | 0 | 0 |
| past | 3 | 4 | 5 | 0 | 0 | 0 |
| barn | 6 | 2 | 3 | 4 | 0 | 0 |
| fell | 4 | 1 | 2 | 3 | 5 | 0 |
Two cells check by hand. Row raced says horse scores 5, because horse sits one word before it. In the same row the scores 4, because the first the sits two words before.
Row barn is the interesting one. The occurs twice in the window, once at distance 1 and once at distance 5, so it collects . A repeated context word accumulates every time it appears. Miss that and your matrix is wrong.
The asymmetry is precisely why a word needs two vectors, not one.
Take the word . Its row says what came before it. Its column says what came after it. Those are the two scans, recovered from the one matrix.
A symmetric model would have nothing to concatenate, because row and column would be identical. HAL concatenates them, giving dimensions for a vocabulary of .
That is enormous and mostly uninformative, so HAL keeps only the columns with the highest variance, typically a few hundred. A column that is nearly constant across words cannot distinguish them, so it goes.
Similarity is then a Minkowski distance rather than a cosine,
with giving ordinary Euclidean distance.
That pruning step is a crude ancestor of the SVD above. Both cut dimensions. The SVD builds new dimensions that capture variance. HAL merely selects existing dimensions that already carry it.
Lund and Burgess were clear about the weakness, and it is the reason COALS exists. Raw weighted counts still track frequency.
Take two unrelated words and with . Their vectors will hold entries of similar magnitude simply because both words are about as common, and any distance measure will call them close. Now take two genuinely related words with . Their magnitudes differ wildly, and the measure will call them far apart.
Similar frequency does not mean similar meaning. That is the problem a normalised statistic has to solve.
Try it yourself.
code/worked_examples/hal.pybuilds the matrix above and lists the most lopsided pairs, so you can see the asymmetry rather than take it on trust.--vectorsshows why a word needs its row and its column, and--windowshortens the ramp.
Correlated Occurrence Analogue to Lexical Semantics keeps the ramped window and changes almost everything else.
This is the central move, and it is the answer to the flaw HAL exposed.
COALS converts each raw count into a correlation between the word and the context, computed over the whole matrix. Write for the count in row and column , and let be the grand total of every entry. Then
The numerator is the same comparison PMI makes. is what we observed, scaled up, and the product of the two margins is what independence predicts. The denominator normalises by how much each margin could vary, which puts every entry on the same scale no matter how common the words are.
That last part is what HAL lacked. A frequent word now has a large margin in both numerator and denominator, so being common stops earning a large score.
The lectures use a deliberately silly corpus:
How much wood would a woodchuck chuck, if a woodchuck could chuck wood? As much wood as a woodchuck would, if a woodchuck could chuck wood.
A ramped window of size 4 over 13 word types gives a count matrix whose grand total is . Four row and column sums we will need: a sums to 80, if to 31, woodchuck to 75, and wood to 81 down its column and 71 across its row.
Now compute three cells with Equation (7.7).
| cell | arithmetic | |
|---|---|---|
The first cell is the instructive one. A never sits next to itself, so , and the correlation goes firmly negative. The statistic has noticed an avoidance, not merely an absence.
The second and third are positive, and they say that a genuinely attracts if and woodchuck. A is the most frequent word in the corpus. Under raw counts it would have dominated every row. Here it does not.
Two steps finish the job:
Negatives go to zero for the same reason PPMI clips negative PMI. There is rarely enough evidence to trust an avoidance claim, and zeros keep the matrix sparse.
The square root damps what survives. It pulls in the large values, so a few strong pairings cannot dominate a vector. Applying it to our three cells, becomes , while becomes and becomes . Those two are far closer after the root than before it.
COALS drops HAL’s direction distinction, so the matrix stays symmetric and half the size. It also discards all but the columns for the most common open class words, with in the original paper. It can then be run through an SVD, as Section 1.4 describes, to get dense vectors.
Rohde and colleagues reported that this beat both HAL and Latent Semantic Analysis on word similarity judgements. The gain came mostly from the correlation step and the square root. The reweighting mattered more than the reduction, which is a useful thing to know.
Try it yourself.
code/worked_examples/coals.pyprints all three steps on this corpus, reproducing the tables above.--cell a ashows the arithmetic for one cell the long way, which is the quickest route to believing the formula.
Set the three models side by side and the family resemblance is plain.
| HAL | COALS | PPMI SVD | |
|---|---|---|---|
| window | ramped | ramped | flat |
| direction | kept | discarded | discarded |
| reweighting | none | correlation | PMI |
| negatives | n/a | clipped to 0 | clipped to 0 |
| damping | none | square root | log, inside PMI |
| reduction | pick high variance columns | SVD | SVD |
Every one of them does the same four things. Count co-occurrences. Reweight them into association rather than frequency. Optionally compress. Read similarity as an angle. They disagree about the statistic and about whether order matters. They agree about the shape.
That shape is what the next chapter abandons. Not the distributional hypothesis, which survives untouched, but the idea that you must build the matrix at all.
The reweighted matrix is better but no smaller. It is still as wide as the vocabulary.
The second repair compresses it, using the workhorse of linear algebra, the singular value decomposition. Any real matrix can be factored as
where and have orthonormal columns, and is diagonal with non negative entries in descending order. Those entries are the singular values.
The singular values measure how much of the matrix’s variance each new dimension accounts for. names the single direction along which the data vary most. names the next. And so on.
Because they decay, most of the structure lives in the first handful of dimensions. The long tail contributes mostly noise.
That suggests an obvious compression. Keep only the top singular values and their vectors. Discard the rest.
Which raises the practical question. How large should be?
The singular values answer it themselves. Each one carries a share of the total, and that share is its contribution ratio:
What you actually want is the running total. The cumulative contribution of the first dimensions is
Now is a decision you can make on evidence. Pick the smallest whose crosses a threshold you are willing to state, commonly or . Or plot against , look for the elbow where the curve flattens, and cut there.
Take a small co-occurrence matrix over eight words and eight contexts. Four of the words are animals, four are vehicles, and the two groups share no context at all. Here is what the SVD returns.
| share | cumulative | ||
|---|---|---|---|
| 1 | 11.446 | 39.5% | 39.5% |
| 2 | 11.020 | 38.1% | 77.6% |
| 3 | 3.038 | 10.5% | 88.1% |
| 4 | 1.849 | 6.4% | 94.5% |
| 5 | 0.679 | 2.3% | 96.8% |
| 6 | 0.576 | 2.0% | 98.8% |
| 7 | 0.348 | 1.2% | 100.0% |
| 8 | 0.000 | 0.0% | 100.0% |
The share column holds two values near , then a fall off a cliff to , then a long dwindle. The elbow is unmistakable, and it is between rows 2 and 3.
So the elbow says , holding of the total. Push to and you buy another . Every dimension after that buys almost nothing.
Now notice what means. The matrix really does have two hidden groups, animals and vehicles. Nobody told the decomposition that. It read the number of underlying themes off the data, and the contribution ratio let us see it without ever looking at the words.
Watch what a threshold does here. An rule would reject , because falls just short, and take instead. The elbow was right and the threshold was wrong, by percentage points.
That is not an argument against thresholds. It is a warning that and are conventions, not findings, and the spectrum should be consulted before either is trusted. When the two criteria disagree, the elbow is usually telling you something about the data and the threshold is telling you about itself.
Real corpora rarely produce a cliff this clean. There the threshold earns its keep, because there is no elbow to see. The point is to make the choice on a stated criterion rather than a hunch, and to say which criterion you used.
Some authors define contribution with squared singular values, , because is the variance along that direction. It is the same idea and it gives larger numbers, since squaring exaggerates the lead of the top values. The same spectrum reads for the first dimension and for the first two.
That matters more than it looks. Under the squared convention an threshold now picks , agreeing with the elbow, where the unsquared one picked . The convention you choose changes the you get. Both are in use. State which one you used.
The resulting rank- matrix has a strong guarantee behind it. By the Eckart-Young theorem it is the best possible approximation of by a matrix of rank . No other -dimensional representation loses less.
Each word is now a dense vector of numbers. A few hundred, say, in place of tens of thousands.
The truncation is not merely thrift. Throwing away the noisy tail forces words that behaved similarly to collapse onto shared latent dimensions. So the compressed vectors generalise. Two words can end up close even when their raw rows overlapped only partially.
A term matrix with a truncated SVD is Latent Semantic Analysis . For years, that was how one turned a corpus into usable word and document vectors.
Try it yourself. Two scripts cover this section.
code/worked_examples/svd_rank.pyprints the spectrum table above;--squaredswitches convention and--thresholdmoves the cut, so you can watch the two criteria agree and disagree.code/worked_examples/svd.pythen shows what the chosen buys. Run it with--k 2and dog scores against cat and against car, in two dimensions.
Step back and see what the pipeline achieves. From nothing but a corpus and some counting, PPMI plus SVD produces dense, low dimensional vectors whose geometry encodes real semantic similarity. The procedure is unsupervised and principled, and it works.
But it has a ceiling. At bottom it is still a count and factor procedure over a fixed matrix.
Three consequences follow. The matrix must be built in full before it can be decomposed. Adding fresh text means rebuilding and re-factoring. And the SVD is one global linear compression, blind to anything that is not a direction of variance in the count statistics.
So a natural question arises. Could we get the same dense vectors without ever building the giant matrix, by learning each word’s vector directly from its contexts?
Chapter 9 answers it with word2vec. word2vec turns out to be almost the same object, seen from the other side. It can be shown to be implicitly factorising a shifted PMI matrix. The learning of the next chapters and the counting of this one are two routes to one destination.
Learning needs a learning machine, though. It needs a way to adjust parameters to reduce an error, which counting never required. Chapter 8 builds exactly that machine, the neural network. Then Chapter 9 turns it loose on the distributional hypothesis.
From here on, meaning as geometry is fixed. What changes is that we stop computing the geometry and start training it.
is the original Latent Semantic Analysis paper. on HAL and on COALS are influential count based models with different weighting choices. The semantic space formalism underlying all of them is set out by . Manning, Raghavan and Schütze cover matrix decompositions for retrieval and their latent semantic interpretation.
PMI by hand. In a corpus of tokens, the words ice and cream each occur times. In your chosen window they co-occur times. Compute in bits. Then compute it for a pair that co-occurs exactly as often as independence predicts, and confirm you get .
Why clip the negatives? Explain why negative PMI values are statistically unreliable in a sparse co-occurrence matrix. State what PPMI, in Equation (7.2), does about it. What practical property of the matrix does clipping to zero help preserve?
The rare word inflation. Show, from Equation (7.1), why a very rare word tends to receive a large PMI with whatever it happens to co-occur with. Explain how smoothing the context distribution with the power reduces this. Then note where else in the book that exponent appears.
What the singular values tell you. You compute the SVD of a PPMI matrix. The first of singular values account for most of the total. What does that say about the co-occurrence data? Keeping the top dimensions is obviously smaller than keeping all . Why is it often better as well? Use the Eckart-Young property in your answer.
Counting versus learning. List two concrete disadvantages of the count and factor pipeline that a method learning vectors directly from context could avoid. This is the case Chapter 9 will make for word2vec.