collocations.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. # Natural Language Toolkit: Collocations and Association Measures
  2. #
  3. # Copyright (C) 2001-2020 NLTK Project
  4. # Author: Joel Nothman <jnothman@student.usyd.edu.au>
  5. # URL: <http://nltk.org>
  6. # For license information, see LICENSE.TXT
  7. #
  8. """
  9. Tools to identify collocations --- words that often appear consecutively
  10. --- within corpora. They may also be used to find other associations between
  11. word occurrences.
  12. See Manning and Schutze ch. 5 at http://nlp.stanford.edu/fsnlp/promo/colloc.pdf
  13. and the Text::NSP Perl package at http://ngram.sourceforge.net
  14. Finding collocations requires first calculating the frequencies of words and
  15. their appearance in the context of other words. Often the collection of words
  16. will then requiring filtering to only retain useful content terms. Each ngram
  17. of words may then be scored according to some association measure, in order
  18. to determine the relative likelihood of each ngram being a collocation.
  19. The ``BigramCollocationFinder`` and ``TrigramCollocationFinder`` classes provide
  20. these functionalities, dependent on being provided a function which scores a
  21. ngram given appropriate frequency counts. A number of standard association
  22. measures are provided in bigram_measures and trigram_measures.
  23. """
  24. # Possible TODOs:
  25. # - consider the distinction between f(x,_) and f(x) and whether our
  26. # approximation is good enough for fragmented data, and mention it
  27. # - add a n-gram collocation finder with measures which only utilise n-gram
  28. # and unigram counts (raw_freq, pmi, student_t)
  29. import itertools as _itertools
  30. from nltk.probability import FreqDist
  31. from nltk.util import ngrams
  32. # these two unused imports are referenced in collocations.doctest
  33. from nltk.metrics import (
  34. ContingencyMeasures,
  35. BigramAssocMeasures,
  36. TrigramAssocMeasures,
  37. QuadgramAssocMeasures,
  38. )
  39. from nltk.metrics.spearman import ranks_from_scores, spearman_correlation
  40. class AbstractCollocationFinder(object):
  41. """
  42. An abstract base class for collocation finders whose purpose is to
  43. collect collocation candidate frequencies, filter and rank them.
  44. As a minimum, collocation finders require the frequencies of each
  45. word in a corpus, and the joint frequency of word tuples. This data
  46. should be provided through nltk.probability.FreqDist objects or an
  47. identical interface.
  48. """
  49. def __init__(self, word_fd, ngram_fd):
  50. self.word_fd = word_fd
  51. self.N = word_fd.N()
  52. self.ngram_fd = ngram_fd
  53. @classmethod
  54. def _build_new_documents(
  55. cls, documents, window_size, pad_left=False, pad_right=False, pad_symbol=None
  56. ):
  57. """
  58. Pad the document with the place holder according to the window_size
  59. """
  60. padding = (pad_symbol,) * (window_size - 1)
  61. if pad_right:
  62. return _itertools.chain.from_iterable(
  63. _itertools.chain(doc, padding) for doc in documents
  64. )
  65. if pad_left:
  66. return _itertools.chain.from_iterable(
  67. _itertools.chain(padding, doc) for doc in documents
  68. )
  69. @classmethod
  70. def from_documents(cls, documents):
  71. """Constructs a collocation finder given a collection of documents,
  72. each of which is a list (or iterable) of tokens.
  73. """
  74. # return cls.from_words(_itertools.chain(*documents))
  75. return cls.from_words(
  76. cls._build_new_documents(documents, cls.default_ws, pad_right=True)
  77. )
  78. @staticmethod
  79. def _ngram_freqdist(words, n):
  80. return FreqDist(tuple(words[i : i + n]) for i in range(len(words) - 1))
  81. def _apply_filter(self, fn=lambda ngram, freq: False):
  82. """Generic filter removes ngrams from the frequency distribution
  83. if the function returns True when passed an ngram tuple.
  84. """
  85. tmp_ngram = FreqDist()
  86. for ngram, freq in self.ngram_fd.items():
  87. if not fn(ngram, freq):
  88. tmp_ngram[ngram] = freq
  89. self.ngram_fd = tmp_ngram
  90. def apply_freq_filter(self, min_freq):
  91. """Removes candidate ngrams which have frequency less than min_freq."""
  92. self._apply_filter(lambda ng, freq: freq < min_freq)
  93. def apply_ngram_filter(self, fn):
  94. """Removes candidate ngrams (w1, w2, ...) where fn(w1, w2, ...)
  95. evaluates to True.
  96. """
  97. self._apply_filter(lambda ng, f: fn(*ng))
  98. def apply_word_filter(self, fn):
  99. """Removes candidate ngrams (w1, w2, ...) where any of (fn(w1), fn(w2),
  100. ...) evaluates to True.
  101. """
  102. self._apply_filter(lambda ng, f: any(fn(w) for w in ng))
  103. def _score_ngrams(self, score_fn):
  104. """Generates of (ngram, score) pairs as determined by the scoring
  105. function provided.
  106. """
  107. for tup in self.ngram_fd:
  108. score = self.score_ngram(score_fn, *tup)
  109. if score is not None:
  110. yield tup, score
  111. def score_ngrams(self, score_fn):
  112. """Returns a sequence of (ngram, score) pairs ordered from highest to
  113. lowest score, as determined by the scoring function provided.
  114. """
  115. return sorted(self._score_ngrams(score_fn), key=lambda t: (-t[1], t[0]))
  116. def nbest(self, score_fn, n):
  117. """Returns the top n ngrams when scored by the given function."""
  118. return [p for p, s in self.score_ngrams(score_fn)[:n]]
  119. def above_score(self, score_fn, min_score):
  120. """Returns a sequence of ngrams, ordered by decreasing score, whose
  121. scores each exceed the given minimum score.
  122. """
  123. for ngram, score in self.score_ngrams(score_fn):
  124. if score > min_score:
  125. yield ngram
  126. else:
  127. break
  128. class BigramCollocationFinder(AbstractCollocationFinder):
  129. """A tool for the finding and ranking of bigram collocations or other
  130. association measures. It is often useful to use from_words() rather than
  131. constructing an instance directly.
  132. """
  133. default_ws = 2
  134. def __init__(self, word_fd, bigram_fd, window_size=2):
  135. """Construct a BigramCollocationFinder, given FreqDists for
  136. appearances of words and (possibly non-contiguous) bigrams.
  137. """
  138. AbstractCollocationFinder.__init__(self, word_fd, bigram_fd)
  139. self.window_size = window_size
  140. @classmethod
  141. def from_words(cls, words, window_size=2):
  142. """Construct a BigramCollocationFinder for all bigrams in the given
  143. sequence. When window_size > 2, count non-contiguous bigrams, in the
  144. style of Church and Hanks's (1990) association ratio.
  145. """
  146. wfd = FreqDist()
  147. bfd = FreqDist()
  148. if window_size < 2:
  149. raise ValueError("Specify window_size at least 2")
  150. for window in ngrams(words, window_size, pad_right=True):
  151. w1 = window[0]
  152. if w1 is None:
  153. continue
  154. wfd[w1] += 1
  155. for w2 in window[1:]:
  156. if w2 is not None:
  157. bfd[(w1, w2)] += 1
  158. return cls(wfd, bfd, window_size=window_size)
  159. def score_ngram(self, score_fn, w1, w2):
  160. """Returns the score for a given bigram using the given scoring
  161. function. Following Church and Hanks (1990), counts are scaled by
  162. a factor of 1/(window_size - 1).
  163. """
  164. n_all = self.N
  165. n_ii = self.ngram_fd[(w1, w2)] / (self.window_size - 1.0)
  166. if not n_ii:
  167. return
  168. n_ix = self.word_fd[w1]
  169. n_xi = self.word_fd[w2]
  170. return score_fn(n_ii, (n_ix, n_xi), n_all)
  171. class TrigramCollocationFinder(AbstractCollocationFinder):
  172. """A tool for the finding and ranking of trigram collocations or other
  173. association measures. It is often useful to use from_words() rather than
  174. constructing an instance directly.
  175. """
  176. default_ws = 3
  177. def __init__(self, word_fd, bigram_fd, wildcard_fd, trigram_fd):
  178. """Construct a TrigramCollocationFinder, given FreqDists for
  179. appearances of words, bigrams, two words with any word between them,
  180. and trigrams.
  181. """
  182. AbstractCollocationFinder.__init__(self, word_fd, trigram_fd)
  183. self.wildcard_fd = wildcard_fd
  184. self.bigram_fd = bigram_fd
  185. @classmethod
  186. def from_words(cls, words, window_size=3):
  187. """Construct a TrigramCollocationFinder for all trigrams in the given
  188. sequence.
  189. """
  190. if window_size < 3:
  191. raise ValueError("Specify window_size at least 3")
  192. wfd = FreqDist()
  193. wildfd = FreqDist()
  194. bfd = FreqDist()
  195. tfd = FreqDist()
  196. for window in ngrams(words, window_size, pad_right=True):
  197. w1 = window[0]
  198. if w1 is None:
  199. continue
  200. for w2, w3 in _itertools.combinations(window[1:], 2):
  201. wfd[w1] += 1
  202. if w2 is None:
  203. continue
  204. bfd[(w1, w2)] += 1
  205. if w3 is None:
  206. continue
  207. wildfd[(w1, w3)] += 1
  208. tfd[(w1, w2, w3)] += 1
  209. return cls(wfd, bfd, wildfd, tfd)
  210. def bigram_finder(self):
  211. """Constructs a bigram collocation finder with the bigram and unigram
  212. data from this finder. Note that this does not include any filtering
  213. applied to this finder.
  214. """
  215. return BigramCollocationFinder(self.word_fd, self.bigram_fd)
  216. def score_ngram(self, score_fn, w1, w2, w3):
  217. """Returns the score for a given trigram using the given scoring
  218. function.
  219. """
  220. n_all = self.N
  221. n_iii = self.ngram_fd[(w1, w2, w3)]
  222. if not n_iii:
  223. return
  224. n_iix = self.bigram_fd[(w1, w2)]
  225. n_ixi = self.wildcard_fd[(w1, w3)]
  226. n_xii = self.bigram_fd[(w2, w3)]
  227. n_ixx = self.word_fd[w1]
  228. n_xix = self.word_fd[w2]
  229. n_xxi = self.word_fd[w3]
  230. return score_fn(n_iii, (n_iix, n_ixi, n_xii), (n_ixx, n_xix, n_xxi), n_all)
  231. class QuadgramCollocationFinder(AbstractCollocationFinder):
  232. """A tool for the finding and ranking of quadgram collocations or other association measures.
  233. It is often useful to use from_words() rather than constructing an instance directly.
  234. """
  235. default_ws = 4
  236. def __init__(self, word_fd, quadgram_fd, ii, iii, ixi, ixxi, iixi, ixii):
  237. """Construct a QuadgramCollocationFinder, given FreqDists for appearances of words,
  238. bigrams, trigrams, two words with one word and two words between them, three words
  239. with a word between them in both variations.
  240. """
  241. AbstractCollocationFinder.__init__(self, word_fd, quadgram_fd)
  242. self.iii = iii
  243. self.ii = ii
  244. self.ixi = ixi
  245. self.ixxi = ixxi
  246. self.iixi = iixi
  247. self.ixii = ixii
  248. @classmethod
  249. def from_words(cls, words, window_size=4):
  250. if window_size < 4:
  251. raise ValueError("Specify window_size at least 4")
  252. ixxx = FreqDist()
  253. iiii = FreqDist()
  254. ii = FreqDist()
  255. iii = FreqDist()
  256. ixi = FreqDist()
  257. ixxi = FreqDist()
  258. iixi = FreqDist()
  259. ixii = FreqDist()
  260. for window in ngrams(words, window_size, pad_right=True):
  261. w1 = window[0]
  262. if w1 is None:
  263. continue
  264. for w2, w3, w4 in _itertools.combinations(window[1:], 3):
  265. ixxx[w1] += 1
  266. if w2 is None:
  267. continue
  268. ii[(w1, w2)] += 1
  269. if w3 is None:
  270. continue
  271. iii[(w1, w2, w3)] += 1
  272. ixi[(w1, w3)] += 1
  273. if w4 is None:
  274. continue
  275. iiii[(w1, w2, w3, w4)] += 1
  276. ixxi[(w1, w4)] += 1
  277. ixii[(w1, w3, w4)] += 1
  278. iixi[(w1, w2, w4)] += 1
  279. return cls(ixxx, iiii, ii, iii, ixi, ixxi, iixi, ixii)
  280. def score_ngram(self, score_fn, w1, w2, w3, w4):
  281. n_all = self.N
  282. n_iiii = self.ngram_fd[(w1, w2, w3, w4)]
  283. if not n_iiii:
  284. return
  285. n_iiix = self.iii[(w1, w2, w3)]
  286. n_xiii = self.iii[(w2, w3, w4)]
  287. n_iixi = self.iixi[(w1, w2, w4)]
  288. n_ixii = self.ixii[(w1, w3, w4)]
  289. n_iixx = self.ii[(w1, w2)]
  290. n_xxii = self.ii[(w3, w4)]
  291. n_xiix = self.ii[(w2, w3)]
  292. n_ixix = self.ixi[(w1, w3)]
  293. n_ixxi = self.ixxi[(w1, w4)]
  294. n_xixi = self.ixi[(w2, w4)]
  295. n_ixxx = self.word_fd[w1]
  296. n_xixx = self.word_fd[w2]
  297. n_xxix = self.word_fd[w3]
  298. n_xxxi = self.word_fd[w4]
  299. return score_fn(
  300. n_iiii,
  301. (n_iiix, n_iixi, n_ixii, n_xiii),
  302. (n_iixx, n_ixix, n_ixxi, n_xixi, n_xxii, n_xiix),
  303. (n_ixxx, n_xixx, n_xxix, n_xxxi),
  304. n_all,
  305. )
  306. def demo(scorer=None, compare_scorer=None):
  307. """Finds bigram collocations in the files of the WebText corpus."""
  308. from nltk.metrics import (
  309. BigramAssocMeasures,
  310. spearman_correlation,
  311. ranks_from_scores,
  312. )
  313. if scorer is None:
  314. scorer = BigramAssocMeasures.likelihood_ratio
  315. if compare_scorer is None:
  316. compare_scorer = BigramAssocMeasures.raw_freq
  317. from nltk.corpus import stopwords, webtext
  318. ignored_words = stopwords.words("english")
  319. word_filter = lambda w: len(w) < 3 or w.lower() in ignored_words
  320. for file in webtext.fileids():
  321. words = [word.lower() for word in webtext.words(file)]
  322. cf = BigramCollocationFinder.from_words(words)
  323. cf.apply_freq_filter(3)
  324. cf.apply_word_filter(word_filter)
  325. corr = spearman_correlation(
  326. ranks_from_scores(cf.score_ngrams(scorer)),
  327. ranks_from_scores(cf.score_ngrams(compare_scorer)),
  328. )
  329. print(file)
  330. print("\t", [" ".join(tup) for tup in cf.nbest(scorer, 15)])
  331. print("\t Correlation to %s: %0.4f" % (compare_scorer.__name__, corr))
  332. # Slows down loading too much
  333. # bigram_measures = BigramAssocMeasures()
  334. # trigram_measures = TrigramAssocMeasures()
  335. if __name__ == "__main__":
  336. import sys
  337. from nltk.metrics import BigramAssocMeasures
  338. try:
  339. scorer = eval("BigramAssocMeasures." + sys.argv[1])
  340. except IndexError:
  341. scorer = None
  342. try:
  343. compare_scorer = eval("BigramAssocMeasures." + sys.argv[2])
  344. except IndexError:
  345. compare_scorer = None
  346. demo(scorer, compare_scorer)
  347. __all__ = [
  348. "BigramCollocationFinder",
  349. "TrigramCollocationFinder",
  350. "QuadgramCollocationFinder",
  351. ]