2020-07-22 11:42:59 +00:00
|
|
|
# cython: infer_types=True, profile=True, binding=True
|
|
|
|
from typing import Optional
|
2020-04-02 12:46:32 +00:00
|
|
|
import srsly
|
2020-07-22 11:42:59 +00:00
|
|
|
from thinc.api import SequenceCategoricalCrossentropy, Model, Config
|
2020-01-29 16:06:46 +00:00
|
|
|
|
2020-03-02 10:48:10 +00:00
|
|
|
from ..tokens.doc cimport Doc
|
|
|
|
from ..vocab cimport Vocab
|
|
|
|
from ..morphology cimport Morphology
|
2020-08-11 21:29:31 +00:00
|
|
|
|
2020-04-02 12:46:32 +00:00
|
|
|
from ..parts_of_speech import IDS as POS_IDS
|
|
|
|
from ..symbols import POS
|
2020-07-22 11:42:59 +00:00
|
|
|
from ..language import Language
|
|
|
|
from ..errors import Errors
|
|
|
|
from .pipe import deserialize_config
|
|
|
|
from .tagger import Tagger
|
2019-03-07 09:46:27 +00:00
|
|
|
from .. import util
|
Refactor the Scorer to improve flexibility (#5731)
* Refactor the Scorer to improve flexibility
Refactor the `Scorer` to improve flexibility for arbitrary pipeline
components.
* Individual pipeline components provide their own `evaluate` methods
that score a list of `Example`s and return a dictionary of scores
* `Scorer` is initialized either:
* with a provided pipeline containing components to be scored
* with a default pipeline containing the built-in statistical
components (senter, tagger, morphologizer, parser, ner)
* `Scorer.score` evaluates a list of `Example`s and returns a dictionary
of scores referring to the scores provided by the components in the
pipeline
Significant differences:
* `tags_acc` is renamed to `tag_acc` to be consistent with `token_acc`
and the new `morph_acc`, `pos_acc`, and `lemma_acc`
* Scoring is no longer cumulative: `Scorer.score` scores a list of
examples rather than a single example and does not retain any state
about previously scored examples
* PRF values in the returned scores are no longer multiplied by 100
* Add kwargs to Morphologizer.evaluate
* Create generalized scoring methods in Scorer
* Generalized static scoring methods are added to `Scorer`
* Methods require an attribute (either on Token or Doc) that is
used to key the returned scores
Naming differences:
* `uas`, `las`, and `las_per_type` in the scores dict are renamed to
`dep_uas`, `dep_las`, and `dep_las_per_type`
Scoring differences:
* `Doc.sents` is now scored as spans rather than on sentence-initial
token positions so that `Doc.sents` and `Doc.ents` can be scored with
the same method (this lowers scores since a single incorrect sentence
start results in two incorrect spans)
* Simplify / extend hasattr check for eval method
* Add hasattr check to tokenizer scoring
* Simplify to hasattr check for component scoring
* Reset Example alignment if docs are set
Reset the Example alignment if either doc is set in case the
tokenization has changed.
* Add PRF tokenization scoring for tokens as spans
Add PRF scores for tokens as character spans. The scores are:
* token_acc: # correct tokens / # gold tokens
* token_p/r/f: PRF for (token.idx, token.idx + len(token))
* Add docstring to Scorer.score_tokenization
* Rename component.evaluate() to component.score()
* Update Scorer API docs
* Update scoring for positive_label in textcat
* Fix TextCategorizer.score kwargs
* Update Language.evaluate docs
* Update score names in default config
2020-07-25 10:53:02 +00:00
|
|
|
from ..scorer import Scorer
|
2020-08-11 21:29:31 +00:00
|
|
|
from ..gold import validate_examples
|
2018-09-24 21:14:06 +00:00
|
|
|
|
|
|
|
|
2020-07-22 11:42:59 +00:00
|
|
|
default_model_config = """
|
|
|
|
[model]
|
|
|
|
@architectures = "spacy.Tagger.v1"
|
|
|
|
|
|
|
|
[model.tok2vec]
|
2020-07-28 20:59:42 +00:00
|
|
|
@architectures = "spacy.Tok2Vec.v1"
|
|
|
|
|
|
|
|
[model.tok2vec.embed]
|
|
|
|
@architectures = "spacy.CharacterEmbed.v1"
|
|
|
|
width = 128
|
|
|
|
rows = 7000
|
|
|
|
nM = 64
|
|
|
|
nC = 8
|
|
|
|
|
|
|
|
[model.tok2vec.encode]
|
|
|
|
@architectures = "spacy.MaxoutWindowEncoder.v1"
|
2020-07-22 11:42:59 +00:00
|
|
|
width = 128
|
|
|
|
depth = 4
|
|
|
|
window_size = 1
|
|
|
|
maxout_pieces = 3
|
|
|
|
"""
|
2020-07-28 20:59:42 +00:00
|
|
|
|
2020-07-22 11:42:59 +00:00
|
|
|
DEFAULT_MORPH_MODEL = Config().from_str(default_model_config)["model"]
|
|
|
|
|
|
|
|
|
|
|
|
@Language.factory(
|
|
|
|
"morphologizer",
|
|
|
|
assigns=["token.morph", "token.pos"],
|
2020-07-27 10:27:40 +00:00
|
|
|
default_config={"model": DEFAULT_MORPH_MODEL},
|
|
|
|
scores=["pos_acc", "morph_acc", "morph_per_feat"],
|
|
|
|
default_score_weights={"pos_acc": 0.5, "morph_acc": 0.5},
|
2020-07-22 11:42:59 +00:00
|
|
|
)
|
|
|
|
def make_morphologizer(
|
|
|
|
nlp: Language,
|
|
|
|
model: Model,
|
|
|
|
name: str,
|
|
|
|
):
|
|
|
|
return Morphologizer(nlp.vocab, model, name)
|
|
|
|
|
2019-10-27 12:35:49 +00:00
|
|
|
|
2020-07-22 11:42:59 +00:00
|
|
|
class Morphologizer(Tagger):
|
2020-07-19 09:10:51 +00:00
|
|
|
POS_FEAT = "POS"
|
|
|
|
|
2020-07-22 11:42:59 +00:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
vocab: Vocab,
|
|
|
|
model: Model,
|
|
|
|
name: str = "morphologizer",
|
|
|
|
*,
|
|
|
|
labels_morph: Optional[dict] = None,
|
|
|
|
labels_pos: Optional[dict] = None,
|
|
|
|
):
|
2020-07-27 16:11:45 +00:00
|
|
|
"""Initialize a morphologizer.
|
|
|
|
|
|
|
|
vocab (Vocab): The shared vocabulary.
|
|
|
|
model (thinc.api.Model): The Thinc Model powering the pipeline component.
|
|
|
|
name (str): The component instance name, used to add entries to the
|
|
|
|
losses during training.
|
2020-08-09 20:31:52 +00:00
|
|
|
labels_morph (dict): Mapping of morph + POS tags to morph labels.
|
|
|
|
labels_pos (dict): Mapping of morph + POS tags to POS tags.
|
2020-07-27 16:11:45 +00:00
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/morphologizer#init
|
2020-07-27 16:11:45 +00:00
|
|
|
"""
|
2018-09-24 21:14:06 +00:00
|
|
|
self.vocab = vocab
|
|
|
|
self.model = model
|
2020-07-22 11:42:59 +00:00
|
|
|
self.name = name
|
2020-04-02 12:46:32 +00:00
|
|
|
self._rehearsal_model = None
|
2020-07-19 09:10:51 +00:00
|
|
|
# to be able to set annotations without string operations on labels,
|
|
|
|
# store mappings from morph+POS labels to token-level annotations:
|
|
|
|
# 1) labels_morph stores a mapping from morph+POS->morph
|
|
|
|
# 2) labels_pos stores a mapping from morph+POS->POS
|
2020-07-22 11:42:59 +00:00
|
|
|
cfg = {"labels_morph": labels_morph or {}, "labels_pos": labels_pos or {}}
|
|
|
|
self.cfg = dict(sorted(cfg.items()))
|
2020-07-19 09:10:51 +00:00
|
|
|
# add mappings for empty morph
|
|
|
|
self.cfg["labels_morph"][Morphology.EMPTY_MORPH] = Morphology.EMPTY_MORPH
|
|
|
|
self.cfg["labels_pos"][Morphology.EMPTY_MORPH] = POS_IDS[""]
|
2018-09-24 21:14:06 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def labels(self):
|
2020-07-27 16:11:45 +00:00
|
|
|
"""RETURNS (Tuple[str]): The labels currently added to the component."""
|
2020-07-19 09:10:51 +00:00
|
|
|
return tuple(self.cfg["labels_morph"].keys())
|
2020-04-02 12:46:32 +00:00
|
|
|
|
|
|
|
def add_label(self, label):
|
2020-07-27 16:11:45 +00:00
|
|
|
"""Add a new label to the pipe.
|
|
|
|
|
|
|
|
label (str): The label to add.
|
2020-07-28 11:37:31 +00:00
|
|
|
RETURNS (int): 0 if label is already present, otherwise 1.
|
2020-07-27 16:11:45 +00:00
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/morphologizer#add_label
|
2020-07-27 16:11:45 +00:00
|
|
|
"""
|
2020-04-02 12:46:32 +00:00
|
|
|
if not isinstance(label, str):
|
|
|
|
raise ValueError(Errors.E187)
|
|
|
|
if label in self.labels:
|
|
|
|
return 0
|
2020-07-19 09:10:51 +00:00
|
|
|
# normalize label
|
|
|
|
norm_label = self.vocab.morphology.normalize_features(label)
|
|
|
|
# extract separate POS and morph tags
|
|
|
|
label_dict = Morphology.feats_to_dict(label)
|
|
|
|
pos = label_dict.get(self.POS_FEAT, "")
|
|
|
|
if self.POS_FEAT in label_dict:
|
|
|
|
label_dict.pop(self.POS_FEAT)
|
|
|
|
# normalize morph string and add to morphology table
|
|
|
|
norm_morph = self.vocab.strings[self.vocab.morphology.add(label_dict)]
|
|
|
|
# add label mappings
|
|
|
|
if norm_label not in self.cfg["labels_morph"]:
|
|
|
|
self.cfg["labels_morph"][norm_label] = norm_morph
|
|
|
|
self.cfg["labels_pos"][norm_label] = POS_IDS[pos]
|
2020-04-02 12:46:32 +00:00
|
|
|
return 1
|
2018-09-24 21:14:06 +00:00
|
|
|
|
2020-08-11 21:29:31 +00:00
|
|
|
def begin_training(self, get_examples, *, pipeline=None, sgd=None):
|
2020-07-27 16:11:45 +00:00
|
|
|
"""Initialize the pipe for training, using data examples if available.
|
|
|
|
|
|
|
|
get_examples (Callable[[], Iterable[Example]]): Optional function that
|
|
|
|
returns gold-standard Example objects.
|
|
|
|
pipeline (List[Tuple[str, Callable]]): Optional list of pipeline
|
|
|
|
components that this component is part of. Corresponds to
|
|
|
|
nlp.pipeline.
|
|
|
|
sgd (thinc.api.Optimizer): Optional optimizer. Will be created with
|
|
|
|
create_optimizer if it doesn't exist.
|
|
|
|
RETURNS (thinc.api.Optimizer): The optimizer.
|
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/morphologizer#begin_training
|
2020-07-27 16:11:45 +00:00
|
|
|
"""
|
2020-08-11 21:29:31 +00:00
|
|
|
if not hasattr(get_examples, "__call__"):
|
|
|
|
err = Errors.E930.format(name="Morphologizer", obj=type(get_examples))
|
|
|
|
raise ValueError(err)
|
2020-04-02 12:46:32 +00:00
|
|
|
for example in get_examples():
|
2020-06-26 17:34:12 +00:00
|
|
|
for i, token in enumerate(example.reference):
|
|
|
|
pos = token.pos_
|
2020-07-19 09:10:51 +00:00
|
|
|
morph = token.morph_
|
|
|
|
# create and add the combined morph+POS label
|
|
|
|
morph_dict = Morphology.feats_to_dict(morph)
|
2020-04-02 12:46:32 +00:00
|
|
|
if pos:
|
2020-07-19 09:10:51 +00:00
|
|
|
morph_dict[self.POS_FEAT] = pos
|
|
|
|
norm_label = self.vocab.strings[self.vocab.morphology.add(morph_dict)]
|
|
|
|
# add label->morph and label->POS mappings
|
|
|
|
if norm_label not in self.cfg["labels_morph"]:
|
|
|
|
self.cfg["labels_morph"][norm_label] = morph
|
|
|
|
self.cfg["labels_pos"][norm_label] = POS_IDS[pos]
|
2020-02-27 17:42:27 +00:00
|
|
|
self.set_output(len(self.labels))
|
|
|
|
self.model.initialize()
|
|
|
|
if sgd is None:
|
|
|
|
sgd = self.create_optimizer()
|
|
|
|
return sgd
|
|
|
|
|
2020-04-02 12:46:32 +00:00
|
|
|
def set_annotations(self, docs, batch_tag_ids):
|
2020-07-27 16:11:45 +00:00
|
|
|
"""Modify a batch of documents, using pre-computed scores.
|
|
|
|
|
|
|
|
docs (Iterable[Doc]): The documents to modify.
|
|
|
|
batch_tag_ids: The IDs to set, produced by Morphologizer.predict.
|
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/morphologizer#set_annotations
|
2020-07-27 16:11:45 +00:00
|
|
|
"""
|
2018-09-24 21:14:06 +00:00
|
|
|
if isinstance(docs, Doc):
|
|
|
|
docs = [docs]
|
|
|
|
cdef Doc doc
|
|
|
|
cdef Vocab vocab = self.vocab
|
|
|
|
for i, doc in enumerate(docs):
|
2020-04-02 12:46:32 +00:00
|
|
|
doc_tag_ids = batch_tag_ids[i]
|
|
|
|
if hasattr(doc_tag_ids, "get"):
|
|
|
|
doc_tag_ids = doc_tag_ids.get()
|
|
|
|
for j, tag_id in enumerate(doc_tag_ids):
|
|
|
|
morph = self.labels[tag_id]
|
2020-07-19 09:10:51 +00:00
|
|
|
doc.c[j].morph = self.vocab.morphology.add(self.cfg["labels_morph"][morph])
|
|
|
|
doc.c[j].pos = self.cfg["labels_pos"][morph]
|
2020-04-02 12:46:32 +00:00
|
|
|
|
|
|
|
doc.is_morphed = True
|
2018-09-24 21:14:06 +00:00
|
|
|
|
2019-11-11 16:35:27 +00:00
|
|
|
def get_loss(self, examples, scores):
|
2020-07-27 16:11:45 +00:00
|
|
|
"""Find the loss and gradient of loss for the batch of documents and
|
|
|
|
their predicted scores.
|
|
|
|
|
|
|
|
examples (Iterable[Examples]): The batch of examples.
|
|
|
|
scores: Scores representing the model's predictions.
|
|
|
|
RETUTNRS (Tuple[float, float]): The loss and the gradient.
|
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/morphologizer#get_loss
|
2020-07-27 16:11:45 +00:00
|
|
|
"""
|
2020-08-11 21:29:31 +00:00
|
|
|
validate_examples(examples, "Morphologizer.get_loss")
|
2020-07-08 11:59:28 +00:00
|
|
|
loss_func = SequenceCategoricalCrossentropy(names=self.labels, normalize=False)
|
|
|
|
truths = []
|
2020-06-26 17:34:12 +00:00
|
|
|
for eg in examples:
|
2020-07-08 11:59:28 +00:00
|
|
|
eg_truths = []
|
2020-06-26 17:34:12 +00:00
|
|
|
pos_tags = eg.get_aligned("POS", as_string=True)
|
|
|
|
morphs = eg.get_aligned("MORPH", as_string=True)
|
|
|
|
for i in range(len(morphs)):
|
|
|
|
pos = pos_tags[i]
|
|
|
|
morph = morphs[i]
|
2020-07-19 09:10:51 +00:00
|
|
|
# POS may align (same value for multiple tokens) when morph
|
|
|
|
# doesn't, so if either is None, treat both as None here so that
|
|
|
|
# truths doesn't end up with an unknown morph+POS combination
|
|
|
|
if pos is None or morph is None:
|
|
|
|
pos = None
|
|
|
|
morph = None
|
|
|
|
label_dict = Morphology.feats_to_dict(morph)
|
2020-04-02 12:46:32 +00:00
|
|
|
if pos:
|
2020-07-19 09:10:51 +00:00
|
|
|
label_dict[self.POS_FEAT] = pos
|
|
|
|
label = self.vocab.strings[self.vocab.morphology.add(label_dict)]
|
|
|
|
eg_truths.append(label)
|
2020-07-08 11:59:28 +00:00
|
|
|
truths.append(eg_truths)
|
|
|
|
d_scores, loss = loss_func(scores, truths)
|
|
|
|
if self.model.ops.xp.isnan(loss):
|
|
|
|
raise ValueError("nan value when computing loss")
|
2018-09-24 21:14:06 +00:00
|
|
|
return float(loss), d_scores
|
|
|
|
|
Refactor the Scorer to improve flexibility (#5731)
* Refactor the Scorer to improve flexibility
Refactor the `Scorer` to improve flexibility for arbitrary pipeline
components.
* Individual pipeline components provide their own `evaluate` methods
that score a list of `Example`s and return a dictionary of scores
* `Scorer` is initialized either:
* with a provided pipeline containing components to be scored
* with a default pipeline containing the built-in statistical
components (senter, tagger, morphologizer, parser, ner)
* `Scorer.score` evaluates a list of `Example`s and returns a dictionary
of scores referring to the scores provided by the components in the
pipeline
Significant differences:
* `tags_acc` is renamed to `tag_acc` to be consistent with `token_acc`
and the new `morph_acc`, `pos_acc`, and `lemma_acc`
* Scoring is no longer cumulative: `Scorer.score` scores a list of
examples rather than a single example and does not retain any state
about previously scored examples
* PRF values in the returned scores are no longer multiplied by 100
* Add kwargs to Morphologizer.evaluate
* Create generalized scoring methods in Scorer
* Generalized static scoring methods are added to `Scorer`
* Methods require an attribute (either on Token or Doc) that is
used to key the returned scores
Naming differences:
* `uas`, `las`, and `las_per_type` in the scores dict are renamed to
`dep_uas`, `dep_las`, and `dep_las_per_type`
Scoring differences:
* `Doc.sents` is now scored as spans rather than on sentence-initial
token positions so that `Doc.sents` and `Doc.ents` can be scored with
the same method (this lowers scores since a single incorrect sentence
start results in two incorrect spans)
* Simplify / extend hasattr check for eval method
* Add hasattr check to tokenizer scoring
* Simplify to hasattr check for component scoring
* Reset Example alignment if docs are set
Reset the Example alignment if either doc is set in case the
tokenization has changed.
* Add PRF tokenization scoring for tokens as spans
Add PRF scores for tokens as character spans. The scores are:
* token_acc: # correct tokens / # gold tokens
* token_p/r/f: PRF for (token.idx, token.idx + len(token))
* Add docstring to Scorer.score_tokenization
* Rename component.evaluate() to component.score()
* Update Scorer API docs
* Update scoring for positive_label in textcat
* Fix TextCategorizer.score kwargs
* Update Language.evaluate docs
* Update score names in default config
2020-07-25 10:53:02 +00:00
|
|
|
def score(self, examples, **kwargs):
|
2020-07-27 16:11:45 +00:00
|
|
|
"""Score a batch of examples.
|
|
|
|
|
|
|
|
examples (Iterable[Example]): The examples to score.
|
|
|
|
RETURNS (Dict[str, Any]): The scores, produced by
|
|
|
|
Scorer.score_token_attr for the attributes "pos" and "morph" and
|
|
|
|
Scorer.score_token_attr_per_feat for the attribute "morph".
|
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/morphologizer#score
|
2020-07-27 16:11:45 +00:00
|
|
|
"""
|
2020-08-11 21:29:31 +00:00
|
|
|
validate_examples(examples, "Morphologizer.score")
|
Refactor the Scorer to improve flexibility (#5731)
* Refactor the Scorer to improve flexibility
Refactor the `Scorer` to improve flexibility for arbitrary pipeline
components.
* Individual pipeline components provide their own `evaluate` methods
that score a list of `Example`s and return a dictionary of scores
* `Scorer` is initialized either:
* with a provided pipeline containing components to be scored
* with a default pipeline containing the built-in statistical
components (senter, tagger, morphologizer, parser, ner)
* `Scorer.score` evaluates a list of `Example`s and returns a dictionary
of scores referring to the scores provided by the components in the
pipeline
Significant differences:
* `tags_acc` is renamed to `tag_acc` to be consistent with `token_acc`
and the new `morph_acc`, `pos_acc`, and `lemma_acc`
* Scoring is no longer cumulative: `Scorer.score` scores a list of
examples rather than a single example and does not retain any state
about previously scored examples
* PRF values in the returned scores are no longer multiplied by 100
* Add kwargs to Morphologizer.evaluate
* Create generalized scoring methods in Scorer
* Generalized static scoring methods are added to `Scorer`
* Methods require an attribute (either on Token or Doc) that is
used to key the returned scores
Naming differences:
* `uas`, `las`, and `las_per_type` in the scores dict are renamed to
`dep_uas`, `dep_las`, and `dep_las_per_type`
Scoring differences:
* `Doc.sents` is now scored as spans rather than on sentence-initial
token positions so that `Doc.sents` and `Doc.ents` can be scored with
the same method (this lowers scores since a single incorrect sentence
start results in two incorrect spans)
* Simplify / extend hasattr check for eval method
* Add hasattr check to tokenizer scoring
* Simplify to hasattr check for component scoring
* Reset Example alignment if docs are set
Reset the Example alignment if either doc is set in case the
tokenization has changed.
* Add PRF tokenization scoring for tokens as spans
Add PRF scores for tokens as character spans. The scores are:
* token_acc: # correct tokens / # gold tokens
* token_p/r/f: PRF for (token.idx, token.idx + len(token))
* Add docstring to Scorer.score_tokenization
* Rename component.evaluate() to component.score()
* Update Scorer API docs
* Update scoring for positive_label in textcat
* Fix TextCategorizer.score kwargs
* Update Language.evaluate docs
* Update score names in default config
2020-07-25 10:53:02 +00:00
|
|
|
results = {}
|
|
|
|
results.update(Scorer.score_token_attr(examples, "pos", **kwargs))
|
|
|
|
results.update(Scorer.score_token_attr(examples, "morph", **kwargs))
|
|
|
|
results.update(Scorer.score_token_attr_per_feat(examples,
|
|
|
|
"morph", **kwargs))
|
|
|
|
return results
|
|
|
|
|
2020-07-29 13:14:07 +00:00
|
|
|
def to_bytes(self, *, exclude=tuple()):
|
2020-07-27 16:11:45 +00:00
|
|
|
"""Serialize the pipe to a bytestring.
|
|
|
|
|
|
|
|
exclude (Iterable[str]): String names of serialization fields to exclude.
|
|
|
|
RETURNS (bytes): The serialized object.
|
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/morphologizer#to_bytes
|
2020-07-27 16:11:45 +00:00
|
|
|
"""
|
2020-04-02 12:46:32 +00:00
|
|
|
serialize = {}
|
|
|
|
serialize["model"] = self.model.to_bytes
|
|
|
|
serialize["vocab"] = self.vocab.to_bytes
|
|
|
|
serialize["cfg"] = lambda: srsly.json_dumps(self.cfg)
|
|
|
|
return util.to_bytes(serialize, exclude)
|
|
|
|
|
2020-07-29 13:14:07 +00:00
|
|
|
def from_bytes(self, bytes_data, *, exclude=tuple()):
|
2020-07-27 16:11:45 +00:00
|
|
|
"""Load the pipe from a bytestring.
|
|
|
|
|
|
|
|
bytes_data (bytes): The serialized pipe.
|
|
|
|
exclude (Iterable[str]): String names of serialization fields to exclude.
|
|
|
|
RETURNS (Morphologizer): The loaded Morphologizer.
|
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/morphologizer#from_bytes
|
2020-07-27 16:11:45 +00:00
|
|
|
"""
|
2020-04-02 12:46:32 +00:00
|
|
|
def load_model(b):
|
|
|
|
try:
|
|
|
|
self.model.from_bytes(b)
|
|
|
|
except AttributeError:
|
2020-08-05 21:53:21 +00:00
|
|
|
raise ValueError(Errors.E149) from None
|
2020-04-02 12:46:32 +00:00
|
|
|
|
|
|
|
deserialize = {
|
|
|
|
"vocab": lambda b: self.vocab.from_bytes(b),
|
|
|
|
"cfg": lambda b: self.cfg.update(srsly.json_loads(b)),
|
|
|
|
"model": lambda b: load_model(b),
|
|
|
|
}
|
|
|
|
util.from_bytes(bytes_data, deserialize, exclude)
|
|
|
|
return self
|
|
|
|
|
2020-07-29 13:14:07 +00:00
|
|
|
def to_disk(self, path, *, exclude=tuple()):
|
2020-07-27 16:11:45 +00:00
|
|
|
"""Serialize the pipe to disk.
|
|
|
|
|
|
|
|
path (str / Path): Path to a directory.
|
|
|
|
exclude (Iterable[str]): String names of serialization fields to exclude.
|
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/morphologizer#to_disk
|
2020-07-27 16:11:45 +00:00
|
|
|
"""
|
2020-04-02 12:46:32 +00:00
|
|
|
serialize = {
|
|
|
|
"vocab": lambda p: self.vocab.to_disk(p),
|
|
|
|
"model": lambda p: p.open("wb").write(self.model.to_bytes()),
|
|
|
|
"cfg": lambda p: srsly.write_json(p, self.cfg),
|
|
|
|
}
|
|
|
|
util.to_disk(path, serialize, exclude)
|
|
|
|
|
2020-07-29 13:14:07 +00:00
|
|
|
def from_disk(self, path, *, exclude=tuple()):
|
2020-07-27 16:11:45 +00:00
|
|
|
"""Load the pipe from disk. Modifies the object in place and returns it.
|
|
|
|
|
|
|
|
path (str / Path): Path to a directory.
|
|
|
|
exclude (Iterable[str]): String names of serialization fields to exclude.
|
|
|
|
RETURNS (Morphologizer): The modified Morphologizer object.
|
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/morphologizer#from_disk
|
2020-07-27 16:11:45 +00:00
|
|
|
"""
|
2020-04-02 12:46:32 +00:00
|
|
|
def load_model(p):
|
|
|
|
with p.open("rb") as file_:
|
|
|
|
try:
|
|
|
|
self.model.from_bytes(file_.read())
|
|
|
|
except AttributeError:
|
2020-08-05 21:53:21 +00:00
|
|
|
raise ValueError(Errors.E149) from None
|
2020-04-02 12:46:32 +00:00
|
|
|
|
|
|
|
deserialize = {
|
|
|
|
"vocab": lambda p: self.vocab.from_disk(p),
|
2020-07-22 11:42:59 +00:00
|
|
|
"cfg": lambda p: self.cfg.update(deserialize_config(p)),
|
2020-04-02 12:46:32 +00:00
|
|
|
"model": load_model,
|
|
|
|
}
|
|
|
|
util.from_disk(path, deserialize, exclude)
|
|
|
|
return self
|