2020-08-10 11:13:18 +00:00
|
|
|
# cython: infer_types=True, profile=True
|
2020-10-03 20:34:10 +00:00
|
|
|
import warnings
|
2020-09-29 14:22:13 +00:00
|
|
|
from typing import Optional, Tuple
|
2020-07-22 11:42:59 +00:00
|
|
|
import srsly
|
2020-08-11 21:29:31 +00:00
|
|
|
from thinc.api import set_dropout_rate, Model
|
2020-07-22 11:42:59 +00:00
|
|
|
|
|
|
|
from ..tokens.doc cimport Doc
|
|
|
|
|
2020-09-09 08:31:03 +00:00
|
|
|
from ..training import validate_examples
|
2020-10-03 20:34:10 +00:00
|
|
|
from ..errors import Errors, Warnings
|
2020-07-22 11:42:59 +00:00
|
|
|
from .. import util
|
|
|
|
|
|
|
|
|
2020-07-30 21:30:54 +00:00
|
|
|
cdef class Pipe:
|
2020-07-28 11:37:31 +00:00
|
|
|
"""This class is a base class and not instantiated directly. Trainable
|
|
|
|
pipeline components like the EntityRecognizer or TextCategorizer inherit
|
|
|
|
from it and it defines the interface that components should follow to
|
|
|
|
function as trainable components in a spaCy pipeline.
|
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/pipe
|
2020-07-22 11:42:59 +00:00
|
|
|
"""
|
2020-07-27 16:11:45 +00:00
|
|
|
def __init__(self, vocab, model, name, **cfg):
|
2020-07-28 11:37:31 +00:00
|
|
|
"""Initialize a pipeline component.
|
|
|
|
|
|
|
|
vocab (Vocab): The shared vocabulary.
|
|
|
|
model (thinc.api.Model): The Thinc Model powering the pipeline component.
|
|
|
|
name (str): The component instance name.
|
|
|
|
**cfg: Additonal settings and config parameters.
|
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/pipe#init
|
2020-07-28 11:37:31 +00:00
|
|
|
"""
|
2020-08-11 21:29:31 +00:00
|
|
|
self.vocab = vocab
|
|
|
|
self.model = model
|
|
|
|
self.name = name
|
|
|
|
self.cfg = dict(cfg)
|
2020-07-22 11:42:59 +00:00
|
|
|
|
2020-10-03 20:34:10 +00:00
|
|
|
@classmethod
|
|
|
|
def __init_subclass__(cls, **kwargs):
|
|
|
|
"""Raise a warning if an inheriting class implements 'begin_training'
|
|
|
|
(from v2) instead of the new 'initialize' method (from v3)"""
|
|
|
|
if hasattr(cls, "begin_training"):
|
|
|
|
warnings.warn(Warnings.W088)
|
|
|
|
|
2020-09-29 14:22:13 +00:00
|
|
|
@property
|
|
|
|
def labels(self) -> Optional[Tuple[str]]:
|
2020-09-29 14:55:07 +00:00
|
|
|
return []
|
2020-09-29 22:05:27 +00:00
|
|
|
|
2020-09-29 14:22:13 +00:00
|
|
|
@property
|
|
|
|
def label_data(self):
|
|
|
|
"""Optional JSON-serializable data that would be sufficient to recreate
|
|
|
|
the label set if provided to the `pipe.initialize()` method.
|
|
|
|
"""
|
|
|
|
return None
|
|
|
|
|
2020-07-22 11:42:59 +00:00
|
|
|
def __call__(self, Doc doc):
|
2020-07-29 12:03:35 +00:00
|
|
|
"""Apply the pipe to one document. The document is modified in place,
|
|
|
|
and returned. This usually happens under the hood when the nlp object
|
|
|
|
is called on a text and all components are applied to the Doc.
|
2020-07-28 11:37:31 +00:00
|
|
|
|
2020-08-31 10:41:39 +00:00
|
|
|
docs (Doc): The Doc to process.
|
2020-07-28 11:37:31 +00:00
|
|
|
RETURNS (Doc): The processed Doc.
|
2020-07-22 11:42:59 +00:00
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/pipe#call
|
2020-07-22 11:42:59 +00:00
|
|
|
"""
|
|
|
|
scores = self.predict([doc])
|
|
|
|
self.set_annotations([doc], scores)
|
|
|
|
return doc
|
|
|
|
|
2020-07-28 11:37:31 +00:00
|
|
|
def pipe(self, stream, *, batch_size=128):
|
|
|
|
"""Apply the pipe to a stream of documents. This usually happens under
|
|
|
|
the hood when the nlp object is called on a text and all components are
|
|
|
|
applied to the Doc.
|
|
|
|
|
|
|
|
stream (Iterable[Doc]): A stream of documents.
|
|
|
|
batch_size (int): The number of documents to buffer.
|
|
|
|
YIELDS (Doc): Processed documents in order.
|
2020-07-22 11:42:59 +00:00
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/pipe#pipe
|
2020-07-22 11:42:59 +00:00
|
|
|
"""
|
|
|
|
for docs in util.minibatch(stream, size=batch_size):
|
|
|
|
scores = self.predict(docs)
|
|
|
|
self.set_annotations(docs, scores)
|
|
|
|
yield from docs
|
|
|
|
|
|
|
|
def predict(self, docs):
|
2020-07-28 11:37:31 +00:00
|
|
|
"""Apply the pipeline's model to a batch of docs, without modifying them.
|
|
|
|
Returns a single tensor for a batch of documents.
|
|
|
|
|
|
|
|
docs (Iterable[Doc]): The documents to predict.
|
|
|
|
RETURNS: Vector representations for each token in the documents.
|
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/pipe#predict
|
2020-07-22 11:42:59 +00:00
|
|
|
"""
|
2020-08-11 21:29:31 +00:00
|
|
|
raise NotImplementedError(Errors.E931.format(method="predict", name=self.name))
|
2020-07-22 11:42:59 +00:00
|
|
|
|
|
|
|
def set_annotations(self, docs, scores):
|
2020-07-28 11:37:31 +00:00
|
|
|
"""Modify a batch of documents, using pre-computed scores.
|
|
|
|
|
|
|
|
docs (Iterable[Doc]): The documents to modify.
|
2020-07-29 12:07:13 +00:00
|
|
|
scores: The scores to assign.
|
2020-07-28 11:37:31 +00:00
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/pipe#set_annotations
|
2020-07-28 11:37:31 +00:00
|
|
|
"""
|
2020-08-11 21:29:31 +00:00
|
|
|
raise NotImplementedError(Errors.E931.format(method="set_annotations", name=self.name))
|
|
|
|
|
|
|
|
def update(self, examples, *, drop=0.0, set_annotations=False, sgd=None, losses=None):
|
|
|
|
"""Learn from a batch of documents and gold-standard information,
|
|
|
|
updating the pipe's model. Delegates to predict and get_loss.
|
|
|
|
|
|
|
|
examples (Iterable[Example]): A batch of Example objects.
|
|
|
|
drop (float): The dropout rate.
|
|
|
|
set_annotations (bool): Whether or not to update the Example objects
|
|
|
|
with the predictions.
|
|
|
|
sgd (thinc.api.Optimizer): The optimizer.
|
|
|
|
losses (Dict[str, float]): Optional record of the loss during training.
|
|
|
|
Updated using the component name as the key.
|
|
|
|
RETURNS (Dict[str, float]): The updated losses dictionary.
|
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/pipe#update
|
2020-08-11 21:29:31 +00:00
|
|
|
"""
|
|
|
|
if losses is None:
|
|
|
|
losses = {}
|
|
|
|
if not hasattr(self, "model") or self.model in (None, True, False):
|
|
|
|
return losses
|
|
|
|
losses.setdefault(self.name, 0.0)
|
|
|
|
validate_examples(examples, "Pipe.update")
|
|
|
|
if not any(len(eg.predicted) if eg.predicted else 0 for eg in examples):
|
|
|
|
# Handle cases where there are no tokens in any docs.
|
|
|
|
return
|
|
|
|
set_dropout_rate(self.model, drop)
|
|
|
|
scores, bp_scores = self.model.begin_update([eg.predicted for eg in examples])
|
|
|
|
loss, d_scores = self.get_loss(examples, scores)
|
|
|
|
bp_scores(d_scores)
|
|
|
|
if sgd not in (None, False):
|
|
|
|
self.model.finish_update(sgd)
|
|
|
|
losses[self.name] += loss
|
|
|
|
if set_annotations:
|
|
|
|
docs = [eg.predicted for eg in examples]
|
|
|
|
self.set_annotations(docs, scores=scores)
|
|
|
|
return losses
|
2020-07-22 11:42:59 +00:00
|
|
|
|
2020-07-28 11:37:31 +00:00
|
|
|
def rehearse(self, examples, *, sgd=None, losses=None, **config):
|
|
|
|
"""Perform a "rehearsal" update from a batch of data. Rehearsal updates
|
|
|
|
teach the current model to make predictions similar to an initial model,
|
|
|
|
to try to address the "catastrophic forgetting" problem. This feature is
|
|
|
|
experimental.
|
|
|
|
|
|
|
|
examples (Iterable[Example]): A batch of Example objects.
|
|
|
|
drop (float): The dropout rate.
|
|
|
|
sgd (thinc.api.Optimizer): The optimizer.
|
|
|
|
losses (Dict[str, float]): Optional record of the loss during training.
|
|
|
|
Updated using the component name as the key.
|
|
|
|
RETURNS (Dict[str, float]): The updated losses dictionary.
|
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/pipe#rehearse
|
2020-07-28 11:37:31 +00:00
|
|
|
"""
|
2020-07-22 11:42:59 +00:00
|
|
|
pass
|
|
|
|
|
|
|
|
def get_loss(self, examples, scores):
|
2020-07-28 11:37:31 +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/pipe#get_loss
|
2020-07-28 11:37:31 +00:00
|
|
|
"""
|
2020-08-11 21:29:31 +00:00
|
|
|
raise NotImplementedError(Errors.E931.format(method="get_loss", name=self.name))
|
2020-07-22 11:42:59 +00:00
|
|
|
|
|
|
|
def add_label(self, label):
|
2020-07-28 11:37:31 +00:00
|
|
|
"""Add an output label, to be predicted by the model. It's possible to
|
|
|
|
extend pretrained models with new labels, but care should be taken to
|
|
|
|
avoid the "catastrophic forgetting" problem.
|
|
|
|
|
|
|
|
label (str): The label to add.
|
|
|
|
RETURNS (int): 0 if label is already present, otherwise 1.
|
2020-07-22 11:42:59 +00:00
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/pipe#add_label
|
2020-07-22 11:42:59 +00:00
|
|
|
"""
|
2020-08-11 21:29:31 +00:00
|
|
|
raise NotImplementedError(Errors.E931.format(method="add_label", name=self.name))
|
2020-07-22 11:42:59 +00:00
|
|
|
|
2020-09-08 20:44:25 +00:00
|
|
|
|
|
|
|
def _require_labels(self) -> None:
|
|
|
|
"""Raise an error if the component's model has no labels defined."""
|
|
|
|
if not self.labels or list(self.labels) == [""]:
|
|
|
|
raise ValueError(Errors.E143.format(name=self.name))
|
|
|
|
|
|
|
|
|
|
|
|
def _allow_extra_label(self) -> None:
|
|
|
|
"""Raise an error if the component can not add any more labels."""
|
|
|
|
if self.model.has_dim("nO") and self.model.get_dim("nO") == len(self.labels):
|
|
|
|
if not self.is_resizable():
|
|
|
|
raise ValueError(Errors.E922.format(name=self.name, nO=self.model.get_dim("nO")))
|
|
|
|
|
|
|
|
|
2020-07-22 11:42:59 +00:00
|
|
|
def create_optimizer(self):
|
2020-07-28 11:37:31 +00:00
|
|
|
"""Create an optimizer for the pipeline component.
|
|
|
|
|
|
|
|
RETURNS (thinc.api.Optimizer): The optimizer.
|
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/pipe#create_optimizer
|
2020-07-28 11:37:31 +00:00
|
|
|
"""
|
2020-08-11 21:29:31 +00:00
|
|
|
return util.create_default_optimizer()
|
2020-07-22 11:42:59 +00:00
|
|
|
|
2020-09-29 10:20:26 +00:00
|
|
|
def initialize(self, get_examples, *, nlp=None):
|
2020-07-28 11:37:31 +00:00
|
|
|
"""Initialize the pipe for training, using data examples if available.
|
2020-09-08 20:44:25 +00:00
|
|
|
This method needs to be implemented by each Pipe component,
|
|
|
|
ensuring the internal model (if available) is initialized properly
|
|
|
|
using the provided sample of Example objects.
|
2020-07-28 11:37:31 +00:00
|
|
|
|
2020-09-08 20:44:25 +00:00
|
|
|
get_examples (Callable[[], Iterable[Example]]): Function that
|
|
|
|
returns a representative sample of gold-standard Example objects.
|
2020-09-29 10:20:26 +00:00
|
|
|
nlp (Language): The current nlp object the component is part of.
|
2020-07-28 11:37:31 +00:00
|
|
|
|
2020-09-28 19:35:09 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/pipe#initialize
|
2020-07-28 11:37:31 +00:00
|
|
|
"""
|
2020-09-29 22:05:27 +00:00
|
|
|
pass
|
2020-09-08 20:44:25 +00:00
|
|
|
|
|
|
|
def _ensure_examples(self, get_examples):
|
|
|
|
if get_examples is None or not hasattr(get_examples, "__call__"):
|
|
|
|
err = Errors.E930.format(name=self.name, obj=type(get_examples))
|
|
|
|
raise ValueError(err)
|
|
|
|
if not get_examples():
|
|
|
|
err = Errors.E930.format(name=self.name, obj=get_examples())
|
|
|
|
raise ValueError(err)
|
|
|
|
|
|
|
|
def is_resizable(self):
|
|
|
|
return hasattr(self, "model") and "resize_output" in self.model.attrs
|
2020-07-22 11:42:59 +00:00
|
|
|
|
|
|
|
def set_output(self, nO):
|
2020-09-08 20:44:25 +00:00
|
|
|
if self.is_resizable():
|
|
|
|
self.model.attrs["resize_output"](self.model, nO)
|
|
|
|
else:
|
|
|
|
raise NotImplementedError(Errors.E921)
|
2020-07-22 11:42:59 +00:00
|
|
|
|
|
|
|
def use_params(self, params):
|
2020-07-28 11:37:31 +00:00
|
|
|
"""Modify the pipe's model, to use the given parameter values. At the
|
|
|
|
end of the context, the original parameters are restored.
|
|
|
|
|
|
|
|
params (dict): The parameter values to use in the model.
|
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/pipe#use_params
|
2020-07-28 11:37:31 +00:00
|
|
|
"""
|
2020-07-22 11:42:59 +00:00
|
|
|
with self.model.use_params(params):
|
|
|
|
yield
|
|
|
|
|
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-28 11:37:31 +00:00
|
|
|
"""Score a batch of examples.
|
|
|
|
|
|
|
|
examples (Iterable[Example]): The examples to score.
|
|
|
|
RETURNS (Dict[str, Any]): The scores.
|
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/pipe#score
|
2020-07-28 11:37:31 +00:00
|
|
|
"""
|
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
|
|
|
return {}
|
|
|
|
|
2020-07-29 13:14:07 +00:00
|
|
|
def to_bytes(self, *, exclude=tuple()):
|
2020-07-22 11:42:59 +00:00
|
|
|
"""Serialize the pipe to a bytestring.
|
|
|
|
|
2020-07-28 11:37:31 +00:00
|
|
|
exclude (Iterable[str]): String names of serialization fields to exclude.
|
2020-07-22 11:42:59 +00:00
|
|
|
RETURNS (bytes): The serialized object.
|
2020-07-28 11:37:31 +00:00
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/pipe#to_bytes
|
2020-07-22 11:42:59 +00:00
|
|
|
"""
|
|
|
|
serialize = {}
|
|
|
|
serialize["cfg"] = lambda: srsly.json_dumps(self.cfg)
|
|
|
|
serialize["model"] = self.model.to_bytes
|
|
|
|
if hasattr(self, "vocab"):
|
|
|
|
serialize["vocab"] = self.vocab.to_bytes
|
|
|
|
return util.to_bytes(serialize, exclude)
|
|
|
|
|
2020-07-29 13:14:07 +00:00
|
|
|
def from_bytes(self, bytes_data, *, exclude=tuple()):
|
2020-07-28 11:37:31 +00:00
|
|
|
"""Load the pipe from a bytestring.
|
|
|
|
|
|
|
|
exclude (Iterable[str]): String names of serialization fields to exclude.
|
|
|
|
RETURNS (Pipe): The loaded object.
|
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/pipe#from_bytes
|
2020-07-28 11:37:31 +00:00
|
|
|
"""
|
2020-07-22 11:42:59 +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-07-22 11:42:59 +00:00
|
|
|
|
|
|
|
deserialize = {}
|
|
|
|
if hasattr(self, "vocab"):
|
|
|
|
deserialize["vocab"] = lambda b: self.vocab.from_bytes(b)
|
|
|
|
deserialize["cfg"] = lambda b: self.cfg.update(srsly.json_loads(b))
|
|
|
|
deserialize["model"] = load_model
|
|
|
|
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-28 11:37:31 +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/pipe#to_disk
|
2020-07-28 11:37:31 +00:00
|
|
|
"""
|
2020-07-22 11:42:59 +00:00
|
|
|
serialize = {}
|
|
|
|
serialize["cfg"] = lambda p: srsly.write_json(p, self.cfg)
|
|
|
|
serialize["vocab"] = lambda p: self.vocab.to_disk(p)
|
|
|
|
serialize["model"] = lambda p: self.model.to_disk(p)
|
|
|
|
util.to_disk(path, serialize, exclude)
|
|
|
|
|
2020-07-29 13:14:07 +00:00
|
|
|
def from_disk(self, path, *, exclude=tuple()):
|
2020-07-28 11:37:31 +00:00
|
|
|
"""Load the pipe from disk.
|
|
|
|
|
|
|
|
path (str / Path): Path to a directory.
|
|
|
|
exclude (Iterable[str]): String names of serialization fields to exclude.
|
|
|
|
RETURNS (Pipe): The loaded object.
|
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/pipe#from_disk
|
2020-07-28 11:37:31 +00:00
|
|
|
"""
|
2020-07-22 11:42:59 +00:00
|
|
|
|
|
|
|
def load_model(p):
|
|
|
|
try:
|
|
|
|
self.model.from_bytes(p.open("rb").read())
|
|
|
|
except AttributeError:
|
2020-08-05 21:53:21 +00:00
|
|
|
raise ValueError(Errors.E149) from None
|
2020-07-22 11:42:59 +00:00
|
|
|
|
|
|
|
deserialize = {}
|
|
|
|
deserialize["vocab"] = lambda p: self.vocab.from_disk(p)
|
|
|
|
deserialize["cfg"] = lambda p: self.cfg.update(deserialize_config(p))
|
|
|
|
deserialize["model"] = load_model
|
|
|
|
util.from_disk(path, deserialize, exclude)
|
|
|
|
return self
|
2020-07-28 11:37:31 +00:00
|
|
|
|
|
|
|
|
|
|
|
def deserialize_config(path):
|
|
|
|
if path.exists():
|
|
|
|
return srsly.read_json(path)
|
|
|
|
else:
|
|
|
|
return {}
|