17.3 Mutual information, PMI, and PPMI
Where do word vectors come from? Before word2vec, the answer was to count: build a table of how often each word appears near each context word, then factor it. Raw counts are dominated by frequent words (“the” co-occurs with everything), so the table first has to say not “how often” but “how much more often than chance”. That ratio, in logs, is pointwise mutual information (PMI), and its average is the mutual information between a word and its context.
Concepts from other sections (11)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- skip-gram: a model that predicts the context words around each center word. Read more: 8.3 word2vec skip-gram with negative sampling, and the PPMI-SVD baseline in AI Engineering
- negative sampling: replacing the softmax with logistic classification of the real context against words drawn from a noise distribution. Read more: 8.3 word2vec skip-gram with negative sampling, and the PPMI-SVD baseline in AI Engineering
- Entropy: , the average surprise of a distribution. Read more: 17.1 Entropy, cross-entropy, KL, JS, and the k3 estimator
- KL divergence: , the excess cost of predicting with ; nonnegative and asymmetric. Read more: 17.1 Entropy, cross-entropy, KL, JS, and the k3 estimator
- Maximum-likelihood estimate (MLE): the distribution that maximizes the log-likelihood; for counts, the frequency . Read more: 13.3 MLE, Laplace, absolute discounting
- Random variable: a number assigned to each outcome of a random experiment; a discrete one is a table of values and probabilities. Read more: 13.1 Random variables, expectation, variance, and normal draws by Box-Muller
- Joint entropy: , the uncertainty of a pair of random variables taken together; it is at most , with equality when they are independent. Read more: Chapter 17: Information Theory
- Joint distribution: the table over pairs of values; it determines marginals and conditionals. Read more: 13.10 Probability problem set, part b: joint distributions, covariance, MLE
- Gibbs’ inequality: , with equality if and only if ; coding data from with a code built for always costs extra bits, so cross-entropy is never below entropy. Read more: Chapter 17: Information Theory
- dynamic window: a per-center window radius drawn uniformly from , so nearer words pair more often. Read more: 8.3 word2vec skip-gram with negative sampling, and the PPMI-SVD baseline in AI Engineering
- Eigenvector / eigenvalue: a non-zero and scalar with . Read more: 9.4 Eigenvalues, power iteration, and the spectral radius
This matters beyond history. Levy and Goldberg showed that skip-gram with negative sampling implicitly factorizes a shifted PMI matrix, so the PPMI matrix built here is the yardstick for the neural model in word2vec skip-gram with negative sampling, and the PPMI-SVD baseline in AI Engineering. Get the marginals, the smoothing, or the zeros wrong here and the baseline that model is compared against is wrong too.
This section derives mutual information, PMI, context distribution smoothing and PPMI, works all of them by hand on a two-word table, and walks through the reference implementation, pmi.py (contract: pmi.pyi). It reuses kl from Entropy, cross-entropy, KL, JS, and the k3 estimator, and reads probabilities as count ratios the way MLE, Laplace, absolute discounting does. Problem set A is useful practice with the entropy identities first.
Learning objectives
- Define mutual information as a KL divergence and derive .
- Compute PMI, smoothed PMI and PPMI for every cell of a small co-occurrence table by hand.
- Explain why context distribution smoothing lowers PMI for rare contexts, and why it renormalizes over contexts.
- Implement PMI so that unseen pairs are exactly and zero rows and columns produce no NaN or warnings.
Notation
Section titled “Notation”The section uses these symbols.
| Symbol | Meaning | Type / shape |
|---|---|---|
| co-occurrence count of word with context | float64[W, C] | |
| total count, | scalar | |
| , | row sum and column sum | scalars |
| joint probability (the MLE) | scalar | |
| , | marginal probabilities | scalars |
| two discrete random variables with joint | ||
| , | entropy and joint entropy, in nats | scalars |
| mutual information, in nats | scalar | |
| pointwise mutual information | scalar, possibly | |
| context distribution smoothing exponent, | scalar | |
| smoothed context distribution | scalar |
Mutual information
Section titled “Mutual information”If and were independent, their joint distribution would be the product of the marginals, . Mutual information measures how far the real joint is from that:
Splitting the logarithm gives : the reduction in uncertainty about from learning . (Problem set B proves the identity.) Gibbs’ inequality makes it non-negative, and zero exactly when and are independent. It is symmetric, , even though KL is not; and since conditioning can remove at most all of the uncertainty, .
The implementation computes it the way the definition reads: normalize the table, take its marginals, and call kl on the flattened joint and the flattened outer product of the marginals. kl already handles , and wherever both marginals are positive, so the product never rules out a pair the joint produces. A table of raw counts is normalized first, so counts and probabilities give the same answer.
Pointwise mutual information
Section titled “Pointwise mutual information”Mutual information is a single number for the whole table. For word vectors you want one number per cell, and the sum already contains it. The log ratio inside the sum, for one pair, is the pointwise mutual information:
It is positive when and appear together more often than independence predicts, zero at chance, negative below chance, and for a pair never seen (). Mutual information is the average PMI under the joint, , where unseen pairs carry weight zero and contribute nothing.
Context distribution smoothing
Section titled “Context distribution smoothing”Plain PMI has a known bias toward rare contexts: a context seen twice, once with , gets a huge ratio from tiny counts. Levy, Goldberg, and Dagan borrowed word2vec’s fix, raising context counts to before normalizing over contexts:
Since grows slower than , rare contexts get a larger share of the probability than their counts alone would give, so their PMI drops and frequent contexts’ PMI rises.
Three details matter. The smoothing applies to the context marginal only; the word marginal keeps its plain MLE. The denominator is , not : dividing by leaves numbers that do not sum to 1 and shifts every PMI by the same constant. And is plain PMI; the contract allows , because at every context, even an unused one (), would get the same weight.
Positive PMI
Section titled “Positive PMI”One problem remains before the matrix can be factored. Negative PMI values are unreliable, since they need many observations to tell “below chance” from “not yet seen”, and cannot go into an SVD. PPMI keeps only the positive part:
so unseen pairs and below-chance pairs become exact zeros. The result is finite, non-negative, and mostly zeros: the matrix the word2vec section factors with the SVD of SVD, Eckart-Young low rank, and least squares. A row or column that is entirely zero (a word never seen, a context never used) must come out as zeros too, with no divide-by-zero warnings. The implementation computes the logs under np.errstate(divide="ignore"), takes the marginal logs only where the marginals are positive, and writes wherever the count is 0.
Working it by hand
Section titled “Working it by hand”Here is a table with two words and three contexts:
| pet | bark | meow | ||
|---|---|---|---|---|
| cat | 2 | 0 | 2 | 4 |
| dog | 2 | 4 | 0 | 6 |
| 4 | 4 | 2 |
Plain PMI () for every cell:
| Pair | PMI | PPMI | ||
|---|---|---|---|---|
| cat, pet | 0.2 | 0.2231 | ||
| cat, bark | 0 | 0.16 | 0 | |
| cat, meow | 0.2 | 0.9163 | ||
| dog, pet | 0.2 | 0 | ||
| dog, bark | 0.4 | 0.5108 | ||
| dog, meow | 0 | 0.12 | 0 |
Dog and pet co-occur, but less than chance (dogs are mostly about barking here), so PPMI drops the pair.
Mutual information is the average PMI under the joint: nats (to 16 digits, ).
Now smooth with . and , so and , up from 0.2. Then , down from 0.9163: the rare context lost PMI. The frequent context pet went the other way, with and .
Designing the interface
Section titled “Designing the interface”Three functions cover the section:
def mutual_information(joint: ArrayLike) -> float: """I(X; Y) in nats = kl(joint, outer(marginals)), the table normalized first."""
def pmi_matrix(cooc: ArrayLike, cds_alpha: float = 0.75) -> NDArray: """ln P(w, c) - ln P(w) - ln P_alpha(c); -inf where cooc == 0."""
def ppmi(cooc: ArrayLike, cds_alpha: float = 0.75) -> NDArray: """max(pmi_matrix(cooc, cds_alpha), 0): finite and non-negative."""mutual_information returns nats, as the KL divergence from the joint to the product of its marginals. pmi_matrix returns pointwise mutual information with context distribution smoothing, and ppmi its positive part.
Building it step by step
Section titled “Building it step by step”The implementation follows from seven observations.
- Everything starts from one validated table. All three functions read a 2-D, finite, non-negative count table with a positive total; anything else (a 1-D vector, a NaN, a negative count, an empty corpus) has no probability interpretation. So one helper validates and returns a float64 copy, which also guarantees the caller’s table is never modified when the functions normalize it.
- Mutual information is already a KL divergence, so reuse
kl. is a KL between two distributions over the pairs. Flattening the joint and the outer product of marginals turns it into exactly the 1-D caseklhandles, zero conventions included. The only preparation is normalizing the table so that counts and probabilities give the same answer. - The product never has a zero where the joint is positive. If then both and , so and
kl’s branch is never reached. Unseen pairs have and contribute 0 by . - PMI is three logs, kept apart. . Computing the logs separately, rather than forming the ratio , makes the one legitimate infinity ( for an unseen pair) appear only in the joint term, and lets the marginal terms be guarded on their own.
- Smoothing touches only the context marginal, renormalized over contexts. , so the smoothed values sum to 1. The word marginal stays .
- Unseen pairs are exactly , and zero rows and columns are quiet. For a word with (or a context with ), every one of its counts is 0, so its PMI entries are by the rule for unseen pairs anyway. The marginal log is therefore replaced by where the marginal is 0, purely to avoid computing and , and the final
np.where(C > 0, ..., -inf)writes the answer. - PPMI is a clip. maps and every negative value to exactly 0, so the result is finite and non-negative by construction.
The validation helper comes first:
def _table(x: ArrayLike, who: str) -> NDArray: """A validated float64 copy of a 2-D non-negative table with a positive sum.""" t = np.array(x, dtype=np.float64) # np.array, not np.asarray: always a copy, # so later in-place division is safe if t.ndim != 2: raise ValueError(f"{who}: need a 2-D table, got shape {t.shape}") if not np.isfinite(t).all() or (t < 0).any(): raise ValueError(f"{who}: entries must be finite and non-negative") if not t.sum() > 0: # "not > 0" also rejects a NaN sum raise ValueError(f"{who}: the table sums to 0") return tConverting to float64 here is also what makes int64 count tables give the same results as float tables.
Mutual information is then four lines:
def mutual_information(joint: ArrayLike) -> float: P = _table(joint, "mutual_information") # our own copy P /= P.sum() # counts or probabilities: same answer px = P.sum(axis=1) # P(x), row sums py = P.sum(axis=0) # P(y), column sums # I(X; Y) = KL(P_XY || P_X P_Y): flatten both tables into one # distribution over pairs. Wherever P(x, y) > 0 the product is > 0 too. return float(kl(P.ravel(), np.outer(px, py).ravel()))kl uses the natural log, so the result is in nats like every other quantity in this chapter. Because and the outer product are both normalized, the result does not scale with the corpus size.
PMI carries the smoothing and the zero handling:
def pmi_matrix(cooc: ArrayLike, cds_alpha: float = 0.75) -> NDArray: C = _table(cooc, "pmi_matrix") # alpha = 0 would give an unused context weight 0^0 = 1; alpha > 1 sharpens # instead of smoothing. Neither is context distribution smoothing. if not 0.0 < cds_alpha <= 1.0: raise ValueError(f"pmi_matrix: need 0 < cds_alpha <= 1, got {cds_alpha}") D = C.sum() nw = C.sum(axis=1, keepdims=True) # #(w), [W, 1] nc = C.sum(axis=0, keepdims=True) # #(c), [1, C] # Smooth the CONTEXT distribution only, and renormalize over contexts: # P_alpha(c) = #(c)^alpha / sum_c' #(c')^alpha. nca = nc**cds_alpha pc = nca / nca.sum() with np.errstate(divide="ignore"): # Logs of the three probabilities, kept apart: log 0 = -inf only for # the joint, and the marginals of a seen pair are positive. # Where a marginal is 0, log(1.0) = 0 is a placeholder; those entries # are overwritten with -inf below because their counts are all 0. logp = ( np.log(C / D) - np.log(np.where(nw > 0, nw / D, 1.0)) - np.log(np.where(pc > 0, pc, 1.0)) ) return np.where(C > 0, logp, -np.inf) # exactly -inf for unseen pairskeepdims=True gives the marginals shapes [W, 1] and [1, C], so the subtraction broadcasts to the full [W, C] table with the word marginal along rows and the context marginal along columns; transposing them is impossible without a shape error on a non-square table. At , pc is nc / D and the function is plain PMI.
PPMI is the clip:
def ppmi(cooc: ArrayLike, cds_alpha: float = 0.75) -> NDArray: return np.maximum(pmi_matrix(cooc, cds_alpha), 0.0) # -inf and negatives -> 0The full solution is pmi.py.
Why this design
Section titled “Why this design”The cost is time and memory: a few passes over the table and a handful of [W, C] temporaries. For the word2vec section’s vocabularies the dense table is the bottleneck, not the arithmetic; a production system would use sparse counts, but the formulas are the same.
Reusing kl instead of writing the double sum means one implementation of the zero conventions, already tested, and code that reads like the definition. Writing again would duplicate the handling and invite a second, subtly different version. Using three logs instead of one ratio matters for degenerate rows: the ratio form is algebraically equal, but for an all-zero row it computes , while the separated form isolates each zero to a term that can be guarded. And an exact beats : a finite stand-in for unseen pairs is a large negative number that leaks into any average and depends on the arbitrary . is the true value, and PPMI turns it into the exact 0 the SVD wants.
One tradeoff is accepted: pmi_matrix returns a dense matrix full of , which is not directly usable downstream. That is deliberate, since ppmi is the downstream form and pmi_matrix is the honest one.
What can go wrong
Section titled “What can go wrong”A correct implementation must reproduce the hand-worked PMI and PPMI table at , and the mutual information nats from both counts and probabilities (nats, and normalization first). It must match five golden tables (random, quarter counts, independent, one row) at against 50-digit values, which checks that the smoothing renormalizes over contexts. Mutual information must be 0 for an outer product, symmetric under transpose, and satisfy ; it must also equal over seen pairs, which is what makes PPMI the pointwise version of . Smoothing must lower the rarest context’s PMI and raise the most frequent one’s, which is the whole point of .
At the boundaries, an all-zero row and column must give zeros in PPMI with no NaN and no warnings, and PMI must be exactly where the count is 0, because the SVD in the word2vec section takes this matrix. Negative, NaN, 1-D and all-zero tables must be rejected, as must or , so caller bugs fail early. Integer counts must give float64 results equal to the float ones, and the caller’s table must be unchanged, since the word2vec section reuses its count table.
The common mistakes, and how the solution avoids each:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| taking the context marginal from the rows (a transposed marginal) | wrong PMI everywhere; a shape error on non-square tables | nw sums axis=1 to [W, 1], nc sums axis=0 to [1, C]; broadcasting fixes their roles |
| dividing the smoothed context counts by instead of | every shifted by the same constant | pc = nca / nca.sum() |
| PPMI as | below-chance pairs count as associations; unseen pairs become | np.maximum(pmi, 0.0) |
| mutual information in bits | values times too large next to every other number in the book | kl uses the natural log: nats |
| KL of raw counts, not normalized | a number that scales with the corpus size | P /= P.sum() before the marginals |
| smoothing unseen pairs with instead of | a finite but huge negative PMI that leaks into averages | np.where(C > 0, logp, -np.inf) |
| accepting | unused contexts get probability through | rejects anything outside |
| normalizing the caller’s table in place | the counts the word2vec section keeps become probabilities | _table copies with np.array, so P /= ... touches only the copy |
Where this leads
Section titled “Where this leads”Looking back, mutual_information is kl(joint, outer(p_x, p_y)) from Entropy, cross-entropy, KL, JS, and the k3 estimator, with its conventions, and , , are the maximum-likelihood count ratios of MLE, Laplace, absolute discounting. Looking forward, ppmi_svd_embeddings in word2vec skip-gram with negative sampling, and the PPMI-SVD baseline factors ppmi(cooc) with the SVD, the count-based baseline for skip-gram, and Problem set B works mutual information and PMI by hand, including the identity .
Several production systems build on the same ideas. Hyperwords, by Levy and Goldberg (hyperwords/representations/explicit.py), adds sparse co-occurrence counting with dynamic windows and subsampling, PPMI, and SVD with eigenvalue weighting. gensim’s Phrases with the NPMI scorer (gensim/models/phrases.py) uses normalized PMI, in , to find collocations such as “new_york”. scikit-learn’s mutual_info_score (sklearn/metrics/cluster/_supervised.py) computes the same sum from two label arrays via a contingency table, and adjusted_mutual_info_score corrects for chance. And SGNS, word2vec’s objective, factorizes the same matrix shifted by , implicitly by gradient descent (Levy and Goldberg, NeurIPS 2014).
Further reading
Section titled “Further reading”- Cover and Thomas, Elements of Information Theory, sections 2.4 to 2.6.
- Church and Hanks, “Word association norms, mutual information, and lexicography” (1990).
- Levy, Goldberg, and Dagan, “Improving distributional similarity with lessons learned from word embeddings” (TACL 2015).
- Levy and Goldberg, “Neural word embedding as implicit matrix factorization” (NeurIPS 2014).
Key terms
Section titled “Key terms”- Mutual information: , the nats that knowing one variable saves about the other.
- Pointwise mutual information (PMI): for a single pair; positive above chance, for unseen pairs.
- Context distribution smoothing: raising context counts to and renormalizing over contexts, which lowers PMI for rare contexts.
- PPMI: , a finite, sparse, non-negative matrix suitable for SVD.
- Marginal: a row or column sum of the joint table, normalized to a distribution.
Summary
Section titled “Summary”- Mutual information is how many nats knowing saves about : the KL divergence from the joint distribution to the product of its marginals, zero exactly when and are independent.
- PMI is the log ratio inside that sum for one pair, positive when the pair co-occurs more than chance; mutual information is its average under the joint.
- Context distribution smoothing raises context counts to and renormalizes over contexts, which takes PMI away from rare contexts.
- PPMI clips at zero, so unseen pairs () and below-chance pairs become exact zeros: a finite, sparse, non-negative matrix an SVD can factor.
- Keep the three logs apart and guard zero marginals, so degenerate rows and columns produce no NaN.
Review questions
Section titled “Review questions”- Why is divided by and not by ?
Answer
$\#(c)^\alpha$ no longer sums to $D$ when $\alpha < 1$, so dividing by $D$ gives numbers that do not sum to 1. The error is a common factor for every context, so it shifts every $\operatorname{PMI}_\alpha$ by the same constant, $\ln(\sum_{c'} \#(c')^\alpha / D)$, which then changes which pairs PPMI keeps. - Why can
mutual_informationcallklwithout ever getting ?Answer
KL is infinite only where the second distribution is 0 and the first is positive. If $P(x, y) > 0$ then $P(x) \ge P(x, y) > 0$ and $P(y) \ge P(x, y) > 0$, so the product is positive wherever the joint is. - The marginal logs use
np.where(nw > 0, nw / D, 1.0). Why is replacing a zero marginal by 1 not a bug?Answer
A zero marginal means every count in that row (or column) is 0, so every entry it affects is an unseen pair, and the final `np.where(C > 0, logp, -np.inf)` overwrites all of them with $-\infty$. The placeholder only prevents $\ln 0$ and $0/0$ from being computed, and therefore the NaN and warnings they would bring. - Why does smoothing lower PMI for rare contexts and raise it for frequent ones?
Answer
$t \mapsto t^\alpha$ with $\alpha < 1$ compresses large counts more than small ones, so after renormalizing a rare context's share $P_\alpha(c)$ is larger than $\#(c)/D$ and a frequent context's share is smaller. PMI subtracts $\ln P_\alpha(c)$, so a larger share means lower PMI. In the worked example, meow goes from 0.2 to 0.2292 and its PMI with cat falls from 0.9163 to 0.7801. - Why is PPMI the max with 0 rather than the absolute value?
Answer
The point is to keep associations stronger than chance. $\lvert \operatorname{PMI} \rvert$ would turn below-chance pairs into apparent associations and unseen pairs into $+\infty$, which an SVD cannot take.