Collocations and Keyword Extraction
A word pair is a 2×2 table, a point in a tetrahedron. PMI, X², and Dunning's G² measure its distance from independence in different ways, only an exact test survives rare pairs, and testing only the pairs you saw makes every rare sighting significant. Then keywords: keyness compares corpora, and TextRank, which compares nothing, ranks by frequency.
Overview & Motivation
The distributional semantics topic ran into a problem it did not solve. Its Proposition 3 found that positive PMI gives large values to pairs that occur once by chance, so that shuffled text, where every association is noise, carried more PPMI mass than the real text. It named the cure: a significance test, Dunning’s in particular. The n-gram topic pointed here too, for association instead of prediction. This page builds that test and then finds a second problem the test alone does not solve.
A collocation is a word pair that occurs together more often than its words’ frequencies explain: “operating margin,” “chief executive.” Every association score for a pair starts from the same four counts. Of the bigram positions in a corpus, how many have first and second, first and something else second, and so on. Divided by , those four numbers are a point of a tetrahedron, and the pairs whose words are independent form a saddle surface inside it. That picture organizes the first half of the page.
- The table as a point. PMI, the t-score, Pearson’s , and Dunning’s measure a table’s distance from the saddle in different ways.
- Rare pairs. The four scores disagree most where the counts are smallest, and we compute them in closed form there.
- Tests and their sizes. Conditioning on the margins gives an exact test; the two tests are right only asymptotically, and we compute how wrong they are before that.
- Testing only what you saw. A list of the bigrams that occur in a corpus is a selected family, and the selection alone makes every rare sighting significant.
The second half turns from pairs to single words. Keyness asks which words a corpus uses more than another corpus does, with the same 2×2 test. TextRank ranks a text’s words by PageRank on their co-occurrence graph, and we prove what that ranking converges to. The finance case study scores everything against an answer key the corpus’s generator keeps: which words were drawn independently, which were fixed template text, and which vocabulary each came from.
The 2×2 table as a point
Fix an ordered pair . Over the corpus’s bigram positions (adjacent tokens within a sentence), let count the positions reading , let count those whose first token is , and let count those whose second token is .
Definition 1 (The bigram's table).
The table of is
with rows “the first token is or not” and columns “the second token is or not.” Its margins are the row totals and the column totals , and its expected count is . Divided by it is a point of the simplex of distributions on four cells.
Draw as a regular tetrahedron with one corner per cell. A table whose row and column indicators are independent factors as the outer product of its margins.
Definition 2 (The independence surface).
The independence surface is .
A table has determinant zero exactly when its rank is at most one, and a nonnegative rank-one table summing to one is for distributions and on two points: its own margins. So is the set of product tables. Fixing and moving traces a straight segment, and so does fixing , so is a doubly ruled saddle. Its boundary is four of the tetrahedron’s six edges, those where or sits at a vertex. The lab’s Table geometry tab draws it.
Definition 3 (Association scores).
For the table of Definition 1, with the cells of the product of its margins ():
- pointwise mutual information ;
- the t-score ;
- Pearson’s statistic ;
- Dunning’s log-likelihood ratio , with ,
where are the table’s four cells.
PMI is Definition 2 of the distributional semantics topic, read off one cell. The t-score is a -statistic whose variance is estimated by the count itself (Manning and Schütze 1999, §5.3.1; Church and Hanks 1990 suggested t-scores as a fix for PMI). The other two look at all four cells, and the next theorem says what measures.
Theorem 1 (The product of the margins is the KL projection).
Let have row margin and column margin . For all distributions on two points,
So is the unique point of closest to in KL divergence, at distance , the mutual information of the row and column indicators. For a table,
and is the generalized likelihood ratio statistic for independence under multinomial sampling.
Proof.
Write and for the margins. For every cell,
Multiply by and sum. The first term gives ; summing the second over first gives , and the third likewise gives . The last two are nonnegative and vanish only at , , by Gibbs’ inequality, so the product of the margins is the unique minimizer. The minimum is the mutual information (formalML, Shannon Entropy, Definition 5). For a table, and , so . Finally, the multinomial log-likelihood of a table is , maximized over all of at and over at ; twice the difference is , the statistic of formalStatistics (Likelihood-Ratio Tests, Definition 5).
∎Moore (2004, §3) gives as times the mutual information. measures distance to the same point with a different divergence, and for a 2×2 table it collapses to a correlation.
Proposition 1 (X² is N times the squared correlation).
For a table with positive margins, all four differences equal , and
where and is the correlation of the two indicators. In particular .
Proof.
, and the other three cells differ from their expectations by the same amount with alternating signs, since every row and column of sums to zero. Then
which gives the middle formula. The correlation of the indicators is , whose square times is the same expression, and a correlation has modulus at most one by Cauchy–Schwarz.
∎So all four scores ask how far the table sits from the saddle. PMI looks at one cell’s log ratio, at a squared correlation, and at a KL divergence. Near the surface they agree to second order. The rest of the page is about where they do not.
Rare pairs, in closed form
Zipf’s law (the vocabulary statistics topic) guarantees that most word types are rare, so most candidate pairs involve a rare word. The extreme case is a pair of words that each occur once, and only together.
Proposition 2 (The hapax pair).
For the table :
- , the largest PMI of any table with ;
- , the largest of any table;
- ;
- ;
- the exact probability, under independence with these margins, of a count at least this large is .
Proof.
Substitute into Definition 3 and Proposition 1. Since , , with equality only at ; and . The expansion gives the asymptotic form. The last claim is Lemma 1 below: with one row and one column of total one, is with probability .
∎At the finance corpus’s bigram positions, the hapax pair has and , the most extreme values either score can give, while and . Is the pair significant? Its exact probability is , so as one test it is. We will return to that “as one test.”
The hapax pair is the first member of a family that separates the scores cleanly: pairs whose words never occur apart.
Proposition 3 (Perfect pairs: PMI falls as the evidence rises).
For the table with :
- , which decreases in ;
- for every ;
- , which increases in ;
- , with the binary entropy in nats, which increases in ;
- the exact -value is , so , which increases in and equals the PMI at .
Proof.
Substitution, as before. For : when the two indicators are equal, their mutual information is the entropy of either one, , and Theorem 1 applies. The derivative of is positive for , and increases on . Given margins in both directions, is the largest possible count and the only table that large, with hypergeometric probability (Lemma 1).
∎Seen ten times, always together, a pair is far stronger evidence of association than one seen once, yet PMI ranks it lower. Manning and Schütze (1999, §5.4) make the point for PMI: for perfectly dependent pairs, “as they get rarer, their mutual information increases.” And cannot tell the two apart at all. Dunning (1993, §6.1) found the same pattern in real text: ranked by , “the overestimate of the significance of items that occur only a few times is dramatic.” The lab’s Rare pairs tab plots the five scores for .
Tests and their sizes
A score becomes a test once we know its distribution when the words are independent. The cleanest route conditions on what the pair cannot tell us about association: how often each word occurs.
Lemma 1 (Conditioning on the margins).
Suppose the positions are independent and identically distributed, with independent row and column indicators of probabilities and . Given the margins , the count is hypergeometric:
whatever and are.
Proof.
The table is multinomial with cell probabilities , , , , so
The row indicators and the column indicators are independent families, so and independently. Dividing, the powers of and cancel, and leaves the hypergeometric probability.
∎Definition 4 (Fisher's exact test).
Given the margins, the one-sided exact -value of a table is under Lemma 1, and the two-sided one is the total probability of the tables no more probable than the observed one.
formalStatistics computes this tail in an example (Discrete Distributions, Example 6); Lemma 1 is why it is exact for every and . The test is Fisher’s (1935, Example 1), who conditioned on the margins of a fourfold table in just this way. Because is computed from the exact conditional law, for every margin, and so unconditionally.
The two tests replace the hypergeometric by a limit.
Theorem 2 (The χ² limits, and G² ≈ X²).
Under independence with fixed :
- , so ;
- , so .
Proof.
Write and for the row and column indicators of position . (1) The numerator of is
Under independence the summands have mean zero and variance , so times the first term converges to by the central limit theorem. Each factor of the second term is , so times it tends to zero. The denominator of converges almost surely to . Slutsky’s theorem and the continuous mapping theorem (formalStatistics, Modes of Convergence, Theorems 10 and 9) give both limits.
(2) Put . The function has and , and the terms sum to zero over the cells, so by Taylor’s theorem
for some between and . Comparing with ,
By Proposition 1, each , which is by part (1), and converge to positive limits. The bound is .
∎formalStatistics proves Wilks’ theorem for a scalar parameter and states the vector case, of which this is an instance, without proof (Likelihood-Ratio Tests, Theorem 4 and Remark 13); Theorem 2 proves the 2×2 case directly. On independent tables per size with and , the median of is at , at , and at , falling by about per decade.
The limit holds with and fixed. A word pair is the opposite regime: as the corpus grows, so does the vocabulary, and the expected count of a typical pair stays small. How far off are the tests there?
Proposition 4 (Exact sizes).
Given the margins, the probability that a test rejects under independence is over its rejection region , so it can be computed exactly from Lemma 1. Fisher’s test never exceeds its level.
Proof.
Lemma 1 gives the conditional law of , and a test’s rejection region given the margins is a set of values of . For Fisher’s test, on , and the definition of as a tail probability under that same law makes .
∎The lab’s Test size tab plots the exact sizes at , with and , against . Each test fails in its own regime. The size of peaks at near , three times nominal. The size of peaks at near . Fisher’s test stays at or below everywhere, and below all three have the same size, the probability that the pair is seen at all. Dunning (1993, §4, Table 1) measured how badly the normal approximation behind overstates rare events. Moore (2004, §6) found that overstates them too, more mildly, and recommended Fisher’s test.
Testing only what you saw
That last regime deserves its own statement. A pair with tiny margins is rarely seen, and when it is, the exact test calls it significant.
Proposition 5 (Testing only what you saw).
Fix the margins and the one-sided exact test at level , under independence.
- .
- If , then .
- If , then every is rejected: , while .
Hence in a family of independent pairs, every pair seen whose chance of being seen was at most is a false rejection; a multiple-testing correction computed over the observed pairs alone does not control what it promises, and one computed over all candidate pairs, with for the pairs never seen, does.
Proof.
Part 1 is Proposition 4. A sighting is the event , and ; since decreases in , for every . In part 3, , so every rejects, and the rejection event is the sighting event. In part 2, rejecting requires (as ), so , and part 1 bounds the numerator. The family statement applies part 3 to each pair; a correction that counts only the observed pairs uses a smaller number of hypotheses than were at risk, while an unseen pair’s -value of one never rejects, so counting it costs nothing but the count.
∎Moore (2004, §2.1) made the family-wide point for pairs seen once: a pair of words each seen once and seen together has an exact -value of in his data, but there were possible such pairs, so were expected by chance. Dunning’s (1993, §6.1) own bigram study scored only the bigrams that occurred, using the statistic “as a measure.” In the lab’s Test size tab, at the finance stratum’s below, every sighting rejects exactly when , that is ; at a sighting rejects with probability .
Remark.
Many tests at once. A vocabulary of types has candidate pairs. Bonferroni’s correction (formalStatistics, Multiple Testing, Theorem 1) holds under any dependence. Benjamini–Hochberg’s (Theorem 5) assumes independent or positively dependent -values, which pairs sharing a word need not have. The field’s practical response has been a frequency threshold: Church and Hanks (1990, §4) set aside pairs seen at most five times, and Evert (2004, §4.3.3) excludes pairs seen fewer than three times. A threshold fixed before looking shrinks the family to pairs whose chance of being seen is not negligible. The significance-testing topic later in the curriculum takes up testing for NLP systems.
Keyness
Swap the second variable. Instead of “is the second token ,” ask “is this token in corpus or corpus .”
Definition 5 (Keyness).
For a target corpus and a reference corpus , with and tokens, and a word seen times in and times in , the keyness table is
rows the corpus and columns “the token is or not.” The keyness of is its , signed positive when , and its log ratio is , an effect size.
Proposition 6 (Keyness is the same test).
The keyness of is , where is the empirical mutual information between the corpus indicator and the indicator of , and transposing the table leaves it unchanged.
Proof.
Theorem 1 with ; mutual information is symmetric in its two variables (formalML, Shannon Entropy, Proposition 5).
∎Remark.
TF-IDF answers another question. TF-IDF (formalRAG, Vector Space Model and TF-IDF, Definition 4) weights a term inside one collection by how few of its documents contain it. Keyness compares a word’s rate in two corpora, and it is a test.
Remark.
Rayson and Garside’s log-likelihood is one row of the table. Rayson and Garside (2000, §2) compute keyness as over the word’s row only, the cells and . The omitted row, the other words, contributes a nonnegative term, at most with and , because KL divergence is at most divergence. So their score sits just below . On the finance sectors the largest relative gap is below , and the two scores give the same top words in every sector. They sort by it and compare no critical value.
TextRank
Keyness needs a second corpus. TextRank (Mihalcea and Tarau 2004) ranks the words of one text by how central they are in its co-occurrence graph, with nothing to compare against.
Definition 6 (Co-occurrence graph).
Remove a set of stop words from each sentence. Join two distinct words that occur within positions of each other in a filtered sentence, with weight the number of such co-occurrences (or , for the binary graph). The nodes are the words with at least one edge; a word’s strength is the total weight of its edges.
Definition 7 (PageRank).
Let be a nonnegative weight matrix, the row-stochastic matrix with each row of zeros replaced by the uniform row, and . The Google matrix is
and a PageRank vector is a row vector with . TextRank is PageRank on Definition 6’s graph.
A random surfer follows an edge with probability and jumps to a uniform node otherwise (Page et al. 1999, §2.5). Mihalcea and Tarau write the update unnormalized, , which is when no row is empty, with ; for keywords they use an undirected, unweighted graph over nouns and adjectives, and found a window of best (§3). formalML describes this teleporting walk without proving that exists or is unique (Random Walks, the remark on PageRank). We prove both, and the rate.
Theorem 3 (Perron–Frobenius for positive stochastic matrices).
Let be an row-stochastic matrix with every entry at least . Then:
- has exactly one stationary distribution ;
- for every ;
- every eigenvalue of has .
The Google matrix has and , and its PageRank vector is
Proof.
Write , where and is nonnegative with rows summing to one (if , and everything is immediate). For any row vector , real or complex, : a stochastic matrix does not expand . If then , so and .
(1) For distributions , sums to zero, so is a contraction of the simplex in with factor . The simplex is closed in , hence complete, and the Banach contraction mapping theorem (formalCalculus, Metric Spaces, Theorem 4) gives exactly one fixed point. (2) . (3) If with and , then forces , so . For the formula, reads , using . The rows of sum to , so by the bound above every eigenvalue of has modulus at most , the Neumann series converges, and is invertible.
∎Haveliwala and Kamvar (2003, Theorem 1) proved part 3 for the Google matrix, with equality when the link graph has two closed classes (Theorem 2). The contraction also gives the rate of the algorithm everyone uses.
Theorem 4 (Power iteration converges geometrically).
The iteration from any satisfies
Stopping at the first step shorter than leaves an error of at most , and happens within steps.
Proof.
Both inequalities apply Theorem 3’s contraction times, to and to , each of which sums to zero. After a step shorter than , the remaining steps are at most , whose sum bounds the distance to the limit. The step count solves .
∎This is the argument that makes the Bellman operator a contraction (formalCalculus, Metric Spaces, Example 14), with the damping factor in place of the discount. What does TextRank converge to? On an undirected graph, the answer is close to something much simpler.
Proposition 7 (Strength, and the limit d → 1).
- On the weighted graph with window , a word’s strength is , where counts its occurrences in the filtered text, those at the first or last filtered position of a sentence (a one-word sentence counts twice), and its adjacent repeats.
- On an undirected graph with no isolated nodes and connected components , every gives each component exactly mass , and
- On a connected undirected graph, if the surfer jumps to node with probability instead of uniformly, then for every .
Proof.
(1) Each occurrence of is joined to the filtered tokens just before and after it, two unless it sits at an end of its sentence, and a neighbor equal to adds no edge; a repeat removes one neighbor from each of the two occurrences.
(2) No row is empty, so , which never leaves a component. Summing over gives , so . Any limit point of as (they exist by compactness) satisfies , so its restriction to is a stationary measure of the walk on with mass . The walk on a connected graph has stationary distribution (formalML, Random Walks, Theorem 1), and only one: its lazy version has the same stationary distributions and is ergodic, so Theorem 3 there makes the distribution unique. Every limit point is therefore the stated one.
(3) is stationary for , so ; by Theorem 3 (the same contraction, with any teleport distribution) it is the only solution.
∎So with weak damping, TextRank on the weighted window-2 graph ranks each component’s words by strength, which is twice their frequency up to sentence-boundary terms. Grolmusz (2015) proves part 3 and notes that with uniform jumps PageRank is not exactly proportional to degree. Boudin (2013, §5) found plain degree centrality as good as TextRank for keyphrase extraction, with an F-score at ten of for both on Inspec.
Finance case study
Dividing a table by N makes it a point of the tetrahedron whose corners are the four cells. With the margins fixed, the tables form a straight segment that crosses the saddle once, at a = E, where every score is zero. G² is 2N times the KL divergence from the point to that crossing (Theorem 1), and X² is N times the χ² divergence (Proposition 1).
Where this sits
A word pair is a 2×2 table, and every association score measures how far the table sits from the saddle of independent tables (Theorem 1, Proposition 1). The scores disagree on rare pairs, where PMI and reach their maxima on a pair seen once (Propositions 2 and 3). Conditioning on the margins gives the exact test (Lemma 1); the tests are right only in the limit (Theorem 2), and at small expected counts each fails in its own regime (Proposition 4). Then the step that is easy to miss: a list of observed bigrams is a selected family, and testing only its members makes every rare sighting significant (Proposition 5). Keyness is the same test across corpora (Proposition 6). TextRank’s PageRank exists, is unique, and is reached geometrically fast (Theorems 3 and 4), and with weak damping it ranks words by frequency (Proposition 7).
The distributional semantics topic built word vectors from PPMI, and Proposition 5 explains why its positive values on rare pairs were noise. The topic models topic found the same sector vocabularies that keyness finds here, without the sector labels keyness needs. The next topics turn to evaluation, starting with the overlap metrics used to score generated text.
Honest caveats
Implementation
The companion notebook (notebookPath) imports the topic’s Python module, which owns every number on this page. It imports the distributional semantics topic’s module, and through it the n-gram and vocabulary-statistics modules and the finance corpus. The tagged generator subclasses the corpus generator and wraps each content-noun draw in marker characters without changing a single random call, and the harness asserts that the stripped text equals the corpus. Exact tails are log-sum-exp sums of hypergeometric probabilities. Its harness checks:
- Theorem 1, Propositions 1–3, and Definition 3 at random tables and against SciPy;
- Lemma 1 by enumeration, Theorem 2 by simulation, and Propositions 4 and 5 exactly, on random margins;
- Theorems 3 and 4 and Proposition 7 on random directed and undirected graphs and on the finance text;
- every finance number this page states.
The laboratory reads its data from a JSON file that one of the harness’s tests requires to equal the module’s viz_payload() exactly, so the figure cannot drift from the code.
Connections
- That topic's Proposition 3 found shuffled text carrying more PPMI mass than real text and named a significance test as the cure; Theorem 1 here puts PMI and G² on one table, and Proposition 5 shows which family of tests the cure must run on. distributional-semantics-ppmi-svd
- Both topics find sector vocabularies in the same synthetic filings: a topic model from which words share documents, keyness from a two-corpus test against the other sectors, which needs the sector labels a topic model does without. topic-models-lda
- G² is twice the log-likelihood gained by modeling a pair jointly instead of as independent, the same nats-per-token currency in which that topic compares language models. perplexity-cross-entropy
References & Further Reading
- paper Accurate Methods for the Statistics of Surprise and Coincidence — Ted Dunning (1993) Computational Linguistics 19 (1): 61–74. Equations are unnumbered. Section 5.2: the likelihood ratio and its asymptotic χ² distribution; Section 5.3: the binomial and multinomial forms; Section 6.1 and Tables 2–4: a 31,777-word bigram study, ranked by the log-likelihood and by X²; Section 7 suggests Fisher's exact method
- paper Word Association Norms, Mutual Information, and Lexicography — Kenneth Ward Church and Patrick Hanks (1990) Computational Linguistics 16 (1): 22–29. Section 4: the association ratio over ordered pairs within a window of five words, unstable for small counts, with pairs of frequency at most 5 set aside
- paper On Log-Likelihood-Ratios and the Significance of Rare Events — Robert C. Moore (2004) Proceedings of EMNLP 2004, 333–40. Section 2.1: when a pair seen only once is significant, counted against all possible singleton pairs; Section 3, Formula 5: G² as 2N times the mutual information; Section 6, Table 1: log-likelihood p-values understate noise for rare events; Section 7 recommends Fisher's exact test. The data are bilingual word pairs
- book The Statistics of Word Cooccurrences: Word Pairs and Collocations — Stefan Evert (2004) PhD dissertation, Universität Stuttgart (published 2005). Section 2.2: sampling models for the contingency table, including conditioning on the margins (2.2.4); Section 4.3.3: excluding pairs seen fewer than three times
- book Foundations of Statistical Natural Language Processing — Christopher D. Manning and Hinrich Schütze (1999) MIT Press. Chapter 5, Collocations: Section 5.3.1 the t test, 5.3.3 Pearson's chi-square, 5.3.4 likelihood ratios, 5.4 pointwise mutual information and its failure for rare perfectly dependent pairs
- paper The Logic of Inductive Inference — R. A. Fisher (1935) Journal of the Royal Statistical Society 98 (1): 39–82. Example 1, pp. 48–50: the exact test for a fourfold table, conditioning on its margins
- paper On the Interpretation of χ² from Contingency Tables, and the Calculation of P — R. A. Fisher (1922) Journal of the Royal Statistical Society 85 (1): 87–94. A fourfold table with fixed margins has one degree of freedom
- paper On the Criterion That a Given System of Deviations from the Probable in the Case of a Correlated System of Variables Is Such That It Can Be Reasonably Supposed to Have Arisen from Random Sampling — Karl Pearson (1900) Philosophical Magazine, 5th series, 50 (302): 157–75
- paper The Large-Sample Distribution of the Likelihood Ratio for Testing Composite Hypotheses — S. S. Wilks (1938) Annals of Mathematical Statistics 9 (1): 60–62
- paper Controlling the False Discovery Rate: A Practical and Powerful Approach to Multiple Testing — Yoav Benjamini and Yosef Hochberg (1995) Journal of the Royal Statistical Society, Series B 57 (1): 289–300
- paper Comparing Corpora Using Frequency Profiling — Paul Rayson and Roger Garside (2000) Workshop on Comparing Corpora (ACL 2000), 1–6. Section 2 and Table 1: the log-likelihood over the word's row of the two-corpus table; words are sorted by it, with no χ² critical value
- paper TextRank: Bringing Order into Texts — Rada Mihalcea and Paul Tarau (2004) Proceedings of EMNLP 2004, 404–11. Section 2: the unnormalized PageRank update with d = 0.85 and threshold 0.0001; Section 3.1: keyword extraction on an undirected, unweighted graph over nouns and adjectives; Section 3.2 and Table 1: a window of 2 is best on Inspec
- paper The PageRank Citation Ranking: Bringing Order to the Web — Lawrence Page, Sergey Brin, Rajeev Motwani, and Terry Winograd (1999) Technical report, Stanford InfoLab. Section 2.4, Definition 1 and Eq. 1: PageRank with a source of rank E; Section 2.5: the random surfer
- paper The Second Eigenvalue of the Google Matrix — Taher H. Haveliwala and Sepandar D. Kamvar (2003) Technical report, Stanford InfoLab. Theorem 1: the second eigenvalue has modulus at most the damping factor; Theorem 2: equality when the chain has two irreducible closed subsets
- paper A Note on the PageRank of Undirected Graphs — Vince Grolmusz (2015) Information Processing Letters 115: 633–34 (arXiv 1205.1960). PageRank is proportional to degree for a degree-proportional personalization vector, and not exactly otherwise
- paper A Comparison of Centrality Measures for Graph-Based Keyphrase Extraction — Florian Boudin (2013) Proceedings of IJCNLP 2013, 834–38. Section 5 and Table 2: degree centrality performs as well as TextRank (F@10 of 32.2 for both on Inspec)
- paper Improved Automatic Keyword Extraction Given More Linguistic Knowledge — Anette Hulth (2003) Proceedings of EMNLP 2003, 216–23. The Inspec abstracts on which TextRank's keyword extraction was evaluated