collocations.doctest 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. .. Copyright (C) 2001-2019 NLTK Project
  2. .. For license information, see LICENSE.TXT
  3. ==============
  4. Collocations
  5. ==============
  6. Overview
  7. ~~~~~~~~
  8. Collocations are expressions of multiple words which commonly co-occur. For
  9. example, the top ten bigram collocations in Genesis are listed below, as
  10. measured using Pointwise Mutual Information.
  11. >>> import nltk
  12. >>> from nltk.collocations import *
  13. >>> bigram_measures = nltk.collocations.BigramAssocMeasures()
  14. >>> trigram_measures = nltk.collocations.TrigramAssocMeasures()
  15. >>> fourgram_measures = nltk.collocations.QuadgramAssocMeasures()
  16. >>> finder = BigramCollocationFinder.from_words(
  17. ... nltk.corpus.genesis.words('english-web.txt'))
  18. >>> finder.nbest(bigram_measures.pmi, 10) # doctest: +NORMALIZE_WHITESPACE
  19. [(u'Allon', u'Bacuth'), (u'Ashteroth', u'Karnaim'), (u'Ben', u'Ammi'),
  20. (u'En', u'Mishpat'), (u'Jegar', u'Sahadutha'), (u'Salt', u'Sea'),
  21. (u'Whoever', u'sheds'), (u'appoint', u'overseers'), (u'aromatic', u'resin'),
  22. (u'cutting', u'instrument')]
  23. While these words are highly collocated, the expressions are also very
  24. infrequent. Therefore it is useful to apply filters, such as ignoring all
  25. bigrams which occur less than three times in the corpus:
  26. >>> finder.apply_freq_filter(3)
  27. >>> finder.nbest(bigram_measures.pmi, 10) # doctest: +NORMALIZE_WHITESPACE
  28. [(u'Beer', u'Lahai'), (u'Lahai', u'Roi'), (u'gray', u'hairs'),
  29. (u'Most', u'High'), (u'ewe', u'lambs'), (u'many', u'colors'),
  30. (u'burnt', u'offering'), (u'Paddan', u'Aram'), (u'east', u'wind'),
  31. (u'living', u'creature')]
  32. We may similarly find collocations among tagged words:
  33. >>> finder = BigramCollocationFinder.from_words(
  34. ... nltk.corpus.brown.tagged_words('ca01', tagset='universal'))
  35. >>> finder.nbest(bigram_measures.pmi, 5) # doctest: +NORMALIZE_WHITESPACE
  36. [(('1,119', 'NUM'), ('votes', 'NOUN')),
  37. (('1962', 'NUM'), ("governor's", 'NOUN')),
  38. (('637', 'NUM'), ('E.', 'NOUN')),
  39. (('Alpharetta', 'NOUN'), ('prison', 'NOUN')),
  40. (('Bar', 'NOUN'), ('Association', 'NOUN'))]
  41. Or tags alone:
  42. >>> finder = BigramCollocationFinder.from_words(t for w, t in
  43. ... nltk.corpus.brown.tagged_words('ca01', tagset='universal'))
  44. >>> finder.nbest(bigram_measures.pmi, 10) # doctest: +NORMALIZE_WHITESPACE
  45. [('PRT', 'VERB'), ('PRON', 'VERB'), ('ADP', 'DET'), ('.', 'PRON'), ('DET', 'ADJ'),
  46. ('CONJ', 'PRON'), ('ADP', 'NUM'), ('NUM', '.'), ('ADV', 'ADV'), ('VERB', 'ADV')]
  47. Or spanning intervening words:
  48. >>> finder = BigramCollocationFinder.from_words(
  49. ... nltk.corpus.genesis.words('english-web.txt'),
  50. ... window_size = 20)
  51. >>> finder.apply_freq_filter(2)
  52. >>> ignored_words = nltk.corpus.stopwords.words('english')
  53. >>> finder.apply_word_filter(lambda w: len(w) < 3 or w.lower() in ignored_words)
  54. >>> finder.nbest(bigram_measures.likelihood_ratio, 10) # doctest: +NORMALIZE_WHITESPACE
  55. [(u'chief', u'chief'), (u'became', u'father'), (u'years', u'became'),
  56. (u'hundred', u'years'), (u'lived', u'became'), (u'king', u'king'),
  57. (u'lived', u'years'), (u'became', u'became'), (u'chief', u'chiefs'),
  58. (u'hundred', u'became')]
  59. Finders
  60. ~~~~~~~
  61. The collocations package provides collocation finders which by default
  62. consider all ngrams in a text as candidate collocations:
  63. >>> text = "I do not like green eggs and ham, I do not like them Sam I am!"
  64. >>> tokens = nltk.wordpunct_tokenize(text)
  65. >>> finder = BigramCollocationFinder.from_words(tokens)
  66. >>> scored = finder.score_ngrams(bigram_measures.raw_freq)
  67. >>> sorted(bigram for bigram, score in scored) # doctest: +NORMALIZE_WHITESPACE
  68. [(',', 'I'), ('I', 'am'), ('I', 'do'), ('Sam', 'I'), ('am', '!'),
  69. ('and', 'ham'), ('do', 'not'), ('eggs', 'and'), ('green', 'eggs'),
  70. ('ham', ','), ('like', 'green'), ('like', 'them'), ('not', 'like'),
  71. ('them', 'Sam')]
  72. We could otherwise construct the collocation finder from manually-derived
  73. FreqDists:
  74. >>> word_fd = nltk.FreqDist(tokens)
  75. >>> bigram_fd = nltk.FreqDist(nltk.bigrams(tokens))
  76. >>> finder = BigramCollocationFinder(word_fd, bigram_fd)
  77. >>> scored == finder.score_ngrams(bigram_measures.raw_freq)
  78. True
  79. A similar interface is provided for trigrams:
  80. >>> finder = TrigramCollocationFinder.from_words(tokens)
  81. >>> scored = finder.score_ngrams(trigram_measures.raw_freq)
  82. >>> set(trigram for trigram, score in scored) == set(nltk.trigrams(tokens))
  83. True
  84. We may want to select only the top n results:
  85. >>> sorted(finder.nbest(trigram_measures.raw_freq, 2))
  86. [('I', 'do', 'not'), ('do', 'not', 'like')]
  87. Alternatively, we can select those above a minimum score value:
  88. >>> sorted(finder.above_score(trigram_measures.raw_freq,
  89. ... 1.0 / len(tuple(nltk.trigrams(tokens)))))
  90. [('I', 'do', 'not'), ('do', 'not', 'like')]
  91. Now spanning intervening words:
  92. >>> finder = TrigramCollocationFinder.from_words(tokens)
  93. >>> finder = TrigramCollocationFinder.from_words(tokens, window_size=4)
  94. >>> sorted(finder.nbest(trigram_measures.raw_freq, 4))
  95. [('I', 'do', 'like'), ('I', 'do', 'not'), ('I', 'not', 'like'), ('do', 'not', 'like')]
  96. A closer look at the finder's ngram frequencies:
  97. >>> sorted(finder.ngram_fd.items(), key=lambda t: (-t[1], t[0]))[:10] # doctest: +NORMALIZE_WHITESPACE
  98. [(('I', 'do', 'like'), 2), (('I', 'do', 'not'), 2), (('I', 'not', 'like'), 2),
  99. (('do', 'not', 'like'), 2), ((',', 'I', 'do'), 1), ((',', 'I', 'not'), 1),
  100. ((',', 'do', 'not'), 1), (('I', 'am', '!'), 1), (('Sam', 'I', '!'), 1),
  101. (('Sam', 'I', 'am'), 1)]
  102. A similar interface is provided for fourgrams:
  103. >>> finder_4grams = QuadgramCollocationFinder.from_words(tokens)
  104. >>> scored_4grams = finder_4grams.score_ngrams(fourgram_measures.raw_freq)
  105. >>> set(fourgram for fourgram, score in scored_4grams) == set(nltk.ngrams(tokens, n=4))
  106. True
  107. Filtering candidates
  108. ~~~~~~~~~~~~~~~~~~~~
  109. All the ngrams in a text are often too many to be useful when finding
  110. collocations. It is generally useful to remove some words or punctuation,
  111. and to require a minimum frequency for candidate collocations.
  112. Given our sample text above, if we remove all trigrams containing personal
  113. pronouns from candidature, score_ngrams should return 6 less results, and
  114. 'do not like' will be the only candidate which occurs more than once:
  115. >>> finder = TrigramCollocationFinder.from_words(tokens)
  116. >>> len(finder.score_ngrams(trigram_measures.raw_freq))
  117. 14
  118. >>> finder.apply_word_filter(lambda w: w in ('I', 'me'))
  119. >>> len(finder.score_ngrams(trigram_measures.raw_freq))
  120. 8
  121. >>> sorted(finder.above_score(trigram_measures.raw_freq,
  122. ... 1.0 / len(tuple(nltk.trigrams(tokens)))))
  123. [('do', 'not', 'like')]
  124. Sometimes a filter is a function on the whole ngram, rather than each word,
  125. such as if we may permit 'and' to appear in the middle of a trigram, but
  126. not on either edge:
  127. >>> finder.apply_ngram_filter(lambda w1, w2, w3: 'and' in (w1, w3))
  128. >>> len(finder.score_ngrams(trigram_measures.raw_freq))
  129. 6
  130. Finally, it is often important to remove low frequency candidates, as we
  131. lack sufficient evidence about their significance as collocations:
  132. >>> finder.apply_freq_filter(2)
  133. >>> len(finder.score_ngrams(trigram_measures.raw_freq))
  134. 1
  135. Association measures
  136. ~~~~~~~~~~~~~~~~~~~~
  137. A number of measures are available to score collocations or other associations.
  138. The arguments to measure functions are marginals of a contingency table, in the
  139. bigram case (n_ii, (n_ix, n_xi), n_xx)::
  140. w1 ~w1
  141. ------ ------
  142. w2 | n_ii | n_oi | = n_xi
  143. ------ ------
  144. ~w2 | n_io | n_oo |
  145. ------ ------
  146. = n_ix TOTAL = n_xx
  147. We test their calculation using some known values presented in Manning and
  148. Schutze's text and other papers.
  149. Student's t: examples from Manning and Schutze 5.3.2
  150. >>> print('%0.4f' % bigram_measures.student_t(8, (15828, 4675), 14307668))
  151. 0.9999
  152. >>> print('%0.4f' % bigram_measures.student_t(20, (42, 20), 14307668))
  153. 4.4721
  154. Chi-square: examples from Manning and Schutze 5.3.3
  155. >>> print('%0.2f' % bigram_measures.chi_sq(8, (15828, 4675), 14307668))
  156. 1.55
  157. >>> print('%0.0f' % bigram_measures.chi_sq(59, (67, 65), 571007))
  158. 456400
  159. Likelihood ratios: examples from Dunning, CL, 1993
  160. >>> print('%0.2f' % bigram_measures.likelihood_ratio(110, (2552, 221), 31777))
  161. 270.72
  162. >>> print('%0.2f' % bigram_measures.likelihood_ratio(8, (13, 32), 31777))
  163. 95.29
  164. Pointwise Mutual Information: examples from Manning and Schutze 5.4
  165. >>> print('%0.2f' % bigram_measures.pmi(20, (42, 20), 14307668))
  166. 18.38
  167. >>> print('%0.2f' % bigram_measures.pmi(20, (15019, 15629), 14307668))
  168. 0.29
  169. TODO: Find authoritative results for trigrams.
  170. Using contingency table values
  171. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  172. While frequency counts make marginals readily available for collocation
  173. finding, it is common to find published contingency table values. The
  174. collocations package therefore provides a wrapper, ContingencyMeasures, which
  175. wraps an association measures class, providing association measures which
  176. take contingency values as arguments, (n_ii, n_io, n_oi, n_oo) in the
  177. bigram case.
  178. >>> from nltk.metrics import ContingencyMeasures
  179. >>> cont_bigram_measures = ContingencyMeasures(bigram_measures)
  180. >>> print('%0.2f' % cont_bigram_measures.likelihood_ratio(8, 5, 24, 31740))
  181. 95.29
  182. >>> print('%0.2f' % cont_bigram_measures.chi_sq(8, 15820, 4667, 14287173))
  183. 1.55
  184. Ranking and correlation
  185. ~~~~~~~~~~~~~~~~~~~~~~~
  186. It is useful to consider the results of finding collocations as a ranking, and
  187. the rankings output using different association measures can be compared using
  188. the Spearman correlation coefficient.
  189. Ranks can be assigned to a sorted list of results trivially by assigning
  190. strictly increasing ranks to each result:
  191. >>> from nltk.metrics.spearman import *
  192. >>> results_list = ['item1', 'item2', 'item3', 'item4', 'item5']
  193. >>> print(list(ranks_from_sequence(results_list)))
  194. [('item1', 0), ('item2', 1), ('item3', 2), ('item4', 3), ('item5', 4)]
  195. If scores are available for each result, we may allow sufficiently similar
  196. results (differing by no more than rank_gap) to be assigned the same rank:
  197. >>> results_scored = [('item1', 50.0), ('item2', 40.0), ('item3', 38.0),
  198. ... ('item4', 35.0), ('item5', 14.0)]
  199. >>> print(list(ranks_from_scores(results_scored, rank_gap=5)))
  200. [('item1', 0), ('item2', 1), ('item3', 1), ('item4', 1), ('item5', 4)]
  201. The Spearman correlation coefficient gives a number from -1.0 to 1.0 comparing
  202. two rankings. A coefficient of 1.0 indicates identical rankings; -1.0 indicates
  203. exact opposite rankings.
  204. >>> print('%0.1f' % spearman_correlation(
  205. ... ranks_from_sequence(results_list),
  206. ... ranks_from_sequence(results_list)))
  207. 1.0
  208. >>> print('%0.1f' % spearman_correlation(
  209. ... ranks_from_sequence(reversed(results_list)),
  210. ... ranks_from_sequence(results_list)))
  211. -1.0
  212. >>> results_list2 = ['item2', 'item3', 'item1', 'item5', 'item4']
  213. >>> print('%0.1f' % spearman_correlation(
  214. ... ranks_from_sequence(results_list),
  215. ... ranks_from_sequence(results_list2)))
  216. 0.6
  217. >>> print('%0.1f' % spearman_correlation(
  218. ... ranks_from_sequence(reversed(results_list)),
  219. ... ranks_from_sequence(results_list2)))
  220. -0.6