intermediate text-mining 35 min read

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 (w1,w2)(w_1, w_2) starts from the same four counts. Of the NN bigram positions in a corpus, how many have w1w_1 first and w2w_2 second, w1w_1 first and something else second, and so on. Divided by NN, 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.

  1. The table as a point. PMI, the t-score, Pearson’s X2X^2, and Dunning’s G2G^2 measure a table’s distance from the saddle in different ways.
  2. Rare pairs. The four scores disagree most where the counts are smallest, and we compute them in closed form there.
  3. Tests and their sizes. Conditioning on the margins gives an exact test; the two χ2\chi^2 tests are right only asymptotically, and we compute how wrong they are before that.
  4. 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 (w1,w2)(w_1, w_2). Over the corpus’s NN bigram positions (adjacent tokens within a sentence), let aa count the positions reading w1 w2w_1\, w_2, let rr count those whose first token is w1w_1, and let cc count those whose second token is w2w_2.

Definition 1 (The bigram's table).

The table of (w1,w2)(w_1, w_2) is

(abc′d),b=r−a,c′=c−a,d=N−r−c+a,\begin{pmatrix} a & b \\ c' & d \end{pmatrix}, \qquad b = r - a, \quad c' = c - a, \quad d = N - r - c + a,

with rows “the first token is w1w_1 or not” and columns “the second token is w2w_2 or not.” Its margins are the row totals (r,N−r)(r, N - r) and the column totals (c,N−c)(c, N - c), and its expected count is E=rc/NE = rc/N. Divided by NN it is a point p^\hat p of the simplex Δ3\Delta^3 of distributions on four cells.

Draw Δ3\Delta^3 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 S={q∈Δ3:q11q22=q12q21}S = \lbrace q \in \Delta^3 : q_{11} q_{22} = q_{12} q_{21} \rbrace.

A table qq has determinant zero exactly when its rank is at most one, and a nonnegative rank-one table summing to one is uv⊤u v^\top for distributions uu and vv on two points: its own margins. So SS is the set of product tables. Fixing uu and moving vv traces a straight segment, and so does fixing vv, so SS is a doubly ruled saddle. Its boundary is four of the tetrahedron’s six edges, those where uu or vv sits at a vertex. The lab’s Table geometry tab draws it.

Definition 3 (Association scores).

For the table of Definition 1, with EijE_{ij} the cells of the product of its margins (E11=EE_{11} = E):

  • pointwise mutual information PMI=log⁡aNrc\mathrm{PMI} = \log \dfrac{aN}{rc};
  • the t-score t=a−Eat = \dfrac{a - E}{\sqrt a};
  • Pearson’s statistic X2=∑ij(Oij−Eij)2EijX^2 = \sum_{ij} \dfrac{(O_{ij} - E_{ij})^2}{E_{ij}};
  • Dunning’s log-likelihood ratio G2=2∑ijOijlog⁡OijEijG^2 = 2 \sum_{ij} O_{ij} \log \dfrac{O_{ij}}{E_{ij}}, with 0log⁡0=00 \log 0 = 0,

where OijO_{ij} are the table’s four cells.

PMI is Definition 2 of the distributional semantics topic, read off one cell. The t-score is a zz-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 G2G^2 measures.

Theorem 1 (The product of the margins is the KL projection).

Let p∈Δ3p \in \Delta^3 have row margin prp_r and column margin pcp_c. For all distributions u,vu, v on two points,

KL(p ∥ uv⊤)=KL(p ∥ prpc⊤)+KL(pr ∥ u)+KL(pc ∥ v).\mathrm{KL}\big(p \,\Vert\, u v^\top\big) = \mathrm{KL}\big(p \,\Vert\, p_r p_c^\top\big) + \mathrm{KL}(p_r \,\Vert\, u) + \mathrm{KL}(p_c \,\Vert\, v).

So prpc⊤p_r p_c^\top is the unique point of SS closest to pp in KL divergence, at distance I(p)I(p), the mutual information of the row and column indicators. For a table,

G2=2N KL(p^ ∥ p^rp^c⊤)=2N I^,G^2 = 2N\, \mathrm{KL}\big(\hat p \,\Vert\, \hat p_r \hat p_c^\top\big) = 2N\, \hat I,

and G2G^2 is the generalized likelihood ratio statistic for independence under multinomial sampling.

Proof.

Write pi⋅p_{i\cdot} and p⋅jp_{\cdot j} for the margins. For every cell,

log⁡pijuivj=log⁡pijpi⋅ p⋅j+log⁡pi⋅ui+log⁡p⋅jvj.\log \frac{p_{ij}}{u_i v_j} = \log \frac{p_{ij}}{p_{i\cdot}\, p_{\cdot j}} + \log \frac{p_{i\cdot}}{u_i} + \log \frac{p_{\cdot j}}{v_j}.

Multiply by pijp_{ij} and sum. The first term gives KL(p ∥ prpc⊤)\mathrm{KL}(p \,\Vert\, p_r p_c^\top); summing the second over jj first gives ∑ipi⋅log⁡(pi⋅/ui)=KL(pr ∥ u)\sum_i p_{i\cdot} \log (p_{i\cdot}/u_i) = \mathrm{KL}(p_r \,\Vert\, u), and the third likewise gives KL(pc ∥ v)\mathrm{KL}(p_c \,\Vert\, v). The last two are nonnegative and vanish only at u=pru = p_r, v=pcv = p_c, by Gibbs’ inequality, so the product of the margins is the unique minimizer. The minimum KL(p ∥ prpc⊤)\mathrm{KL}(p \,\Vert\, p_r p_c^\top) is the mutual information (formalML, Shannon Entropy, Definition 5). For a table, Oij=Np^ijO_{ij} = N \hat p_{ij} and Eij=Np^i⋅p^⋅jE_{ij} = N \hat p_{i\cdot} \hat p_{\cdot j}, so G2=2N∑p^ijlog⁡(p^ij/(p^i⋅p^⋅j))G^2 = 2N \sum \hat p_{ij} \log\big(\hat p_{ij} / (\hat p_{i\cdot} \hat p_{\cdot j})\big). Finally, the multinomial log-likelihood of a table qq is ∑Oijlog⁡qij=−N[H(p^)+KL(p^ ∥ q)]\sum O_{ij} \log q_{ij} = -N\big[H(\hat p) + \mathrm{KL}(\hat p \,\Vert\, q)\big], maximized over all of Δ3\Delta^3 at p^\hat p and over SS at p^rp^c⊤\hat p_r \hat p_c^\top; twice the difference is G2G^2, the statistic of formalStatistics (Likelihood-Ratio Tests, Definition 5).

∎

Moore (2004, §3) gives G2G^2 as 2N2N times the mutual information. X2X^2 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 Oij−EijO_{ij} - E_{ij} equal ±(ad−bc′)/N\pm(ad - bc')/N, and

X2=N χ2(p^ ∥ p^rp^c⊤)=N (ad−bc′)2r(N−r) c(N−c)=Nφ^2,X^2 = N\, \chi^2\big(\hat p \,\Vert\, \hat p_r \hat p_c^\top\big) = \frac{N\,(ad - bc')^2}{r(N-r)\,c(N-c)} = N \hat\varphi^2,

where χ2(p ∥ q)=∑(p−q)2/q\chi^2(p \,\Vert\, q) = \sum (p - q)^2/q and φ^\hat\varphi is the correlation of the two indicators. In particular X2≤NX^2 \le N.

Proof.

a−rc/N=(a(a+b+c′+d)−(a+b)(a+c′))/N=(ad−bc′)/Na - rc/N = \big(a(a + b + c' + d) - (a + b)(a + c')\big)/N = (ad - bc')/N, and the other three cells differ from their expectations by the same amount with alternating signs, since every row and column of O−EO - E sums to zero. Then

∑ij1Eij=N[1rc+1r(N−c)+1(N−r)c+1(N−r)(N−c)]=N3r(N−r) c(N−c),\sum_{ij} \frac{1}{E_{ij}} = N\left[\frac{1}{rc} + \frac{1}{r(N-c)} + \frac{1}{(N-r)c} + \frac{1}{(N-r)(N-c)}\right] = \frac{N^3}{r(N-r)\,c(N-c)},

which gives the middle formula. The correlation of the indicators is (p^11−p^1⋅p^⋅1)/p^1⋅(1−p^1⋅)p^⋅1(1−p^⋅1)(\hat p_{11} - \hat p_{1\cdot}\hat p_{\cdot 1}) \big/ \sqrt{\hat p_{1\cdot}(1 - \hat p_{1\cdot})\hat p_{\cdot 1}(1 - \hat p_{\cdot 1})}, whose square times NN 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, X2X^2 at a squared correlation, and G2G^2 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 (100N−1)\begin{pmatrix} 1 & 0 \\ 0 & N-1 \end{pmatrix}:

  • PMI=log⁡N\mathrm{PMI} = \log N, the largest PMI of any table with a≥1a \ge 1;
  • X2=NX^2 = N, the largest X2X^2 of any table;
  • t=1−1/Nt = 1 - 1/N;
  • G2=2[log⁡N−(N−1)log⁡(1−1/N)]=2log⁡N+2−1/N−O(N−2)G^2 = 2\big[\log N - (N-1)\log(1 - 1/N)\big] = 2\log N + 2 - 1/N - O(N^{-2});
  • the exact probability, under independence with these margins, of a count at least this large is 1/N1/N.
Proof.

Substitute a=r=c=1a = r = c = 1 into Definition 3 and Proposition 1. Since a≤min⁡(r,c)a \le \min(r, c), aN/(rc)≤N/max⁡(r,c)≤NaN/(rc) \le N/\max(r, c) \le N, with equality only at a=r=c=1a = r = c = 1; and X2=Nφ^2≤NX^2 = N\hat\varphi^2 \le N. The expansion −(N−1)log⁡(1−1/N)=1−12N−16N2−⋯-(N-1)\log(1 - 1/N) = 1 - \frac{1}{2N} - \frac{1}{6N^2} - \cdots gives the asymptotic form. The last claim is Lemma 1 below: with one row and one column of total one, aa is 11 with probability rc/N=1/Nrc/N = 1/N.

∎

At the finance corpus’s N=57,052N = 57{,}052 bigram positions, the hapax pair has PMI=10.952\mathrm{PMI} = 10.952 and X2=57,052X^2 = 57{,}052, the most extreme values either score can give, while G2=23.903G^2 = 23.903 and t=1.000t = 1.000. Is the pair significant? Its exact probability is 1/N≈1.75×10−51/N \approx 1.75 \times 10^{-5}, 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 (k00N−k)\begin{pmatrix} k & 0 \\ 0 & N-k \end{pmatrix} with 1≤k<N/31 \le k \lt N/3:

  • PMI=log⁡(N/k)\mathrm{PMI} = \log(N/k), which decreases in kk;
  • X2=NX^2 = N for every kk;
  • t=k (1−k/N)t = \sqrt k\,(1 - k/N), which increases in kk;
  • G2=2N H(k/N)G^2 = 2N\, H(k/N), with HH the binary entropy in nats, which increases in kk;
  • the exact pp-value is 1/(Nk)1/\binom{N}{k}, so −log⁡p=log⁡(Nk)-\log p = \log \binom{N}{k}, which increases in kk and equals the PMI at k=1k = 1.
Proof.

Substitution, as before. For G2G^2: when the two indicators are equal, their mutual information is the entropy of either one, H(k/N)H(k/N), and Theorem 1 applies. The derivative of k−k3/2/N\sqrt k - k^{3/2}/N is positive for k<N/3k \lt N/3, and H(x)H(x) increases on [0,12][0, \frac12]. Given margins (k,N−k)(k, N - k) in both directions, a=ka = k is the largest possible count and the only table that large, with hypergeometric probability 1/(Nk)1/\binom{N}{k} (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 X2X^2 cannot tell the two apart at all. Dunning (1993, §6.1) found the same pattern in real text: ranked by X2X^2, “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 k=1,…,20k = 1, \dots, 20.


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 NN positions are independent and identically distributed, with independent row and column indicators of probabilities π\pi and ρ\rho. Given the margins (r,c)(r, c), the count aa is hypergeometric:

P(a∣r,c)=(ra)(N−rc−a)(Nc),P(a \mid r, c) = \frac{\binom{r}{a}\binom{N - r}{c - a}}{\binom{N}{c}},

whatever π\pi and ρ\rho are.

Proof.

The table is multinomial with cell probabilities πρ\pi\rho, π(1−ρ)\pi(1-\rho), (1−π)ρ(1-\pi)\rho, (1−π)(1−ρ)(1-\pi)(1-\rho), so

P(a,b,c′,d)=N!a! b! c′! d!  πr(1−π)N−rρc(1−ρ)N−c.P(a, b, c', d) = \frac{N!}{a!\, b!\, c'!\, d!}\; \pi^{r} (1-\pi)^{N-r} \rho^{c} (1-\rho)^{N-c}.

The row indicators and the column indicators are independent families, so r∼Bin(N,π)r \sim \mathrm{Bin}(N, \pi) and c∼Bin(N,ρ)c \sim \mathrm{Bin}(N, \rho) independently. Dividing, the powers of π\pi and ρ\rho cancel, and N!a! b! c′! d!=(Nr)(ra)(N−rc′)\frac{N!}{a!\, b!\, c'!\, d!} = \binom{N}{r}\binom{r}{a}\binom{N-r}{c'} leaves the hypergeometric probability.

∎

Definition 4 (Fisher's exact test).

Given the margins, the one-sided exact pp-value of a table is p(a)=P(A≥a∣r,c)p(a) = P(A \ge a \mid r, c) 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 π\pi and ρ\rho. The test is Fisher’s (1935, Example 1), who conditioned on the margins of a fourfold table in just this way. Because pp is computed from the exact conditional law, P(p≤α∣r,c)≤αP(p \le \alpha \mid r, c) \le \alpha for every margin, and so unconditionally.

The two χ2\chi^2 tests replace the hypergeometric by a limit.

Theorem 2 (The χ² limits, and G² ≈ X²).

Under independence with fixed 0<π,ρ<10 \lt \pi, \rho \lt 1:

  1. N φ^⇒N(0,1)\sqrt N\, \hat\varphi \Rightarrow \mathcal N(0, 1), so X2=Nφ^2⇒χ12X^2 = N\hat\varphi^2 \Rightarrow \chi^2_1;
  2. G2−X2=Op(N−1/2)G^2 - X^2 = O_p(N^{-1/2}), so G2⇒χ12G^2 \Rightarrow \chi^2_1.
Proof.

Write XiX_i and YiY_i for the row and column indicators of position ii. (1) The numerator of φ^\hat\varphi is

p^11−p^1⋅p^⋅1=1N∑i(Xi−π)(Yi−ρ)−(Xˉ−π)(Yˉ−ρ).\hat p_{11} - \hat p_{1\cdot}\hat p_{\cdot 1} = \frac1N \sum_i (X_i - \pi)(Y_i - \rho) - (\bar X - \pi)(\bar Y - \rho).

Under independence the summands (Xi−π)(Yi−ρ)(X_i - \pi)(Y_i - \rho) have mean zero and variance π(1−π)ρ(1−ρ)\pi(1-\pi)\rho(1-\rho), so N\sqrt N times the first term converges to N(0,π(1−π)ρ(1−ρ))\mathcal N\big(0, \pi(1-\pi)\rho(1-\rho)\big) by the central limit theorem. Each factor of the second term is Op(N−1/2)O_p(N^{-1/2}), so N\sqrt N times it tends to zero. The denominator of φ^\hat\varphi converges almost surely to π(1−π)ρ(1−ρ)\sqrt{\pi(1-\pi)\rho(1-\rho)}. Slutsky’s theorem and the continuous mapping theorem (formalStatistics, Modes of Convergence, Theorems 10 and 9) give both limits.

(2) Put q=p^rp^c⊤q = \hat p_r \hat p_c^\top. The function f(x)=xlog⁡(x/q)−(x−q)f(x) = x\log(x/q) - (x - q) has f(q)=f′(q)=0f(q) = f'(q) = 0 and f′′(x)=1/xf''(x) = 1/x, and the terms −(x−q)-(x - q) sum to zero over the cells, so by Taylor’s theorem

KL(p^ ∥ q)=∑ij(p^ij−qij)22ξij\mathrm{KL}(\hat p \,\Vert\, q) = \sum_{ij} \frac{(\hat p_{ij} - q_{ij})^2}{2\xi_{ij}}

for some ξij\xi_{ij} between p^ij\hat p_{ij} and qijq_{ij}. Comparing with X2=N∑(p^ij−qij)2/qijX^2 = N\sum (\hat p_{ij} - q_{ij})^2/q_{ij},

∣G2−X2∣≤N∑ij∣p^ij−qij∣3ξij qij.\big|G^2 - X^2\big| \le N \sum_{ij} \frac{|\hat p_{ij} - q_{ij}|^3}{\xi_{ij}\, q_{ij}}.

By Proposition 1, each ∣p^ij−qij∣=∣ad−bc′∣/N2|\hat p_{ij} - q_{ij}| = |ad - bc'|/N^2, which is Op(N−1/2)O_p(N^{-1/2}) by part (1), and ξij,qij\xi_{ij}, q_{ij} converge to positive limits. The bound is N⋅Op(N−3/2)N \cdot O_p(N^{-3/2}).

∎

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 20,00020{,}000 independent tables per size with π=0.3\pi = 0.3 and ρ=0.4\rho = 0.4, the median of ∣G2−X2∣|G^2 - X^2| is 0.001110.00111 at N=103N = 10^3, 0.0003620.000362 at 10410^4, and 0.0001130.000113 at 10510^5, falling by about 10\sqrt{10} per decade.

The limit holds with π\pi and ρ\rho fixed. A word pair is the opposite regime: as the corpus grows, so does the vocabulary, and the expected count E=rc/NE = rc/N of a typical pair stays small. How far off are the χ2\chi^2 tests there?

Proposition 4 (Exact sizes).

Given the margins, the probability that a test rejects under independence is ∑a∈RP(a∣r,c)\sum_{a \in R} P(a \mid r, c) over its rejection region RR, so it can be computed exactly from Lemma 1. Fisher’s test never exceeds its level.

Proof.

Lemma 1 gives the conditional law of aa, and a test’s rejection region given the margins is a set of values of aa. For Fisher’s test, p(a)≤αp(a) \le \alpha on RR, and the definition of pp as a tail probability under that same law makes P(p(A)≤α)≤αP(p(A) \le \alpha) \le \alpha.

∎

The lab’s Test size tab plots the exact sizes at N=10,000N = 10{,}000, with r=cr = c and α=0.05\alpha = 0.05, against EE. Each χ2\chi^2 test fails in its own regime. The size of X2X^2 peaks at 0.1620.162 near E=0.18E = 0.18, three times nominal. The size of G2G^2 peaks at 0.1570.157 near E=1.9E = 1.9. Fisher’s test stays at or below 0.050.05 everywhere, and below E≈0.05E \approx 0.05 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 X2X^2 overstates rare events. Moore (2004, §6) found that G2G^2 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 α\alpha, under independence.

  1. P(reject)≤αP(\text{reject}) \le \alpha.
  2. If P(A≥1)>αP(A \ge 1) \gt \alpha, then P(reject∣A≥1)≤α/P(A≥1)P(\text{reject} \mid A \ge 1) \le \alpha / P(A \ge 1).
  3. If P(A≥1)≤αP(A \ge 1) \le \alpha, then every a≥1a \ge 1 is rejected: P(reject∣A≥1)=1P(\text{reject} \mid A \ge 1) = 1, while P(reject)=P(A≥1)≤αP(\text{reject}) = P(A \ge 1) \le \alpha.

Hence in a family of independent pairs, every pair seen whose chance of being seen was at most α\alpha 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 p=1p = 1 for the pairs never seen, does.

Proof.

Part 1 is Proposition 4. A sighting is the event A≥1A \ge 1, and p(1)=P(A≥1)p(1) = P(A \ge 1); since pp decreases in aa, p(a)≤p(1)p(a) \le p(1) for every a≥1a \ge 1. In part 3, p(1)≤αp(1) \le \alpha, so every a≥1a \ge 1 rejects, and the rejection event is the sighting event. In part 2, rejecting requires a≥1a \ge 1 (as p(0)=1>αp(0) = 1 \gt \alpha), so P(reject∣A≥1)=P(reject)/P(A≥1)P(\text{reject} \mid A \ge 1) = P(\text{reject})/P(A \ge 1), 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 pp-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 pp-value of 2×10−62 \times 10^{-6} in his data, but there were 391,236,048391{,}236{,}048 possible such pairs, so 782.5782.5 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 N=4,182N = 4{,}182 below, every sighting rejects exactly when r=c≤14r = c \le 14, that is E≤0.047E \le 0.047; at r=c=20r = c = 20 a sighting rejects with probability 0.04280.0428.

Remark.

Many tests at once. A vocabulary of VV types has V2V^2 candidate pairs. Bonferroni’s correction (formalStatistics, Multiple Testing, Theorem 1) holds under any dependence. Benjamini–Hochberg’s (Theorem 5) assumes independent or positively dependent pp-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 w2w_2,” ask “is this token in corpus TT or corpus RR.”

Definition 5 (Keyness).

For a target corpus TT and a reference corpus RR, with NTN_T and NRN_R tokens, and a word ww seen aa times in TT and bb times in RR, the keyness table is

(aNT−abNR−b),\begin{pmatrix} a & N_T - a \\ b & N_R - b \end{pmatrix},

rows the corpus and columns “the token is ww or not.” The keyness of ww is its G2G^2, signed positive when a/NT>b/NRa/N_T \gt b/N_R, and its log ratio is log⁡2(a+12)/NT(b+12)/NR\log_2 \dfrac{(a + \frac12)/N_T}{(b + \frac12)/N_R}, an effect size.

Proposition 6 (Keyness is the same test).

The keyness of ww is 2(NT+NR) I^2(N_T + N_R)\,\hat I, where I^\hat I is the empirical mutual information between the corpus indicator and the indicator of ww, and transposing the table leaves it unchanged.

Proof.

Theorem 1 with N=NT+NRN = N_T + N_R; 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 2∑Olog⁡(O/E)2\sum O \log(O/E) over the word’s row only, the cells aa and bb. The omitted row, the other words, contributes a nonnegative term, at most 2(a−E1)2[1/(NT−E1)+1/(NR−E2)]2(a - E_1)^2\big[1/(N_T - E_1) + 1/(N_R - E_2)\big] with E1=NT(a+b)/(NT+NR)E_1 = N_T(a + b)/(N_T + N_R) and E2=NR(a+b)/(NT+NR)E_2 = N_R(a + b)/(N_T + N_R), because KL divergence is at most χ2\chi^2 divergence. So their score sits just below G2G^2. On the finance sectors the largest relative gap is below 0.070.07, and the two scores give the same top 2525 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 WW positions of each other in a filtered sentence, with weight the number of such co-occurrences (or 11, for the binary graph). The nodes are the words with at least one edge; a word’s strength s(w)s(w) is the total weight of its edges.

Definition 7 (PageRank).

Let WW be a nonnegative n×nn \times n weight matrix, P~\tilde P the row-stochastic matrix D−1WD^{-1} W with each row of zeros replaced by the uniform row, and 0≤d<10 \le d \lt 1. The Google matrix is

G=1−dn 11⊤+d P~,G = \frac{1 - d}{n}\, \mathbf 1 \mathbf 1^\top + d\, \tilde P,

and a PageRank vector is a row vector π∈Δn−1\pi \in \Delta^{n-1} with πG=π\pi G = \pi. TextRank is PageRank on Definition 6’s graph.

A random surfer follows an edge with probability dd and jumps to a uniform node otherwise (Page et al. 1999, §2.5). Mihalcea and Tarau write the update unnormalized, S(Vi)=(1−d)+d∑jS(Vj)/∣Out(Vj)∣S(V_i) = (1 - d) + d \sum_j S(V_j)/\lvert \mathrm{Out}(V_j) \rvert, which is nπn\pi when no row is empty, with d=0.85d = 0.85; for keywords they use an undirected, unweighted graph over nouns and adjectives, and found a window of W=2W = 2 best (§3). formalML describes this teleporting walk without proving that π\pi 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 MM be an n×nn \times n row-stochastic matrix with every entry at least δ>0\delta \gt 0. Then:

  1. MM has exactly one stationary distribution π\pi;
  2. πi≥δ\pi_i \ge \delta for every ii;
  3. every eigenvalue λ≠1\lambda \ne 1 of MM has ∣λ∣≤1−nδ|\lambda| \le 1 - n\delta.

The Google matrix has δ=(1−d)/n\delta = (1 - d)/n and 1−nδ=d1 - n\delta = d, and its PageRank vector is

π=1−dn 1⊤∑t≥0dtP~t=1−dn 1⊤(I−dP~)−1.\pi = \frac{1 - d}{n}\, \mathbf 1^\top \sum_{t \ge 0} d^t \tilde P^t = \frac{1 - d}{n}\, \mathbf 1^\top (I - d\tilde P)^{-1}.
Proof.

Write M=nδ U+(1−nδ) QM = n\delta\, U + (1 - n\delta)\, Q, where U=1n11⊤U = \frac1n \mathbf 1 \mathbf 1^\top and Q=(M−nδU)/(1−nδ)Q = (M - n\delta U)/(1 - n\delta) is nonnegative with rows summing to one (if nδ=1n\delta = 1, M=UM = U and everything is immediate). For any row vector yy, real or complex, ∥yQ∥1=∑j∣∑iyiQij∣≤∑i∣yi∣∑jQij=∥y∥1\lVert yQ \rVert_1 = \sum_j \lvert \sum_i y_i Q_{ij} \rvert \le \sum_i \lvert y_i \rvert \sum_j Q_{ij} = \lVert y \rVert_1: a stochastic matrix does not expand ℓ1\ell_1. If y1=0y \mathbf 1 = 0 then yU=0yU = 0, so yM=(1−nδ) yQyM = (1 - n\delta)\, yQ and ∥yM∥1≤(1−nδ)∥y∥1\lVert yM \rVert_1 \le (1 - n\delta)\lVert y \rVert_1.

(1) For distributions x,x′x, x', x−x′x - x' sums to zero, so x↦xMx \mapsto xM is a contraction of the simplex in ℓ1\ell_1 with factor 1−nδ<11 - n\delta \lt 1. The simplex is closed in Rn\mathbb R^n, hence complete, and the Banach contraction mapping theorem (formalCalculus, Metric Spaces, Theorem 4) gives exactly one fixed point. (2) πj=∑iπiMij≥δ∑iπi=δ\pi_j = \sum_i \pi_i M_{ij} \ge \delta \sum_i \pi_i = \delta. (3) If yM=λyyM = \lambda y with y≠0y \ne 0 and λ≠1\lambda \ne 1, then λ y1=yM1=y1\lambda\, y\mathbf 1 = yM\mathbf 1 = y \mathbf 1 forces y1=0y \mathbf 1 = 0, so ∣λ∣∥y∥1=∥yM∥1≤(1−nδ)∥y∥1\lvert\lambda\rvert \lVert y \rVert_1 = \lVert yM \rVert_1 \le (1 - n\delta)\lVert y \rVert_1. For the formula, πG=π\pi G = \pi reads π(I−dP~)=1−dn1⊤\pi (I - d\tilde P) = \frac{1-d}{n}\mathbf 1^\top, using π1=1\pi\mathbf 1 = 1. The rows of dP~d\tilde P sum to d<1d \lt 1, so by the bound above every eigenvalue of dP~d\tilde P has modulus at most dd, the Neumann series converges, and I−dP~I - d\tilde P 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 xt+1=xtGx_{t+1} = x_t G from any x0∈Δn−1x_0 \in \Delta^{n-1} satisfies

∥xt−π∥1≤dt∥x0−π∥1≤2dt,∥xt+1−xt∥1≤dt∥x1−x0∥1.\lVert x_t - \pi \rVert_1 \le d^t \lVert x_0 - \pi \rVert_1 \le 2d^t, \qquad \lVert x_{t+1} - x_t \rVert_1 \le d^t \lVert x_1 - x_0 \rVert_1 .

Stopping at the first step shorter than ε\varepsilon leaves an error of at most εd/(1−d)\varepsilon d/(1 - d), and happens within ⌈log⁡(ε/∥x1−x0∥1)/log⁡d⌉+1\lceil \log(\varepsilon / \lVert x_1 - x_0 \rVert_1) / \log d \rceil + 1 steps.

Proof.

Both inequalities apply Theorem 3’s contraction tt times, to xt−πx_t - \pi and to xt+1−xtx_{t+1} - x_t, each of which sums to zero. After a step shorter than ε\varepsilon, the remaining steps are at most εd,εd2,…\varepsilon d, \varepsilon d^2, \dots, whose sum bounds the distance to the limit. The step count solves dt∥x1−x0∥1<εd^t \lVert x_1 - x_0 \rVert_1 \lt \varepsilon.

∎

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).

  1. On the weighted graph with window W=2W = 2, a word’s strength is s(w)=2c(w)−e(w)−2σ(w)s(w) = 2c(w) - e(w) - 2\sigma(w), where c(w)c(w) counts its occurrences in the filtered text, e(w)e(w) those at the first or last filtered position of a sentence (a one-word sentence counts twice), and σ(w)\sigma(w) its adjacent repeats.
  2. On an undirected graph with no isolated nodes and connected components C1,…,CmC_1, \dots, C_m, every dd gives each component exactly mass ∣Cj∣/n\lvert C_j \rvert / n, and
lim⁡d→1πd=∑j∣Cj∣n s∣Cjvol(Cj),vol(Cj)=∑w∈Cjs(w).\lim_{d \to 1} \pi_d = \sum_j \frac{\lvert C_j \rvert}{n}\, \frac{s|_{C_j}}{\mathrm{vol}(C_j)}, \qquad \mathrm{vol}(C_j) = \sum_{w \in C_j} s(w).
  1. On a connected undirected graph, if the surfer jumps to node ww with probability s(w)/vols(w)/\mathrm{vol} instead of uniformly, then πd=s/vol\pi_d = s/\mathrm{vol} for every dd.
Proof.

(1) Each occurrence of ww 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 ww adds no edge; a repeat w ww\,w removes one neighbor from each of the two occurrences.

(2) No row is empty, so P~=D−1W\tilde P = D^{-1}W, which never leaves a component. Summing πd=1−dn1⊤+d πdP~\pi_d = \frac{1-d}{n}\mathbf 1^\top + d\,\pi_d \tilde P over CjC_j gives πd(Cj)=(1−d)∣Cj∣/n+d πd(Cj)\pi_d(C_j) = (1 - d)\lvert C_j \rvert/n + d\, \pi_d(C_j), so πd(Cj)=∣Cj∣/n\pi_d(C_j) = \lvert C_j \rvert / n. Any limit point of πd\pi_d as d→1d \to 1 (they exist by compactness) satisfies π=πP~\pi = \pi\tilde P, so its restriction to CjC_j is a stationary measure of the walk on CjC_j with mass ∣Cj∣/n\lvert C_j\rvert/n. The walk on a connected graph has stationary distribution s/vols/\mathrm{vol} (formalML, Random Walks, Theorem 1), and only one: its lazy version 12(I+P~)\frac12(I + \tilde P) 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) s/vols/\mathrm{vol} is stationary for P~\tilde P, so (1−d) s/vol+d (s/vol)P~=s/vol(1 - d)\, s/\mathrm{vol} + d\, (s/\mathrm{vol})\tilde P = s/\mathrm{vol}; 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 32.232.2 for both on Inspec.


Finance case study

A word pair's table is a point of the tetrahedron; independent tables form the saddle
margins (N, r, c)
p₁₁p₁₂p₂₁p₂₂
independence saddle Stables with these marginsthe table at acrossing S at a = E
expected count E
20.000
PMI
0.000
t-score
0.000
X²
0.000
G²
0.000
exact p, P(A ≥ a)
0.5808

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 X2X^2 reach their maxima on a pair seen once (Propositions 2 and 3). Conditioning on the margins gives the exact test (Lemma 1); the χ2\chi^2 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