2017-04-15 10:05:47 +00:00
|
|
|
# coding: utf8
|
2017-11-15 12:58:03 +00:00
|
|
|
# cython: profile=True
|
2015-07-23 11:24:20 +00:00
|
|
|
from __future__ import unicode_literals
|
|
|
|
|
2017-08-22 17:46:35 +00:00
|
|
|
import numpy
|
2017-10-17 16:17:45 +00:00
|
|
|
import dill
|
2014-12-19 19:54:03 +00:00
|
|
|
|
2017-05-29 11:04:40 +00:00
|
|
|
from collections import OrderedDict
|
2017-10-30 16:59:43 +00:00
|
|
|
from thinc.neural.util import get_array_module
|
2014-12-19 19:54:03 +00:00
|
|
|
from .lexeme cimport EMPTY_LEXEME
|
2015-01-17 05:21:17 +00:00
|
|
|
from .lexeme cimport Lexeme
|
2015-01-11 23:26:22 +00:00
|
|
|
from .strings cimport hash_string
|
2015-01-31 05:38:58 +00:00
|
|
|
from .typedefs cimport attr_t
|
2016-11-25 11:43:24 +00:00
|
|
|
from .tokens.token cimport Token
|
2017-10-27 17:45:19 +00:00
|
|
|
from .attrs cimport PROB, LANG, ORTH, TAG
|
2017-05-17 10:04:50 +00:00
|
|
|
from .structs cimport SerializedLexemeC
|
2016-09-24 13:42:01 +00:00
|
|
|
|
2017-10-27 17:45:19 +00:00
|
|
|
from .compat import copy_reg, basestring_
|
2018-04-03 13:50:31 +00:00
|
|
|
from .errors import Errors
|
2017-04-15 10:05:47 +00:00
|
|
|
from .lemmatizer import Lemmatizer
|
|
|
|
from .attrs import intify_attrs
|
2017-08-19 16:50:16 +00:00
|
|
|
from .vectors import Vectors
|
2017-09-22 14:38:22 +00:00
|
|
|
from ._ml import link_vectors_to_models
|
2017-10-27 19:07:59 +00:00
|
|
|
from . import util
|
2015-10-13 09:04:40 +00:00
|
|
|
|
2014-12-24 06:42:00 +00:00
|
|
|
|
2014-12-19 19:54:03 +00:00
|
|
|
cdef class Vocab:
|
2017-05-20 11:59:31 +00:00
|
|
|
"""A look-up table that allows you to access `Lexeme` objects. The `Vocab`
|
|
|
|
instance also provides access to the `StringStore`, and owns underlying
|
|
|
|
C-data that is shared between `Doc` objects.
|
2017-04-15 09:59:21 +00:00
|
|
|
"""
|
2016-09-25 12:49:53 +00:00
|
|
|
def __init__(self, lex_attr_getters=None, tag_map=None, lemmatizer=None,
|
2017-10-30 15:08:50 +00:00
|
|
|
strings=tuple(), oov_prob=-20., **deprecated_kwargs):
|
2017-05-20 11:59:31 +00:00
|
|
|
"""Create the vocabulary.
|
|
|
|
|
2017-10-27 17:45:19 +00:00
|
|
|
lex_attr_getters (dict): A dictionary mapping attribute IDs to
|
|
|
|
functions to compute them. Defaults to `None`.
|
|
|
|
tag_map (dict): Dictionary mapping fine-grained tags to coarse-grained
|
2017-05-20 11:59:31 +00:00
|
|
|
parts-of-speech, and optionally morphological attributes.
|
|
|
|
lemmatizer (object): A lemmatizer. Defaults to `None`.
|
|
|
|
strings (StringStore): StringStore that maps strings to integers, and
|
|
|
|
vice versa.
|
2017-10-27 17:45:19 +00:00
|
|
|
RETURNS (Vocab): The newly constructed object.
|
2017-04-15 09:59:21 +00:00
|
|
|
"""
|
2016-09-25 12:49:53 +00:00
|
|
|
lex_attr_getters = lex_attr_getters if lex_attr_getters is not None else {}
|
|
|
|
tag_map = tag_map if tag_map is not None else {}
|
|
|
|
if lemmatizer in (None, True, False):
|
2015-09-10 12:49:10 +00:00
|
|
|
lemmatizer = Lemmatizer({}, {}, {})
|
2017-10-30 15:08:50 +00:00
|
|
|
self.cfg = {'oov_prob': oov_prob}
|
2015-09-10 12:49:10 +00:00
|
|
|
self.mem = Pool()
|
|
|
|
self._by_hash = PreshMap()
|
|
|
|
self._by_orth = PreshMap()
|
|
|
|
self.strings = StringStore()
|
2017-06-02 08:57:25 +00:00
|
|
|
self.length = 0
|
2017-03-17 17:29:04 +00:00
|
|
|
if strings:
|
|
|
|
for string in strings:
|
2017-06-02 08:57:06 +00:00
|
|
|
_ = self[string]
|
2016-09-25 12:49:53 +00:00
|
|
|
self.lex_attr_getters = lex_attr_getters
|
2015-09-10 12:49:10 +00:00
|
|
|
self.morphology = Morphology(self.strings, tag_map, lemmatizer)
|
2017-10-31 17:25:08 +00:00
|
|
|
self.vectors = Vectors()
|
2016-12-21 17:04:41 +00:00
|
|
|
|
2016-03-16 14:53:35 +00:00
|
|
|
property lang:
|
|
|
|
def __get__(self):
|
|
|
|
langfunc = None
|
2016-09-25 12:49:53 +00:00
|
|
|
if self.lex_attr_getters:
|
|
|
|
langfunc = self.lex_attr_getters.get(LANG, None)
|
2016-03-16 14:53:35 +00:00
|
|
|
return langfunc('_') if langfunc else ''
|
|
|
|
|
2014-12-19 19:54:03 +00:00
|
|
|
def __len__(self):
|
2017-05-20 11:59:31 +00:00
|
|
|
"""The current number of lexemes stored.
|
|
|
|
|
|
|
|
RETURNS (int): The current number of lexemes stored.
|
2017-04-15 09:59:21 +00:00
|
|
|
"""
|
2015-07-18 20:42:15 +00:00
|
|
|
return self.length
|
2017-05-20 11:59:31 +00:00
|
|
|
|
2016-10-14 10:15:38 +00:00
|
|
|
def add_flag(self, flag_getter, int flag_id=-1):
|
2017-05-20 11:59:31 +00:00
|
|
|
"""Set a new boolean flag to words in the vocabulary.
|
2016-12-21 17:04:41 +00:00
|
|
|
|
2017-05-20 11:59:31 +00:00
|
|
|
The flag_getter function will be called over the words currently in the
|
2016-11-01 11:25:36 +00:00
|
|
|
vocab, and then applied to new words as they occur. You'll then be able
|
2017-10-27 17:45:19 +00:00
|
|
|
to access the flag value on each token using token.check_flag(flag_id).
|
2017-05-20 11:59:31 +00:00
|
|
|
See also: `Lexeme.set_flag`, `Lexeme.check_flag`, `Token.set_flag`,
|
|
|
|
`Token.check_flag`.
|
|
|
|
|
2017-10-27 17:45:19 +00:00
|
|
|
flag_getter (callable): A function `f(unicode) -> bool`, to get the
|
|
|
|
flag value.
|
2017-05-20 11:59:31 +00:00
|
|
|
flag_id (int): An integer between 1 and 63 (inclusive), specifying
|
|
|
|
the bit at which the flag will be stored. If -1, the lowest
|
|
|
|
available bit will be chosen.
|
|
|
|
RETURNS (int): The integer ID by which the flag value can be checked.
|
|
|
|
|
|
|
|
EXAMPLE:
|
2017-10-27 17:45:19 +00:00
|
|
|
>>> my_product_getter = lambda text: text in ['spaCy', 'dislaCy']
|
|
|
|
>>> MY_PRODUCT = nlp.vocab.add_flag(my_product_getter)
|
2017-05-20 11:59:31 +00:00
|
|
|
>>> doc = nlp(u'I like spaCy')
|
|
|
|
>>> assert doc[2].check_flag(MY_PRODUCT) == True
|
2017-04-15 09:59:21 +00:00
|
|
|
"""
|
2016-10-14 10:15:38 +00:00
|
|
|
if flag_id == -1:
|
|
|
|
for bit in range(1, 64):
|
|
|
|
if bit not in self.lex_attr_getters:
|
|
|
|
flag_id = bit
|
|
|
|
break
|
|
|
|
else:
|
2018-04-03 13:50:31 +00:00
|
|
|
raise ValueError(Errors.E062)
|
2016-10-14 10:15:38 +00:00
|
|
|
elif flag_id >= 64 or flag_id < 1:
|
2018-04-03 13:50:31 +00:00
|
|
|
raise ValueError(Errors.E063.format(value=flag_id))
|
2016-10-14 10:15:38 +00:00
|
|
|
for lex in self:
|
|
|
|
lex.set_flag(flag_id, flag_getter(lex.orth_))
|
|
|
|
self.lex_attr_getters[flag_id] = flag_getter
|
|
|
|
return flag_id
|
|
|
|
|
2015-07-22 02:49:39 +00:00
|
|
|
cdef const LexemeC* get(self, Pool mem, unicode string) except NULL:
|
2017-10-27 17:45:19 +00:00
|
|
|
"""Get a pointer to a `LexemeC` from the lexicon, creating a new
|
|
|
|
`Lexeme` if necessary using memory acquired from the given pool. If the
|
|
|
|
pool is the lexicon's own memory, the lexeme is saved in the lexicon.
|
2017-04-15 09:59:21 +00:00
|
|
|
"""
|
2015-07-25 22:18:30 +00:00
|
|
|
if string == u'':
|
|
|
|
return &EMPTY_LEXEME
|
2015-01-11 23:26:22 +00:00
|
|
|
cdef LexemeC* lex
|
2015-07-22 02:49:39 +00:00
|
|
|
cdef hash_t key = hash_string(string)
|
|
|
|
lex = <LexemeC*>self._by_hash.get(key)
|
2015-08-23 18:49:18 +00:00
|
|
|
cdef size_t addr
|
2014-12-19 19:54:03 +00:00
|
|
|
if lex != NULL:
|
2016-09-30 18:20:22 +00:00
|
|
|
if lex.orth != self.strings[string]:
|
2018-04-03 13:50:31 +00:00
|
|
|
raise KeyError(Errors.E064.format(string=lex.orth,
|
|
|
|
orth=self.strings[string],
|
|
|
|
orth_id=string))
|
2014-12-19 19:54:03 +00:00
|
|
|
return lex
|
2015-07-19 23:37:34 +00:00
|
|
|
else:
|
2015-08-22 20:04:34 +00:00
|
|
|
return self._new_lexeme(mem, string)
|
2014-12-19 19:54:03 +00:00
|
|
|
|
2015-07-22 23:18:19 +00:00
|
|
|
cdef const LexemeC* get_by_orth(self, Pool mem, attr_t orth) except NULL:
|
2017-10-27 17:45:19 +00:00
|
|
|
"""Get a pointer to a `LexemeC` from the lexicon, creating a new
|
|
|
|
`Lexeme` if necessary using memory acquired from the given pool. If the
|
|
|
|
pool is the lexicon's own memory, the lexeme is saved in the lexicon.
|
2017-04-15 09:59:21 +00:00
|
|
|
"""
|
2015-07-26 17:26:41 +00:00
|
|
|
if orth == 0:
|
2015-07-26 16:39:27 +00:00
|
|
|
return &EMPTY_LEXEME
|
2015-07-22 23:18:19 +00:00
|
|
|
cdef LexemeC* lex
|
|
|
|
lex = <LexemeC*>self._by_orth.get(orth)
|
|
|
|
if lex != NULL:
|
|
|
|
return lex
|
2015-08-22 20:04:34 +00:00
|
|
|
else:
|
2016-09-30 18:10:30 +00:00
|
|
|
return self._new_lexeme(mem, self.strings[orth])
|
2015-08-22 20:04:34 +00:00
|
|
|
|
|
|
|
cdef const LexemeC* _new_lexeme(self, Pool mem, unicode string) except NULL:
|
2015-08-23 18:49:18 +00:00
|
|
|
cdef hash_t key
|
2016-12-27 20:03:45 +00:00
|
|
|
if len(string) < 3 or self.length < 10000:
|
2016-09-30 18:10:30 +00:00
|
|
|
mem = self.mem
|
2016-12-27 20:03:45 +00:00
|
|
|
cdef bint is_oov = mem is not self.mem
|
2016-09-30 18:10:30 +00:00
|
|
|
lex = <LexemeC*>mem.alloc(sizeof(LexemeC), 1)
|
2017-05-28 13:10:22 +00:00
|
|
|
lex.orth = self.strings.add(string)
|
2015-08-26 17:21:46 +00:00
|
|
|
lex.length = len(string)
|
2017-11-15 13:23:58 +00:00
|
|
|
if self.vectors is not None:
|
|
|
|
lex.id = self.vectors.key2row.get(lex.orth, 0)
|
|
|
|
else:
|
|
|
|
lex.id = 0
|
2016-09-25 12:49:53 +00:00
|
|
|
if self.lex_attr_getters is not None:
|
|
|
|
for attr, func in self.lex_attr_getters.items():
|
2015-08-23 18:49:18 +00:00
|
|
|
value = func(string)
|
|
|
|
if isinstance(value, unicode):
|
2017-05-28 10:36:27 +00:00
|
|
|
value = self.strings.add(value)
|
2015-08-26 17:21:46 +00:00
|
|
|
if attr == PROB:
|
|
|
|
lex.prob = value
|
2016-10-09 10:24:24 +00:00
|
|
|
elif value is not None:
|
2015-08-26 17:21:46 +00:00
|
|
|
Lexeme.set_struct_attr(lex, attr, value)
|
2017-11-15 12:58:03 +00:00
|
|
|
if not is_oov:
|
2015-08-23 18:49:18 +00:00
|
|
|
key = hash_string(string)
|
2015-08-22 20:04:34 +00:00
|
|
|
self._add_lex_to_vocab(key, lex)
|
2018-04-03 13:50:31 +00:00
|
|
|
if lex == NULL:
|
|
|
|
raise ValueError(Errors.E085.format(string=string))
|
2015-07-22 23:18:19 +00:00
|
|
|
return lex
|
|
|
|
|
2015-01-13 13:03:48 +00:00
|
|
|
cdef int _add_lex_to_vocab(self, hash_t key, const LexemeC* lex) except -1:
|
2015-07-18 20:42:15 +00:00
|
|
|
self._by_hash.set(key, <void*>lex)
|
|
|
|
self._by_orth.set(lex.orth, <void*>lex)
|
|
|
|
self.length += 1
|
|
|
|
|
2018-01-23 22:26:47 +00:00
|
|
|
def __contains__(self, key):
|
|
|
|
"""Check whether the string or int key has an entry in the vocabulary.
|
2016-11-01 11:25:36 +00:00
|
|
|
|
2017-05-20 11:59:31 +00:00
|
|
|
string (unicode): The ID string.
|
|
|
|
RETURNS (bool) Whether the string has an entry in the vocabulary.
|
2017-04-15 09:59:21 +00:00
|
|
|
"""
|
2018-01-23 22:26:47 +00:00
|
|
|
cdef hash_t int_key
|
|
|
|
if isinstance(key, bytes):
|
|
|
|
int_key = hash_string(key.decode('utf8'))
|
|
|
|
elif isinstance(key, unicode):
|
|
|
|
int_key = hash_string(key)
|
|
|
|
else:
|
|
|
|
int_key = key
|
|
|
|
lex = self._by_hash.get(int_key)
|
2017-01-11 09:18:22 +00:00
|
|
|
return lex is not NULL
|
2016-03-08 15:49:10 +00:00
|
|
|
|
2015-07-18 20:42:15 +00:00
|
|
|
def __iter__(self):
|
2017-05-20 11:59:31 +00:00
|
|
|
"""Iterate over the lexemes in the vocabulary.
|
2016-11-01 11:25:36 +00:00
|
|
|
|
2017-05-20 11:59:31 +00:00
|
|
|
YIELDS (Lexeme): An entry in the vocabulary.
|
2017-04-15 09:59:21 +00:00
|
|
|
"""
|
2017-10-31 01:00:26 +00:00
|
|
|
cdef attr_t key
|
2015-07-18 20:42:15 +00:00
|
|
|
cdef size_t addr
|
2017-10-31 01:00:26 +00:00
|
|
|
for key, addr in self._by_orth.items():
|
|
|
|
lex = Lexeme(self, key)
|
|
|
|
yield lex
|
2015-01-13 13:03:48 +00:00
|
|
|
|
2017-10-27 17:45:19 +00:00
|
|
|
def __getitem__(self, id_or_string):
|
|
|
|
"""Retrieve a lexeme, given an int ID or a unicode string. If a
|
2017-05-20 11:59:31 +00:00
|
|
|
previously unseen unicode string is given, a new lexeme is created and
|
|
|
|
stored.
|
|
|
|
|
|
|
|
id_or_string (int or unicode): The integer ID of a word, or its unicode
|
|
|
|
string. If `int >= Lexicon.size`, `IndexError` is raised. If
|
|
|
|
`id_or_string` is neither an int nor a unicode string, `ValueError`
|
|
|
|
is raised.
|
|
|
|
RETURNS (Lexeme): The lexeme indicated by the given ID.
|
|
|
|
|
|
|
|
EXAMPLE:
|
|
|
|
>>> apple = nlp.vocab.strings['apple']
|
|
|
|
>>> assert nlp.vocab[apple] == nlp.vocab[u'apple']
|
2017-04-15 09:59:21 +00:00
|
|
|
"""
|
2015-07-18 20:42:15 +00:00
|
|
|
cdef attr_t orth
|
2017-10-31 01:00:26 +00:00
|
|
|
if isinstance(id_or_string, unicode):
|
2017-05-28 10:36:27 +00:00
|
|
|
orth = self.strings.add(id_or_string)
|
2015-01-14 13:33:16 +00:00
|
|
|
else:
|
2015-08-23 18:49:18 +00:00
|
|
|
orth = id_or_string
|
|
|
|
return Lexeme(self, orth)
|
2014-12-19 19:54:03 +00:00
|
|
|
|
2015-08-28 00:02:33 +00:00
|
|
|
cdef const TokenC* make_fused_token(self, substrings) except NULL:
|
|
|
|
cdef int i
|
|
|
|
tokens = <TokenC*>self.mem.alloc(len(substrings) + 1, sizeof(TokenC))
|
|
|
|
for i, props in enumerate(substrings):
|
2017-10-27 17:45:19 +00:00
|
|
|
props = intify_attrs(props, strings_map=self.strings,
|
|
|
|
_do_deprecated=True)
|
2015-08-28 00:02:33 +00:00
|
|
|
token = &tokens[i]
|
2016-11-25 11:43:24 +00:00
|
|
|
# Set the special tokens up to have arbitrary attributes
|
2017-10-27 17:45:19 +00:00
|
|
|
lex = <LexemeC*>self.get_by_orth(self.mem, props[ORTH])
|
2017-06-03 17:44:39 +00:00
|
|
|
token.lex = lex
|
2017-10-27 17:45:19 +00:00
|
|
|
if TAG in props:
|
|
|
|
self.morphology.assign_tag(token, props[TAG])
|
2016-11-25 11:43:24 +00:00
|
|
|
for attr_id, value in props.items():
|
|
|
|
Token.set_struct_attr(token, attr_id, value)
|
2017-06-03 17:44:39 +00:00
|
|
|
Lexeme.set_struct_attr(lex, attr_id, value)
|
2015-08-28 00:02:33 +00:00
|
|
|
return tokens
|
2016-12-21 17:04:41 +00:00
|
|
|
|
2017-05-30 21:34:50 +00:00
|
|
|
@property
|
|
|
|
def vectors_length(self):
|
2017-08-22 17:46:35 +00:00
|
|
|
return self.vectors.data.shape[1]
|
2017-05-30 21:34:50 +00:00
|
|
|
|
2017-10-31 17:25:08 +00:00
|
|
|
def reset_vectors(self, *, width=None, shape=None):
|
2017-05-30 21:34:50 +00:00
|
|
|
"""Drop the current vector table. Because all vectors must be the same
|
|
|
|
width, you have to call this to change the size of the vectors.
|
|
|
|
"""
|
2017-10-31 17:25:08 +00:00
|
|
|
if width is not None and shape is not None:
|
2018-04-03 13:50:31 +00:00
|
|
|
raise ValueError(Errors.E065.format(width=width, shape=shape))
|
2017-10-31 17:25:08 +00:00
|
|
|
elif shape is not None:
|
|
|
|
self.vectors = Vectors(shape=shape)
|
|
|
|
else:
|
|
|
|
width = width if width is not None else self.vectors.data.shape[1]
|
|
|
|
self.vectors = Vectors(shape=(self.vectors.shape[0], width))
|
2017-10-31 01:00:26 +00:00
|
|
|
|
2017-10-31 17:25:08 +00:00
|
|
|
def prune_vectors(self, nr_row, batch_size=1024):
|
2017-10-31 01:00:26 +00:00
|
|
|
"""Reduce the current vector table to `nr_row` unique entries. Words
|
|
|
|
mapped to the discarded vectors will be remapped to the closest vector
|
|
|
|
among those remaining.
|
|
|
|
|
|
|
|
For example, suppose the original table had vectors for the words:
|
|
|
|
['sat', 'cat', 'feline', 'reclined']. If we prune the vector table to,
|
|
|
|
two rows, we would discard the vectors for 'feline' and 'reclined'.
|
|
|
|
These words would then be remapped to the closest remaining vector
|
|
|
|
-- so "feline" would have the same vector as "cat", and "reclined"
|
|
|
|
would have the same vector as "sat".
|
|
|
|
|
|
|
|
The similarities are judged by cosine. The original vectors may
|
|
|
|
be large, so the cosines are calculated in minibatches, to reduce
|
|
|
|
memory usage.
|
|
|
|
|
|
|
|
nr_row (int): The number of rows to keep in the vector table.
|
|
|
|
batch_size (int): Batch of vectors for calculating the similarities.
|
|
|
|
Larger batch sizes might be faster, while temporarily requiring
|
|
|
|
more memory.
|
|
|
|
RETURNS (dict): A dictionary keyed by removed words mapped to
|
|
|
|
`(string, score)` tuples, where `string` is the entry the removed
|
|
|
|
word was mapped to, and `score` the similarity score between the
|
|
|
|
two words.
|
|
|
|
"""
|
|
|
|
xp = get_array_module(self.vectors.data)
|
2017-10-31 17:25:08 +00:00
|
|
|
# Make prob negative so it sorts by rank ascending
|
|
|
|
# (key2row contains the rank)
|
|
|
|
priority = [(-lex.prob, self.vectors.key2row[lex.orth], lex.orth)
|
|
|
|
for lex in self if lex.orth in self.vectors.key2row]
|
|
|
|
priority.sort()
|
|
|
|
indices = xp.asarray([i for (prob, i, key) in priority], dtype='i')
|
|
|
|
keys = xp.asarray([key for (prob, i, key) in priority], dtype='uint64')
|
2017-10-31 23:34:55 +00:00
|
|
|
|
2017-10-31 17:25:08 +00:00
|
|
|
keep = xp.ascontiguousarray(self.vectors.data[indices[:nr_row]])
|
|
|
|
toss = xp.ascontiguousarray(self.vectors.data[indices[nr_row:]])
|
|
|
|
|
|
|
|
self.vectors = Vectors(data=keep, keys=keys)
|
|
|
|
|
2018-11-28 18:49:33 +00:00
|
|
|
syn_keys, syn_rows, scores = self.vectors.most_similar(toss, batch_size=batch_size)
|
2017-10-31 17:25:08 +00:00
|
|
|
|
2017-10-31 10:40:46 +00:00
|
|
|
remap = {}
|
2017-10-31 17:25:08 +00:00
|
|
|
for i, key in enumerate(keys[nr_row:]):
|
|
|
|
self.vectors.add(key, row=syn_rows[i])
|
|
|
|
word = self.strings[key]
|
|
|
|
synonym = self.strings[syn_keys[i]]
|
|
|
|
score = scores[i]
|
|
|
|
remap[word] = (synonym, score)
|
2017-10-31 01:00:26 +00:00
|
|
|
link_vectors_to_models(self)
|
|
|
|
return remap
|
2017-05-30 21:34:50 +00:00
|
|
|
|
2017-05-28 09:45:32 +00:00
|
|
|
def get_vector(self, orth):
|
2017-10-27 17:45:19 +00:00
|
|
|
"""Retrieve a vector for a word in the vocabulary. Words can be looked
|
|
|
|
up by string or int ID. If no vectors data is loaded, ValueError is
|
|
|
|
raised.
|
2017-05-28 09:45:32 +00:00
|
|
|
|
2017-10-27 17:45:19 +00:00
|
|
|
RETURNS (numpy.ndarray): A word vector. Size
|
|
|
|
and shape determined by the `vocab.vectors` instance. Usually, a
|
|
|
|
numpy ndarray of shape (300,) and dtype float32.
|
2017-05-28 09:45:32 +00:00
|
|
|
"""
|
2017-08-19 17:52:25 +00:00
|
|
|
if isinstance(orth, basestring_):
|
|
|
|
orth = self.strings.add(orth)
|
2017-08-22 17:46:35 +00:00
|
|
|
if orth in self.vectors.key2row:
|
|
|
|
return self.vectors[orth]
|
|
|
|
else:
|
|
|
|
return numpy.zeros((self.vectors_length,), dtype='f')
|
2017-05-28 09:45:32 +00:00
|
|
|
|
2017-05-30 21:34:50 +00:00
|
|
|
def set_vector(self, orth, vector):
|
2017-10-27 17:45:19 +00:00
|
|
|
"""Set a vector for a word in the vocabulary. Words can be referenced
|
|
|
|
by string or int ID.
|
2017-05-30 21:34:50 +00:00
|
|
|
"""
|
2017-10-31 17:25:08 +00:00
|
|
|
if isinstance(orth, basestring_):
|
|
|
|
orth = self.strings.add(orth)
|
|
|
|
if self.vectors.is_full and orth not in self.vectors:
|
|
|
|
new_rows = max(100, int(self.vectors.shape[0]*1.3))
|
|
|
|
if self.vectors.shape[1] == 0:
|
|
|
|
width = vector.size
|
|
|
|
else:
|
|
|
|
width = self.vectors.shape[1]
|
|
|
|
self.vectors.resize((new_rows, width))
|
2018-01-14 12:57:57 +00:00
|
|
|
lex = self[orth] # Adds worse to vocab
|
2017-10-31 17:25:08 +00:00
|
|
|
self.vectors.add(orth, vector=vector)
|
2017-08-19 18:35:33 +00:00
|
|
|
self.vectors.add(orth, vector=vector)
|
2017-05-30 21:34:50 +00:00
|
|
|
|
2017-05-28 09:45:32 +00:00
|
|
|
def has_vector(self, orth):
|
2017-10-27 17:45:19 +00:00
|
|
|
"""Check whether a word has a vector. Returns False if no vectors have
|
|
|
|
been loaded. Words can be looked up by string or int ID."""
|
2017-08-19 17:52:25 +00:00
|
|
|
if isinstance(orth, basestring_):
|
|
|
|
orth = self.strings.add(orth)
|
|
|
|
return orth in self.vectors
|
2017-05-28 09:45:32 +00:00
|
|
|
|
2017-08-18 18:46:56 +00:00
|
|
|
def to_disk(self, path, **exclude):
|
2017-05-20 11:59:31 +00:00
|
|
|
"""Save the current state to a directory.
|
|
|
|
|
|
|
|
path (unicode or Path): A path to a directory, which will be created if
|
2017-10-27 17:45:19 +00:00
|
|
|
it doesn't exist. Paths may be either strings or Path-like objects.
|
2017-05-20 11:59:31 +00:00
|
|
|
"""
|
2017-05-17 10:04:50 +00:00
|
|
|
path = util.ensure_path(path)
|
|
|
|
if not path.exists():
|
|
|
|
path.mkdir()
|
2017-05-28 21:34:12 +00:00
|
|
|
self.strings.to_disk(path / 'strings.json')
|
|
|
|
with (path / 'lexemes.bin').open('wb') as file_:
|
|
|
|
file_.write(self.lexemes_to_bytes())
|
2017-08-18 18:46:56 +00:00
|
|
|
if self.vectors is not None:
|
2017-08-19 19:27:35 +00:00
|
|
|
self.vectors.to_disk(path)
|
2017-05-20 11:59:31 +00:00
|
|
|
|
2017-08-18 18:46:56 +00:00
|
|
|
def from_disk(self, path, **exclude):
|
2017-05-20 11:59:31 +00:00
|
|
|
"""Loads state from a directory. Modifies the object in place and
|
|
|
|
returns it.
|
|
|
|
|
|
|
|
path (unicode or Path): A path to a directory. Paths may be either
|
|
|
|
strings or `Path`-like objects.
|
|
|
|
RETURNS (Vocab): The modified `Vocab` object.
|
|
|
|
"""
|
2017-05-17 10:04:50 +00:00
|
|
|
path = util.ensure_path(path)
|
2017-05-28 21:34:12 +00:00
|
|
|
self.strings.from_disk(path / 'strings.json')
|
|
|
|
with (path / 'lexemes.bin').open('rb') as file_:
|
|
|
|
self.lexemes_from_bytes(file_.read())
|
2017-08-18 18:46:56 +00:00
|
|
|
if self.vectors is not None:
|
2017-08-19 19:27:35 +00:00
|
|
|
self.vectors.from_disk(path, exclude='strings.json')
|
2018-03-28 14:02:59 +00:00
|
|
|
if self.vectors.name is not None:
|
|
|
|
link_vectors_to_models(self)
|
2017-05-28 21:34:12 +00:00
|
|
|
return self
|
2016-11-01 11:25:36 +00:00
|
|
|
|
2017-05-20 11:59:31 +00:00
|
|
|
def to_bytes(self, **exclude):
|
|
|
|
"""Serialize the current state to a binary string.
|
|
|
|
|
|
|
|
**exclude: Named attributes to prevent from being serialized.
|
|
|
|
RETURNS (bytes): The serialized form of the `Vocab` object.
|
|
|
|
"""
|
2017-08-18 18:46:56 +00:00
|
|
|
def deserialize_vectors():
|
|
|
|
if self.vectors is None:
|
|
|
|
return None
|
|
|
|
else:
|
2017-10-20 11:59:24 +00:00
|
|
|
return self.vectors.to_bytes()
|
2017-09-17 17:29:39 +00:00
|
|
|
|
2017-05-29 22:52:36 +00:00
|
|
|
getters = OrderedDict((
|
|
|
|
('strings', lambda: self.strings.to_bytes()),
|
|
|
|
('lexemes', lambda: self.lexemes_to_bytes()),
|
2017-08-18 18:46:56 +00:00
|
|
|
('vectors', deserialize_vectors)
|
2017-05-29 22:52:36 +00:00
|
|
|
))
|
2017-05-29 08:14:20 +00:00
|
|
|
return util.to_bytes(getters, exclude)
|
2017-05-20 11:59:31 +00:00
|
|
|
|
2017-05-21 12:18:46 +00:00
|
|
|
def from_bytes(self, bytes_data, **exclude):
|
2017-05-20 11:59:31 +00:00
|
|
|
"""Load state from a binary string.
|
|
|
|
|
|
|
|
bytes_data (bytes): The data to load from.
|
|
|
|
**exclude: Named attributes to prevent from being loaded.
|
|
|
|
RETURNS (Vocab): The `Vocab` object.
|
|
|
|
"""
|
2017-08-18 18:46:56 +00:00
|
|
|
def serialize_vectors(b):
|
|
|
|
if self.vectors is None:
|
|
|
|
return None
|
|
|
|
else:
|
2017-10-20 11:59:24 +00:00
|
|
|
return self.vectors.from_bytes(b)
|
2017-05-29 11:04:40 +00:00
|
|
|
setters = OrderedDict((
|
|
|
|
('strings', lambda b: self.strings.from_bytes(b)),
|
2017-05-29 22:52:36 +00:00
|
|
|
('lexemes', lambda b: self.lexemes_from_bytes(b)),
|
2017-08-18 18:46:56 +00:00
|
|
|
('vectors', lambda b: serialize_vectors(b))
|
2017-05-29 11:04:40 +00:00
|
|
|
))
|
2017-06-02 08:56:40 +00:00
|
|
|
util.from_bytes(bytes_data, setters, exclude)
|
2018-03-28 14:02:59 +00:00
|
|
|
if self.vectors.name is not None:
|
|
|
|
link_vectors_to_models(self)
|
2017-06-02 08:56:40 +00:00
|
|
|
return self
|
2017-05-28 21:34:12 +00:00
|
|
|
|
|
|
|
def lexemes_to_bytes(self):
|
2014-12-19 19:54:03 +00:00
|
|
|
cdef hash_t key
|
2017-05-17 10:04:50 +00:00
|
|
|
cdef size_t addr
|
2017-03-11 18:43:09 +00:00
|
|
|
cdef LexemeC* lexeme = NULL
|
2017-05-17 10:04:50 +00:00
|
|
|
cdef SerializedLexemeC lex_data
|
|
|
|
cdef int size = 0
|
2015-07-27 08:58:15 +00:00
|
|
|
for key, addr in self._by_hash.items():
|
2017-05-17 10:04:50 +00:00
|
|
|
if addr == 0:
|
|
|
|
continue
|
|
|
|
size += sizeof(lex_data.data)
|
|
|
|
byte_string = b'\0' * size
|
|
|
|
byte_ptr = <unsigned char*>byte_string
|
|
|
|
cdef int j
|
|
|
|
cdef int i = 0
|
|
|
|
for key, addr in self._by_hash.items():
|
|
|
|
if addr == 0:
|
|
|
|
continue
|
2015-07-18 20:42:15 +00:00
|
|
|
lexeme = <LexemeC*>addr
|
2017-05-17 10:04:50 +00:00
|
|
|
lex_data = Lexeme.c_to_bytes(lexeme)
|
|
|
|
for j in range(sizeof(lex_data.data)):
|
|
|
|
byte_ptr[i] = lex_data.data[j]
|
|
|
|
i += 1
|
|
|
|
return byte_string
|
2016-11-01 11:25:36 +00:00
|
|
|
|
2017-05-17 10:04:50 +00:00
|
|
|
def lexemes_from_bytes(self, bytes bytes_data):
|
2017-05-20 11:59:31 +00:00
|
|
|
"""Load the binary vocabulary data from the given string."""
|
2017-05-17 10:04:50 +00:00
|
|
|
cdef LexemeC* lexeme
|
2017-03-07 19:25:12 +00:00
|
|
|
cdef hash_t key
|
|
|
|
cdef unicode py_str
|
2017-05-17 10:04:50 +00:00
|
|
|
cdef int i = 0
|
|
|
|
cdef int j = 0
|
|
|
|
cdef SerializedLexemeC lex_data
|
|
|
|
chunk_size = sizeof(lex_data.data)
|
2017-10-20 22:51:42 +00:00
|
|
|
cdef void* ptr
|
2017-05-17 10:04:50 +00:00
|
|
|
cdef unsigned char* bytes_ptr = bytes_data
|
|
|
|
for i in range(0, len(bytes_data), chunk_size):
|
|
|
|
lexeme = <LexemeC*>self.mem.alloc(1, sizeof(LexemeC))
|
|
|
|
for j in range(sizeof(lex_data.data)):
|
|
|
|
lex_data.data[j] = bytes_ptr[i+j]
|
|
|
|
Lexeme.c_from_bytes(lexeme, lex_data)
|
2017-03-07 19:25:12 +00:00
|
|
|
|
2017-10-20 22:51:42 +00:00
|
|
|
ptr = self.strings._map.get(lexeme.orth)
|
|
|
|
if ptr == NULL:
|
|
|
|
continue
|
2017-03-07 19:25:12 +00:00
|
|
|
py_str = self.strings[lexeme.orth]
|
2018-04-03 13:50:31 +00:00
|
|
|
if self.strings[py_str] != lexeme.orth:
|
|
|
|
raise ValueError(Errors.E086.format(string=py_str,
|
|
|
|
orth_id=lexeme.orth,
|
|
|
|
hash_id=self.strings[py_str]))
|
2017-03-07 19:25:12 +00:00
|
|
|
key = hash_string(py_str)
|
|
|
|
self._by_hash.set(key, lexeme)
|
|
|
|
self._by_orth.set(lexeme.orth, lexeme)
|
|
|
|
self.length += 1
|
|
|
|
|
2017-11-14 18:15:04 +00:00
|
|
|
def _reset_cache(self, keys, strings):
|
|
|
|
for k in keys:
|
|
|
|
del self._by_hash[k]
|
|
|
|
|
2017-11-14 19:58:46 +00:00
|
|
|
if len(strings) != 0:
|
|
|
|
self._by_orth = PreshMap()
|
2017-11-14 18:15:04 +00:00
|
|
|
|
2017-05-17 10:04:50 +00:00
|
|
|
|
2017-03-07 19:25:12 +00:00
|
|
|
def pickle_vocab(vocab):
|
|
|
|
sstore = vocab.strings
|
2017-11-23 16:19:50 +00:00
|
|
|
vectors = vocab.vectors
|
2017-03-07 19:25:12 +00:00
|
|
|
morph = vocab.morphology
|
|
|
|
length = vocab.length
|
|
|
|
data_dir = vocab.data_dir
|
2017-10-17 16:17:45 +00:00
|
|
|
lex_attr_getters = dill.dumps(vocab.lex_attr_getters)
|
2017-05-17 10:04:50 +00:00
|
|
|
lexemes_data = vocab.lexemes_to_bytes()
|
2017-03-07 19:25:12 +00:00
|
|
|
return (unpickle_vocab,
|
2017-11-23 16:19:50 +00:00
|
|
|
(sstore, vectors, morph, data_dir, lex_attr_getters, lexemes_data, length))
|
2017-03-07 19:25:12 +00:00
|
|
|
|
|
|
|
|
2017-11-23 16:19:50 +00:00
|
|
|
def unpickle_vocab(sstore, vectors, morphology, data_dir,
|
2017-10-27 17:45:19 +00:00
|
|
|
lex_attr_getters, bytes lexemes_data, int length):
|
2017-03-07 19:25:12 +00:00
|
|
|
cdef Vocab vocab = Vocab()
|
|
|
|
vocab.length = length
|
2017-11-23 16:19:50 +00:00
|
|
|
vocab.vectors = vectors
|
2017-03-07 19:25:12 +00:00
|
|
|
vocab.strings = sstore
|
|
|
|
vocab.morphology = morphology
|
|
|
|
vocab.data_dir = data_dir
|
2017-10-17 16:17:45 +00:00
|
|
|
vocab.lex_attr_getters = dill.loads(lex_attr_getters)
|
2017-05-17 10:04:50 +00:00
|
|
|
vocab.lexemes_from_bytes(lexemes_data)
|
2017-03-07 19:25:12 +00:00
|
|
|
vocab.length = length
|
|
|
|
return vocab
|
|
|
|
|
|
|
|
|
|
|
|
copy_reg.pickle(Vocab, pickle_vocab, unpickle_vocab)
|