Contents Meaning as Geometry Code Course home

Chapter 7Count Vectors, PPMI, and SVD

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.

Two repairs

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 MM and read similarity of meaning as the cosine between rows. The complaints are that the raw counts in MM 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.

From counts to association: PMI

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:

PMI⁡(w,c)=log⁡2p(w,c)p(w)p(c),(7.1)\begin{equation} \operatorname{PMI}(w, c) \;=\; \log_2 \frac{p(w, c)}{p(w)\,p(c)}, \label{eq:pmi} \quad\text{(7.1)} \end{equation}

where p(w,c)p(w,c) is the probability that ww and cc co-occur, and p(w)p(w) and p(c)p(c) 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 00 means the words are independent, since p(w,c)=p(w)p(c)p(w,c) = p(w)p(c). 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 log⁡22=1\log_2 2 = 1 bit, and ten times as often gives log⁡210≈3.32\log_2 10 \approx 3.32 bits. The estimate is a count computation, so with a corpus of NN tokens,

PMI⁡(w,c)=log⁡2count⁡(w,c)Ncount⁡(w)count⁡(c).\operatorname{PMI}(w,c) \;=\; \log_2 \frac{\operatorname{count}(w,c)\;N}{\operatorname{count}(w)\,\operatorname{count}(c)}.

Take a pair seen together 1010 times in a corpus of 10610^{6} tokens, where each word occurs 1,0001{,}000 times on its own. The score is log⁡2(10⋅106/(1000⋅1000))=log⁡210≈3.32\log_2\!\big(10 \cdot 10^{6} / (1000 \cdot 1000)\big) = \log_2 10 \approx 3.32 bits, a strong and clearly above-chance association. The word the does not inflate the score, because its large marginal p(c)p(c) sits in the denominator and cancels its large joint count.

Figure 7.1. PMI against the ratio of observed to expected co-occurrence. It is zero at independence, one bit at twice chance and about 3.323.32 bits at ten times chance. PPMI keeps only the solid branch.

Run it. code/worked_examples/weighting.py pmi tabulates 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.

Run it

Keep the positives: 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:

PPMI⁡(w,c)=max⁡(PMI⁡(w,c),0),(7.2)\begin{equation} \operatorname{PPMI}(w, c) \;=\; \max\!\big(\operatorname{PMI}(w, c),\; 0\big), \label{eq:ppmi} \quad\text{(7.2)} \end{equation}

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 p(w)p(w) 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, pα(c)∝count⁡(c)αp_\alpha(c) \propto \operatorname{count}(c)^{\alpha} with α≈0.75\alpha \approx 0.75, which lifts the probability of rare contexts and so lowers their PMI. Remember that exponent of 0.750.75. 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.

Observed counts against the counts chance predicts, and the resulting PMI
Pointwise mutual information measures how much more often two words occur together than chance predicts. A pair of very common words can have a large count and a small PMI.

Two count models: HAL and COALS

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.

HAL

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 WW, the window size, for the adjacent word down to 11 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 M[a,b]M[a,b] counts bb before aa and M[b,a]M[b,a] counts aa before bb, 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 2|V|2|V| 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 1.4141.414, while dog and slept land at 4.6904.690. 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 2.242.24, 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 21.9821.98 away from chai because one cell carries 400400 of the 483483 squared differences. Dividing out the size, which is the cosine, puts it back beside chai at 0.9600.960.

COALS

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 [−1,1][-1, 1] 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 m=14,000m = 14{,}000 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.

What they share

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.

A window sliding over a sentence filling an asymmetric co-occurrence matrix
HAL represents a word by the words that precede it, weighting nearer words more. The resulting matrix is asymmetric because what comes before a word differs from what comes after.

From sparse to dense: SVD

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 MM can be factored as

M=UΣV⊤,(7.3)\begin{equation} M \;=\; U\,\Sigma\,V^{\!\top}, \label{eq:svd} \quad\text{(7.3)} \end{equation}

where UU and VV have orthonormal columns (columns of length one, at right angles to each other), and Σ\Sigma is diagonal with non-negative entries σ1≥σ2≥⋯≥0\sigma_1 \geq \sigma_2 \geq \cdots \geq 0 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 σ1\sigma_1 names the single direction along which the data vary most, σ2\sigma_2 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 KK singular values and their vectors, and discard the rest (Figure 7.2).

Figure 7.2. Truncated SVD. The matrix MM is approximated by the product of three thin factors. Each word is then the row of UKΣKU_K\Sigma_K, a dense vector of KK numbers in place of |C||C| sparse ones. The shaded areas are what the truncation throws away.

Choosing K by contribution

That raises the practical question of how large KK should be, and the singular values answer it themselves. Each one carries a share of the total, its contribution ratio:

