You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

514 lines
20 KiB

4 years ago
  1. # coding: utf8
  2. # cython: profile=True
  3. from __future__ import unicode_literals
  4. import numpy
  5. import dill
  6. from collections import OrderedDict
  7. from thinc.neural.util import get_array_module
  8. from .lexeme cimport EMPTY_LEXEME
  9. from .lexeme cimport Lexeme
  10. from .strings cimport hash_string
  11. from .typedefs cimport attr_t
  12. from .tokens.token cimport Token
  13. from .attrs cimport PROB, LANG, ORTH, TAG
  14. from .structs cimport SerializedLexemeC
  15. from .compat import copy_reg, basestring_
  16. from .errors import Errors
  17. from .lemmatizer import Lemmatizer
  18. from .attrs import intify_attrs
  19. from .vectors import Vectors
  20. from ._ml import link_vectors_to_models
  21. from . import util
  22. cdef class Vocab:
  23. """A look-up table that allows you to access `Lexeme` objects. The `Vocab`
  24. instance also provides access to the `StringStore`, and owns underlying
  25. C-data that is shared between `Doc` objects.
  26. """
  27. def __init__(self, lex_attr_getters=None, tag_map=None, lemmatizer=None,
  28. strings=tuple(), oov_prob=-20., **deprecated_kwargs):
  29. """Create the vocabulary.
  30. lex_attr_getters (dict): A dictionary mapping attribute IDs to
  31. functions to compute them. Defaults to `None`.
  32. tag_map (dict): Dictionary mapping fine-grained tags to coarse-grained
  33. parts-of-speech, and optionally morphological attributes.
  34. lemmatizer (object): A lemmatizer. Defaults to `None`.
  35. strings (StringStore): StringStore that maps strings to integers, and
  36. vice versa.
  37. RETURNS (Vocab): The newly constructed object.
  38. """
  39. lex_attr_getters = lex_attr_getters if lex_attr_getters is not None else {}
  40. tag_map = tag_map if tag_map is not None else {}
  41. if lemmatizer in (None, True, False):
  42. lemmatizer = Lemmatizer({}, {}, {})
  43. self.cfg = {'oov_prob': oov_prob}
  44. self.mem = Pool()
  45. self._by_hash = PreshMap()
  46. self._by_orth = PreshMap()
  47. self.strings = StringStore()
  48. self.length = 0
  49. if strings:
  50. for string in strings:
  51. _ = self[string]
  52. self.lex_attr_getters = lex_attr_getters
  53. self.morphology = Morphology(self.strings, tag_map, lemmatizer)
  54. self.vectors = Vectors()
  55. property lang:
  56. def __get__(self):
  57. langfunc = None
  58. if self.lex_attr_getters:
  59. langfunc = self.lex_attr_getters.get(LANG, None)
  60. return langfunc('_') if langfunc else ''
  61. def __len__(self):
  62. """The current number of lexemes stored.
  63. RETURNS (int): The current number of lexemes stored.
  64. """
  65. return self.length
  66. def add_flag(self, flag_getter, int flag_id=-1):
  67. """Set a new boolean flag to words in the vocabulary.
  68. The flag_getter function will be called over the words currently in the
  69. vocab, and then applied to new words as they occur. You'll then be able
  70. to access the flag value on each token using token.check_flag(flag_id).
  71. See also: `Lexeme.set_flag`, `Lexeme.check_flag`, `Token.set_flag`,
  72. `Token.check_flag`.
  73. flag_getter (callable): A function `f(unicode) -> bool`, to get the
  74. flag value.
  75. flag_id (int): An integer between 1 and 63 (inclusive), specifying
  76. the bit at which the flag will be stored. If -1, the lowest
  77. available bit will be chosen.
  78. RETURNS (int): The integer ID by which the flag value can be checked.
  79. EXAMPLE:
  80. >>> my_product_getter = lambda text: text in ['spaCy', 'dislaCy']
  81. >>> MY_PRODUCT = nlp.vocab.add_flag(my_product_getter)
  82. >>> doc = nlp(u'I like spaCy')
  83. >>> assert doc[2].check_flag(MY_PRODUCT) == True
  84. """
  85. if flag_id == -1:
  86. for bit in range(1, 64):
  87. if bit not in self.lex_attr_getters:
  88. flag_id = bit
  89. break
  90. else:
  91. raise ValueError(Errors.E062)
  92. elif flag_id >= 64 or flag_id < 1:
  93. raise ValueError(Errors.E063.format(value=flag_id))
  94. for lex in self:
  95. lex.set_flag(flag_id, flag_getter(lex.orth_))
  96. self.lex_attr_getters[flag_id] = flag_getter
  97. return flag_id
  98. cdef const LexemeC* get(self, Pool mem, unicode string) except NULL:
  99. """Get a pointer to a `LexemeC` from the lexicon, creating a new
  100. `Lexeme` if necessary using memory acquired from the given pool. If the
  101. pool is the lexicon's own memory, the lexeme is saved in the lexicon.
  102. """
  103. if string == u'':
  104. return &EMPTY_LEXEME
  105. cdef LexemeC* lex
  106. cdef hash_t key = hash_string(string)
  107. lex = <LexemeC*>self._by_hash.get(key)
  108. cdef size_t addr
  109. if lex != NULL:
  110. if lex.orth != self.strings[string]:
  111. raise KeyError(Errors.E064.format(string=lex.orth,
  112. orth=self.strings[string],
  113. orth_id=string))
  114. return lex
  115. else:
  116. return self._new_lexeme(mem, string)
  117. cdef const LexemeC* get_by_orth(self, Pool mem, attr_t orth) except NULL:
  118. """Get a pointer to a `LexemeC` from the lexicon, creating a new
  119. `Lexeme` if necessary using memory acquired from the given pool. If the
  120. pool is the lexicon's own memory, the lexeme is saved in the lexicon.
  121. """
  122. if orth == 0:
  123. return &EMPTY_LEXEME
  124. cdef LexemeC* lex
  125. lex = <LexemeC*>self._by_orth.get(orth)
  126. if lex != NULL:
  127. return lex
  128. else:
  129. return self._new_lexeme(mem, self.strings[orth])
  130. cdef const LexemeC* _new_lexeme(self, Pool mem, unicode string) except NULL:
  131. cdef hash_t key
  132. if len(string) < 3 or self.length < 10000:
  133. mem = self.mem
  134. cdef bint is_oov = mem is not self.mem
  135. lex = <LexemeC*>mem.alloc(sizeof(LexemeC), 1)
  136. lex.orth = self.strings.add(string)
  137. lex.length = len(string)
  138. if self.vectors is not None:
  139. lex.id = self.vectors.key2row.get(lex.orth, 0)
  140. else:
  141. lex.id = 0
  142. if self.lex_attr_getters is not None:
  143. for attr, func in self.lex_attr_getters.items():
  144. value = func(string)
  145. if isinstance(value, unicode):
  146. value = self.strings.add(value)
  147. if attr == PROB:
  148. lex.prob = value
  149. elif value is not None:
  150. Lexeme.set_struct_attr(lex, attr, value)
  151. if not is_oov:
  152. key = hash_string(string)
  153. self._add_lex_to_vocab(key, lex)
  154. if lex == NULL:
  155. raise ValueError(Errors.E085.format(string=string))
  156. return lex
  157. cdef int _add_lex_to_vocab(self, hash_t key, const LexemeC* lex) except -1:
  158. self._by_hash.set(key, <void*>lex)
  159. self._by_orth.set(lex.orth, <void*>lex)
  160. self.length += 1
  161. def __contains__(self, key):
  162. """Check whether the string or int key has an entry in the vocabulary.
  163. string (unicode): The ID string.
  164. RETURNS (bool) Whether the string has an entry in the vocabulary.
  165. """
  166. cdef hash_t int_key
  167. if isinstance(key, bytes):
  168. int_key = hash_string(key.decode('utf8'))
  169. elif isinstance(key, unicode):
  170. int_key = hash_string(key)
  171. else:
  172. int_key = key
  173. lex = self._by_hash.get(int_key)
  174. return lex is not NULL
  175. def __iter__(self):
  176. """Iterate over the lexemes in the vocabulary.
  177. YIELDS (Lexeme): An entry in the vocabulary.
  178. """
  179. cdef attr_t key
  180. cdef size_t addr
  181. for key, addr in self._by_orth.items():
  182. lex = Lexeme(self, key)
  183. yield lex
  184. def __getitem__(self, id_or_string):
  185. """Retrieve a lexeme, given an int ID or a unicode string. If a
  186. previously unseen unicode string is given, a new lexeme is created and
  187. stored.
  188. id_or_string (int or unicode): The integer ID of a word, or its unicode
  189. string. If `int >= Lexicon.size`, `IndexError` is raised. If
  190. `id_or_string` is neither an int nor a unicode string, `ValueError`
  191. is raised.
  192. RETURNS (Lexeme): The lexeme indicated by the given ID.
  193. EXAMPLE:
  194. >>> apple = nlp.vocab.strings['apple']
  195. >>> assert nlp.vocab[apple] == nlp.vocab[u'apple']
  196. """
  197. cdef attr_t orth
  198. if isinstance(id_or_string, unicode):
  199. orth = self.strings.add(id_or_string)
  200. else:
  201. orth = id_or_string
  202. return Lexeme(self, orth)
  203. cdef const TokenC* make_fused_token(self, substrings) except NULL:
  204. cdef int i
  205. tokens = <TokenC*>self.mem.alloc(len(substrings) + 1, sizeof(TokenC))
  206. for i, props in enumerate(substrings):
  207. props = intify_attrs(props, strings_map=self.strings,
  208. _do_deprecated=True)
  209. token = &tokens[i]
  210. # Set the special tokens up to have arbitrary attributes
  211. lex = <LexemeC*>self.get_by_orth(self.mem, props[ORTH])
  212. token.lex = lex
  213. if TAG in props:
  214. self.morphology.assign_tag(token, props[TAG])
  215. for attr_id, value in props.items():
  216. Token.set_struct_attr(token, attr_id, value)
  217. Lexeme.set_struct_attr(lex, attr_id, value)
  218. return tokens
  219. @property
  220. def vectors_length(self):
  221. return self.vectors.data.shape[1]
  222. def reset_vectors(self, *, width=None, shape=None):
  223. """Drop the current vector table. Because all vectors must be the same
  224. width, you have to call this to change the size of the vectors.
  225. """
  226. if width is not None and shape is not None:
  227. raise ValueError(Errors.E065.format(width=width, shape=shape))
  228. elif shape is not None:
  229. self.vectors = Vectors(shape=shape)
  230. else:
  231. width = width if width is not None else self.vectors.data.shape[1]
  232. self.vectors = Vectors(shape=(self.vectors.shape[0], width))
  233. def prune_vectors(self, nr_row, batch_size=1024):
  234. """Reduce the current vector table to `nr_row` unique entries. Words
  235. mapped to the discarded vectors will be remapped to the closest vector
  236. among those remaining.
  237. For example, suppose the original table had vectors for the words:
  238. ['sat', 'cat', 'feline', 'reclined']. If we prune the vector table to,
  239. two rows, we would discard the vectors for 'feline' and 'reclined'.
  240. These words would then be remapped to the closest remaining vector
  241. -- so "feline" would have the same vector as "cat", and "reclined"
  242. would have the same vector as "sat".
  243. The similarities are judged by cosine. The original vectors may
  244. be large, so the cosines are calculated in minibatches, to reduce
  245. memory usage.
  246. nr_row (int): The number of rows to keep in the vector table.
  247. batch_size (int): Batch of vectors for calculating the similarities.
  248. Larger batch sizes might be faster, while temporarily requiring
  249. more memory.
  250. RETURNS (dict): A dictionary keyed by removed words mapped to
  251. `(string, score)` tuples, where `string` is the entry the removed
  252. word was mapped to, and `score` the similarity score between the
  253. two words.
  254. """
  255. xp = get_array_module(self.vectors.data)
  256. # Make prob negative so it sorts by rank ascending
  257. # (key2row contains the rank)
  258. priority = [(-lex.prob, self.vectors.key2row[lex.orth], lex.orth)
  259. for lex in self if lex.orth in self.vectors.key2row]
  260. priority.sort()
  261. indices = xp.asarray([i for (prob, i, key) in priority], dtype='i')
  262. keys = xp.asarray([key for (prob, i, key) in priority], dtype='uint64')
  263. keep = xp.ascontiguousarray(self.vectors.data[indices[:nr_row]])
  264. toss = xp.ascontiguousarray(self.vectors.data[indices[nr_row:]])
  265. self.vectors = Vectors(data=keep, keys=keys)
  266. syn_keys, syn_rows, scores = self.vectors.most_similar(toss, batch_size=batch_size)
  267. remap = {}
  268. for i, key in enumerate(keys[nr_row:]):
  269. self.vectors.add(key, row=syn_rows[i])
  270. word = self.strings[key]
  271. synonym = self.strings[syn_keys[i]]
  272. score = scores[i]
  273. remap[word] = (synonym, score)
  274. link_vectors_to_models(self)
  275. return remap
  276. def get_vector(self, orth):
  277. """Retrieve a vector for a word in the vocabulary. Words can be looked
  278. up by string or int ID. If no vectors data is loaded, ValueError is
  279. raised.
  280. RETURNS (numpy.ndarray): A word vector. Size
  281. and shape determined by the `vocab.vectors` instance. Usually, a
  282. numpy ndarray of shape (300,) and dtype float32.
  283. """
  284. if isinstance(orth, basestring_):
  285. orth = self.strings.add(orth)
  286. if orth in self.vectors.key2row:
  287. return self.vectors[orth]
  288. else:
  289. return numpy.zeros((self.vectors_length,), dtype='f')
  290. def set_vector(self, orth, vector):
  291. """Set a vector for a word in the vocabulary. Words can be referenced
  292. by string or int ID.
  293. """
  294. if isinstance(orth, basestring_):
  295. orth = self.strings.add(orth)
  296. if self.vectors.is_full and orth not in self.vectors:
  297. new_rows = max(100, int(self.vectors.shape[0]*1.3))
  298. if self.vectors.shape[1] == 0:
  299. width = vector.size
  300. else:
  301. width = self.vectors.shape[1]
  302. self.vectors.resize((new_rows, width))
  303. lex = self[orth] # Adds worse to vocab
  304. self.vectors.add(orth, vector=vector)
  305. self.vectors.add(orth, vector=vector)
  306. def has_vector(self, orth):
  307. """Check whether a word has a vector. Returns False if no vectors have
  308. been loaded. Words can be looked up by string or int ID."""
  309. if isinstance(orth, basestring_):
  310. orth = self.strings.add(orth)
  311. return orth in self.vectors
  312. def to_disk(self, path, **exclude):
  313. """Save the current state to a directory.
  314. path (unicode or Path): A path to a directory, which will be created if
  315. it doesn't exist. Paths may be either strings or Path-like objects.
  316. """
  317. path = util.ensure_path(path)
  318. if not path.exists():
  319. path.mkdir()
  320. self.strings.to_disk(path / 'strings.json')
  321. with (path / 'lexemes.bin').open('wb') as file_:
  322. file_.write(self.lexemes_to_bytes())
  323. if self.vectors is not None:
  324. self.vectors.to_disk(path)
  325. def from_disk(self, path, **exclude):
  326. """Loads state from a directory. Modifies the object in place and
  327. returns it.
  328. path (unicode or Path): A path to a directory. Paths may be either
  329. strings or `Path`-like objects.
  330. RETURNS (Vocab): The modified `Vocab` object.
  331. """
  332. path = util.ensure_path(path)
  333. self.strings.from_disk(path / 'strings.json')
  334. with (path / 'lexemes.bin').open('rb') as file_:
  335. self.lexemes_from_bytes(file_.read())
  336. if self.vectors is not None:
  337. self.vectors.from_disk(path, exclude='strings.json')
  338. if self.vectors.name is not None:
  339. link_vectors_to_models(self)
  340. return self
  341. def to_bytes(self, **exclude):
  342. """Serialize the current state to a binary string.
  343. **exclude: Named attributes to prevent from being serialized.
  344. RETURNS (bytes): The serialized form of the `Vocab` object.
  345. """
  346. def deserialize_vectors():
  347. if self.vectors is None:
  348. return None
  349. else:
  350. return self.vectors.to_bytes()
  351. getters = OrderedDict((
  352. ('strings', lambda: self.strings.to_bytes()),
  353. ('lexemes', lambda: self.lexemes_to_bytes()),
  354. ('vectors', deserialize_vectors)
  355. ))
  356. return util.to_bytes(getters, exclude)
  357. def from_bytes(self, bytes_data, **exclude):
  358. """Load state from a binary string.
  359. bytes_data (bytes): The data to load from.
  360. **exclude: Named attributes to prevent from being loaded.
  361. RETURNS (Vocab): The `Vocab` object.
  362. """
  363. def serialize_vectors(b):
  364. if self.vectors is None:
  365. return None
  366. else:
  367. return self.vectors.from_bytes(b)
  368. setters = OrderedDict((
  369. ('strings', lambda b: self.strings.from_bytes(b)),
  370. ('lexemes', lambda b: self.lexemes_from_bytes(b)),
  371. ('vectors', lambda b: serialize_vectors(b))
  372. ))
  373. util.from_bytes(bytes_data, setters, exclude)
  374. if self.vectors.name is not None:
  375. link_vectors_to_models(self)
  376. return self
  377. def lexemes_to_bytes(self):
  378. cdef hash_t key
  379. cdef size_t addr
  380. cdef LexemeC* lexeme = NULL
  381. cdef SerializedLexemeC lex_data
  382. cdef int size = 0
  383. for key, addr in self._by_hash.items():
  384. if addr == 0:
  385. continue
  386. size += sizeof(lex_data.data)
  387. byte_string = b'\0' * size
  388. byte_ptr = <unsigned char*>byte_string
  389. cdef int j
  390. cdef int i = 0
  391. for key, addr in self._by_hash.items():
  392. if addr == 0:
  393. continue
  394. lexeme = <LexemeC*>addr
  395. lex_data = Lexeme.c_to_bytes(lexeme)
  396. for j in range(sizeof(lex_data.data)):
  397. byte_ptr[i] = lex_data.data[j]
  398. i += 1
  399. return byte_string
  400. def lexemes_from_bytes(self, bytes bytes_data):
  401. """Load the binary vocabulary data from the given string."""
  402. cdef LexemeC* lexeme
  403. cdef hash_t key
  404. cdef unicode py_str
  405. cdef int i = 0
  406. cdef int j = 0
  407. cdef SerializedLexemeC lex_data
  408. chunk_size = sizeof(lex_data.data)
  409. cdef void* ptr
  410. cdef unsigned char* bytes_ptr = bytes_data
  411. for i in range(0, len(bytes_data), chunk_size):
  412. lexeme = <LexemeC*>self.mem.alloc(1, sizeof(LexemeC))
  413. for j in range(sizeof(lex_data.data)):
  414. lex_data.data[j] = bytes_ptr[i+j]
  415. Lexeme.c_from_bytes(lexeme, lex_data)
  416. ptr = self.strings._map.get(lexeme.orth)
  417. if ptr == NULL:
  418. continue
  419. py_str = self.strings[lexeme.orth]
  420. if self.strings[py_str] != lexeme.orth:
  421. raise ValueError(Errors.E086.format(string=py_str,
  422. orth_id=lexeme.orth,
  423. hash_id=self.strings[py_str]))
  424. key = hash_string(py_str)
  425. self._by_hash.set(key, lexeme)
  426. self._by_orth.set(lexeme.orth, lexeme)
  427. self.length += 1
  428. def _reset_cache(self, keys, strings):
  429. for k in keys:
  430. del self._by_hash[k]
  431. if len(strings) != 0:
  432. self._by_orth = PreshMap()
  433. def pickle_vocab(vocab):
  434. sstore = vocab.strings
  435. vectors = vocab.vectors
  436. morph = vocab.morphology
  437. length = vocab.length
  438. data_dir = vocab.data_dir
  439. lex_attr_getters = dill.dumps(vocab.lex_attr_getters)
  440. lexemes_data = vocab.lexemes_to_bytes()
  441. return (unpickle_vocab,
  442. (sstore, vectors, morph, data_dir, lex_attr_getters, lexemes_data, length))
  443. def unpickle_vocab(sstore, vectors, morphology, data_dir,
  444. lex_attr_getters, bytes lexemes_data, int length):
  445. cdef Vocab vocab = Vocab()
  446. vocab.length = length
  447. vocab.vectors = vectors
  448. vocab.strings = sstore
  449. vocab.morphology = morphology
  450. vocab.data_dir = data_dir
  451. vocab.lex_attr_getters = dill.loads(lex_attr_getters)
  452. vocab.lexemes_from_bytes(lexemes_data)
  453. vocab.length = length
  454. return vocab
  455. copy_reg.pickle(Vocab, pickle_vocab, unpickle_vocab)