2020-07-22 14:42:59 +03:00
|
|
|
# cython: infer_types=True, profile=True, binding=True
|
2021-12-29 13:04:39 +03:00
|
|
|
from itertools import islice
|
2023-06-14 18:48:41 +03:00
|
|
|
from typing import Callable, Optional
|
2020-09-08 23:44:25 +03:00
|
|
|
|
2023-06-14 18:48:41 +03:00
|
|
|
from thinc.api import Config, Model, SequenceCategoricalCrossentropy
|
2020-07-22 14:42:59 +03:00
|
|
|
|
|
|
|
from ..tokens.doc cimport Doc
|
|
|
|
|
2023-06-14 18:48:41 +03:00
|
|
|
from .. import util
|
2020-07-22 14:42:59 +03:00
|
|
|
from ..errors import Errors
|
2023-06-14 18:48:41 +03:00
|
|
|
from ..language import Language
|
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 13:53:02 +03:00
|
|
|
from ..scorer import Scorer
|
2020-10-08 22:33:49 +03:00
|
|
|
from ..training import validate_examples, validate_get_examples
|
2021-08-10 16:13:39 +03:00
|
|
|
from ..util import registry
|
2023-06-14 18:48:41 +03:00
|
|
|
from .tagger import Tagger
|
2020-07-22 14:42:59 +03:00
|
|
|
|
Add overwrite settings for more components (#9050)
* Add overwrite settings for more components
For pipeline components where it's relevant and not already implemented,
add an explicit `overwrite` setting that controls whether
`set_annotations` overwrites existing annotation.
For the `morphologizer`, add an additional setting `extend`, which
controls whether the existing features are preserved.
* +overwrite, +extend: overwrite values of existing features, add any new
features
* +overwrite, -extend: overwrite completely, removing any existing
features
* -overwrite, +extend: keep values of existing features, add any new
features
* -overwrite, -extend: do not modify the existing value if set
In all cases an unset value will be set by `set_annotations`.
Preserve current overwrite defaults:
* True: morphologizer, entity linker
* False: tagger, sentencizer, senter
* Add backwards compat overwrite settings
* Put empty line back
Removed by accident in last commit
* Set backwards-compatible defaults in __init__
Because the `TrainablePipe` serialization methods update `cfg`, there's
no straightforward way to detect whether models serialized with a
previous version are missing the overwrite settings.
It would be possible in the sentencizer due to its separate
serialization methods, however to keep the changes parallel, this also
sets the default in `__init__`.
* Remove traces
Co-authored-by: Paul O'Leary McCann <polm@dampfkraft.com>
2021-09-30 16:35:55 +03:00
|
|
|
# See #9050
|
|
|
|
BACKWARD_OVERWRITE = False
|
2020-07-22 14:42:59 +03:00
|
|
|
|
|
|
|
default_model_config = """
|
|
|
|
[model]
|
2022-03-15 16:15:31 +03:00
|
|
|
@architectures = "spacy.Tagger.v2"
|
2020-07-22 14:42:59 +03:00
|
|
|
|
|
|
|
[model.tok2vec]
|
2021-04-22 11:04:15 +03:00
|
|
|
@architectures = "spacy.HashEmbedCNN.v2"
|
2020-07-22 14:42:59 +03:00
|
|
|
pretrained_vectors = null
|
|
|
|
width = 12
|
|
|
|
depth = 1
|
|
|
|
embed_size = 2000
|
|
|
|
window_size = 1
|
|
|
|
maxout_pieces = 2
|
|
|
|
subword_features = true
|
|
|
|
"""
|
|
|
|
DEFAULT_SENTER_MODEL = Config().from_str(default_model_config)["model"]
|
|
|
|
|
|
|
|
|
|
|
|
@Language.factory(
|
|
|
|
"senter",
|
|
|
|
assigns=["token.is_sent_start"],
|
Add overwrite settings for more components (#9050)
* Add overwrite settings for more components
For pipeline components where it's relevant and not already implemented,
add an explicit `overwrite` setting that controls whether
`set_annotations` overwrites existing annotation.
For the `morphologizer`, add an additional setting `extend`, which
controls whether the existing features are preserved.
* +overwrite, +extend: overwrite values of existing features, add any new
features
* +overwrite, -extend: overwrite completely, removing any existing
features
* -overwrite, +extend: keep values of existing features, add any new
features
* -overwrite, -extend: do not modify the existing value if set
In all cases an unset value will be set by `set_annotations`.
Preserve current overwrite defaults:
* True: morphologizer, entity linker
* False: tagger, sentencizer, senter
* Add backwards compat overwrite settings
* Put empty line back
Removed by accident in last commit
* Set backwards-compatible defaults in __init__
Because the `TrainablePipe` serialization methods update `cfg`, there's
no straightforward way to detect whether models serialized with a
previous version are missing the overwrite settings.
It would be possible in the sentencizer due to its separate
serialization methods, however to keep the changes parallel, this also
sets the default in `__init__`.
* Remove traces
Co-authored-by: Paul O'Leary McCann <polm@dampfkraft.com>
2021-09-30 16:35:55 +03:00
|
|
|
default_config={"model": DEFAULT_SENTER_MODEL, "overwrite": False, "scorer": {"@scorers": "spacy.senter_scorer.v1"}},
|
2020-07-27 13:27:40 +03:00
|
|
|
default_score_weights={"sents_f": 1.0, "sents_p": 0.0, "sents_r": 0.0},
|
2020-07-22 14:42:59 +03:00
|
|
|
)
|
Add overwrite settings for more components (#9050)
* Add overwrite settings for more components
For pipeline components where it's relevant and not already implemented,
add an explicit `overwrite` setting that controls whether
`set_annotations` overwrites existing annotation.
For the `morphologizer`, add an additional setting `extend`, which
controls whether the existing features are preserved.
* +overwrite, +extend: overwrite values of existing features, add any new
features
* +overwrite, -extend: overwrite completely, removing any existing
features
* -overwrite, +extend: keep values of existing features, add any new
features
* -overwrite, -extend: do not modify the existing value if set
In all cases an unset value will be set by `set_annotations`.
Preserve current overwrite defaults:
* True: morphologizer, entity linker
* False: tagger, sentencizer, senter
* Add backwards compat overwrite settings
* Put empty line back
Removed by accident in last commit
* Set backwards-compatible defaults in __init__
Because the `TrainablePipe` serialization methods update `cfg`, there's
no straightforward way to detect whether models serialized with a
previous version are missing the overwrite settings.
It would be possible in the sentencizer due to its separate
serialization methods, however to keep the changes parallel, this also
sets the default in `__init__`.
* Remove traces
Co-authored-by: Paul O'Leary McCann <polm@dampfkraft.com>
2021-09-30 16:35:55 +03:00
|
|
|
def make_senter(nlp: Language, name: str, model: Model, overwrite: bool, scorer: Optional[Callable]):
|
|
|
|
return SentenceRecognizer(nlp.vocab, model, name, overwrite=overwrite, scorer=scorer)
|
2021-08-10 16:13:39 +03:00
|
|
|
|
|
|
|
|
|
|
|
def senter_score(examples, **kwargs):
|
|
|
|
def has_sents(doc):
|
|
|
|
return doc.has_annotation("SENT_START")
|
|
|
|
|
|
|
|
results = Scorer.score_spans(examples, "sents", has_annotation=has_sents, **kwargs)
|
|
|
|
del results["sents_per_type"]
|
|
|
|
return results
|
|
|
|
|
|
|
|
|
|
|
|
@registry.scorers("spacy.senter_scorer.v1")
|
|
|
|
def make_senter_scorer():
|
|
|
|
return senter_score
|
2020-07-22 14:42:59 +03:00
|
|
|
|
|
|
|
|
|
|
|
class SentenceRecognizer(Tagger):
|
|
|
|
"""Pipeline component for sentence segmentation.
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/sentencerecognizer
|
2020-07-22 14:42:59 +03:00
|
|
|
"""
|
Add overwrite settings for more components (#9050)
* Add overwrite settings for more components
For pipeline components where it's relevant and not already implemented,
add an explicit `overwrite` setting that controls whether
`set_annotations` overwrites existing annotation.
For the `morphologizer`, add an additional setting `extend`, which
controls whether the existing features are preserved.
* +overwrite, +extend: overwrite values of existing features, add any new
features
* +overwrite, -extend: overwrite completely, removing any existing
features
* -overwrite, +extend: keep values of existing features, add any new
features
* -overwrite, -extend: do not modify the existing value if set
In all cases an unset value will be set by `set_annotations`.
Preserve current overwrite defaults:
* True: morphologizer, entity linker
* False: tagger, sentencizer, senter
* Add backwards compat overwrite settings
* Put empty line back
Removed by accident in last commit
* Set backwards-compatible defaults in __init__
Because the `TrainablePipe` serialization methods update `cfg`, there's
no straightforward way to detect whether models serialized with a
previous version are missing the overwrite settings.
It would be possible in the sentencizer due to its separate
serialization methods, however to keep the changes parallel, this also
sets the default in `__init__`.
* Remove traces
Co-authored-by: Paul O'Leary McCann <polm@dampfkraft.com>
2021-09-30 16:35:55 +03:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
vocab,
|
|
|
|
model,
|
|
|
|
name="senter",
|
|
|
|
*,
|
|
|
|
overwrite=BACKWARD_OVERWRITE,
|
|
|
|
scorer=senter_score,
|
|
|
|
):
|
2020-07-27 19:11:45 +03:00
|
|
|
"""Initialize a sentence recognizer.
|
|
|
|
|
|
|
|
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.
|
2021-08-12 13:50:03 +03:00
|
|
|
scorer (Optional[Callable]): The scoring method. Defaults to
|
|
|
|
Scorer.score_spans for the attribute "sents".
|
2020-07-27 19:11:45 +03:00
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/sentencerecognizer#init
|
2020-07-27 19:11:45 +03:00
|
|
|
"""
|
2020-07-22 14:42:59 +03:00
|
|
|
self.vocab = vocab
|
|
|
|
self.model = model
|
|
|
|
self.name = name
|
|
|
|
self._rehearsal_model = None
|
Add overwrite settings for more components (#9050)
* Add overwrite settings for more components
For pipeline components where it's relevant and not already implemented,
add an explicit `overwrite` setting that controls whether
`set_annotations` overwrites existing annotation.
For the `morphologizer`, add an additional setting `extend`, which
controls whether the existing features are preserved.
* +overwrite, +extend: overwrite values of existing features, add any new
features
* +overwrite, -extend: overwrite completely, removing any existing
features
* -overwrite, +extend: keep values of existing features, add any new
features
* -overwrite, -extend: do not modify the existing value if set
In all cases an unset value will be set by `set_annotations`.
Preserve current overwrite defaults:
* True: morphologizer, entity linker
* False: tagger, sentencizer, senter
* Add backwards compat overwrite settings
* Put empty line back
Removed by accident in last commit
* Set backwards-compatible defaults in __init__
Because the `TrainablePipe` serialization methods update `cfg`, there's
no straightforward way to detect whether models serialized with a
previous version are missing the overwrite settings.
It would be possible in the sentencizer due to its separate
serialization methods, however to keep the changes parallel, this also
sets the default in `__init__`.
* Remove traces
Co-authored-by: Paul O'Leary McCann <polm@dampfkraft.com>
2021-09-30 16:35:55 +03:00
|
|
|
self.cfg = {"overwrite": overwrite}
|
2021-08-10 16:13:39 +03:00
|
|
|
self.scorer = scorer
|
2020-07-22 14:42:59 +03:00
|
|
|
|
|
|
|
@property
|
|
|
|
def labels(self):
|
2020-07-27 19:11:45 +03:00
|
|
|
"""RETURNS (Tuple[str]): The labels."""
|
2020-07-22 14:42:59 +03:00
|
|
|
# labels are numbered by index internally, so this matches GoldParse
|
|
|
|
# and Example where the sentence-initial tag is 1 and other positions
|
|
|
|
# are 0
|
|
|
|
return tuple(["I", "S"])
|
|
|
|
|
2022-02-05 19:59:24 +03:00
|
|
|
@property
|
|
|
|
def hide_labels(self):
|
|
|
|
return True
|
|
|
|
|
2020-10-03 19:54:09 +03:00
|
|
|
@property
|
|
|
|
def label_data(self):
|
|
|
|
return None
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
def set_annotations(self, docs, batch_tag_ids):
|
2020-07-27 19:11:45 +03: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 SentenceRecognizer.predict.
|
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/sentencerecognizer#set_annotations
|
2020-07-27 19:11:45 +03:00
|
|
|
"""
|
2020-07-22 14:42:59 +03:00
|
|
|
if isinstance(docs, Doc):
|
|
|
|
docs = [docs]
|
|
|
|
cdef Doc doc
|
Add overwrite settings for more components (#9050)
* Add overwrite settings for more components
For pipeline components where it's relevant and not already implemented,
add an explicit `overwrite` setting that controls whether
`set_annotations` overwrites existing annotation.
For the `morphologizer`, add an additional setting `extend`, which
controls whether the existing features are preserved.
* +overwrite, +extend: overwrite values of existing features, add any new
features
* +overwrite, -extend: overwrite completely, removing any existing
features
* -overwrite, +extend: keep values of existing features, add any new
features
* -overwrite, -extend: do not modify the existing value if set
In all cases an unset value will be set by `set_annotations`.
Preserve current overwrite defaults:
* True: morphologizer, entity linker
* False: tagger, sentencizer, senter
* Add backwards compat overwrite settings
* Put empty line back
Removed by accident in last commit
* Set backwards-compatible defaults in __init__
Because the `TrainablePipe` serialization methods update `cfg`, there's
no straightforward way to detect whether models serialized with a
previous version are missing the overwrite settings.
It would be possible in the sentencizer due to its separate
serialization methods, however to keep the changes parallel, this also
sets the default in `__init__`.
* Remove traces
Co-authored-by: Paul O'Leary McCann <polm@dampfkraft.com>
2021-09-30 16:35:55 +03:00
|
|
|
cdef bint overwrite = self.cfg["overwrite"]
|
2020-07-22 14:42:59 +03:00
|
|
|
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):
|
Add overwrite settings for more components (#9050)
* Add overwrite settings for more components
For pipeline components where it's relevant and not already implemented,
add an explicit `overwrite` setting that controls whether
`set_annotations` overwrites existing annotation.
For the `morphologizer`, add an additional setting `extend`, which
controls whether the existing features are preserved.
* +overwrite, +extend: overwrite values of existing features, add any new
features
* +overwrite, -extend: overwrite completely, removing any existing
features
* -overwrite, +extend: keep values of existing features, add any new
features
* -overwrite, -extend: do not modify the existing value if set
In all cases an unset value will be set by `set_annotations`.
Preserve current overwrite defaults:
* True: morphologizer, entity linker
* False: tagger, sentencizer, senter
* Add backwards compat overwrite settings
* Put empty line back
Removed by accident in last commit
* Set backwards-compatible defaults in __init__
Because the `TrainablePipe` serialization methods update `cfg`, there's
no straightforward way to detect whether models serialized with a
previous version are missing the overwrite settings.
It would be possible in the sentencizer due to its separate
serialization methods, however to keep the changes parallel, this also
sets the default in `__init__`.
* Remove traces
Co-authored-by: Paul O'Leary McCann <polm@dampfkraft.com>
2021-09-30 16:35:55 +03:00
|
|
|
if doc.c[j].sent_start == 0 or overwrite:
|
2020-07-22 14:42:59 +03:00
|
|
|
if tag_id == 1:
|
|
|
|
doc.c[j].sent_start = 1
|
|
|
|
else:
|
|
|
|
doc.c[j].sent_start = -1
|
|
|
|
|
|
|
|
def get_loss(self, examples, scores):
|
2020-07-27 19:11:45 +03: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.
|
2020-10-05 15:58:56 +03:00
|
|
|
RETURNS (Tuple[float, float]): The loss and the gradient.
|
2020-07-27 19:11:45 +03:00
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/sentencerecognizer#get_loss
|
2020-07-27 19:11:45 +03:00
|
|
|
"""
|
2020-08-12 00:29:31 +03:00
|
|
|
validate_examples(examples, "SentenceRecognizer.get_loss")
|
2020-07-22 14:42:59 +03:00
|
|
|
labels = self.labels
|
|
|
|
loss_func = SequenceCategoricalCrossentropy(names=labels, normalize=False)
|
|
|
|
truths = []
|
|
|
|
for eg in examples:
|
|
|
|
eg_truth = []
|
2020-08-04 23:22:26 +03:00
|
|
|
for x in eg.get_aligned("SENT_START"):
|
2020-07-31 00:30:54 +03:00
|
|
|
if x is None:
|
2020-07-22 14:42:59 +03:00
|
|
|
eg_truth.append(None)
|
|
|
|
elif x == 1:
|
|
|
|
eg_truth.append(labels[1])
|
|
|
|
else:
|
|
|
|
# anything other than 1: 0, -1, -1 as uint64
|
|
|
|
eg_truth.append(labels[0])
|
|
|
|
truths.append(eg_truth)
|
|
|
|
d_scores, loss = loss_func(scores, truths)
|
|
|
|
if self.model.ops.xp.isnan(loss):
|
2020-10-04 12:16:31 +03:00
|
|
|
raise ValueError(Errors.E910.format(name=self.name))
|
2020-07-22 14:42:59 +03:00
|
|
|
return float(loss), d_scores
|
|
|
|
|
2020-09-29 13:20:26 +03:00
|
|
|
def initialize(self, get_examples, *, nlp=None):
|
2020-09-08 23:44:25 +03:00
|
|
|
"""Initialize the pipe for training, using a representative set
|
|
|
|
of data examples.
|
2020-07-27 19:11:45 +03:00
|
|
|
|
2020-09-08 23:44:25 +03:00
|
|
|
get_examples (Callable[[], Iterable[Example]]): Function that
|
|
|
|
returns a representative sample of gold-standard Example objects.
|
2020-09-29 13:20:26 +03:00
|
|
|
nlp (Language): The current nlp object the component is part of.
|
2020-07-27 19:11:45 +03:00
|
|
|
|
2021-01-30 12:09:38 +03:00
|
|
|
DOCS: https://spacy.io/api/sentencerecognizer#initialize
|
2020-07-27 19:11:45 +03:00
|
|
|
"""
|
2020-10-08 22:33:49 +03:00
|
|
|
validate_get_examples(get_examples, "SentenceRecognizer.initialize")
|
2021-03-19 12:45:16 +03:00
|
|
|
util.check_lexeme_norms(self.vocab, "senter")
|
2020-09-08 23:44:25 +03:00
|
|
|
doc_sample = []
|
|
|
|
label_sample = []
|
|
|
|
assert self.labels, Errors.E924.format(name=self.name)
|
|
|
|
for example in islice(get_examples(), 10):
|
|
|
|
doc_sample.append(example.x)
|
|
|
|
gold_tags = example.get_aligned("SENT_START")
|
|
|
|
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 14:42:59 +03:00
|
|
|
|
|
|
|
def add_label(self, label, values=None):
|
|
|
|
raise NotImplementedError
|