ri=σi∑jσj.(7.4)\begin{equation} r_i \;=\; \frac{\sigma_i}{\sum_{j} \sigma_j}. \label{eq:contribution} \quad\text{(7.4)} \end{equation}

What you want is the running total. The cumulative contribution of the first KK dimensions is

RK=∑i=1Kσi∑jσj.(7.5)\begin{equation} R_K \;=\; \frac{\sum_{i=1}^{K} \sigma_i}{\sum_{j} \sigma_j}. \label{eq:cumcontribution} \quad\text{(7.5)} \end{equation}

Now KK is a decision you can make on evidence. Pick the smallest KK whose RKR_K crosses a threshold you are willing to state, commonly 0.80.8 or 0.90.9. Or plot rir_i against ii, 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.

ii σi\sigma_i share rir_i cumulative RiR_i
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%
Figure 7.3. The spectrum of the eight-by-eight matrix, as shares of the total. Two values near 39%39\%, then a cliff. The elbow between i=2i = 2 and i=3i = 3 says there are two themes.

The share column holds two values near 39%39\%, then falls off a cliff to 10.5%10.5\%, then dwindles for a long while (Figure 7.3). The elbow sits between rows 2 and 3, so it says K=2K = 2, holding 77.6%77.6\% of the total. Pushing to K=3K = 3 buys another 10.5%10.5\%, after which every further dimension buys almost nothing. Notice what K=2K = 2 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 80%80\% rule would reject K=2K = 2 because 77.6%77.6\% falls just short, and would take K=3K = 3 instead. The elbow was right and the threshold was wrong by 2.42.4 percentage points. The values 0.80.8 and 0.90.9 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, σi2/∑jσj2\sigma_i^2 / \sum_j \sigma_j^2, because σi2\sigma_i^2 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 49.2%49.2\% for the first dimension and 94.9%94.9\% for the first two. Under the squared convention an 80%80\% threshold picks K=2K = 2, agreeing with the elbow, where the unsquared one picked K=3K = 3. Both conventions are in use, and the one you choose changes the KK you get, so state which you used.

The resulting rank-KK matrix has a strong guarantee behind it. By the Eckart-Young theorem it is the best possible approximation of MM by a matrix of rank KK, closest in the sense of the sum of squared differences, and no other KK-dimensional representation loses less. Each word is now a dense vector of KK 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.py prints the spectrum table above. --squared switches convention and --threshold moves the cut, so you can watch the two criteria agree and disagree. code/worked_examples/svd.py then shows what the chosen KK buys. Run it with --k 2 and dog scores 1.0001.000 against cat and 0.0000.000 against car, in two dimensions.

Run itRun it

A count matrix, its singular values, rank-k rebuilds and the resulting 2-D word vectors
SVD compresses a sparse count matrix into a few dense dimensions. Keeping the largest directions preserves the main structure, and words that share contexts end up close together.
Singular value shares and their running total, with the elbow at K 2 and the 80 percent rule at K 3
The size of each singular value says how much structure its dimension carries. Rules for choosing how many to keep, an elbow or a threshold, can disagree, so state which one you used.

The ceiling of counting

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 0.750.75, 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-KK 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.

Further reading.

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 kk dimensions, which is the version you need once the matrix is too large to hold.

Practice problems

7.1 PMI by hand. In a corpus of N=106N = 10^{6} tokens, the words ice and cream each occur 2,0002{,}000 times. In your chosen window they co-occur 500500 times. Compute PMI⁡(𝑖𝑐𝑒,𝑐𝑟𝑒𝑎𝑚)\operatorname{PMI}(\mathit{ice}, \mathit{cream}) in bits. Then compute it for a pair that co-occurs exactly as often as independence predicts, and confirm you get 00.

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 10610^{6} tokens, a word seen 55 times co-occurs once with a word seen 200200 times. Compute the PMI. Then compute it for a pair that co-occurs 100100 times with counts 5,0005{,}000 and 20,00020{,}000. 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 0.750.75 power reduces the gap.

7.4 HAL by hand. Take the corpus the dog barked with window W=2W = 2 and the convention of Appendix B that M[a,b]M[a,b] holds the weight of bb occurring before aa. 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 66, 33, 22 and 11. Compute the contribution ratios and the cumulative contributions with and without squaring. For a threshold of 0.80.8, which KK 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 11.44611.446, 11.02011.020, 3.0383.038, 1.8491.849 and the rank of 77. 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 0.20.2 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 0.750.75, and with 11. 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 KK at which the cumulative share reaches 0.80.8, 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 300300 of 50,00050{,}000 singular values account for most of the total. What does that say about the co-occurrence data? Keeping the top 300300 dimensions is obviously smaller than keeping all 50,00050{,}000. 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.

Code for this chapter

Each one reproduces the tables above. Run it in the page, change an input and watch which numbers move.

From Natural Language Processing: From Corpus Statistics to Grounded LLMs, by Ramaseshan Ramachandran.