After this chapter you will be able to
compute pointwise mutual information from counts, and say what it measures that a raw count does not;
explain why negative PMI is clipped and why rare words inflate PMI;
describe in a paragraph what HAL and COALS contribute, and what the two have in common;
choose the number of SVD dimensions from the singular values, and state the convention used;
say what the count-and-factor pipeline cannot do, and what replaces it.
This chapter builds on Chapter 6, which showed that raw counts track frequency and not meaning.
Chapter 6 left us with a working idea and two complaints about it. The idea is to represent a word by a row of a co-occurrence matrix and read similarity of meaning as the cosine between rows. The complaints are that the raw counts in measure frequency more than association, and that the matrix is impossibly wide, with one column per vocabulary word and almost all entries zero. This chapter is the classical repair of both, and it is the pipeline that carried distributional semantics for two decades before neural embeddings. Reweight the counts so they measure association, then factor the matrix so that tens of thousands of sparse dimensions collapse into a few hundred dense ones.
Raw counts are 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, so a raw count credits the with enormous association to words it is adjacent to by grammatical accident. Table 6.1 showed the damage on Brown. What we want is a different quantity. We want to know how much more often two words co-occur 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 and the numerator is what we observe, so PMI is the logarithm of their ratio, measured in bits (Figure 7.1).
The interpretation is clean. A PMI of means the words are independent, since . A positive value means they co-occur more than chance and a negative value less than chance. Two words that co-occur twice as often as independence predicts have a PMI of bit, and ten times as often gives bits. The estimate is a count computation, so with a corpus of tokens,
Take a pair seen together times in a corpus of tokens, where each word occurs times on its own. The score is bits, a strong and clearly above-chance association. The word the does not inflate the score, because its large marginal sits in the denominator and cancels its large joint count.
Run it.
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, and 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. It stays sparse and therefore storable, and it now measures association and not frequency.
One bias survives the clipping, and it returns in Chapter 9 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 by raising its counts to a power less than one, with , which lifts the probability of rare contexts and so lowers their PMI. Remember that exponent of . Chapter 9 introduces word2vec’s negative sampling, which draws negative examples from a distribution smoothed by the same power. The two methods compute closely related things, and the shared exponent is the clue.
Before neural embeddings, several complete systems were built on these ideas. Two are worth knowing, because 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. The full derivations, with every cell worked by hand, are in Appendix B. This section gives the ideas.
Hyperspace Analogue to Language (Lund and Burgess 1996) makes three decisions. First, it weights a context word by its closeness. A neighbour ten words away counts as much as the word next door under plain counting, whereas HAL ramps the weight from , the window size, for the adjacent word down to at the edge of the window. Second, it scans the corpus twice, once in each direction, and keeps the results apart. The matrix is therefore asymmetric on purpose, because counts before and counts before , and word order carries grammar. Third, because order matters, each word gets two vectors, its row for what preceded it and its column for what followed it, and HAL concatenates them. That gives dimensions, so HAL keeps only the few hundred columns of highest variance, on the grounds that a nearly constant column cannot separate words.
The appendix works two tiny corpora through this. In one, dog and puppy are used identically and land at distance , while dog and slept land at . In a made-up corpus of canteen bills, where each bill is one context, chai and coffee are never ordered together and are still the closest pair, at , because the same tiffins and sides arrive around both. The surest sign that two things are interchangeable is that they never appear together, since you choose one or the other.
HAL also exposes its own weakness, and it is the reason COALS exists. A distance on raw weighted counts tracks frequency. Green tea, ordered a fraction as often as chai and keeping the same company, lands away from chai because one cell carries of the squared differences. Dividing out the size, which is the cosine, puts it back beside chai at .
Correlated Occurrence Analogue to Lexical Semantics (Rohde et al. 2006) keeps the ramped window and changes almost everything else. Its central move is to replace each count by a correlation between the word and the context, computed over the whole matrix. The numerator is the same comparison PMI makes, the observed count scaled up against what the margins predict under independence, and the denominator normalises by how much each margin could vary. Every entry then lies in however common the words are, so being frequent stops earning a large score. Negative correlations are set to zero for the reason PPMI clips negative PMI, and the square root of what survives pulls in the large values so that a few strong pairings cannot dominate a vector. COALS drops HAL’s direction, so its matrix is symmetric, and it keeps only the columns of the most common open-class words (nouns, verbs, adjectives and adverbs) of the original paper. Rohde and colleagues reported that it beat both HAL and Latent Semantic Analysis (defined below) on word similarity judgements, with the gain coming mostly from the correlation step and the square root. The reweighting mattered more than the reduction, which is a useful thing to know.
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, not frequency, optionally compress, then read similarity as an angle. They disagree about the statistic and about whether order matters, and they agree about the shape. Chapter 9 abandons that shape. It keeps the distributional hypothesis and drops 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 (columns of length one, at right angles to each other), and is diagonal with non-negative entries in descending order. Those entries are the singular values. They measure how much of the matrix’s variance each new dimension accounts for. The value names the single direction along which the data vary most, names the next, and so on down the list. Because they decay, most of the structure lives in the first handful of dimensions and the long tail contributes mostly noise. That suggests an obvious compression: keep only the top singular values and their vectors, and discard the rest (Figure 7.2).
That raises the practical question of how large should be, and the singular values answer it themselves. Each one carries a share of the total, its contribution ratio:
What you 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. A spectrum makes this readable. Take a small co-occurrence matrix over eight words and eight contexts, where four of the words are animals, four are vehicles, and the two groups share no context at all. This 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 falls off a cliff to , then dwindles for a long while (Figure 7.3). The elbow sits between rows 2 and 3, so it says , holding of the total. Pushing to buys another , after which every further dimension buys almost nothing. Notice what means. The matrix has two hidden groups, animals and vehicles, and nobody told the decomposition. It read the number of underlying themes off the data, and the contribution ratio let us see that without looking at the words.
The two criteria can disagree, though. An rule would reject because falls just short, and would take instead. The elbow was right and the threshold was wrong by percentage points. The values and are conventions, not findings, so consult the spectrum before trusting either. When the two criteria disagree, the elbow is usually telling you something about the data while the threshold is telling you about itself. Real corpora rarely produce a cliff this clean, and there the threshold is useful because there is no elbow to see. The point is to make the choice on a stated criterion instead of a hunch, and to say which criterion you used.
One convention deserves watching. Some authors define contribution with squared singular values, , because is the variance along that direction. It is the same idea and gives larger numbers, since squaring exaggerates the lead of the top values. The same spectrum then reads for the first dimension and for the first two. Under the squared convention an threshold picks , agreeing with the elbow, where the unsquared one picked . Both conventions are in use, and the one you choose changes the you get, so state which 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 , closest in the sense of the sum of squared differences, and 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 more than thrift. Throwing away the noisy tail forces words that behaved similarly to collapse onto shared latent dimensions, so the compressed vectors generalise, and two words can end up close even when their raw rows overlapped only partially. A term-document matrix reduced by a truncated SVD is Latent Semantic Analysis (Deerwester et al. 1990), and for years that was how one turned a corpus into usable word and document vectors.
Run it. 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 a corpus and some counting, PPMI plus SVD produces dense, low-dimensional vectors whose geometry encodes real semantic similarity, and the procedure is unsupervised, principled and effective. It has a ceiling, because it is 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.
A natural question arises. Could we get the same dense vectors without building the giant matrix, by learning each word’s vector directly from its contexts? Chapter 9 answers it with word2vec, which turns out to be almost the same object seen from the other side, since 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, meaning a way to adjust parameters so as to reduce an error, which counting never required. Chapter 8 builds that machine in the neural network, and Chapter 9 turns it loose on the distributional hypothesis. From here on, meaning as geometry is fixed, and what changes is that we stop computing the geometry and start training it.
Summary
Raw co-occurrence counts measure frequency, so each count is replaced by pointwise mutual information, the log of observed over expected co-occurrence. Negative values are unreliable and are clipped, giving PPMI, and rare words inflate PMI unless the context distribution is smoothed with the power , the same exponent word2vec uses for negative sampling. HAL weights by distance and keeps direction, and COALS replaces counts by correlations, clips and takes square roots, and all such models count, reweight, optionally compress and compare by angle. The singular value decomposition compresses the matrix, and its truncation is the best rank- approximation. The number of dimensions is chosen from the spectrum, by threshold or by elbow, and the convention, squared or not, must be stated. Counting and factoring has a ceiling: it needs the whole matrix and a rebuild for new text. Learning the vectors directly comes next, after a chapter on neural networks.
Key terms
pointwise mutual information. the log of the observed co-occurrence probability over what independence predicts.
positive pointwise mutual information. PMI with negative values replaced by zero.
singular value decomposition. the factorisation of a matrix into orthonormal factors and a diagonal matrix of singular values.
singular values. the non-negative diagonal entries of the SVD, in descending order, measuring variance per dimension.
contribution ratio. the share of the total of the singular values carried by one of them.
Latent Semantic Analysis. a term matrix reduced by a truncated singular value decomposition.
Deerwester et al. (1990) is the original Latent Semantic Analysis
paper. Lund and Burgess (1996) on HAL and Rohde et al. (2006) on COALS
are influential count-based models with different weighting choices. The
semantic space formalism underlying all of them is set out by Lowe
(2001). Manning, Raghavan and Schütze (Manning et al. 2009) cover matrix
decompositions for retrieval and their latent semantic interpretation.
The decomposition itself is numpy.linalg.svd, and
sklearn.decomposition.TruncatedSVD computes only the top
dimensions, which is the version you need once the matrix is too large
to hold.
7.1 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 .
7.2 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?
7.3 The rare word inflation. In a corpus of tokens, a word seen times co-occurs once with a word seen times. Compute the PMI. Then compute it for a pair that co-occurs times with counts and . Explain, from Equation (7.1), why the first value is the larger although the second pair is the better-evidenced, and how smoothing the context counts with the power reduces the gap.
7.4 HAL by hand. Take the corpus the dog barked with window and the convention of Appendix B that holds the weight of occurring before . Write the three-by-three matrix. Say which rows are empty and why.
7.5 Choosing K from the spectrum. A matrix has singular values , , and . Compute the contribution ratios and the cumulative contributions with and without squaring. For a threshold of , which does each convention choose, and where would you put the elbow?
Build and measure
7.6 The same decomposition, and a
sign. Run numpy.linalg.svd on this chapter’s
eight-by-eight matrix and confirm the singular values
,
,
,
and the rank of
.
Then fit TruncatedSVD with two components and compare its
second component against numpy’s. Every entry carries the opposite sign.
Explain why both answers are correct, and say what follows for anyone
who publishes the coordinates of a word rather than the distances
between words.
7.7 Predict, then reweight. Using the Brown counts of Chapter 6, predict whether PPMI weighting will put dog nearer cat or car, and whether the cosines will be larger or smaller than the of the stop-list repair. Then build the PPMI matrix for the eight targets and compare with Table 6.1.
7.8 Smoothing the contexts. Repeat the previous problem with the context distribution raised to the power , and with . Report the cosine of doctor with nurse and hospital under each. Say whether the rare word nurse benefits.
7.9 Spectrum of a real matrix. Take the PPMI matrix you built and plot its top fifty singular values. Mark the elbow and the at which the cumulative share reaches , with and without squaring. Say which you would use and why.
In practice
7.10 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.
7.11 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.
7.12 Words that never meet. Chai and coffee are never ordered together and still end up closest. Explain, in terms of rows of the matrix, why that is not a contradiction, and say what would go wrong if you used the PMI of the pair itself as the similarity.
7.13 New text every day. A search team indexes a million new documents a day and rebuilds its PPMI and SVD vectors weekly. List what goes stale, what it costs, and what you would try, short of switching method, to reduce the cost.
Each one reproduces the tables above. Run it in the page, change an input and watch which numbers move.
weighting.pytf-idf and PMI, by hand
The weighting arithmetic the chapters print, on the four document matrix.
runs in your browser Run itsvd_rank.pyChoosing K from the spectrum
The singular value spectrum and the two criteria that read it, which do not always agree.
runs in your browser Run itsvd.pySVD, and what truncation costs
The factorisation, the truncation, and the dense vectors that come out the other side.
runs in your browser Run ithal.pyHAL, ramped and asymmetric
The ramped window, the matrix it fills, and why the matrix is not symmetric.
runs in your browser Run itcoals.pyCOALS, all three steps
The correlation matrix, reproducing the lecture tables on the woodchuck corpus.
runs in your browser Run itFrom Natural Language Processing: From Corpus Statistics to Grounded LLMs, by Ramaseshan Ramachandran.