2020-07-22 11:42:59 +00:00
|
|
|
# cython: infer_types=True, profile=True, binding=True
|
2020-08-09 20:28:29 +00:00
|
|
|
from typing import List
|
2020-07-22 11:42:59 +00:00
|
|
|
import numpy
|
|
|
|
import srsly
|
|
|
|
from thinc.api import Model, set_dropout_rate, SequenceCategoricalCrossentropy, Config
|
2020-08-09 20:28:29 +00:00
|
|
|
from thinc.types import Floats2d
|
2020-07-22 11:42:59 +00:00
|
|
|
import warnings
|
2020-09-08 20:44:25 +00:00
|
|
|
from itertools import islice
|
2020-07-22 11:42:59 +00:00
|
|
|
|
|
|
|
from ..tokens.doc cimport Doc
|
|
|
|
from ..morphology cimport Morphology
|
|
|
|
from ..vocab cimport Vocab
|
|
|
|
|
|
|
|
from .pipe import Pipe, deserialize_config
|
|
|
|
from ..language import Language
|
|
|
|
from ..attrs import POS, ID
|
|
|
|
from ..parts_of_speech import X
|
|
|
|
from ..errors import Errors, TempErrors, Warnings
|
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-09-09 08:31:03 +00:00
|
|
|
from ..training import validate_examples
|
2020-07-22 11:42:59 +00:00
|
|
|
from .. import util
|
|
|
|
|
|
|
|
|
|
|
|
default_model_config = """
|
|
|
|
[model]
|
|
|
|
@architectures = "spacy.Tagger.v1"
|
|
|
|
|
|
|
|
[model.tok2vec]
|
|
|
|
@architectures = "spacy.HashEmbedCNN.v1"
|
|
|
|
pretrained_vectors = null
|
|
|
|
width = 96
|
|
|
|
depth = 4
|
|
|
|
embed_size = 2000
|
|
|
|
window_size = 1
|
|
|
|
maxout_pieces = 3
|
|
|
|
subword_features = true
|
|
|
|
"""
|
|
|
|
DEFAULT_TAGGER_MODEL = Config().from_str(default_model_config)["model"]
|
|
|
|
|
|
|
|
|
|
|
|
@Language.factory(
|
|
|
|
"tagger",
|
|
|
|
assigns=["token.tag"],
|
2020-08-07 13:27:13 +00:00
|
|
|
default_config={"model": DEFAULT_TAGGER_MODEL},
|
|
|
|
scores=["tag_acc"],
|
2020-07-27 10:27:40 +00:00
|
|
|
default_score_weights={"tag_acc": 1.0},
|
2020-07-22 11:42:59 +00:00
|
|
|
)
|
2020-08-10 15:24:30 +00:00
|
|
|
def make_tagger(nlp: Language, name: str, model: Model):
|
2020-08-09 13:09:31 +00:00
|
|
|
"""Construct a part-of-speech tagger component.
|
|
|
|
|
|
|
|
model (Model[List[Doc], List[Floats2d]]): A model instance that predicts
|
|
|
|
the tag probabilities. The output vectors should match the number of tags
|
|
|
|
in size, and be normalized as probabilities (all scores between 0 and 1,
|
|
|
|
with the rows summing to 1).
|
|
|
|
"""
|
2020-08-07 13:27:13 +00:00
|
|
|
return Tagger(nlp.vocab, model, name)
|
2020-07-22 11:42:59 +00:00
|
|
|
|
|
|
|
|
|
|
|
class Tagger(Pipe):
|
|
|
|
"""Pipeline component for part-of-speech tagging.
|
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/tagger
|
2020-07-22 11:42:59 +00:00
|
|
|
"""
|
2020-08-07 13:27:13 +00:00
|
|
|
def __init__(self, vocab, model, name="tagger", *, labels=None):
|
2020-07-27 16:11:45 +00:00
|
|
|
"""Initialize a part-of-speech tagger.
|
|
|
|
|
|
|
|
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-07 13:27:13 +00:00
|
|
|
labels (List): The set of labels. Defaults to None.
|
2020-07-27 16:11:45 +00:00
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/tagger#init
|
2020-07-27 16:11:45 +00:00
|
|
|
"""
|
2020-07-22 11:42:59 +00:00
|
|
|
self.vocab = vocab
|
|
|
|
self.model = model
|
|
|
|
self.name = name
|
|
|
|
self._rehearsal_model = None
|
2020-08-07 13:27:13 +00:00
|
|
|
cfg = {"labels": labels or []}
|
2020-07-22 11:42:59 +00:00
|
|
|
self.cfg = dict(sorted(cfg.items()))
|
|
|
|
|
|
|
|
@property
|
|
|
|
def labels(self):
|
2020-07-27 16:11:45 +00:00
|
|
|
"""The labels currently added to the component. Note that even for a
|
|
|
|
blank component, this will always include the built-in coarse-grained
|
|
|
|
part-of-speech tags by default.
|
|
|
|
|
|
|
|
RETURNS (Tuple[str]): The labels.
|
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/tagger#labels
|
2020-07-27 16:11:45 +00:00
|
|
|
"""
|
2020-08-07 13:27:13 +00:00
|
|
|
return tuple(self.cfg["labels"])
|
2020-07-22 11:42:59 +00:00
|
|
|
|
|
|
|
def __call__(self, doc):
|
2020-07-27 16:11:45 +00:00
|
|
|
"""Apply the pipe to a Doc.
|
|
|
|
|
|
|
|
doc (Doc): The document to process.
|
|
|
|
RETURNS (Doc): The processed Doc.
|
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/tagger#call
|
2020-07-27 16:11:45 +00:00
|
|
|
"""
|
2020-07-22 11:42:59 +00:00
|
|
|
tags = self.predict([doc])
|
|
|
|
self.set_annotations([doc], tags)
|
|
|
|
return doc
|
|
|
|
|
2020-07-27 16:11:45 +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-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/tagger#pipe
|
2020-07-27 16:11:45 +00:00
|
|
|
"""
|
2020-07-22 11:42:59 +00:00
|
|
|
for docs in util.minibatch(stream, size=batch_size):
|
|
|
|
tag_ids = self.predict(docs)
|
|
|
|
self.set_annotations(docs, tag_ids)
|
|
|
|
yield from docs
|
|
|
|
|
|
|
|
def predict(self, docs):
|
2020-07-27 16:11:45 +00:00
|
|
|
"""Apply the pipeline's model to a batch of docs, without modifying them.
|
|
|
|
|
|
|
|
docs (Iterable[Doc]): The documents to predict.
|
|
|
|
RETURNS: The models prediction for each document.
|
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/tagger#predict
|
2020-07-27 16:11:45 +00:00
|
|
|
"""
|
2020-07-22 11:42:59 +00:00
|
|
|
if not any(len(doc) for doc in docs):
|
|
|
|
# Handle cases where there are no tokens in any docs.
|
|
|
|
n_labels = len(self.labels)
|
|
|
|
guesses = [self.model.ops.alloc((0, n_labels)) for doc in docs]
|
|
|
|
assert len(guesses) == len(docs)
|
|
|
|
return guesses
|
|
|
|
scores = self.model.predict(docs)
|
|
|
|
assert len(scores) == len(docs), (len(scores), len(docs))
|
|
|
|
guesses = self._scores2guesses(scores)
|
|
|
|
assert len(guesses) == len(docs)
|
|
|
|
return guesses
|
|
|
|
|
|
|
|
def _scores2guesses(self, scores):
|
|
|
|
guesses = []
|
|
|
|
for doc_scores in scores:
|
|
|
|
doc_guesses = doc_scores.argmax(axis=1)
|
|
|
|
if not isinstance(doc_guesses, numpy.ndarray):
|
|
|
|
doc_guesses = doc_guesses.get()
|
|
|
|
guesses.append(doc_guesses)
|
|
|
|
return guesses
|
|
|
|
|
|
|
|
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 Tagger.predict.
|
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/tagger#set_annotations
|
2020-07-27 16:11:45 +00:00
|
|
|
"""
|
2020-07-22 11:42:59 +00:00
|
|
|
if isinstance(docs, Doc):
|
|
|
|
docs = [docs]
|
|
|
|
cdef Doc doc
|
|
|
|
cdef Vocab vocab = self.vocab
|
|
|
|
for i, doc in enumerate(docs):
|
|
|
|
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):
|
|
|
|
# Don't clobber preset POS tags
|
|
|
|
if doc.c[j].tag == 0:
|
2020-08-07 13:27:13 +00:00
|
|
|
doc.c[j].tag = self.vocab.strings[self.labels[tag_id]]
|
2020-07-22 11:42:59 +00:00
|
|
|
doc.is_tagged = True
|
|
|
|
|
|
|
|
def update(self, examples, *, drop=0., sgd=None, losses=None, set_annotations=False):
|
2020-07-27 16:11:45 +00:00
|
|
|
"""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/tagger#update
|
2020-07-27 16:11:45 +00:00
|
|
|
"""
|
2020-07-22 11:42:59 +00:00
|
|
|
if losses is None:
|
|
|
|
losses = {}
|
|
|
|
losses.setdefault(self.name, 0.0)
|
2020-08-11 21:29:31 +00:00
|
|
|
validate_examples(examples, "Tagger.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
|
2020-07-22 11:42:59 +00:00
|
|
|
set_dropout_rate(self.model, drop)
|
2020-08-11 21:29:31 +00:00
|
|
|
tag_scores, bp_tag_scores = self.model.begin_update([eg.predicted for eg in examples])
|
2020-07-22 11:42:59 +00:00
|
|
|
for sc in tag_scores:
|
|
|
|
if self.model.ops.xp.isnan(sc.sum()):
|
2020-08-11 21:29:31 +00:00
|
|
|
raise ValueError(Errors.E940)
|
2020-07-22 11:42:59 +00:00
|
|
|
loss, d_tag_scores = self.get_loss(examples, tag_scores)
|
|
|
|
bp_tag_scores(d_tag_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, self._scores2guesses(tag_scores))
|
|
|
|
return losses
|
|
|
|
|
2020-07-27 16:11:45 +00:00
|
|
|
def rehearse(self, examples, *, drop=0., sgd=None, losses=None):
|
|
|
|
"""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/tagger#rehearse
|
2020-07-22 11:42:59 +00:00
|
|
|
"""
|
2020-08-11 21:29:31 +00:00
|
|
|
validate_examples(examples, "Tagger.rehearse")
|
|
|
|
docs = [eg.predicted for eg in examples]
|
2020-07-22 11:42:59 +00:00
|
|
|
if self._rehearsal_model is None:
|
|
|
|
return
|
|
|
|
if not any(len(doc) for doc in docs):
|
|
|
|
# Handle cases where there are no tokens in any docs.
|
|
|
|
return
|
|
|
|
set_dropout_rate(self.model, drop)
|
|
|
|
guesses, backprop = self.model.begin_update(docs)
|
|
|
|
target = self._rehearsal_model(examples)
|
|
|
|
gradient = guesses - target
|
|
|
|
backprop(gradient)
|
|
|
|
self.model.finish_update(sgd)
|
|
|
|
if losses is not None:
|
|
|
|
losses.setdefault(self.name, 0.0)
|
|
|
|
losses[self.name] += (gradient**2).sum()
|
|
|
|
|
|
|
|
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/tagger#get_loss
|
2020-07-27 16:11:45 +00:00
|
|
|
"""
|
2020-08-11 21:29:31 +00:00
|
|
|
validate_examples(examples, "Tagger.get_loss")
|
2020-07-22 11:42:59 +00:00
|
|
|
loss_func = SequenceCategoricalCrossentropy(names=self.labels, normalize=False)
|
2020-08-04 20:22:26 +00:00
|
|
|
truths = [eg.get_aligned("TAG", as_string=True) for eg in examples]
|
2020-07-22 11:42:59 +00:00
|
|
|
d_scores, loss = loss_func(scores, truths)
|
|
|
|
if self.model.ops.xp.isnan(loss):
|
|
|
|
raise ValueError("nan value when computing loss")
|
|
|
|
return float(loss), d_scores
|
|
|
|
|
2020-08-11 21:29:31 +00:00
|
|
|
def begin_training(self, get_examples, *, pipeline=None, sgd=None):
|
2020-09-08 20:44:25 +00:00
|
|
|
"""Initialize the pipe for training, using a representative set
|
|
|
|
of data examples.
|
2020-07-27 16:11:45 +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-07-27 16:11:45 +00:00
|
|
|
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/tagger#begin_training
|
2020-07-27 16:11:45 +00:00
|
|
|
"""
|
2020-09-08 20:44:25 +00:00
|
|
|
self._ensure_examples(get_examples)
|
2020-08-27 01:21:03 +00:00
|
|
|
doc_sample = []
|
2020-09-08 20:44:25 +00:00
|
|
|
label_sample = []
|
|
|
|
tags = set()
|
2020-07-22 11:42:59 +00:00
|
|
|
for example in get_examples():
|
2020-08-11 21:29:31 +00:00
|
|
|
for token in example.y:
|
2020-09-08 20:44:25 +00:00
|
|
|
if token.tag_:
|
|
|
|
tags.add(token.tag_)
|
2020-08-07 13:27:13 +00:00
|
|
|
for tag in sorted(tags):
|
|
|
|
self.add_label(tag)
|
2020-09-08 20:44:25 +00:00
|
|
|
for example in islice(get_examples(), 10):
|
|
|
|
doc_sample.append(example.x)
|
|
|
|
gold_tags = example.get_aligned("TAG", as_string=True)
|
|
|
|
gold_array = [[1.0 if tag == gold_tag else 0.0 for tag in self.labels] for gold_tag in gold_tags]
|
|
|
|
label_sample.append(self.model.ops.asarray(gold_array, dtype="float32"))
|
|
|
|
assert len(doc_sample) > 0, Errors.E923.format(name=self.name)
|
|
|
|
assert len(label_sample) > 0, Errors.E923.format(name=self.name)
|
|
|
|
self.model.initialize(X=doc_sample, Y=label_sample)
|
2020-07-22 11:42:59 +00:00
|
|
|
if sgd is None:
|
|
|
|
sgd = self.create_optimizer()
|
|
|
|
return sgd
|
|
|
|
|
2020-08-07 13:27:13 +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/tagger#add_label
|
2020-07-27 16:11:45 +00:00
|
|
|
"""
|
2020-07-22 11:42:59 +00:00
|
|
|
if not isinstance(label, str):
|
|
|
|
raise ValueError(Errors.E187)
|
|
|
|
if label in self.labels:
|
|
|
|
return 0
|
2020-09-08 20:44:25 +00:00
|
|
|
self._allow_extra_label()
|
2020-08-07 13:27:13 +00:00
|
|
|
self.cfg["labels"].append(label)
|
|
|
|
self.vocab.strings.add(label)
|
2020-07-22 11:42:59 +00:00
|
|
|
return 1
|
|
|
|
|
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
|
2020-08-26 13:39:30 +00:00
|
|
|
Scorer.score_token_attr for the attributes "tag".
|
2020-07-27 16:11:45 +00:00
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/tagger#score
|
2020-07-27 16:11:45 +00:00
|
|
|
"""
|
2020-08-11 21:29:31 +00:00
|
|
|
validate_examples(examples, "Tagger.score")
|
2020-08-07 13:27:13 +00:00
|
|
|
return Scorer.score_token_attr(examples, "tag", **kwargs)
|
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
|
|
|
|
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/tagger#to_bytes
|
2020-07-27 16:11:45 +00:00
|
|
|
"""
|
2020-07-22 11:42:59 +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 (Tagger): The loaded Tagger.
|
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/tagger#from_bytes
|
2020-07-27 16:11:45 +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 = {
|
|
|
|
"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/tagger#to_disk
|
2020-07-27 16:11:45 +00:00
|
|
|
"""
|
2020-07-22 11:42:59 +00:00
|
|
|
serialize = {
|
|
|
|
"vocab": lambda p: self.vocab.to_disk(p),
|
|
|
|
"model": lambda p: self.model.to_disk(p),
|
|
|
|
"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 (Tagger): The modified Tagger object.
|
|
|
|
|
2020-09-04 10:58:50 +00:00
|
|
|
DOCS: https://nightly.spacy.io/api/tagger#from_disk
|
2020-07-27 16:11:45 +00:00
|
|
|
"""
|
2020-07-22 11:42:59 +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-07-22 11:42:59 +00:00
|
|
|
|
|
|
|
deserialize = {
|
|
|
|
"vocab": lambda p: self.vocab.from_disk(p),
|
|
|
|
"cfg": lambda p: self.cfg.update(deserialize_config(p)),
|
|
|
|
"model": load_model,
|
|
|
|
}
|
|
|
|
util.from_disk(path, deserialize, exclude)
|
|
|
|
return self
|