Find collocations by ranking bigrams with pointwise mutual information

Why it matters PMI-based collocation finding is used to build phrase vocabularies, keyword lists and word2vec phrase detection.

Pairs like 'new york' or 'machine learning' appear together far more often than their separate frequencies would predict. Pointwise mutual information (PMI) measures exactly that, and a minimum count stops one-off pairs from topping the list.

Write pmi_bigrams(tokens, min_count). tokens is a list of str of length N >= 2. Let c(x) be the count of word x among the N tokens and c(x, y) the count of the adjacent pair (x, y) among the N - 1 bigrams. With p(x) = c(x) / N and p(x, y) = c(x, y) / (N - 1):
PMI(x, y) = log2(p(x, y) / (p(x) * p(y))).
Keep only bigrams with c(x, y) >= min_count. Return a list of (x, y, pmi) tuples sorted by pmi descending, then x ascending, then y ascending.

Signaturedef pmi_bigrams(tokens, min_count)

Example

pmi_bigrams('new york is big and new york is old'.split(), 2) is about [('new', 'york', 2.3399), ('york', 'is', 2.3399)].

Understand the idea

Pointwise mutual information asks: do x and y appear next to each other more than chance? If words were independent, the pair (x, y) would show up with probability p(x) * p(y). PMI is the log of the ratio between the real pair probability and that baseline. PMI = 0 means chance level; positive means the words attract.

Worked example: 'new york is big and new york is old' has N = 9 tokens and 8 bigrams. 'new' appears 2 times, 'york' 2 times, and the pair (new, york) 2 times. p(new, york) = 2 / 8 = 0.25 and p(new) * p(york) = (2 / 9) * (2 / 9) = 0.0494. The ratio is 5.06, and log2(5.06) = 2.34 bits.

Rule: PMI(x, y) = log2( (c(x, y) / (N - 1)) / ((c(x) / N) * (c(y) / N)) ), kept only when c(x, y) >= min_count.

Phrase detection before training word embeddings, keyword extraction and building multi-word vocab entries all use PMI.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplepmi_bigrams('new york is big and new york is old'.split(), 2)
  • Sample 2: rare pairs filteredpmi_bigrams('machine learning is fun and machine learning is hard but rust is fun'.split(), 2)