template.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. # -*- coding: utf-8 -*-
  2. # Natural Language Toolkit: Transformation-based learning
  3. #
  4. # Copyright (C) 2001-2019 NLTK Project
  5. # Author: Marcus Uneson <marcus.uneson@gmail.com>
  6. # based on previous (nltk2) version by
  7. # Christopher Maloof, Edward Loper, Steven Bird
  8. # URL: <http://nltk.org/>
  9. # For license information, see LICENSE.TXT
  10. from __future__ import print_function
  11. from abc import ABCMeta, abstractmethod
  12. from six import add_metaclass
  13. import itertools as it
  14. from nltk.tbl.feature import Feature
  15. from nltk.tbl.rule import Rule
  16. @add_metaclass(ABCMeta)
  17. class BrillTemplateI(object):
  18. """
  19. An interface for generating lists of transformational rules that
  20. apply at given sentence positions. ``BrillTemplateI`` is used by
  21. ``Brill`` training algorithms to generate candidate rules.
  22. """
  23. @abstractmethod
  24. def applicable_rules(self, tokens, i, correctTag):
  25. """
  26. Return a list of the transformational rules that would correct
  27. the *i*th subtoken's tag in the given token. In particular,
  28. return a list of zero or more rules that would change
  29. *tokens*[i][1] to *correctTag*, if applied to *token*[i].
  30. If the *i*th token already has the correct tag (i.e., if
  31. tagged_tokens[i][1] == correctTag), then
  32. ``applicable_rules()`` should return the empty list.
  33. :param tokens: The tagged tokens being tagged.
  34. :type tokens: list(tuple)
  35. :param i: The index of the token whose tag should be corrected.
  36. :type i: int
  37. :param correctTag: The correct tag for the *i*th token.
  38. :type correctTag: any
  39. :rtype: list(BrillRule)
  40. """
  41. @abstractmethod
  42. def get_neighborhood(self, token, index):
  43. """
  44. Returns the set of indices *i* such that
  45. ``applicable_rules(token, i, ...)`` depends on the value of
  46. the *index*th token of *token*.
  47. This method is used by the "fast" Brill tagger trainer.
  48. :param token: The tokens being tagged.
  49. :type token: list(tuple)
  50. :param index: The index whose neighborhood should be returned.
  51. :type index: int
  52. :rtype: set
  53. """
  54. class Template(BrillTemplateI):
  55. """
  56. A tbl Template that generates a list of L{Rule}s that apply at a given sentence
  57. position. In particular, each C{Template} is parameterized by a list of
  58. independent features (a combination of a specific
  59. property to extract and a list C{L} of relative positions at which to extract
  60. it) and generates all Rules that:
  61. - use the given features, each at its own independent position; and
  62. - are applicable to the given token.
  63. """
  64. ALLTEMPLATES = []
  65. # record a unique id of form "001", for each template created
  66. # _ids = it.count(0)
  67. def __init__(self, *features):
  68. """
  69. Construct a Template for generating Rules.
  70. Takes a list of Features. A C{Feature} is a combination
  71. of a specific property and its relative positions and should be
  72. a subclass of L{nltk.tbl.feature.Feature}.
  73. An alternative calling convention (kept for backwards compatibility,
  74. but less expressive as it only permits one feature type) is
  75. Template(Feature, (start1, end1), (start2, end2), ...)
  76. In new code, that would be better written
  77. Template(Feature(start1, end1), Feature(start2, end2), ...)
  78. #For instance, importing some features
  79. >>> from nltk.tbl.template import Template
  80. >>> from nltk.tag.brill import Word, Pos
  81. #create some features
  82. >>> wfeat1, wfeat2, pfeat = (Word([-1]), Word([1,2]), Pos([-2,-1]))
  83. #Create a single-feature template
  84. >>> Template(wfeat1)
  85. Template(Word([-1]))
  86. #or a two-feature one
  87. >>> Template(wfeat1, wfeat2)
  88. Template(Word([-1]),Word([1, 2]))
  89. #or a three-feature one with two different feature types
  90. >>> Template(wfeat1, wfeat2, pfeat)
  91. Template(Word([-1]),Word([1, 2]),Pos([-2, -1]))
  92. #deprecated api: Feature subclass, followed by list of (start,end) pairs
  93. #(permits only a single Feature)
  94. >>> Template(Word, (-2,-1), (0,0))
  95. Template(Word([-2, -1]),Word([0]))
  96. #incorrect specification raises TypeError
  97. >>> Template(Word, (-2,-1), Pos, (0,0))
  98. Traceback (most recent call last):
  99. File "<stdin>", line 1, in <module>
  100. File "nltk/tag/tbl/template.py", line 143, in __init__
  101. raise TypeError(
  102. TypeError: expected either Feature1(args), Feature2(args), ... or Feature, (start1, end1), (start2, end2), ...
  103. :type features: list of Features
  104. :param features: the features to build this Template on
  105. """
  106. # determine the calling form: either
  107. # Template(Feature, args1, [args2, ...)]
  108. # Template(Feature1(args), Feature2(args), ...)
  109. if all(isinstance(f, Feature) for f in features):
  110. self._features = features
  111. elif issubclass(features[0], Feature) and all(
  112. isinstance(a, tuple) for a in features[1:]
  113. ):
  114. self._features = [features[0](*tp) for tp in features[1:]]
  115. else:
  116. raise TypeError(
  117. "expected either Feature1(args), Feature2(args), ... or Feature, (start1, end1), (start2, end2), ..."
  118. )
  119. self.id = "{0:03d}".format(len(self.ALLTEMPLATES))
  120. self.ALLTEMPLATES.append(self)
  121. def __repr__(self):
  122. return "%s(%s)" % (
  123. self.__class__.__name__,
  124. ",".join([str(f) for f in self._features]),
  125. )
  126. def applicable_rules(self, tokens, index, correct_tag):
  127. if tokens[index][1] == correct_tag:
  128. return []
  129. # For each of this Template's features, find the conditions
  130. # that are applicable for the given token.
  131. # Then, generate one Rule for each combination of features
  132. # (the crossproduct of the conditions).
  133. applicable_conditions = self._applicable_conditions(tokens, index)
  134. xs = list(it.product(*applicable_conditions))
  135. return [Rule(self.id, tokens[index][1], correct_tag, tuple(x)) for x in xs]
  136. def _applicable_conditions(self, tokens, index):
  137. """
  138. :returns: A set of all conditions for rules
  139. that are applicable to C{tokens[index]}.
  140. """
  141. conditions = []
  142. for feature in self._features:
  143. conditions.append([])
  144. for pos in feature.positions:
  145. if not (0 <= index + pos < len(tokens)):
  146. continue
  147. value = feature.extract_property(tokens, index + pos)
  148. conditions[-1].append((feature, value))
  149. return conditions
  150. def get_neighborhood(self, tokens, index):
  151. # inherit docs from BrillTemplateI
  152. # applicable_rules(tokens, index, ...) depends on index.
  153. neighborhood = set([index]) # set literal for python 2.7+
  154. # applicable_rules(tokens, i, ...) depends on index if
  155. # i+start < index <= i+end.
  156. allpositions = [0] + [p for feat in self._features for p in feat.positions]
  157. start, end = min(allpositions), max(allpositions)
  158. s = max(0, index + (-end))
  159. e = min(index + (-start) + 1, len(tokens))
  160. for i in range(s, e):
  161. neighborhood.add(i)
  162. return neighborhood
  163. @classmethod
  164. def expand(cls, featurelists, combinations=None, skipintersecting=True):
  165. """
  166. Factory method to mass generate Templates from a list L of lists of Features.
  167. #With combinations=(k1, k2), the function will in all possible ways choose k1 ... k2
  168. #of the sublists in L; it will output all Templates formed by the Cartesian product
  169. #of this selection, with duplicates and other semantically equivalent
  170. #forms removed. Default for combinations is (1, len(L)).
  171. The feature lists may have been specified
  172. manually, or generated from Feature.expand(). For instance,
  173. >>> from nltk.tbl.template import Template
  174. >>> from nltk.tag.brill import Word, Pos
  175. #creating some features
  176. >>> (wd_0, wd_01) = (Word([0]), Word([0,1]))
  177. >>> (pos_m2, pos_m33) = (Pos([-2]), Pos([3-2,-1,0,1,2,3]))
  178. >>> list(Template.expand([[wd_0], [pos_m2]]))
  179. [Template(Word([0])), Template(Pos([-2])), Template(Pos([-2]),Word([0]))]
  180. >>> list(Template.expand([[wd_0, wd_01], [pos_m2]]))
  181. [Template(Word([0])), Template(Word([0, 1])), Template(Pos([-2])), Template(Pos([-2]),Word([0])), Template(Pos([-2]),Word([0, 1]))]
  182. #note: with Feature.expand(), it is very easy to generate more templates
  183. #than your system can handle -- for instance,
  184. >>> wordtpls = Word.expand([-2,-1,0,1], [1,2], excludezero=False)
  185. >>> len(wordtpls)
  186. 7
  187. >>> postpls = Pos.expand([-3,-2,-1,0,1,2], [1,2,3], excludezero=True)
  188. >>> len(postpls)
  189. 9
  190. #and now the Cartesian product of all non-empty combinations of two wordtpls and
  191. #two postpls, with semantic equivalents removed
  192. >>> templates = list(Template.expand([wordtpls, wordtpls, postpls, postpls]))
  193. >>> len(templates)
  194. 713
  195. will return a list of eight templates
  196. Template(Word([0])),
  197. Template(Word([0, 1])),
  198. Template(Pos([-2])),
  199. Template(Pos([-1])),
  200. Template(Pos([-2]),Word([0])),
  201. Template(Pos([-1]),Word([0])),
  202. Template(Pos([-2]),Word([0, 1])),
  203. Template(Pos([-1]),Word([0, 1]))]
  204. #Templates where one feature is a subset of another, such as
  205. #Template(Word([0,1]), Word([1]), will not appear in the output.
  206. #By default, this non-subset constraint is tightened to disjointness:
  207. #Templates of type Template(Word([0,1]), Word([1,2]) will also be filtered out.
  208. #With skipintersecting=False, then such Templates are allowed
  209. WARNING: this method makes it very easy to fill all your memory when training
  210. generated templates on any real-world corpus
  211. :param featurelists: lists of Features, whose Cartesian product will return a set of Templates
  212. :type featurelists: list of (list of Features)
  213. :param combinations: given n featurelists: if combinations=k, all generated Templates will have
  214. k features; if combinations=(k1,k2) they will have k1..k2 features; if None, defaults to 1..n
  215. :type combinations: None, int, or (int, int)
  216. :param skipintersecting: if True, do not output intersecting Templates (non-disjoint positions for some feature)
  217. :type skipintersecting: bool
  218. :returns: generator of Templates
  219. """
  220. def nonempty_powerset(xs): # xs is a list
  221. # itertools docnonempty_powerset([1,2,3]) --> (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)
  222. # find the correct tuple given combinations, one of {None, k, (k1,k2)}
  223. k = combinations # for brevity
  224. combrange = (
  225. (1, len(xs) + 1)
  226. if k is None
  227. else (k, k + 1) # n over 1 .. n over n (all non-empty combinations)
  228. if isinstance(k, int)
  229. else (k[0], k[1] + 1) # n over k (only
  230. ) # n over k1, n over k1+1... n over k2
  231. return it.chain.from_iterable(
  232. it.combinations(xs, r) for r in range(*combrange)
  233. )
  234. seentemplates = set()
  235. for picks in nonempty_powerset(featurelists):
  236. for pick in it.product(*picks):
  237. if any(
  238. i != j and x.issuperset(y)
  239. for (i, x) in enumerate(pick)
  240. for (j, y) in enumerate(pick)
  241. ):
  242. continue
  243. if skipintersecting and any(
  244. i != j and x.intersects(y)
  245. for (i, x) in enumerate(pick)
  246. for (j, y) in enumerate(pick)
  247. ):
  248. continue
  249. thistemplate = cls(*sorted(pick))
  250. strpick = str(thistemplate)
  251. #!!FIXME --this is hackish
  252. if strpick in seentemplates: # already added
  253. cls._poptemplate()
  254. continue
  255. seentemplates.add(strpick)
  256. yield thistemplate
  257. @classmethod
  258. def _cleartemplates(cls):
  259. cls.ALLTEMPLATES = []
  260. @classmethod
  261. def _poptemplate(cls):
  262. return cls.ALLTEMPLATES.pop() if cls.ALLTEMPLATES else None