2017-11-26 22:21:47 +00:00
|
|
|
# coding: utf8
|
|
|
|
from __future__ import unicode_literals
|
|
|
|
|
|
|
|
import plac
|
|
|
|
import math
|
|
|
|
import numpy
|
|
|
|
from ast import literal_eval
|
|
|
|
from pathlib import Path
|
|
|
|
from preshed.counter import PreshCounter
|
2018-03-21 13:33:23 +00:00
|
|
|
import tarfile
|
|
|
|
import gzip
|
2018-03-27 21:01:18 +00:00
|
|
|
import zipfile
|
💫 Replace ujson, msgpack and dill/pickle/cloudpickle with srsly (#3003)
Remove hacks and wrappers, keep code in sync across our libraries and move spaCy a few steps closer to only depending on packages with binary wheels 🎉
See here: https://github.com/explosion/srsly
Serialization is hard, especially across Python versions and multiple platforms. After dealing with many subtle bugs over the years (encodings, locales, large files) our libraries like spaCy and Prodigy have steadily grown a number of utility functions to wrap the multiple serialization formats we need to support (especially json, msgpack and pickle). These wrapping functions ended up duplicated across our codebases, so we wanted to put them in one place.
At the same time, we noticed that having a lot of small dependencies was making maintainence harder, and making installation slower. To solve this, we've made srsly standalone, by including the component packages directly within it. This way we can provide all the serialization utilities we need in a single binary wheel.
srsly currently includes forks of the following packages:
ujson
msgpack
msgpack-numpy
cloudpickle
* WIP: replace json/ujson with srsly
* Replace ujson in examples
Use regular json instead of srsly to make code easier to read and follow
* Update requirements
* Fix imports
* Fix typos
* Replace msgpack with srsly
* Fix warning
2018-12-03 00:28:22 +00:00
|
|
|
import srsly
|
Generalize handling of tokenizer special cases (#4259)
* Generalize handling of tokenizer special cases
Handle tokenizer special cases more generally by using the Matcher
internally to match special cases after the affix/token_match
tokenization is complete.
Instead of only matching special cases while processing balanced or
nearly balanced prefixes and suffixes, this recognizes special cases in
a wider range of contexts:
* Allows arbitrary numbers of prefixes/affixes around special cases
* Allows special cases separated by infixes
Existing tests/settings that couldn't be preserved as before:
* The emoticon '")' is no longer a supported special case
* The emoticon ':)' in "example:)" is a false positive again
When merged with #4258 (or the relevant cache bugfix), the affix and
token_match properties should be modified to flush and reload all
special cases to use the updated internal tokenization with the Matcher.
* Remove accidentally added test case
* Really remove accidentally added test
* Reload special cases when necessary
Reload special cases when affixes or token_match are modified. Skip
reloading during initialization.
* Update error code number
* Fix offset and whitespace in Matcher special cases
* Fix offset bugs when merging and splitting tokens
* Set final whitespace on final token in inserted special case
* Improve cache flushing in tokenizer
* Separate cache and specials memory (temporarily)
* Flush cache when adding special cases
* Repeated `self._cache = PreshMap()` and `self._specials = PreshMap()`
are necessary due to this bug:
https://github.com/explosion/preshed/issues/21
* Remove reinitialized PreshMaps on cache flush
* Update UD bin scripts
* Update imports for `bin/`
* Add all currently supported languages
* Update subtok merger for new Matcher validation
* Modify blinded check to look at tokens instead of lemmas (for corpora
with tokens but not lemmas like Telugu)
* Use special Matcher only for cases with affixes
* Reinsert specials cache checks during normal tokenization for special
cases as much as possible
* Additionally include specials cache checks while splitting on infixes
* Since the special Matcher needs consistent affix-only tokenization
for the special cases themselves, introduce the argument
`with_special_cases` in order to do tokenization with or without
specials cache checks
* After normal tokenization, postprocess with special cases Matcher for
special cases containing affixes
* Replace PhraseMatcher with Aho-Corasick
Replace PhraseMatcher with the Aho-Corasick algorithm over numpy arrays
of the hash values for the relevant attribute. The implementation is
based on FlashText.
The speed should be similar to the previous PhraseMatcher. It is now
possible to easily remove match IDs and matches don't go missing with
large keyword lists / vocabularies.
Fixes #4308.
* Restore support for pickling
* Fix internal keyword add/remove for numpy arrays
* Add test for #4248, clean up test
* Improve efficiency of special cases handling
* Use PhraseMatcher instead of Matcher
* Improve efficiency of merging/splitting special cases in document
* Process merge/splits in one pass without repeated token shifting
* Merge in place if no splits
* Update error message number
* Remove UD script modifications
Only used for timing/testing, should be a separate PR
* Remove final traces of UD script modifications
* Update UD bin scripts
* Update imports for `bin/`
* Add all currently supported languages
* Update subtok merger for new Matcher validation
* Modify blinded check to look at tokens instead of lemmas (for corpora
with tokens but not lemmas like Telugu)
* Add missing loop for match ID set in search loop
* Remove cruft in matching loop for partial matches
There was a bit of unnecessary code left over from FlashText in the
matching loop to handle partial token matches, which we don't have with
PhraseMatcher.
* Replace dict trie with MapStruct trie
* Fix how match ID hash is stored/added
* Update fix for match ID vocab
* Switch from map_get_unless_missing to map_get
* Switch from numpy array to Token.get_struct_attr
Access token attributes directly in Doc instead of making a copy of the
relevant values in a numpy array.
Add unsatisfactory warning for hash collision with reserved terminal
hash key. (Ideally it would change the reserved terminal hash and redo
the whole trie, but for now, I'm hoping there won't be collisions.)
* Restructure imports to export find_matches
* Implement full remove()
Remove unnecessary trie paths and free unused maps.
Parallel to Matcher, raise KeyError when attempting to remove a match ID
that has not been added.
* Switch to PhraseMatcher.find_matches
* Switch to local cdef functions for span filtering
* Switch special case reload threshold to variable
Refer to variable instead of hard-coded threshold
* Move more of special case retokenize to cdef nogil
Move as much of the special case retokenization to nogil as possible.
* Rewrap sort as stdsort for OS X
* Rewrap stdsort with specific types
* Switch to qsort
* Fix merge
* Improve cmp functions
* Fix realloc
* Fix realloc again
* Initialize span struct while retokenizing
* Temporarily skip retokenizing
* Revert "Move more of special case retokenize to cdef nogil"
This reverts commit 0b7e52c797cd8ff1548f214bd4186ebb3a7ce8b1.
* Revert "Switch to qsort"
This reverts commit a98d71a942fc9bca531cf5eb05cf89fa88153b60.
* Fix specials check while caching
* Modify URL test with emoticons
The multiple suffix tests result in the emoticon `:>`, which is now
retokenized into one token as a special case after the suffixes are
split off.
* Refactor _apply_special_cases()
* Use cdef ints for span info used in multiple spots
* Modify _filter_special_spans() to prefer earlier
Parallel to #4414, modify _filter_special_spans() so that the earlier
span is preferred for overlapping spans of the same length.
* Replace MatchStruct with Entity
Replace MatchStruct with Entity since the existing Entity struct is
nearly identical.
* Replace Entity with more general SpanC
* Replace MatchStruct with SpanC
* Add error in debug-data if no dev docs are available (see #4575)
* Update azure-pipelines.yml
* Revert "Update azure-pipelines.yml"
This reverts commit ed1060cf59e5895b5fe92ad5b894fd1078ec4c49.
* Use latest wasabi
* Reorganise install_requires
* add dframcy to universe.json (#4580)
* Update universe.json [ci skip]
* Fix multiprocessing for as_tuples=True (#4582)
* Fix conllu script (#4579)
* force extensions to avoid clash between example scripts
* fix arg order and default file encoding
* add example config for conllu script
* newline
* move extension definitions to main function
* few more encodings fixes
* Add load_from_docbin example [ci skip]
TODO: upload the file somewhere
* Update README.md
* Add warnings about 3.8 (resolves #4593) [ci skip]
* Fixed typo: Added space between "recognize" and "various" (#4600)
* Fix DocBin.merge() example (#4599)
* Replace function registries with catalogue (#4584)
* Replace functions registries with catalogue
* Update __init__.py
* Fix test
* Revert unrelated flag [ci skip]
* Bugfix/dep matcher issue 4590 (#4601)
* add contributor agreement for prilopes
* add test for issue #4590
* fix on_match params for DependencyMacther (#4590)
* Minor updates to language example sentences (#4608)
* Add punctuation to Spanish example sentences
* Combine multilanguage examples for lang xx
* Add punctuation to nb examples
* Always realloc to a larger size
Avoid potential (unlikely) edge case and cymem error seen in #4604.
* Add error in debug-data if no dev docs are available (see #4575)
* Update debug-data for GoldCorpus / Example
* Ignore None label in misaligned NER data
2019-11-13 20:24:35 +00:00
|
|
|
from wasabi import msg
|
2017-11-26 22:21:47 +00:00
|
|
|
|
2017-12-07 09:03:07 +00:00
|
|
|
from ..vectors import Vectors
|
2018-04-10 19:26:37 +00:00
|
|
|
from ..errors import Errors, Warnings, user_warning
|
💫 Replace ujson, msgpack and dill/pickle/cloudpickle with srsly (#3003)
Remove hacks and wrappers, keep code in sync across our libraries and move spaCy a few steps closer to only depending on packages with binary wheels 🎉
See here: https://github.com/explosion/srsly
Serialization is hard, especially across Python versions and multiple platforms. After dealing with many subtle bugs over the years (encodings, locales, large files) our libraries like spaCy and Prodigy have steadily grown a number of utility functions to wrap the multiple serialization formats we need to support (especially json, msgpack and pickle). These wrapping functions ended up duplicated across our codebases, so we wanted to put them in one place.
At the same time, we noticed that having a lot of small dependencies was making maintainence harder, and making installation slower. To solve this, we've made srsly standalone, by including the component packages directly within it. This way we can provide all the serialization utilities we need in a single binary wheel.
srsly currently includes forks of the following packages:
ujson
msgpack
msgpack-numpy
cloudpickle
* WIP: replace json/ujson with srsly
* Replace ujson in examples
Use regular json instead of srsly to make code easier to read and follow
* Update requirements
* Fix imports
* Fix typos
* Replace msgpack with srsly
* Fix warning
2018-12-03 00:28:22 +00:00
|
|
|
from ..util import ensure_path, get_lang_class
|
2017-11-26 22:21:47 +00:00
|
|
|
|
2018-04-10 17:08:06 +00:00
|
|
|
try:
|
|
|
|
import ftfy
|
|
|
|
except ImportError:
|
|
|
|
ftfy = None
|
|
|
|
|
2017-11-26 22:21:47 +00:00
|
|
|
|
2019-08-01 15:26:09 +00:00
|
|
|
DEFAULT_OOV_PROB = -20
|
2018-11-30 19:16:14 +00:00
|
|
|
|
|
|
|
|
2017-11-26 22:21:47 +00:00
|
|
|
@plac.annotations(
|
2018-11-30 19:16:14 +00:00
|
|
|
lang=("Model language", "positional", None, str),
|
|
|
|
output_dir=("Model output directory", "positional", None, Path),
|
|
|
|
freqs_loc=("Location of words frequencies file", "option", "f", Path),
|
|
|
|
jsonl_loc=("Location of JSONL-formatted attributes file", "option", "j", Path),
|
|
|
|
clusters_loc=("Optional location of brown clusters data", "option", "c", str),
|
2018-12-06 21:48:31 +00:00
|
|
|
vectors_loc=("Optional vectors file in Word2Vec format", "option", "v", str),
|
2018-11-30 19:16:14 +00:00
|
|
|
prune_vectors=("Optional number of vectors to prune to", "option", "V", int),
|
2019-09-25 12:21:27 +00:00
|
|
|
vectors_name=(
|
|
|
|
"Optional name for the word vectors, e.g. en_core_web_lg.vectors",
|
|
|
|
"option",
|
|
|
|
"vn",
|
|
|
|
str,
|
|
|
|
),
|
2019-09-26 01:01:32 +00:00
|
|
|
model_name=("Optional name for the model meta", "option", "mn", str),
|
2017-11-26 22:21:47 +00:00
|
|
|
)
|
2018-11-30 19:16:14 +00:00
|
|
|
def init_model(
|
|
|
|
lang,
|
|
|
|
output_dir,
|
|
|
|
freqs_loc=None,
|
|
|
|
clusters_loc=None,
|
|
|
|
jsonl_loc=None,
|
|
|
|
vectors_loc=None,
|
|
|
|
prune_vectors=-1,
|
2019-09-25 12:21:27 +00:00
|
|
|
vectors_name=None,
|
2019-09-26 01:01:32 +00:00
|
|
|
model_name=None,
|
2018-11-30 19:16:14 +00:00
|
|
|
):
|
2017-12-07 09:23:09 +00:00
|
|
|
"""
|
|
|
|
Create a new model from raw data, like word frequencies, Brown clusters
|
2018-11-30 19:16:14 +00:00
|
|
|
and word vectors. If vectors are provided in Word2Vec format, they can
|
|
|
|
be either a .txt or zipped as a .zip or .tar.gz.
|
2017-12-07 09:23:09 +00:00
|
|
|
"""
|
2018-07-03 10:22:56 +00:00
|
|
|
if jsonl_loc is not None:
|
|
|
|
if freqs_loc is not None or clusters_loc is not None:
|
2018-11-30 19:16:14 +00:00
|
|
|
settings = ["-j"]
|
2018-07-03 10:22:56 +00:00
|
|
|
if freqs_loc:
|
2018-11-30 19:16:14 +00:00
|
|
|
settings.append("-f")
|
2018-07-03 10:22:56 +00:00
|
|
|
if clusters_loc:
|
2018-11-30 19:16:14 +00:00
|
|
|
settings.append("-c")
|
2018-12-08 10:49:43 +00:00
|
|
|
msg.warn(
|
|
|
|
"Incompatible arguments",
|
|
|
|
"The -f and -c arguments are deprecated, and not compatible "
|
|
|
|
"with the -j argument, which should specify the same "
|
|
|
|
"information. Either merge the frequencies and clusters data "
|
|
|
|
"into the JSONL-formatted file (recommended), or use only the "
|
|
|
|
"-f and -c files, without the other lexical attributes.",
|
|
|
|
)
|
2018-07-03 10:22:56 +00:00
|
|
|
jsonl_loc = ensure_path(jsonl_loc)
|
💫 Replace ujson, msgpack and dill/pickle/cloudpickle with srsly (#3003)
Remove hacks and wrappers, keep code in sync across our libraries and move spaCy a few steps closer to only depending on packages with binary wheels 🎉
See here: https://github.com/explosion/srsly
Serialization is hard, especially across Python versions and multiple platforms. After dealing with many subtle bugs over the years (encodings, locales, large files) our libraries like spaCy and Prodigy have steadily grown a number of utility functions to wrap the multiple serialization formats we need to support (especially json, msgpack and pickle). These wrapping functions ended up duplicated across our codebases, so we wanted to put them in one place.
At the same time, we noticed that having a lot of small dependencies was making maintainence harder, and making installation slower. To solve this, we've made srsly standalone, by including the component packages directly within it. This way we can provide all the serialization utilities we need in a single binary wheel.
srsly currently includes forks of the following packages:
ujson
msgpack
msgpack-numpy
cloudpickle
* WIP: replace json/ujson with srsly
* Replace ujson in examples
Use regular json instead of srsly to make code easier to read and follow
* Update requirements
* Fix imports
* Fix typos
* Replace msgpack with srsly
* Fix warning
2018-12-03 00:28:22 +00:00
|
|
|
lex_attrs = srsly.read_jsonl(jsonl_loc)
|
2018-07-03 10:22:56 +00:00
|
|
|
else:
|
|
|
|
clusters_loc = ensure_path(clusters_loc)
|
|
|
|
freqs_loc = ensure_path(freqs_loc)
|
|
|
|
if freqs_loc is not None and not freqs_loc.exists():
|
2018-12-08 10:49:43 +00:00
|
|
|
msg.fail("Can't find words frequencies file", freqs_loc, exits=1)
|
2018-07-03 10:22:56 +00:00
|
|
|
lex_attrs = read_attrs_from_deprecated(freqs_loc, clusters_loc)
|
2018-07-04 00:29:48 +00:00
|
|
|
|
2018-11-30 19:16:14 +00:00
|
|
|
with msg.loading("Creating model..."):
|
2019-09-26 01:01:32 +00:00
|
|
|
nlp = create_model(lang, lex_attrs, name=model_name)
|
2018-11-30 19:16:14 +00:00
|
|
|
msg.good("Successfully created model")
|
2018-07-04 00:29:48 +00:00
|
|
|
if vectors_loc is not None:
|
2019-09-25 11:11:00 +00:00
|
|
|
add_vectors(nlp, vectors_loc, prune_vectors, vectors_name)
|
2018-07-04 00:29:48 +00:00
|
|
|
vec_added = len(nlp.vocab.vectors)
|
|
|
|
lex_added = len(nlp.vocab)
|
2018-12-08 10:49:43 +00:00
|
|
|
msg.good(
|
|
|
|
"Sucessfully compiled vocab",
|
|
|
|
"{} entries, {} vectors".format(lex_added, vec_added),
|
|
|
|
)
|
2017-11-26 22:21:47 +00:00
|
|
|
if not output_dir.exists():
|
|
|
|
output_dir.mkdir()
|
|
|
|
nlp.to_disk(output_dir)
|
|
|
|
return nlp
|
|
|
|
|
2018-11-30 19:16:14 +00:00
|
|
|
|
2018-03-21 13:33:23 +00:00
|
|
|
def open_file(loc):
|
2018-11-30 19:16:14 +00:00
|
|
|
"""Handle .gz, .tar.gz or unzipped files"""
|
2018-03-21 13:33:23 +00:00
|
|
|
loc = ensure_path(loc)
|
|
|
|
if tarfile.is_tarfile(str(loc)):
|
2018-11-30 19:16:14 +00:00
|
|
|
return tarfile.open(str(loc), "r:gz")
|
|
|
|
elif loc.parts[-1].endswith("gz"):
|
|
|
|
return (line.decode("utf8") for line in gzip.open(str(loc), "r"))
|
|
|
|
elif loc.parts[-1].endswith("zip"):
|
2018-03-27 21:01:18 +00:00
|
|
|
zip_file = zipfile.ZipFile(str(loc))
|
|
|
|
names = zip_file.namelist()
|
|
|
|
file_ = zip_file.open(names[0])
|
2018-11-30 19:16:14 +00:00
|
|
|
return (line.decode("utf8") for line in file_)
|
2018-03-21 13:33:23 +00:00
|
|
|
else:
|
2018-11-30 19:16:14 +00:00
|
|
|
return loc.open("r", encoding="utf8")
|
|
|
|
|
2018-03-21 13:33:23 +00:00
|
|
|
|
2018-07-03 10:22:56 +00:00
|
|
|
def read_attrs_from_deprecated(freqs_loc, clusters_loc):
|
2019-09-09 14:32:11 +00:00
|
|
|
# temp fix to avoid import issues cf https://github.com/explosion/spaCy/issues/4200
|
|
|
|
from tqdm import tqdm
|
|
|
|
|
2019-08-01 15:26:09 +00:00
|
|
|
if freqs_loc is not None:
|
|
|
|
with msg.loading("Counting frequencies..."):
|
|
|
|
probs, _ = read_freqs(freqs_loc)
|
|
|
|
msg.good("Counted frequencies")
|
|
|
|
else:
|
2019-08-18 13:09:16 +00:00
|
|
|
probs, _ = ({}, DEFAULT_OOV_PROB) # noqa: F841
|
2019-08-01 15:26:09 +00:00
|
|
|
if clusters_loc:
|
|
|
|
with msg.loading("Reading clusters..."):
|
|
|
|
clusters = read_clusters(clusters_loc)
|
|
|
|
msg.good("Read clusters")
|
|
|
|
else:
|
|
|
|
clusters = {}
|
2018-08-14 11:19:15 +00:00
|
|
|
lex_attrs = []
|
2018-07-03 10:22:56 +00:00
|
|
|
sorted_probs = sorted(probs.items(), key=lambda item: item[1], reverse=True)
|
2019-08-01 15:26:09 +00:00
|
|
|
if len(sorted_probs):
|
|
|
|
for i, (word, prob) in tqdm(enumerate(sorted_probs)):
|
|
|
|
attrs = {"orth": word, "id": i, "prob": prob}
|
|
|
|
# Decode as a little-endian string, so that we can do & 15 to get
|
|
|
|
# the first 4 bits. See _parse_features.pyx
|
|
|
|
if word in clusters:
|
|
|
|
attrs["cluster"] = int(clusters[word][::-1], 2)
|
|
|
|
else:
|
|
|
|
attrs["cluster"] = 0
|
|
|
|
lex_attrs.append(attrs)
|
2018-07-03 10:22:56 +00:00
|
|
|
return lex_attrs
|
|
|
|
|
|
|
|
|
2019-09-26 01:01:32 +00:00
|
|
|
def create_model(lang, lex_attrs, name=None):
|
2017-12-07 08:59:23 +00:00
|
|
|
lang_class = get_lang_class(lang)
|
|
|
|
nlp = lang_class()
|
2017-11-26 22:21:47 +00:00
|
|
|
for lexeme in nlp.vocab:
|
|
|
|
lexeme.rank = 0
|
|
|
|
lex_added = 0
|
2018-07-03 10:22:56 +00:00
|
|
|
for attrs in lex_attrs:
|
2018-11-30 19:16:14 +00:00
|
|
|
if "settings" in attrs:
|
2018-07-04 00:29:48 +00:00
|
|
|
continue
|
2018-11-30 19:16:14 +00:00
|
|
|
lexeme = nlp.vocab[attrs["orth"]]
|
2018-07-04 00:29:48 +00:00
|
|
|
lexeme.set_attrs(**attrs)
|
2017-11-26 22:21:47 +00:00
|
|
|
lexeme.is_oov = False
|
|
|
|
lex_added += 1
|
2018-07-03 10:22:56 +00:00
|
|
|
lex_added += 1
|
2019-08-01 15:26:09 +00:00
|
|
|
if len(nlp.vocab):
|
|
|
|
oov_prob = min(lex.prob for lex in nlp.vocab) - 1
|
|
|
|
else:
|
|
|
|
oov_prob = DEFAULT_OOV_PROB
|
|
|
|
nlp.vocab.cfg.update({"oov_prob": oov_prob})
|
2019-09-26 01:01:32 +00:00
|
|
|
if name:
|
|
|
|
nlp.meta["name"] = name
|
2017-11-26 22:21:47 +00:00
|
|
|
return nlp
|
|
|
|
|
2018-11-30 19:16:14 +00:00
|
|
|
|
2019-09-25 11:11:00 +00:00
|
|
|
def add_vectors(nlp, vectors_loc, prune_vectors, name=None):
|
2018-07-04 00:29:48 +00:00
|
|
|
vectors_loc = ensure_path(vectors_loc)
|
2018-11-30 19:16:14 +00:00
|
|
|
if vectors_loc and vectors_loc.parts[-1].endswith(".npz"):
|
|
|
|
nlp.vocab.vectors = Vectors(data=numpy.load(vectors_loc.open("rb")))
|
2018-07-04 00:29:48 +00:00
|
|
|
for lex in nlp.vocab:
|
|
|
|
if lex.rank:
|
|
|
|
nlp.vocab.vectors.add(lex.orth, row=lex.rank)
|
|
|
|
else:
|
2018-11-30 19:16:14 +00:00
|
|
|
if vectors_loc:
|
|
|
|
with msg.loading("Reading vectors from {}".format(vectors_loc)):
|
|
|
|
vectors_data, vector_keys = read_vectors(vectors_loc)
|
|
|
|
msg.good("Loaded vectors from {}".format(vectors_loc))
|
|
|
|
else:
|
|
|
|
vectors_data, vector_keys = (None, None)
|
2018-07-04 00:29:48 +00:00
|
|
|
if vector_keys is not None:
|
|
|
|
for word in vector_keys:
|
|
|
|
if word not in nlp.vocab:
|
|
|
|
lexeme = nlp.vocab[word]
|
|
|
|
lexeme.is_oov = False
|
|
|
|
if vectors_data is not None:
|
|
|
|
nlp.vocab.vectors = Vectors(data=vectors_data, keys=vector_keys)
|
2019-09-25 11:11:00 +00:00
|
|
|
if name is None:
|
|
|
|
nlp.vocab.vectors.name = "%s_model.vectors" % nlp.meta["lang"]
|
|
|
|
else:
|
|
|
|
nlp.vocab.vectors.name = name
|
2018-11-30 19:16:14 +00:00
|
|
|
nlp.meta["vectors"]["name"] = nlp.vocab.vectors.name
|
2018-07-04 00:29:48 +00:00
|
|
|
if prune_vectors >= 1:
|
|
|
|
nlp.vocab.prune_vectors(prune_vectors)
|
2017-11-26 22:21:47 +00:00
|
|
|
|
2018-11-30 19:16:14 +00:00
|
|
|
|
2017-11-26 22:21:47 +00:00
|
|
|
def read_vectors(vectors_loc):
|
2019-09-09 14:32:11 +00:00
|
|
|
# temp fix to avoid import issues cf https://github.com/explosion/spaCy/issues/4200
|
|
|
|
from tqdm import tqdm
|
|
|
|
|
2018-03-21 13:33:23 +00:00
|
|
|
f = open_file(vectors_loc)
|
|
|
|
shape = tuple(int(size) for size in next(f).split())
|
2018-11-30 19:16:14 +00:00
|
|
|
vectors_data = numpy.zeros(shape=shape, dtype="f")
|
2018-03-21 13:33:23 +00:00
|
|
|
vectors_keys = []
|
|
|
|
for i, line in enumerate(tqdm(f)):
|
2018-03-27 21:01:18 +00:00
|
|
|
line = line.rstrip()
|
2019-05-06 21:00:38 +00:00
|
|
|
pieces = line.rsplit(" ", vectors_data.shape[1])
|
2018-03-21 13:33:23 +00:00
|
|
|
word = pieces.pop(0)
|
2018-03-27 21:01:18 +00:00
|
|
|
if len(pieces) != vectors_data.shape[1]:
|
2018-11-30 19:16:14 +00:00
|
|
|
msg.fail(Errors.E094.format(line_num=i, loc=vectors_loc), exits=1)
|
|
|
|
vectors_data[i] = numpy.asarray(pieces, dtype="f")
|
2018-03-21 13:33:23 +00:00
|
|
|
vectors_keys.append(word)
|
2017-11-26 22:21:47 +00:00
|
|
|
return vectors_data, vectors_keys
|
|
|
|
|
|
|
|
|
|
|
|
def read_freqs(freqs_loc, max_length=100, min_doc_freq=5, min_freq=50):
|
2019-09-09 14:32:11 +00:00
|
|
|
# temp fix to avoid import issues cf https://github.com/explosion/spaCy/issues/4200
|
|
|
|
from tqdm import tqdm
|
|
|
|
|
2017-11-26 22:21:47 +00:00
|
|
|
counts = PreshCounter()
|
|
|
|
total = 0
|
|
|
|
with freqs_loc.open() as f:
|
|
|
|
for i, line in enumerate(f):
|
2018-11-30 19:16:14 +00:00
|
|
|
freq, doc_freq, key = line.rstrip().split("\t", 2)
|
2017-11-26 22:21:47 +00:00
|
|
|
freq = int(freq)
|
|
|
|
counts.inc(i + 1, freq)
|
|
|
|
total += freq
|
|
|
|
counts.smooth()
|
|
|
|
log_total = math.log(total)
|
|
|
|
probs = {}
|
|
|
|
with freqs_loc.open() as f:
|
|
|
|
for line in tqdm(f):
|
2018-11-30 19:16:14 +00:00
|
|
|
freq, doc_freq, key = line.rstrip().split("\t", 2)
|
2017-11-26 22:21:47 +00:00
|
|
|
doc_freq = int(doc_freq)
|
|
|
|
freq = int(freq)
|
|
|
|
if doc_freq >= min_doc_freq and freq >= min_freq and len(key) < max_length:
|
2019-01-14 22:48:30 +00:00
|
|
|
try:
|
|
|
|
word = literal_eval(key)
|
|
|
|
except SyntaxError:
|
|
|
|
# Take odd strings literally.
|
|
|
|
word = literal_eval("'%s'" % key)
|
2017-11-26 22:21:47 +00:00
|
|
|
smooth_count = counts.smoother(int(freq))
|
|
|
|
probs[word] = math.log(smooth_count) - log_total
|
|
|
|
oov_prob = math.log(counts.smoother(0)) - log_total
|
|
|
|
return probs, oov_prob
|
|
|
|
|
|
|
|
|
|
|
|
def read_clusters(clusters_loc):
|
2019-09-09 14:32:11 +00:00
|
|
|
# temp fix to avoid import issues cf https://github.com/explosion/spaCy/issues/4200
|
|
|
|
from tqdm import tqdm
|
|
|
|
|
2017-11-26 22:21:47 +00:00
|
|
|
clusters = {}
|
2018-04-10 17:08:06 +00:00
|
|
|
if ftfy is None:
|
|
|
|
user_warning(Warnings.W004)
|
2017-11-26 22:21:47 +00:00
|
|
|
with clusters_loc.open() as f:
|
|
|
|
for line in tqdm(f):
|
|
|
|
try:
|
|
|
|
cluster, word, freq = line.split()
|
2018-04-10 17:08:06 +00:00
|
|
|
if ftfy is not None:
|
|
|
|
word = ftfy.fix_text(word)
|
2017-11-26 22:21:47 +00:00
|
|
|
except ValueError:
|
|
|
|
continue
|
|
|
|
# If the clusterer has only seen the word a few times, its
|
|
|
|
# cluster is unreliable.
|
|
|
|
if int(freq) >= 3:
|
|
|
|
clusters[word] = cluster
|
|
|
|
else:
|
2018-11-30 19:16:14 +00:00
|
|
|
clusters[word] = "0"
|
2017-11-26 22:21:47 +00:00
|
|
|
# Expand clusters with re-casing
|
|
|
|
for word, cluster in list(clusters.items()):
|
|
|
|
if word.lower() not in clusters:
|
|
|
|
clusters[word.lower()] = cluster
|
|
|
|
if word.title() not in clusters:
|
|
|
|
clusters[word.title()] = cluster
|
|
|
|
if word.upper() not in clusters:
|
|
|
|
clusters[word.upper()] = cluster
|
|
|
|
return clusters
|