2020-03-02 13:48:10 +03:00
|
|
|
|
# cython: infer_types=True, profile=True
|
2019-02-10 14:14:51 +03:00
|
|
|
|
import numpy
|
💫 Replace ujson, msgpack and dill/pickle/cloudpickle with srsly (#3003)
Remove hacks and wrappers, keep code in sync across our libraries and move spaCy a few steps closer to only depending on packages with binary wheels 🎉
See here: https://github.com/explosion/srsly
Serialization is hard, especially across Python versions and multiple platforms. After dealing with many subtle bugs over the years (encodings, locales, large files) our libraries like spaCy and Prodigy have steadily grown a number of utility functions to wrap the multiple serialization formats we need to support (especially json, msgpack and pickle). These wrapping functions ended up duplicated across our codebases, so we wanted to put them in one place.
At the same time, we noticed that having a lot of small dependencies was making maintainence harder, and making installation slower. To solve this, we've made srsly standalone, by including the component packages directly within it. This way we can provide all the serialization utilities we need in a single binary wheel.
srsly currently includes forks of the following packages:
ujson
msgpack
msgpack-numpy
cloudpickle
* WIP: replace json/ujson with srsly
* Replace ujson in examples
Use regular json instead of srsly to make code easier to read and follow
* Update requirements
* Fix imports
* Fix typos
* Replace msgpack with srsly
* Fix warning
2018-12-03 03:28:22 +03:00
|
|
|
|
import srsly
|
2019-06-28 09:29:31 +03:00
|
|
|
|
import random
|
2020-05-19 17:20:03 +03:00
|
|
|
|
|
2020-02-27 20:42:27 +03:00
|
|
|
|
from thinc.api import CosineDistance, to_categorical, get_array_module
|
2020-05-18 23:23:33 +03:00
|
|
|
|
from thinc.api import set_dropout_rate, SequenceCategoricalCrossentropy
|
2020-04-28 14:37:37 +03:00
|
|
|
|
import warnings
|
2018-03-15 02:18:51 +03:00
|
|
|
|
|
2019-02-10 14:14:51 +03:00
|
|
|
|
from ..tokens.doc cimport Doc
|
|
|
|
|
from ..syntax.nn_parser cimport Parser
|
|
|
|
|
from ..syntax.ner cimport BiluoPushDown
|
|
|
|
|
from ..syntax.arc_eager cimport ArcEager
|
|
|
|
|
from ..morphology cimport Morphology
|
|
|
|
|
from ..vocab cimport Vocab
|
2018-07-18 20:43:16 +03:00
|
|
|
|
|
2020-05-19 17:20:03 +03:00
|
|
|
|
from .defaults import default_tagger, default_parser, default_ner, default_textcat
|
2020-06-02 00:38:48 +03:00
|
|
|
|
from .defaults import default_nel, default_senter
|
2019-10-27 15:35:49 +03:00
|
|
|
|
from .functions import merge_subtokens
|
|
|
|
|
from ..language import Language, component
|
2019-02-10 14:14:51 +03:00
|
|
|
|
from ..syntax import nonproj
|
2020-06-26 20:34:12 +03:00
|
|
|
|
from ..gold.example import Example
|
2019-02-10 14:14:51 +03:00
|
|
|
|
from ..attrs import POS, ID
|
2020-01-29 19:06:46 +03:00
|
|
|
|
from ..util import link_vectors_to_models, create_default_optimizer
|
2019-02-10 14:14:51 +03:00
|
|
|
|
from ..parts_of_speech import X
|
2019-08-20 16:08:59 +03:00
|
|
|
|
from ..kb import KnowledgeBase
|
2020-04-28 14:37:37 +03:00
|
|
|
|
from ..errors import Errors, TempErrors, Warnings
|
2019-02-10 14:14:51 +03:00
|
|
|
|
from .. import util
|
2018-07-18 20:43:16 +03:00
|
|
|
|
|
|
|
|
|
|
2019-02-10 14:14:51 +03:00
|
|
|
|
def _load_cfg(path):
|
|
|
|
|
if path.exists():
|
|
|
|
|
return srsly.read_json(path)
|
|
|
|
|
else:
|
|
|
|
|
return {}
|
2018-07-18 20:43:16 +03:00
|
|
|
|
|
2018-03-27 20:23:02 +03:00
|
|
|
|
|
2017-10-26 13:40:40 +03:00
|
|
|
|
class Pipe(object):
|
2017-10-27 21:29:08 +03:00
|
|
|
|
"""This class is not instantiated directly. Components inherit from it, and
|
|
|
|
|
it defines the interface that components should follow to function as
|
|
|
|
|
components in a spaCy analysis pipeline.
|
|
|
|
|
"""
|
2019-02-10 14:14:51 +03:00
|
|
|
|
|
2017-07-20 01:18:15 +03:00
|
|
|
|
name = None
|
|
|
|
|
|
|
|
|
|
@classmethod
|
2020-02-27 20:42:27 +03:00
|
|
|
|
def from_nlp(cls, nlp, model, **cfg):
|
|
|
|
|
return cls(nlp.vocab, model, **cfg)
|
2017-07-20 01:18:15 +03:00
|
|
|
|
|
2020-02-27 20:42:27 +03:00
|
|
|
|
def __init__(self, vocab, model, **cfg):
|
2017-09-25 19:37:13 +03:00
|
|
|
|
"""Create a new pipe instance."""
|
2017-07-20 01:18:15 +03:00
|
|
|
|
raise NotImplementedError
|
|
|
|
|
|
2020-06-26 20:34:12 +03:00
|
|
|
|
def __call__(self, Doc doc):
|
2017-09-25 19:37:13 +03:00
|
|
|
|
"""Apply the pipe to one document. The document is
|
2017-09-25 17:20:49 +03:00
|
|
|
|
modified in-place, and returned.
|
2017-09-25 19:37:13 +03:00
|
|
|
|
|
2017-09-25 17:20:49 +03:00
|
|
|
|
Both __call__ and pipe should delegate to the `predict()`
|
|
|
|
|
and `set_annotations()` methods.
|
2017-09-25 19:37:13 +03:00
|
|
|
|
"""
|
2019-08-01 18:29:01 +03:00
|
|
|
|
predictions = self.predict([doc])
|
2019-09-12 11:44:49 +03:00
|
|
|
|
if isinstance(predictions, tuple) and len(predictions) == 2:
|
2019-08-01 18:29:01 +03:00
|
|
|
|
scores, tensors = predictions
|
2019-09-18 22:31:27 +03:00
|
|
|
|
self.set_annotations([doc], scores, tensors=tensors)
|
2019-08-01 18:29:01 +03:00
|
|
|
|
else:
|
|
|
|
|
self.set_annotations([doc], predictions)
|
2017-07-20 01:18:15 +03:00
|
|
|
|
return doc
|
|
|
|
|
|
2020-07-06 14:06:25 +03:00
|
|
|
|
def pipe(self, stream, batch_size=128):
|
2017-09-25 19:37:13 +03:00
|
|
|
|
"""Apply the pipe to a stream of documents.
|
2017-09-25 17:20:49 +03:00
|
|
|
|
|
|
|
|
|
Both __call__ and pipe should delegate to the `predict()`
|
|
|
|
|
and `set_annotations()` methods.
|
2017-09-25 19:37:13 +03:00
|
|
|
|
"""
|
2020-06-26 20:34:12 +03:00
|
|
|
|
for docs in util.minibatch(stream, size=batch_size):
|
2019-07-28 18:56:11 +03:00
|
|
|
|
predictions = self.predict(docs)
|
|
|
|
|
if isinstance(predictions, tuple) and len(tuple) == 2:
|
|
|
|
|
scores, tensors = predictions
|
2019-09-18 22:31:27 +03:00
|
|
|
|
self.set_annotations(docs, scores, tensors=tensors)
|
2019-07-28 18:56:11 +03:00
|
|
|
|
else:
|
|
|
|
|
self.set_annotations(docs, predictions)
|
2020-06-26 20:34:12 +03:00
|
|
|
|
yield from docs
|
2017-07-20 01:18:15 +03:00
|
|
|
|
|
|
|
|
|
def predict(self, docs):
|
2017-09-25 19:37:13 +03:00
|
|
|
|
"""Apply the pipeline's model to a batch of docs, without
|
2017-09-25 17:20:49 +03:00
|
|
|
|
modifying them.
|
2017-09-25 19:37:13 +03:00
|
|
|
|
"""
|
2017-07-20 01:18:15 +03:00
|
|
|
|
raise NotImplementedError
|
|
|
|
|
|
2017-11-03 13:20:05 +03:00
|
|
|
|
def set_annotations(self, docs, scores, tensors=None):
|
2017-09-25 19:37:13 +03:00
|
|
|
|
"""Modify a batch of documents, using pre-computed scores."""
|
2017-07-20 01:18:15 +03:00
|
|
|
|
raise NotImplementedError
|
|
|
|
|
|
2019-11-11 19:35:27 +03:00
|
|
|
|
def rehearse(self, examples, sgd=None, losses=None, **config):
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
pass
|
|
|
|
|
|
2019-11-11 19:35:27 +03:00
|
|
|
|
def get_loss(self, examples, scores):
|
2017-09-25 19:37:13 +03:00
|
|
|
|
"""Find the loss and gradient of loss for the batch of
|
2019-11-11 19:35:27 +03:00
|
|
|
|
examples (with embedded docs) and their predicted scores."""
|
2017-07-20 01:18:15 +03:00
|
|
|
|
raise NotImplementedError
|
|
|
|
|
|
2017-11-01 18:32:44 +03:00
|
|
|
|
def add_label(self, label):
|
|
|
|
|
"""Add an output label, to be predicted by the model.
|
|
|
|
|
|
2019-10-02 11:37:39 +03:00
|
|
|
|
It's possible to extend pretrained models with new labels,
|
2017-11-01 18:32:44 +03:00
|
|
|
|
but care should be taken to avoid the "catastrophic forgetting"
|
|
|
|
|
problem.
|
|
|
|
|
"""
|
|
|
|
|
raise NotImplementedError
|
2018-03-27 20:23:02 +03:00
|
|
|
|
|
2017-11-06 16:26:26 +03:00
|
|
|
|
def create_optimizer(self):
|
2020-01-29 19:06:46 +03:00
|
|
|
|
return create_default_optimizer()
|
2017-11-01 18:32:44 +03:00
|
|
|
|
|
2019-02-10 14:14:51 +03:00
|
|
|
|
def begin_training(
|
2019-11-11 19:35:27 +03:00
|
|
|
|
self, get_examples=lambda: [], pipeline=None, sgd=None, **kwargs
|
2019-02-10 14:14:51 +03:00
|
|
|
|
):
|
2017-09-25 19:37:13 +03:00
|
|
|
|
"""Initialize the pipe for training, using data exampes if available.
|
|
|
|
|
If no model has been initialized yet, the model is added."""
|
2020-02-27 20:42:27 +03:00
|
|
|
|
self.model.initialize()
|
2019-07-28 18:56:11 +03:00
|
|
|
|
if hasattr(self, "vocab"):
|
|
|
|
|
link_vectors_to_models(self.vocab)
|
2017-11-06 16:26:26 +03:00
|
|
|
|
if sgd is None:
|
|
|
|
|
sgd = self.create_optimizer()
|
|
|
|
|
return sgd
|
2017-07-20 01:18:15 +03:00
|
|
|
|
|
2020-02-27 20:42:27 +03:00
|
|
|
|
def set_output(self, nO):
|
2020-03-29 20:40:36 +03:00
|
|
|
|
if self.model.has_dim("nO") is not False:
|
|
|
|
|
self.model.set_dim("nO", nO)
|
2020-02-27 20:42:27 +03:00
|
|
|
|
if self.model.has_ref("output_layer"):
|
|
|
|
|
self.model.get_ref("output_layer").set_dim("nO", nO)
|
|
|
|
|
|
2020-01-29 19:06:46 +03:00
|
|
|
|
def get_gradients(self):
|
|
|
|
|
"""Get non-zero gradients of the model's parameters, as a dictionary
|
|
|
|
|
keyed by the parameter ID. The values are (weights, gradients) tuples.
|
|
|
|
|
"""
|
|
|
|
|
gradients = {}
|
|
|
|
|
queue = [self.model]
|
|
|
|
|
seen = set()
|
|
|
|
|
for node in queue:
|
|
|
|
|
if node.id in seen:
|
|
|
|
|
continue
|
|
|
|
|
seen.add(node.id)
|
|
|
|
|
if hasattr(node, "_mem") and node._mem.gradient.any():
|
|
|
|
|
gradients[node.id] = [node._mem.weights, node._mem.gradient]
|
|
|
|
|
if hasattr(node, "_layers"):
|
|
|
|
|
queue.extend(node._layers)
|
|
|
|
|
return gradients
|
|
|
|
|
|
2017-07-20 01:18:15 +03:00
|
|
|
|
def use_params(self, params):
|
2017-10-27 21:29:08 +03:00
|
|
|
|
"""Modify the pipe's model, to use the given parameter values."""
|
2017-07-20 01:18:15 +03:00
|
|
|
|
with self.model.use_params(params):
|
|
|
|
|
yield
|
|
|
|
|
|
2020-07-06 14:06:25 +03:00
|
|
|
|
def to_bytes(self, exclude=tuple()):
|
2019-03-10 21:16:45 +03:00
|
|
|
|
"""Serialize the pipe to a bytestring.
|
|
|
|
|
|
|
|
|
|
exclude (list): String names of serialization fields to exclude.
|
|
|
|
|
RETURNS (bytes): The serialized object.
|
|
|
|
|
"""
|
2019-12-22 03:53:56 +03:00
|
|
|
|
serialize = {}
|
2019-02-10 14:14:51 +03:00
|
|
|
|
serialize["cfg"] = lambda: srsly.json_dumps(self.cfg)
|
2020-02-27 20:42:27 +03:00
|
|
|
|
serialize["model"] = self.model.to_bytes
|
2019-07-28 18:56:11 +03:00
|
|
|
|
if hasattr(self, "vocab"):
|
|
|
|
|
serialize["vocab"] = self.vocab.to_bytes
|
2017-07-20 01:18:15 +03:00
|
|
|
|
return util.to_bytes(serialize, exclude)
|
|
|
|
|
|
2020-07-06 14:06:25 +03:00
|
|
|
|
def from_bytes(self, bytes_data, exclude=tuple()):
|
2017-09-25 19:37:13 +03:00
|
|
|
|
"""Load the pipe from a bytestring."""
|
2019-02-10 14:14:51 +03:00
|
|
|
|
|
2017-09-02 16:17:20 +03:00
|
|
|
|
def load_model(b):
|
2019-07-24 12:27:34 +03:00
|
|
|
|
try:
|
|
|
|
|
self.model.from_bytes(b)
|
|
|
|
|
except AttributeError:
|
|
|
|
|
raise ValueError(Errors.E149)
|
2017-09-02 16:17:20 +03:00
|
|
|
|
|
2019-12-22 03:53:56 +03:00
|
|
|
|
deserialize = {}
|
2019-07-28 18:56:11 +03:00
|
|
|
|
if hasattr(self, "vocab"):
|
|
|
|
|
deserialize["vocab"] = lambda b: self.vocab.from_bytes(b)
|
2020-02-27 20:42:27 +03:00
|
|
|
|
deserialize["cfg"] = lambda b: self.cfg.update(srsly.json_loads(b))
|
2019-03-10 21:16:45 +03:00
|
|
|
|
deserialize["model"] = load_model
|
2017-07-20 01:18:15 +03:00
|
|
|
|
util.from_bytes(bytes_data, deserialize, exclude)
|
|
|
|
|
return self
|
|
|
|
|
|
2020-07-06 14:06:25 +03:00
|
|
|
|
def to_disk(self, path, exclude=tuple()):
|
2017-09-25 19:37:13 +03:00
|
|
|
|
"""Serialize the pipe to disk."""
|
2019-12-22 03:53:56 +03:00
|
|
|
|
serialize = {}
|
2019-02-10 14:14:51 +03:00
|
|
|
|
serialize["cfg"] = lambda p: srsly.write_json(p, self.cfg)
|
|
|
|
|
serialize["vocab"] = lambda p: self.vocab.to_disk(p)
|
2020-06-20 16:52:00 +03:00
|
|
|
|
serialize["model"] = lambda p: self.model.to_disk(p)
|
2017-07-20 01:18:15 +03:00
|
|
|
|
util.to_disk(path, serialize, exclude)
|
|
|
|
|
|
2020-07-06 14:06:25 +03:00
|
|
|
|
def from_disk(self, path, exclude=tuple()):
|
2017-09-25 19:37:13 +03:00
|
|
|
|
"""Load the pipe from disk."""
|
2019-02-10 14:14:51 +03:00
|
|
|
|
|
2017-09-02 16:17:20 +03:00
|
|
|
|
def load_model(p):
|
2019-07-24 12:27:34 +03:00
|
|
|
|
try:
|
|
|
|
|
self.model.from_bytes(p.open("rb").read())
|
|
|
|
|
except AttributeError:
|
|
|
|
|
raise ValueError(Errors.E149)
|
2019-02-10 14:14:51 +03:00
|
|
|
|
|
2019-12-22 03:53:56 +03:00
|
|
|
|
deserialize = {}
|
2019-03-10 21:16:45 +03:00
|
|
|
|
deserialize["vocab"] = lambda p: self.vocab.from_disk(p)
|
2020-02-27 20:42:27 +03:00
|
|
|
|
deserialize["cfg"] = lambda p: self.cfg.update(_load_cfg(p))
|
2019-03-10 21:16:45 +03:00
|
|
|
|
deserialize["model"] = load_model
|
2017-07-20 01:18:15 +03:00
|
|
|
|
util.from_disk(path, deserialize, exclude)
|
|
|
|
|
return self
|
|
|
|
|
|
|
|
|
|
|
2020-05-19 17:20:03 +03:00
|
|
|
|
@component("tagger", assigns=["token.tag", "token.pos", "token.lemma"], default_model=default_tagger)
|
2017-10-26 13:40:40 +03:00
|
|
|
|
class Tagger(Pipe):
|
2019-03-08 13:42:26 +03:00
|
|
|
|
"""Pipeline component for part-of-speech tagging.
|
|
|
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/tagger
|
|
|
|
|
"""
|
|
|
|
|
|
2020-02-27 20:42:27 +03:00
|
|
|
|
def __init__(self, vocab, model, **cfg):
|
2017-05-16 17:17:30 +03:00
|
|
|
|
self.vocab = vocab
|
2017-05-17 13:04:50 +03:00
|
|
|
|
self.model = model
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
self._rehearsal_model = None
|
2019-12-22 03:53:56 +03:00
|
|
|
|
self.cfg = dict(sorted(cfg.items()))
|
2017-05-16 17:17:30 +03:00
|
|
|
|
|
2017-11-01 18:32:44 +03:00
|
|
|
|
@property
|
|
|
|
|
def labels(self):
|
2019-02-14 22:03:19 +03:00
|
|
|
|
return tuple(self.vocab.morphology.tag_names)
|
2017-11-01 18:32:44 +03:00
|
|
|
|
|
2020-06-26 20:34:12 +03:00
|
|
|
|
def __call__(self, doc):
|
2020-01-29 19:06:46 +03:00
|
|
|
|
tags = self.predict([doc])
|
|
|
|
|
self.set_annotations([doc], tags)
|
2017-05-28 16:11:58 +03:00
|
|
|
|
return doc
|
2017-05-16 17:17:30 +03:00
|
|
|
|
|
2020-07-06 14:06:25 +03:00
|
|
|
|
def pipe(self, stream, batch_size=128):
|
2020-06-26 20:34:12 +03:00
|
|
|
|
for docs in util.minibatch(stream, size=batch_size):
|
2020-01-29 19:06:46 +03:00
|
|
|
|
tag_ids = self.predict(docs)
|
|
|
|
|
self.set_annotations(docs, tag_ids)
|
2020-06-26 20:34:12 +03:00
|
|
|
|
yield from docs
|
2017-05-16 17:17:30 +03:00
|
|
|
|
|
2017-09-21 15:59:48 +03:00
|
|
|
|
def predict(self, docs):
|
2018-06-29 14:44:25 +03:00
|
|
|
|
if not any(len(doc) for doc in docs):
|
2019-06-28 09:29:31 +03:00
|
|
|
|
# Handle cases where there are no tokens in any docs.
|
2018-06-29 16:13:45 +03:00
|
|
|
|
n_labels = len(self.labels)
|
2020-01-29 19:06:46 +03:00
|
|
|
|
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):
|
2017-11-03 15:29:36 +03:00
|
|
|
|
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)
|
2020-01-29 19:06:46 +03:00
|
|
|
|
return guesses
|
2017-05-16 17:17:30 +03:00
|
|
|
|
|
2020-01-29 19:06:46 +03:00
|
|
|
|
def set_annotations(self, docs, batch_tag_ids):
|
2017-05-16 17:17:30 +03:00
|
|
|
|
if isinstance(docs, Doc):
|
|
|
|
|
docs = [docs]
|
|
|
|
|
cdef Doc doc
|
|
|
|
|
cdef int idx = 0
|
2017-05-18 12:29:51 +03:00
|
|
|
|
cdef Vocab vocab = self.vocab
|
2019-03-08 21:16:02 +03:00
|
|
|
|
assign_morphology = self.cfg.get("set_morphology", True)
|
2017-05-08 15:53:45 +03:00
|
|
|
|
for i, doc in enumerate(docs):
|
2017-05-21 17:05:34 +03:00
|
|
|
|
doc_tag_ids = batch_tag_ids[i]
|
2019-03-08 13:42:26 +03:00
|
|
|
|
if hasattr(doc_tag_ids, "get"):
|
2017-08-18 23:02:35 +03:00
|
|
|
|
doc_tag_ids = doc_tag_ids.get()
|
2017-05-18 12:29:51 +03:00
|
|
|
|
for j, tag_id in enumerate(doc_tag_ids):
|
2017-06-04 23:52:42 +03:00
|
|
|
|
# Don't clobber preset POS tags
|
2019-03-08 21:03:17 +03:00
|
|
|
|
if doc.c[j].tag == 0:
|
2019-03-08 21:16:02 +03:00
|
|
|
|
if doc.c[j].pos == 0 and assign_morphology:
|
2019-03-08 21:03:17 +03:00
|
|
|
|
# Don't clobber preset lemmas
|
|
|
|
|
lemma = doc.c[j].lemma
|
|
|
|
|
vocab.morphology.assign_tag_id(&doc.c[j], tag_id)
|
|
|
|
|
if lemma != 0 and lemma != doc.c[j].lex.orth:
|
|
|
|
|
doc.c[j].lemma = lemma
|
2019-03-10 01:54:59 +03:00
|
|
|
|
else:
|
|
|
|
|
doc.c[j].tag = self.vocab.strings[self.labels[tag_id]]
|
2017-05-08 15:53:45 +03:00
|
|
|
|
idx += 1
|
2018-04-10 17:14:52 +03:00
|
|
|
|
doc.is_tagged = True
|
2017-05-08 15:53:45 +03:00
|
|
|
|
|
2020-01-29 19:06:46 +03:00
|
|
|
|
def update(self, examples, drop=0., sgd=None, losses=None, set_annotations=False):
|
2017-08-20 15:42:23 +03:00
|
|
|
|
if losses is not None and self.name not in losses:
|
|
|
|
|
losses[self.name] = 0.
|
2017-05-16 17:17:30 +03:00
|
|
|
|
|
2020-06-26 20:34:12 +03:00
|
|
|
|
try:
|
|
|
|
|
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
|
|
|
|
|
except AttributeError:
|
|
|
|
|
types = set([type(eg) for eg in examples])
|
2020-07-06 14:02:36 +03:00
|
|
|
|
raise TypeError(Errors.E978.format(name="Tagger", method="update", types=types))
|
2020-01-29 19:06:46 +03:00
|
|
|
|
set_dropout_rate(self.model, drop)
|
2020-06-26 20:34:12 +03:00
|
|
|
|
tag_scores, bp_tag_scores = self.model.begin_update(
|
|
|
|
|
[eg.predicted for eg in examples])
|
2020-05-18 23:23:33 +03:00
|
|
|
|
for sc in tag_scores:
|
|
|
|
|
if self.model.ops.xp.isnan(sc.sum()):
|
|
|
|
|
raise ValueError("nan value in scores")
|
2019-11-11 19:35:27 +03:00
|
|
|
|
loss, d_tag_scores = self.get_loss(examples, tag_scores)
|
2020-01-29 19:06:46 +03:00
|
|
|
|
bp_tag_scores(d_tag_scores)
|
|
|
|
|
if sgd not in (None, False):
|
|
|
|
|
self.model.finish_update(sgd)
|
2017-05-18 12:29:51 +03:00
|
|
|
|
|
2017-08-20 15:42:23 +03:00
|
|
|
|
if losses is not None:
|
|
|
|
|
losses[self.name] += loss
|
2020-01-29 19:06:46 +03:00
|
|
|
|
if set_annotations:
|
2020-06-26 20:34:12 +03:00
|
|
|
|
docs = [eg.predicted for eg in examples]
|
2020-01-29 19:06:46 +03:00
|
|
|
|
self.set_annotations(docs, self._scores2guesses(tag_scores))
|
2017-05-16 17:17:30 +03:00
|
|
|
|
|
2019-11-11 19:35:27 +03:00
|
|
|
|
def rehearse(self, examples, drop=0., sgd=None, losses=None):
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
"""Perform a 'rehearsal' update, where we try to match the output of
|
|
|
|
|
an initial model.
|
|
|
|
|
"""
|
2020-06-26 20:34:12 +03:00
|
|
|
|
try:
|
|
|
|
|
docs = [eg.predicted for eg in examples]
|
|
|
|
|
except AttributeError:
|
|
|
|
|
types = set([type(eg) for eg in examples])
|
2020-07-06 14:02:36 +03:00
|
|
|
|
raise TypeError(Errors.E978.format(name="Tagger", method="rehearse", types=types))
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
if self._rehearsal_model is None:
|
|
|
|
|
return
|
2019-10-02 13:50:48 +03:00
|
|
|
|
if not any(len(doc) for doc in docs):
|
|
|
|
|
# Handle cases where there are no tokens in any docs.
|
|
|
|
|
return
|
2020-01-29 19:06:46 +03:00
|
|
|
|
set_dropout_rate(self.model, drop)
|
|
|
|
|
guesses, backprop = self.model.begin_update(docs)
|
2019-11-11 19:35:27 +03:00
|
|
|
|
target = self._rehearsal_model(examples)
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
gradient = guesses - target
|
2020-01-29 19:06:46 +03:00
|
|
|
|
backprop(gradient)
|
|
|
|
|
self.model.finish_update(sgd)
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
if losses is not None:
|
|
|
|
|
losses.setdefault(self.name, 0.0)
|
|
|
|
|
losses[self.name] += (gradient**2).sum()
|
|
|
|
|
|
2019-11-11 19:35:27 +03:00
|
|
|
|
def get_loss(self, examples, scores):
|
2020-07-07 18:21:58 +03:00
|
|
|
|
loss_func = SequenceCategoricalCrossentropy(names=self.labels, normalize=False)
|
2020-06-26 20:34:12 +03:00
|
|
|
|
truths = [eg.get_aligned("tag", as_string=True) for eg in examples]
|
2020-05-18 23:23:33 +03:00
|
|
|
|
d_scores, loss = loss_func(scores, truths)
|
|
|
|
|
if self.model.ops.xp.isnan(loss):
|
|
|
|
|
raise ValueError("nan value when computing loss")
|
2017-05-18 16:30:59 +03:00
|
|
|
|
return float(loss), d_scores
|
2016-10-16 02:47:12 +03:00
|
|
|
|
|
2019-11-11 19:35:27 +03:00
|
|
|
|
def begin_training(self, get_examples=lambda: [], pipeline=None, sgd=None,
|
2018-02-12 12:18:39 +03:00
|
|
|
|
**kwargs):
|
2019-10-01 16:13:55 +03:00
|
|
|
|
lemma_tables = ["lemma_rules", "lemma_index", "lemma_exc", "lemma_lookup"]
|
|
|
|
|
if not any(table in self.vocab.lookups for table in lemma_tables):
|
2020-04-28 14:37:37 +03:00
|
|
|
|
warnings.warn(Warnings.W022)
|
2020-06-15 15:56:04 +03:00
|
|
|
|
if len(self.vocab.lookups.get_table("lexeme_norm", {})) == 0:
|
|
|
|
|
warnings.warn(Warnings.W033.format(model="part-of-speech tagger"))
|
2017-05-18 16:30:59 +03:00
|
|
|
|
orig_tag_map = dict(self.vocab.morphology.tag_map)
|
2019-12-22 03:53:56 +03:00
|
|
|
|
new_tag_map = {}
|
2019-11-11 19:35:27 +03:00
|
|
|
|
for example in get_examples():
|
2020-06-26 20:34:12 +03:00
|
|
|
|
try:
|
|
|
|
|
y = example.y
|
|
|
|
|
except AttributeError:
|
2020-07-06 14:02:36 +03:00
|
|
|
|
raise TypeError(Errors.E978.format(name="Tagger", method="begin_training", types=type(example)))
|
2020-06-26 20:34:12 +03:00
|
|
|
|
for token in y:
|
|
|
|
|
tag = token.tag_
|
2019-11-25 18:03:28 +03:00
|
|
|
|
if tag in orig_tag_map:
|
|
|
|
|
new_tag_map[tag] = orig_tag_map[tag]
|
|
|
|
|
else:
|
|
|
|
|
new_tag_map[tag] = {POS: X}
|
2020-01-29 19:06:46 +03:00
|
|
|
|
|
2017-05-17 13:04:50 +03:00
|
|
|
|
cdef Vocab vocab = self.vocab
|
2017-06-01 11:04:36 +03:00
|
|
|
|
if new_tag_map:
|
2020-06-20 23:38:00 +03:00
|
|
|
|
if "_SP" in orig_tag_map:
|
|
|
|
|
new_tag_map["_SP"] = orig_tag_map["_SP"]
|
2017-06-01 11:04:36 +03:00
|
|
|
|
vocab.morphology = Morphology(vocab.strings, new_tag_map,
|
2017-06-05 00:34:32 +03:00
|
|
|
|
vocab.morphology.lemmatizer,
|
|
|
|
|
exc=vocab.morphology.exc)
|
2020-02-27 20:42:27 +03:00
|
|
|
|
self.set_output(len(self.labels))
|
2020-05-21 20:26:29 +03:00
|
|
|
|
doc_sample = [Doc(self.vocab, words=["hello", "world"])]
|
2020-05-21 21:46:21 +03:00
|
|
|
|
if pipeline is not None:
|
|
|
|
|
for name, component in pipeline:
|
|
|
|
|
if component is self:
|
|
|
|
|
break
|
|
|
|
|
if hasattr(component, "pipe"):
|
|
|
|
|
doc_sample = list(component.pipe(doc_sample))
|
|
|
|
|
else:
|
|
|
|
|
doc_sample = [component(doc) for doc in doc_sample]
|
2020-05-21 20:26:29 +03:00
|
|
|
|
self.model.initialize(X=doc_sample)
|
2020-01-29 19:06:46 +03:00
|
|
|
|
# Get batch of example docs, example outputs to call begin_training().
|
|
|
|
|
# This lets the model infer shapes.
|
2017-09-26 13:42:52 +03:00
|
|
|
|
link_vectors_to_models(self.vocab)
|
2017-11-06 16:26:26 +03:00
|
|
|
|
if sgd is None:
|
|
|
|
|
sgd = self.create_optimizer()
|
|
|
|
|
return sgd
|
2017-05-29 21:23:47 +03:00
|
|
|
|
|
2017-11-01 23:49:24 +03:00
|
|
|
|
def add_label(self, label, values=None):
|
2019-12-22 03:53:56 +03:00
|
|
|
|
if not isinstance(label, str):
|
2019-11-21 18:24:10 +03:00
|
|
|
|
raise ValueError(Errors.E187)
|
2017-11-01 18:32:44 +03:00
|
|
|
|
if label in self.labels:
|
|
|
|
|
return 0
|
2020-02-27 20:42:27 +03:00
|
|
|
|
if self.model.has_dim("nO"):
|
2017-11-01 23:49:24 +03:00
|
|
|
|
# Here's how the model resizing will work, once the
|
|
|
|
|
# neuron-to-tag mapping is no longer controlled by
|
|
|
|
|
# the Morphology class, which sorts the tag names.
|
|
|
|
|
# The sorting makes adding labels difficult.
|
|
|
|
|
# smaller = self.model._layers[-1]
|
|
|
|
|
# larger = Softmax(len(self.labels)+1, smaller.nI)
|
|
|
|
|
# copy_array(larger.W[:smaller.nO], smaller.W)
|
|
|
|
|
# copy_array(larger.b[:smaller.nO], smaller.b)
|
|
|
|
|
# self.model._layers[-1] = larger
|
2018-04-03 16:50:31 +03:00
|
|
|
|
raise ValueError(TempErrors.T003)
|
2017-11-01 23:49:24 +03:00
|
|
|
|
tag_map = dict(self.vocab.morphology.tag_map)
|
|
|
|
|
if values is None:
|
|
|
|
|
values = {POS: "X"}
|
|
|
|
|
tag_map[label] = values
|
|
|
|
|
self.vocab.morphology = Morphology(
|
|
|
|
|
self.vocab.strings, tag_map=tag_map,
|
|
|
|
|
lemmatizer=self.vocab.morphology.lemmatizer,
|
|
|
|
|
exc=self.vocab.morphology.exc)
|
|
|
|
|
return 1
|
2017-11-01 18:32:44 +03:00
|
|
|
|
|
2017-05-18 16:30:59 +03:00
|
|
|
|
def use_params(self, params):
|
|
|
|
|
with self.model.use_params(params):
|
|
|
|
|
yield
|
|
|
|
|
|
2020-07-06 14:06:25 +03:00
|
|
|
|
def to_bytes(self, exclude=tuple()):
|
2019-12-22 03:53:56 +03:00
|
|
|
|
serialize = {}
|
2020-02-27 20:42:27 +03:00
|
|
|
|
serialize["model"] = self.model.to_bytes
|
2019-03-08 13:42:26 +03:00
|
|
|
|
serialize["vocab"] = self.vocab.to_bytes
|
|
|
|
|
serialize["cfg"] = lambda: srsly.json_dumps(self.cfg)
|
2019-12-22 03:53:56 +03:00
|
|
|
|
tag_map = dict(sorted(self.vocab.morphology.tag_map.items()))
|
2019-03-08 13:42:26 +03:00
|
|
|
|
serialize["tag_map"] = lambda: srsly.msgpack_dumps(tag_map)
|
2017-05-29 11:14:20 +03:00
|
|
|
|
return util.to_bytes(serialize, exclude)
|
|
|
|
|
|
2020-07-06 14:06:25 +03:00
|
|
|
|
def from_bytes(self, bytes_data, exclude=tuple()):
|
2017-05-29 21:23:47 +03:00
|
|
|
|
def load_model(b):
|
2019-07-24 12:27:34 +03:00
|
|
|
|
try:
|
|
|
|
|
self.model.from_bytes(b)
|
|
|
|
|
except AttributeError:
|
|
|
|
|
raise ValueError(Errors.E149)
|
2017-06-02 18:18:37 +03:00
|
|
|
|
|
|
|
|
|
def load_tag_map(b):
|
💫 Replace ujson, msgpack and dill/pickle/cloudpickle with srsly (#3003)
Remove hacks and wrappers, keep code in sync across our libraries and move spaCy a few steps closer to only depending on packages with binary wheels 🎉
See here: https://github.com/explosion/srsly
Serialization is hard, especially across Python versions and multiple platforms. After dealing with many subtle bugs over the years (encodings, locales, large files) our libraries like spaCy and Prodigy have steadily grown a number of utility functions to wrap the multiple serialization formats we need to support (especially json, msgpack and pickle). These wrapping functions ended up duplicated across our codebases, so we wanted to put them in one place.
At the same time, we noticed that having a lot of small dependencies was making maintainence harder, and making installation slower. To solve this, we've made srsly standalone, by including the component packages directly within it. This way we can provide all the serialization utilities we need in a single binary wheel.
srsly currently includes forks of the following packages:
ujson
msgpack
msgpack-numpy
cloudpickle
* WIP: replace json/ujson with srsly
* Replace ujson in examples
Use regular json instead of srsly to make code easier to read and follow
* Update requirements
* Fix imports
* Fix typos
* Replace msgpack with srsly
* Fix warning
2018-12-03 03:28:22 +03:00
|
|
|
|
tag_map = srsly.msgpack_loads(b)
|
2017-06-02 18:18:37 +03:00
|
|
|
|
self.vocab.morphology = Morphology(
|
|
|
|
|
self.vocab.strings, tag_map=tag_map,
|
2017-06-05 00:34:32 +03:00
|
|
|
|
lemmatizer=self.vocab.morphology.lemmatizer,
|
|
|
|
|
exc=self.vocab.morphology.exc)
|
2017-09-16 20:46:02 +03:00
|
|
|
|
|
2019-12-22 03:53:56 +03:00
|
|
|
|
deserialize = {
|
|
|
|
|
"vocab": lambda b: self.vocab.from_bytes(b),
|
|
|
|
|
"tag_map": load_tag_map,
|
|
|
|
|
"cfg": lambda b: self.cfg.update(srsly.json_loads(b)),
|
|
|
|
|
"model": lambda b: load_model(b),
|
|
|
|
|
}
|
2017-05-29 21:23:47 +03:00
|
|
|
|
util.from_bytes(bytes_data, deserialize, exclude)
|
2017-05-29 11:14:20 +03:00
|
|
|
|
return self
|
|
|
|
|
|
2020-07-06 14:06:25 +03:00
|
|
|
|
def to_disk(self, path, exclude=tuple()):
|
2019-12-22 03:53:56 +03:00
|
|
|
|
tag_map = dict(sorted(self.vocab.morphology.tag_map.items()))
|
|
|
|
|
serialize = {
|
|
|
|
|
"vocab": lambda p: self.vocab.to_disk(p),
|
|
|
|
|
"tag_map": lambda p: srsly.write_msgpack(p, tag_map),
|
2020-06-20 16:52:00 +03:00
|
|
|
|
"model": lambda p: self.model.to_disk(p),
|
2020-02-27 20:42:27 +03:00
|
|
|
|
"cfg": lambda p: srsly.write_json(p, self.cfg),
|
2019-12-22 03:53:56 +03:00
|
|
|
|
}
|
2017-05-29 12:45:45 +03:00
|
|
|
|
util.to_disk(path, serialize, exclude)
|
|
|
|
|
|
2020-07-06 14:06:25 +03:00
|
|
|
|
def from_disk(self, path, exclude=tuple()):
|
2017-06-01 20:18:36 +03:00
|
|
|
|
def load_model(p):
|
2019-03-08 13:42:26 +03:00
|
|
|
|
with p.open("rb") as file_:
|
2019-07-24 12:27:34 +03:00
|
|
|
|
try:
|
|
|
|
|
self.model.from_bytes(file_.read())
|
|
|
|
|
except AttributeError:
|
|
|
|
|
raise ValueError(Errors.E149)
|
2017-06-01 20:18:36 +03:00
|
|
|
|
|
|
|
|
|
def load_tag_map(p):
|
💫 Replace ujson, msgpack and dill/pickle/cloudpickle with srsly (#3003)
Remove hacks and wrappers, keep code in sync across our libraries and move spaCy a few steps closer to only depending on packages with binary wheels 🎉
See here: https://github.com/explosion/srsly
Serialization is hard, especially across Python versions and multiple platforms. After dealing with many subtle bugs over the years (encodings, locales, large files) our libraries like spaCy and Prodigy have steadily grown a number of utility functions to wrap the multiple serialization formats we need to support (especially json, msgpack and pickle). These wrapping functions ended up duplicated across our codebases, so we wanted to put them in one place.
At the same time, we noticed that having a lot of small dependencies was making maintainence harder, and making installation slower. To solve this, we've made srsly standalone, by including the component packages directly within it. This way we can provide all the serialization utilities we need in a single binary wheel.
srsly currently includes forks of the following packages:
ujson
msgpack
msgpack-numpy
cloudpickle
* WIP: replace json/ujson with srsly
* Replace ujson in examples
Use regular json instead of srsly to make code easier to read and follow
* Update requirements
* Fix imports
* Fix typos
* Replace msgpack with srsly
* Fix warning
2018-12-03 03:28:22 +03:00
|
|
|
|
tag_map = srsly.read_msgpack(p)
|
2017-06-01 20:18:36 +03:00
|
|
|
|
self.vocab.morphology = Morphology(
|
|
|
|
|
self.vocab.strings, tag_map=tag_map,
|
2017-06-05 00:34:32 +03:00
|
|
|
|
lemmatizer=self.vocab.morphology.lemmatizer,
|
|
|
|
|
exc=self.vocab.morphology.exc)
|
2017-06-01 20:18:36 +03:00
|
|
|
|
|
2019-12-22 03:53:56 +03:00
|
|
|
|
deserialize = {
|
|
|
|
|
"vocab": lambda p: self.vocab.from_disk(p),
|
2020-02-27 20:42:27 +03:00
|
|
|
|
"cfg": lambda p: self.cfg.update(_load_cfg(p)),
|
2019-12-22 03:53:56 +03:00
|
|
|
|
"tag_map": load_tag_map,
|
|
|
|
|
"model": load_model,
|
|
|
|
|
}
|
2017-05-29 12:45:45 +03:00
|
|
|
|
util.from_disk(path, deserialize, exclude)
|
|
|
|
|
return self
|
2017-05-29 11:14:20 +03:00
|
|
|
|
|
|
|
|
|
|
2020-05-19 17:20:03 +03:00
|
|
|
|
@component("senter", assigns=["token.is_sent_start"], default_model=default_senter)
|
2019-11-28 13:10:07 +03:00
|
|
|
|
class SentenceRecognizer(Tagger):
|
|
|
|
|
"""Pipeline component for sentence segmentation.
|
|
|
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/sentencerecognizer
|
|
|
|
|
"""
|
|
|
|
|
|
2020-02-27 20:42:27 +03:00
|
|
|
|
def __init__(self, vocab, model, **cfg):
|
2019-11-28 13:10:07 +03:00
|
|
|
|
self.vocab = vocab
|
|
|
|
|
self.model = model
|
|
|
|
|
self._rehearsal_model = None
|
2019-12-22 03:53:56 +03:00
|
|
|
|
self.cfg = dict(sorted(cfg.items()))
|
2019-11-28 13:10:07 +03:00
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def labels(self):
|
|
|
|
|
# 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"])
|
|
|
|
|
|
2020-03-06 16:45:02 +03:00
|
|
|
|
def set_annotations(self, docs, batch_tag_ids):
|
2019-11-28 13:10:07 +03:00
|
|
|
|
if isinstance(docs, Doc):
|
|
|
|
|
docs = [docs]
|
|
|
|
|
cdef Doc doc
|
|
|
|
|
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 existing sentence boundaries
|
|
|
|
|
if doc.c[j].sent_start == 0:
|
|
|
|
|
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-08 14:59:28 +03:00
|
|
|
|
labels = self.labels
|
|
|
|
|
loss_func = SequenceCategoricalCrossentropy(names=labels, normalize=False)
|
2020-07-09 02:41:58 +03:00
|
|
|
|
truths = []
|
|
|
|
|
for eg in examples:
|
|
|
|
|
eg_truth = []
|
|
|
|
|
for x in eg.get_aligned("sent_start"):
|
|
|
|
|
if x == None:
|
|
|
|
|
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)
|
2020-07-08 14:59:28 +03:00
|
|
|
|
d_scores, loss = loss_func(scores, truths)
|
|
|
|
|
if self.model.ops.xp.isnan(loss):
|
|
|
|
|
raise ValueError("nan value when computing loss")
|
2019-11-28 13:10:07 +03:00
|
|
|
|
return float(loss), d_scores
|
|
|
|
|
|
|
|
|
|
def begin_training(self, get_examples=lambda: [], pipeline=None, sgd=None,
|
|
|
|
|
**kwargs):
|
2020-02-27 20:42:27 +03:00
|
|
|
|
self.set_output(len(self.labels))
|
|
|
|
|
self.model.initialize()
|
2020-03-06 16:45:02 +03:00
|
|
|
|
link_vectors_to_models(self.vocab)
|
2019-11-28 13:10:07 +03:00
|
|
|
|
if sgd is None:
|
|
|
|
|
sgd = self.create_optimizer()
|
|
|
|
|
return sgd
|
|
|
|
|
|
|
|
|
|
def add_label(self, label, values=None):
|
|
|
|
|
raise NotImplementedError
|
|
|
|
|
|
2020-07-06 14:06:25 +03:00
|
|
|
|
def to_bytes(self, exclude=tuple()):
|
2019-12-22 03:53:56 +03:00
|
|
|
|
serialize = {}
|
2020-02-27 20:42:27 +03:00
|
|
|
|
serialize["model"] = self.model.to_bytes
|
2019-11-28 13:10:07 +03:00
|
|
|
|
serialize["vocab"] = self.vocab.to_bytes
|
|
|
|
|
serialize["cfg"] = lambda: srsly.json_dumps(self.cfg)
|
|
|
|
|
return util.to_bytes(serialize, exclude)
|
|
|
|
|
|
2020-07-06 14:06:25 +03:00
|
|
|
|
def from_bytes(self, bytes_data, exclude=tuple()):
|
2019-11-28 13:10:07 +03:00
|
|
|
|
def load_model(b):
|
|
|
|
|
try:
|
|
|
|
|
self.model.from_bytes(b)
|
|
|
|
|
except AttributeError:
|
|
|
|
|
raise ValueError(Errors.E149)
|
|
|
|
|
|
2019-12-22 03:53:56 +03: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),
|
|
|
|
|
}
|
2019-11-28 13:10:07 +03:00
|
|
|
|
util.from_bytes(bytes_data, deserialize, exclude)
|
|
|
|
|
return self
|
|
|
|
|
|
2020-07-06 14:06:25 +03:00
|
|
|
|
def to_disk(self, path, exclude=tuple()):
|
2019-12-22 03:53:56 +03:00
|
|
|
|
serialize = {
|
|
|
|
|
"vocab": lambda p: self.vocab.to_disk(p),
|
|
|
|
|
"model": lambda p: p.open("wb").write(self.model.to_bytes()),
|
2020-02-27 20:42:27 +03:00
|
|
|
|
"cfg": lambda p: srsly.write_json(p, self.cfg),
|
2019-12-22 03:53:56 +03:00
|
|
|
|
}
|
2019-11-28 13:10:07 +03:00
|
|
|
|
util.to_disk(path, serialize, exclude)
|
|
|
|
|
|
2020-07-06 14:06:25 +03:00
|
|
|
|
def from_disk(self, path, exclude=tuple()):
|
2019-11-28 13:10:07 +03:00
|
|
|
|
def load_model(p):
|
|
|
|
|
with p.open("rb") as file_:
|
|
|
|
|
try:
|
|
|
|
|
self.model.from_bytes(file_.read())
|
|
|
|
|
except AttributeError:
|
|
|
|
|
raise ValueError(Errors.E149)
|
|
|
|
|
|
2019-12-22 03:53:56 +03:00
|
|
|
|
deserialize = {
|
|
|
|
|
"vocab": lambda p: self.vocab.from_disk(p),
|
2020-02-27 20:42:27 +03:00
|
|
|
|
"cfg": lambda p: self.cfg.update(_load_cfg(p)),
|
2019-12-22 03:53:56 +03:00
|
|
|
|
"model": load_model,
|
|
|
|
|
}
|
2017-05-29 12:45:45 +03:00
|
|
|
|
util.from_disk(path, deserialize, exclude)
|
|
|
|
|
return self
|
2017-05-29 11:14:20 +03:00
|
|
|
|
|
|
|
|
|
|
2019-10-27 15:35:49 +03:00
|
|
|
|
@component("nn_labeller")
|
2017-10-26 13:38:23 +03:00
|
|
|
|
class MultitaskObjective(Tagger):
|
2017-10-27 21:29:08 +03:00
|
|
|
|
"""Experimental: Assist training of a parser or tagger, by training a
|
|
|
|
|
side-objective.
|
|
|
|
|
"""
|
2019-03-08 13:42:26 +03:00
|
|
|
|
|
2020-06-12 03:02:07 +03:00
|
|
|
|
def __init__(self, vocab, model, **cfg):
|
2017-05-22 01:52:30 +03:00
|
|
|
|
self.vocab = vocab
|
|
|
|
|
self.model = model
|
2020-06-12 03:02:07 +03:00
|
|
|
|
target = cfg["target"] # default: 'dep_tag_offset'
|
2019-03-08 13:42:26 +03:00
|
|
|
|
if target == "dep":
|
2017-09-26 13:42:52 +03:00
|
|
|
|
self.make_label = self.make_dep
|
2019-03-08 13:42:26 +03:00
|
|
|
|
elif target == "tag":
|
2017-09-26 13:42:52 +03:00
|
|
|
|
self.make_label = self.make_tag
|
2019-03-08 13:42:26 +03:00
|
|
|
|
elif target == "ent":
|
2017-09-26 13:42:52 +03:00
|
|
|
|
self.make_label = self.make_ent
|
2019-03-08 13:42:26 +03:00
|
|
|
|
elif target == "dep_tag_offset":
|
2017-09-26 13:42:52 +03:00
|
|
|
|
self.make_label = self.make_dep_tag_offset
|
2019-03-08 13:42:26 +03:00
|
|
|
|
elif target == "ent_tag":
|
2017-09-26 13:42:52 +03:00
|
|
|
|
self.make_label = self.make_ent_tag
|
2019-03-08 13:42:26 +03:00
|
|
|
|
elif target == "sent_start":
|
2018-03-27 20:23:02 +03:00
|
|
|
|
self.make_label = self.make_sent_start
|
2019-03-08 13:42:26 +03:00
|
|
|
|
elif hasattr(target, "__call__"):
|
2017-09-26 13:42:52 +03:00
|
|
|
|
self.make_label = target
|
|
|
|
|
else:
|
2018-04-03 16:50:31 +03:00
|
|
|
|
raise ValueError(Errors.E016)
|
2017-07-23 01:52:47 +03:00
|
|
|
|
self.cfg = dict(cfg)
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def labels(self):
|
2019-03-08 13:42:26 +03:00
|
|
|
|
return self.cfg.setdefault("labels", {})
|
2017-07-23 01:52:47 +03:00
|
|
|
|
|
|
|
|
|
@labels.setter
|
|
|
|
|
def labels(self, value):
|
2019-03-08 13:42:26 +03:00
|
|
|
|
self.cfg["labels"] = value
|
2017-05-22 01:52:30 +03:00
|
|
|
|
|
2017-11-03 13:20:05 +03:00
|
|
|
|
def set_annotations(self, docs, dep_ids, tensors=None):
|
2017-05-22 01:52:30 +03:00
|
|
|
|
pass
|
|
|
|
|
|
2020-06-12 03:02:07 +03:00
|
|
|
|
def begin_training(self, get_examples=lambda: [], pipeline=None,
|
2018-02-12 12:18:39 +03:00
|
|
|
|
sgd=None, **kwargs):
|
2019-11-11 19:35:27 +03:00
|
|
|
|
gold_examples = nonproj.preprocess_training_data(get_examples())
|
|
|
|
|
# for raw_text, doc_annot in gold_tuples:
|
|
|
|
|
for example in gold_examples:
|
2020-06-26 20:34:12 +03:00
|
|
|
|
for token in example.y:
|
|
|
|
|
label = self.make_label(token)
|
2019-11-25 18:03:28 +03:00
|
|
|
|
if label is not None and label not in self.labels:
|
|
|
|
|
self.labels[label] = len(self.labels)
|
2020-01-29 19:06:46 +03:00
|
|
|
|
self.model.initialize()
|
2017-09-26 13:42:52 +03:00
|
|
|
|
link_vectors_to_models(self.vocab)
|
2017-11-06 16:26:26 +03:00
|
|
|
|
if sgd is None:
|
|
|
|
|
sgd = self.create_optimizer()
|
|
|
|
|
return sgd
|
2017-05-29 21:23:47 +03:00
|
|
|
|
|
2018-01-21 21:21:34 +03:00
|
|
|
|
def predict(self, docs):
|
2020-02-27 20:42:27 +03:00
|
|
|
|
tokvecs = self.model.get_ref("tok2vec")(docs)
|
|
|
|
|
scores = self.model.get_ref("softmax")(tokvecs)
|
2018-01-21 21:21:34 +03:00
|
|
|
|
return tokvecs, scores
|
2017-09-16 20:46:02 +03:00
|
|
|
|
|
2019-11-11 19:35:27 +03:00
|
|
|
|
def get_loss(self, examples, scores):
|
2017-05-22 01:52:30 +03:00
|
|
|
|
cdef int idx = 0
|
2019-03-08 13:42:26 +03:00
|
|
|
|
correct = numpy.zeros((scores.shape[0],), dtype="i")
|
2017-05-22 01:52:30 +03:00
|
|
|
|
guesses = scores.argmax(axis=1)
|
2020-06-26 20:34:12 +03:00
|
|
|
|
docs = [eg.predicted for eg in examples]
|
|
|
|
|
for i, eg in enumerate(examples):
|
|
|
|
|
# Handles alignment for tokenization differences
|
|
|
|
|
doc_annots = eg.get_aligned() # TODO
|
|
|
|
|
for j in range(len(eg.predicted)):
|
|
|
|
|
tok_annots = {key: values[j] for key, values in tok_annots.items()}
|
|
|
|
|
label = self.make_label(j, tok_annots)
|
2017-09-26 13:42:52 +03:00
|
|
|
|
if label is None or label not in self.labels:
|
2017-05-22 01:52:30 +03:00
|
|
|
|
correct[idx] = guesses[idx]
|
|
|
|
|
else:
|
2017-09-26 13:42:52 +03:00
|
|
|
|
correct[idx] = self.labels[label]
|
2017-05-22 01:52:30 +03:00
|
|
|
|
idx += 1
|
2019-03-08 13:42:26 +03:00
|
|
|
|
correct = self.model.ops.xp.array(correct, dtype="i")
|
2020-01-29 19:06:46 +03:00
|
|
|
|
d_scores = scores - to_categorical(correct, n_classes=scores.shape[1])
|
2017-05-22 01:52:30 +03:00
|
|
|
|
loss = (d_scores**2).sum()
|
|
|
|
|
return float(loss), d_scores
|
|
|
|
|
|
2017-09-26 13:42:52 +03:00
|
|
|
|
@staticmethod
|
2020-06-26 20:34:12 +03:00
|
|
|
|
def make_dep(token):
|
|
|
|
|
return token.dep_
|
2017-09-26 13:42:52 +03:00
|
|
|
|
|
|
|
|
|
@staticmethod
|
2020-06-26 20:34:12 +03:00
|
|
|
|
def make_tag(token):
|
|
|
|
|
return token.tag_
|
2017-09-26 13:42:52 +03:00
|
|
|
|
|
|
|
|
|
@staticmethod
|
2020-06-26 20:34:12 +03:00
|
|
|
|
def make_ent(token):
|
|
|
|
|
if token.ent_iob_ == "O":
|
|
|
|
|
return "O"
|
|
|
|
|
else:
|
|
|
|
|
return token.ent_iob_ + "-" + token.ent_type_
|
2017-09-26 13:42:52 +03:00
|
|
|
|
|
|
|
|
|
@staticmethod
|
2020-06-26 20:34:12 +03:00
|
|
|
|
def make_dep_tag_offset(token):
|
|
|
|
|
dep = token.dep_
|
|
|
|
|
tag = token.tag_
|
|
|
|
|
offset = token.head.i - token.i
|
2017-09-26 13:42:52 +03:00
|
|
|
|
offset = min(offset, 2)
|
|
|
|
|
offset = max(offset, -2)
|
2020-06-26 20:34:12 +03:00
|
|
|
|
return f"{dep}-{tag}:{offset}"
|
2017-09-26 13:42:52 +03:00
|
|
|
|
|
|
|
|
|
@staticmethod
|
2020-06-26 20:34:12 +03:00
|
|
|
|
def make_ent_tag(token):
|
|
|
|
|
if token.ent_iob_ == "O":
|
|
|
|
|
ent = "O"
|
2017-09-26 13:42:52 +03:00
|
|
|
|
else:
|
2020-06-26 20:34:12 +03:00
|
|
|
|
ent = token.ent_iob_ + "-" + token.ent_type_
|
|
|
|
|
tag = token.tag_
|
|
|
|
|
return f"{tag}-{ent}"
|
2017-09-26 13:42:52 +03:00
|
|
|
|
|
2018-03-27 20:23:02 +03:00
|
|
|
|
@staticmethod
|
2020-06-26 20:34:12 +03:00
|
|
|
|
def make_sent_start(token):
|
2019-03-08 13:42:26 +03:00
|
|
|
|
"""A multi-task objective for representing sentence boundaries,
|
2018-03-27 20:23:02 +03:00
|
|
|
|
using BILU scheme. (O is impossible)
|
2019-03-08 13:42:26 +03:00
|
|
|
|
"""
|
2020-06-26 20:34:12 +03:00
|
|
|
|
if token.is_sent_start and token.is_sent_end:
|
|
|
|
|
return "U-SENT"
|
|
|
|
|
elif token.is_sent_start:
|
|
|
|
|
return "B-SENT"
|
2018-03-27 20:23:02 +03:00
|
|
|
|
else:
|
2020-06-26 20:34:12 +03:00
|
|
|
|
return "I-SENT"
|
2018-03-27 20:23:02 +03:00
|
|
|
|
|
2017-05-17 13:04:50 +03:00
|
|
|
|
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
class ClozeMultitask(Pipe):
|
2020-02-27 20:42:27 +03:00
|
|
|
|
def __init__(self, vocab, model, **cfg):
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
self.vocab = vocab
|
|
|
|
|
self.model = model
|
|
|
|
|
self.cfg = cfg
|
2020-06-12 03:02:07 +03:00
|
|
|
|
self.distance = CosineDistance(ignore_zeros=True, normalize=False) # TODO: in config
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
|
|
|
|
|
def set_annotations(self, docs, dep_ids, tensors=None):
|
|
|
|
|
pass
|
|
|
|
|
|
2019-11-11 19:35:27 +03:00
|
|
|
|
def begin_training(self, get_examples=lambda: [], pipeline=None,
|
2020-06-12 03:02:07 +03:00
|
|
|
|
sgd=None, **kwargs):
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
link_vectors_to_models(self.vocab)
|
2020-01-29 19:06:46 +03:00
|
|
|
|
self.model.initialize()
|
2020-02-27 20:42:27 +03:00
|
|
|
|
X = self.model.ops.alloc((5, self.model.get_ref("tok2vec").get_dim("nO")))
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
self.model.output_layer.begin_training(X)
|
|
|
|
|
if sgd is None:
|
|
|
|
|
sgd = self.create_optimizer()
|
|
|
|
|
return sgd
|
|
|
|
|
|
|
|
|
|
def predict(self, docs):
|
2020-02-27 20:42:27 +03:00
|
|
|
|
tokvecs = self.model.get_ref("tok2vec")(docs)
|
|
|
|
|
vectors = self.model.get_ref("output_layer")(tokvecs)
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
return tokvecs, vectors
|
|
|
|
|
|
2019-11-11 19:35:27 +03:00
|
|
|
|
def get_loss(self, examples, vectors, prediction):
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
# The simplest way to implement this would be to vstack the
|
|
|
|
|
# token.vector values, but that's a bit inefficient, especially on GPU.
|
|
|
|
|
# Instead we fetch the index into the vectors table for each of our tokens,
|
|
|
|
|
# and look them up all at once. This prevents data copying.
|
2020-06-26 20:34:12 +03:00
|
|
|
|
ids = self.model.ops.flatten([eg.predicted.to_array(ID).ravel() for eg in examples])
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
target = vectors[ids]
|
2020-01-29 19:06:46 +03:00
|
|
|
|
gradient = self.distance.get_grad(prediction, target)
|
|
|
|
|
loss = self.distance.get_loss(prediction, target)
|
|
|
|
|
return loss, gradient
|
2019-02-05 14:32:20 +03:00
|
|
|
|
|
2020-01-29 19:06:46 +03:00
|
|
|
|
def update(self, examples, drop=0., set_annotations=False, sgd=None, losses=None):
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
pass
|
|
|
|
|
|
2019-11-11 19:35:27 +03:00
|
|
|
|
def rehearse(self, examples, drop=0., sgd=None, losses=None):
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
if losses is not None and self.name not in losses:
|
|
|
|
|
losses[self.name] = 0.
|
2020-01-29 19:06:46 +03:00
|
|
|
|
set_dropout_rate(self.model, drop)
|
2020-06-26 20:34:12 +03:00
|
|
|
|
try:
|
|
|
|
|
predictions, bp_predictions = self.model.begin_update([eg.predicted for eg in examples])
|
|
|
|
|
except AttributeError:
|
|
|
|
|
types = set([type(eg) for eg in examples])
|
2020-07-06 14:02:36 +03:00
|
|
|
|
raise TypeError(Errors.E978.format(name="ClozeMultitask", method="rehearse", types=types))
|
2019-11-11 19:35:27 +03:00
|
|
|
|
loss, d_predictions = self.get_loss(examples, self.vocab.vectors.data, predictions)
|
2020-01-29 19:06:46 +03:00
|
|
|
|
bp_predictions(d_predictions)
|
|
|
|
|
if sgd is not None:
|
|
|
|
|
self.model.finish_update(sgd)
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
|
|
|
|
|
if losses is not None:
|
|
|
|
|
losses[self.name] += loss
|
|
|
|
|
|
|
|
|
|
|
2020-05-19 17:20:03 +03:00
|
|
|
|
@component("textcat", assigns=["doc.cats"], default_model=default_textcat)
|
2017-10-26 13:40:40 +03:00
|
|
|
|
class TextCategorizer(Pipe):
|
2019-03-08 13:42:26 +03:00
|
|
|
|
"""Pipeline component for text classification.
|
|
|
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/textcategorizer
|
|
|
|
|
"""
|
2020-02-27 20:42:27 +03:00
|
|
|
|
def __init__(self, vocab, model, **cfg):
|
2017-07-20 01:18:15 +03:00
|
|
|
|
self.vocab = vocab
|
|
|
|
|
self.model = model
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
self._rehearsal_model = None
|
2017-07-23 01:52:47 +03:00
|
|
|
|
self.cfg = dict(cfg)
|
2017-07-23 01:33:43 +03:00
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def labels(self):
|
2019-03-08 13:42:26 +03:00
|
|
|
|
return tuple(self.cfg.setdefault("labels", []))
|
2017-07-23 01:33:43 +03:00
|
|
|
|
|
2019-07-10 20:39:38 +03:00
|
|
|
|
def require_labels(self):
|
|
|
|
|
"""Raise an error if the component's model has no labels defined."""
|
|
|
|
|
if not self.labels:
|
|
|
|
|
raise ValueError(Errors.E143.format(name=self.name))
|
|
|
|
|
|
2017-07-23 01:33:43 +03:00
|
|
|
|
@labels.setter
|
|
|
|
|
def labels(self, value):
|
2019-03-08 13:42:26 +03:00
|
|
|
|
self.cfg["labels"] = tuple(value)
|
2017-06-05 16:40:03 +03:00
|
|
|
|
|
2020-07-06 14:06:25 +03:00
|
|
|
|
def pipe(self, stream, batch_size=128):
|
2020-06-26 20:34:12 +03:00
|
|
|
|
for docs in util.minibatch(stream, size=batch_size):
|
2017-11-03 13:20:05 +03:00
|
|
|
|
scores, tensors = self.predict(docs)
|
|
|
|
|
self.set_annotations(docs, scores, tensors=tensors)
|
2020-06-26 20:34:12 +03:00
|
|
|
|
yield from docs
|
2017-07-20 01:18:15 +03:00
|
|
|
|
|
|
|
|
|
def predict(self, docs):
|
2019-07-30 15:58:01 +03:00
|
|
|
|
tensors = [doc.tensor for doc in docs]
|
|
|
|
|
|
|
|
|
|
if not any(len(doc) for doc in docs):
|
|
|
|
|
# Handle cases where there are no tokens in any docs.
|
|
|
|
|
xp = get_array_module(tensors)
|
|
|
|
|
scores = xp.zeros((len(docs), len(self.labels)))
|
|
|
|
|
return scores, tensors
|
|
|
|
|
|
2020-01-29 19:06:46 +03:00
|
|
|
|
scores = self.model.predict(docs)
|
2017-07-20 01:18:15 +03:00
|
|
|
|
scores = self.model.ops.asarray(scores)
|
2017-11-05 14:25:10 +03:00
|
|
|
|
return scores, tensors
|
2017-07-20 01:18:15 +03:00
|
|
|
|
|
2017-11-03 13:20:05 +03:00
|
|
|
|
def set_annotations(self, docs, scores, tensors=None):
|
2017-07-20 01:18:15 +03:00
|
|
|
|
for i, doc in enumerate(docs):
|
2017-07-22 21:04:43 +03:00
|
|
|
|
for j, label in enumerate(self.labels):
|
2017-07-20 01:18:15 +03:00
|
|
|
|
doc.cats[label] = float(scores[i, j])
|
|
|
|
|
|
2020-01-29 19:06:46 +03:00
|
|
|
|
def update(self, examples, state=None, drop=0., set_annotations=False, sgd=None, losses=None):
|
2020-06-26 20:34:12 +03:00
|
|
|
|
try:
|
|
|
|
|
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
|
|
|
|
|
except AttributeError:
|
|
|
|
|
types = set([type(eg) for eg in examples])
|
2020-07-06 14:02:36 +03:00
|
|
|
|
raise TypeError(Errors.E978.format(name="TextCategorizer", method="update", types=types))
|
2020-01-29 19:06:46 +03:00
|
|
|
|
set_dropout_rate(self.model, drop)
|
2020-06-26 20:34:12 +03:00
|
|
|
|
scores, bp_scores = self.model.begin_update(
|
|
|
|
|
[eg.predicted for eg in examples]
|
|
|
|
|
)
|
2019-11-11 19:35:27 +03:00
|
|
|
|
loss, d_scores = self.get_loss(examples, scores)
|
2020-01-29 19:06:46 +03:00
|
|
|
|
bp_scores(d_scores)
|
|
|
|
|
if sgd is not None:
|
|
|
|
|
self.model.finish_update(sgd)
|
2017-07-20 01:18:15 +03:00
|
|
|
|
if losses is not None:
|
|
|
|
|
losses.setdefault(self.name, 0.0)
|
|
|
|
|
losses[self.name] += loss
|
2020-01-29 19:06:46 +03:00
|
|
|
|
if set_annotations:
|
2020-06-26 20:34:12 +03:00
|
|
|
|
docs = [eg.predicted for eg in examples]
|
2020-01-29 19:06:46 +03:00
|
|
|
|
self.set_annotations(docs, scores=scores)
|
2017-07-20 01:18:15 +03:00
|
|
|
|
|
2019-11-11 19:35:27 +03:00
|
|
|
|
def rehearse(self, examples, drop=0., sgd=None, losses=None):
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
if self._rehearsal_model is None:
|
|
|
|
|
return
|
2020-06-26 20:34:12 +03:00
|
|
|
|
try:
|
|
|
|
|
docs = [eg.predicted for eg in examples]
|
|
|
|
|
except AttributeError:
|
|
|
|
|
types = set([type(eg) for eg in examples])
|
2020-07-06 14:02:36 +03:00
|
|
|
|
raise TypeError(Errors.E978.format(name="TextCategorizer", method="rehearse", types=types))
|
2019-10-02 13:50:48 +03:00
|
|
|
|
if not any(len(doc) for doc in docs):
|
|
|
|
|
# Handle cases where there are no tokens in any docs.
|
|
|
|
|
return
|
2020-01-29 19:06:46 +03:00
|
|
|
|
set_dropout_rate(self.model, drop)
|
|
|
|
|
scores, bp_scores = self.model.begin_update(docs)
|
2019-11-11 19:35:27 +03:00
|
|
|
|
target = self._rehearsal_model(examples)
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
gradient = scores - target
|
2020-01-29 19:06:46 +03:00
|
|
|
|
bp_scores(gradient)
|
|
|
|
|
if sgd is not None:
|
|
|
|
|
self.model.finish_update(sgd)
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
|
if losses is not None:
|
|
|
|
|
losses.setdefault(self.name, 0.0)
|
|
|
|
|
losses[self.name] += (gradient**2).sum()
|
|
|
|
|
|
2020-02-27 20:42:27 +03:00
|
|
|
|
def _examples_to_truth(self, examples):
|
2020-06-26 20:34:12 +03:00
|
|
|
|
truths = numpy.zeros((len(examples), len(self.labels)), dtype="f")
|
|
|
|
|
not_missing = numpy.ones((len(examples), len(self.labels)), dtype="f")
|
|
|
|
|
for i, eg in enumerate(examples):
|
2017-07-20 01:18:15 +03:00
|
|
|
|
for j, label in enumerate(self.labels):
|
2020-06-26 20:34:12 +03:00
|
|
|
|
if label in eg.reference.cats:
|
|
|
|
|
truths[i, j] = eg.reference.cats[label]
|
2017-10-06 02:43:02 +03:00
|
|
|
|
else:
|
|
|
|
|
not_missing[i, j] = 0.
|
2017-07-20 01:18:15 +03:00
|
|
|
|
truths = self.model.ops.asarray(truths)
|
2020-02-27 20:42:27 +03:00
|
|
|
|
return truths, not_missing
|
|
|
|
|
|
|
|
|
|
def get_loss(self, examples, scores):
|
|
|
|
|
truths, not_missing = self._examples_to_truth(examples)
|
2017-10-06 02:43:02 +03:00
|
|
|
|
not_missing = self.model.ops.asarray(not_missing)
|
2017-07-20 01:18:15 +03:00
|
|
|
|
d_scores = (scores-truths) / scores.shape[0]
|
2017-10-06 02:43:02 +03:00
|
|
|
|
d_scores *= not_missing
|
2019-02-23 14:28:06 +03:00
|
|
|
|
mean_square_error = (d_scores**2).sum(axis=1).mean()
|
2018-11-03 15:46:58 +03:00
|
|
|
|
return float(mean_square_error), d_scores
|
2017-07-20 01:18:15 +03:00
|
|
|
|
|
2017-11-01 18:32:44 +03:00
|
|
|
|
def add_label(self, label):
|
2019-12-22 03:53:56 +03:00
|
|
|
|
if not isinstance(label, str):
|
2019-11-21 18:24:10 +03:00
|
|
|
|
raise ValueError(Errors.E187)
|
2017-11-01 18:32:44 +03:00
|
|
|
|
if label in self.labels:
|
|
|
|
|
return 0
|
2020-02-27 20:42:27 +03:00
|
|
|
|
if self.model.has_dim("nO"):
|
2018-03-27 20:23:02 +03:00
|
|
|
|
# This functionality was available previously, but was broken.
|
|
|
|
|
# The problem is that we resize the last layer, but the last layer
|
|
|
|
|
# is actually just an ensemble. We're not resizing the child layers
|
2019-03-08 13:42:26 +03:00
|
|
|
|
# - a huge problem.
|
2019-02-14 22:03:19 +03:00
|
|
|
|
raise ValueError(Errors.E116)
|
2019-03-08 13:42:26 +03:00
|
|
|
|
# smaller = self.model._layers[-1]
|
2020-01-29 19:06:46 +03:00
|
|
|
|
# larger = Linear(len(self.labels)+1, smaller.nI)
|
2019-03-08 13:42:26 +03:00
|
|
|
|
# copy_array(larger.W[:smaller.nO], smaller.W)
|
|
|
|
|
# copy_array(larger.b[:smaller.nO], smaller.b)
|
|
|
|
|
# self.model._layers[-1] = larger
|
2019-02-14 22:03:19 +03:00
|
|
|
|
self.labels = tuple(list(self.labels) + [label])
|
2017-11-01 18:32:44 +03:00
|
|
|
|
return 1
|
|
|
|
|
|
2019-11-11 19:35:27 +03:00
|
|
|
|
def begin_training(self, get_examples=lambda: [], pipeline=None, sgd=None, **kwargs):
|
2020-02-27 20:42:27 +03:00
|
|
|
|
# TODO: begin_training is not guaranteed to see all data / labels ?
|
|
|
|
|
examples = list(get_examples())
|
|
|
|
|
for example in examples:
|
2020-06-26 20:34:12 +03:00
|
|
|
|
try:
|
|
|
|
|
y = example.y
|
|
|
|
|
except AttributeError:
|
2020-07-06 14:02:36 +03:00
|
|
|
|
raise TypeError(Errors.E978.format(name="TextCategorizer", method="update", types=type(example)))
|
2020-06-26 20:34:12 +03:00
|
|
|
|
for cat in y.cats:
|
2019-11-11 19:35:27 +03:00
|
|
|
|
self.add_label(cat)
|
2020-02-27 20:42:27 +03:00
|
|
|
|
self.require_labels()
|
|
|
|
|
docs = [Doc(Vocab(), words=["hello"])]
|
|
|
|
|
truths, _ = self._examples_to_truth(examples)
|
|
|
|
|
self.set_output(len(self.labels))
|
2020-03-29 20:40:36 +03:00
|
|
|
|
link_vectors_to_models(self.vocab)
|
2020-02-27 20:42:27 +03:00
|
|
|
|
self.model.initialize(X=docs, Y=truths)
|
2017-11-06 16:26:26 +03:00
|
|
|
|
if sgd is None:
|
|
|
|
|
sgd = self.create_optimizer()
|
|
|
|
|
return sgd
|
2017-06-05 16:40:03 +03:00
|
|
|
|
|
|
|
|
|
|
2017-10-26 13:38:23 +03:00
|
|
|
|
cdef class DependencyParser(Parser):
|
2019-03-08 13:42:26 +03:00
|
|
|
|
"""Pipeline component for dependency parsing.
|
|
|
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/dependencyparser
|
|
|
|
|
"""
|
2019-10-27 15:35:49 +03:00
|
|
|
|
# cdef classes can't have decorators, so we're defining this here
|
2019-03-08 13:42:26 +03:00
|
|
|
|
name = "parser"
|
2019-10-27 15:35:49 +03:00
|
|
|
|
factory = "parser"
|
|
|
|
|
assigns = ["token.dep", "token.is_sent_start", "doc.sents"]
|
|
|
|
|
requires = []
|
2017-05-16 12:21:59 +03:00
|
|
|
|
TransitionSystem = ArcEager
|
|
|
|
|
|
2017-10-07 03:00:47 +03:00
|
|
|
|
@property
|
|
|
|
|
def postprocesses(self):
|
2019-08-23 18:54:00 +03:00
|
|
|
|
output = [nonproj.deprojectivize]
|
|
|
|
|
if self.cfg.get("learn_tokens") is True:
|
|
|
|
|
output.append(merge_subtokens)
|
|
|
|
|
return tuple(output)
|
2018-03-27 20:23:02 +03:00
|
|
|
|
|
2020-06-12 03:02:07 +03:00
|
|
|
|
def add_multitask_objective(self, mt_component):
|
|
|
|
|
self._multitasks.append(mt_component)
|
2017-10-07 03:00:47 +03:00
|
|
|
|
|
2019-11-11 19:35:27 +03:00
|
|
|
|
def init_multitask_objectives(self, get_examples, pipeline, sgd=None, **cfg):
|
2020-06-12 03:02:07 +03:00
|
|
|
|
# TODO: transfer self.model.get_ref("tok2vec") to the multitask's model ?
|
2018-01-21 21:37:02 +03:00
|
|
|
|
for labeller in self._multitasks:
|
2020-06-12 03:02:07 +03:00
|
|
|
|
labeller.model.set_dim("nO", len(self.labels))
|
|
|
|
|
if labeller.model.has_ref("output_layer"):
|
|
|
|
|
labeller.model.get_ref("output_layer").set_dim("nO", len(self.labels))
|
|
|
|
|
labeller.begin_training(get_examples, pipeline=pipeline, sgd=sgd)
|
2017-09-26 13:42:52 +03:00
|
|
|
|
|
2017-05-27 23:46:06 +03:00
|
|
|
|
def __reduce__(self):
|
2020-06-12 03:02:07 +03:00
|
|
|
|
return (DependencyParser, (self.vocab, self.model), (self.moves, self.cfg))
|
2020-03-27 21:35:26 +03:00
|
|
|
|
|
|
|
|
|
def __getstate__(self):
|
2020-06-12 03:02:07 +03:00
|
|
|
|
return (self.moves, self.cfg)
|
2020-03-27 21:35:26 +03:00
|
|
|
|
|
2020-06-12 03:02:07 +03:00
|
|
|
|
def __setstate__(self, state):
|
|
|
|
|
moves, config = state
|
2020-03-27 21:35:26 +03:00
|
|
|
|
self.moves = moves
|
2020-06-12 03:02:07 +03:00
|
|
|
|
self.cfg = config
|
2017-05-27 23:46:06 +03:00
|
|
|
|
|
2019-02-14 22:03:19 +03:00
|
|
|
|
@property
|
|
|
|
|
def labels(self):
|
2019-09-12 19:02:44 +03:00
|
|
|
|
labels = set()
|
2019-02-14 22:03:19 +03:00
|
|
|
|
# Get the labels from the model by looking at the available moves
|
2019-09-12 19:02:44 +03:00
|
|
|
|
for move in self.move_names:
|
|
|
|
|
if "-" in move:
|
|
|
|
|
label = move.split("-")[1]
|
|
|
|
|
if "||" in label:
|
|
|
|
|
label = label.split("||")[1]
|
|
|
|
|
labels.add(label)
|
|
|
|
|
return tuple(sorted(labels))
|
2019-02-14 22:03:19 +03:00
|
|
|
|
|
2017-05-16 12:21:59 +03:00
|
|
|
|
|
2017-10-26 13:38:23 +03:00
|
|
|
|
cdef class EntityRecognizer(Parser):
|
2019-03-08 13:42:26 +03:00
|
|
|
|
"""Pipeline component for named entity recognition.
|
|
|
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/entityrecognizer
|
|
|
|
|
"""
|
2019-02-10 14:14:51 +03:00
|
|
|
|
name = "ner"
|
2019-10-27 15:35:49 +03:00
|
|
|
|
factory = "ner"
|
|
|
|
|
assigns = ["doc.ents", "token.ent_iob", "token.ent_type"]
|
|
|
|
|
requires = []
|
2017-05-16 12:21:59 +03:00
|
|
|
|
TransitionSystem = BiluoPushDown
|
2018-03-27 20:23:02 +03:00
|
|
|
|
|
2020-06-12 03:02:07 +03:00
|
|
|
|
def add_multitask_objective(self, mt_component):
|
|
|
|
|
self._multitasks.append(mt_component)
|
2017-05-17 13:04:50 +03:00
|
|
|
|
|
2019-11-11 19:35:27 +03:00
|
|
|
|
def init_multitask_objectives(self, get_examples, pipeline, sgd=None, **cfg):
|
2020-06-12 03:02:07 +03:00
|
|
|
|
# TODO: transfer self.model.get_ref("tok2vec") to the multitask's model ?
|
2018-01-21 21:37:02 +03:00
|
|
|
|
for labeller in self._multitasks:
|
2020-06-12 03:02:07 +03:00
|
|
|
|
labeller.model.set_dim("nO", len(self.labels))
|
|
|
|
|
if labeller.model.has_ref("output_layer"):
|
|
|
|
|
labeller.model.get_ref("output_layer").set_dim("nO", len(self.labels))
|
|
|
|
|
labeller.begin_training(get_examples, pipeline=pipeline)
|
2017-08-18 23:02:35 +03:00
|
|
|
|
|
2017-05-27 23:46:06 +03:00
|
|
|
|
def __reduce__(self):
|
2020-06-12 03:02:07 +03:00
|
|
|
|
return (EntityRecognizer, (self.vocab, self.model), (self.moves, self.cfg))
|
2020-03-27 21:35:26 +03:00
|
|
|
|
|
|
|
|
|
def __getstate__(self):
|
2020-06-12 03:02:07 +03:00
|
|
|
|
return self.moves, self.cfg
|
2020-03-27 21:35:26 +03:00
|
|
|
|
|
2020-06-12 03:02:07 +03:00
|
|
|
|
def __setstate__(self, state):
|
|
|
|
|
moves, config = state
|
2020-03-27 21:35:26 +03:00
|
|
|
|
self.moves = moves
|
2020-06-12 03:02:07 +03:00
|
|
|
|
self.cfg = config
|
2017-10-07 03:00:47 +03:00
|
|
|
|
|
2018-11-18 02:06:26 +03:00
|
|
|
|
@property
|
|
|
|
|
def labels(self):
|
|
|
|
|
# Get the labels from the model by looking at the available moves, e.g.
|
|
|
|
|
# B-PERSON, I-PERSON, L-PERSON, U-PERSON
|
2019-09-12 19:02:44 +03:00
|
|
|
|
labels = set(move.split("-")[1] for move in self.move_names
|
|
|
|
|
if move[0] in ("B", "I", "L", "U"))
|
|
|
|
|
return tuple(sorted(labels))
|
2018-11-18 02:06:26 +03:00
|
|
|
|
|
2017-03-15 17:27:41 +03:00
|
|
|
|
|
2019-10-27 15:35:49 +03:00
|
|
|
|
@component(
|
|
|
|
|
"entity_linker",
|
2019-12-13 17:55:18 +03:00
|
|
|
|
requires=["doc.ents", "doc.sents", "token.ent_iob", "token.ent_type"],
|
2020-05-19 17:20:03 +03:00
|
|
|
|
assigns=["token.ent_kb_id"],
|
|
|
|
|
default_model=default_nel,
|
2019-10-27 15:35:49 +03:00
|
|
|
|
)
|
2019-03-06 21:34:18 +03:00
|
|
|
|
class EntityLinker(Pipe):
|
2019-06-06 21:22:14 +03:00
|
|
|
|
"""Pipeline component for named entity linking.
|
|
|
|
|
|
2019-08-13 16:38:59 +03:00
|
|
|
|
DOCS: https://spacy.io/api/entitylinker
|
2019-06-06 21:22:14 +03:00
|
|
|
|
"""
|
2019-07-19 13:36:15 +03:00
|
|
|
|
NIL = "NIL" # string used to refer to a non-existing link
|
2019-03-06 21:34:18 +03:00
|
|
|
|
|
2020-02-27 20:42:27 +03:00
|
|
|
|
def __init__(self, vocab, model, **cfg):
|
2019-07-03 16:00:42 +03:00
|
|
|
|
self.vocab = vocab
|
2020-02-27 20:42:27 +03:00
|
|
|
|
self.model = model
|
2019-06-13 17:25:39 +03:00
|
|
|
|
self.kb = None
|
2020-05-20 12:41:12 +03:00
|
|
|
|
self.kb = cfg.get("kb", None)
|
|
|
|
|
if self.kb is None:
|
|
|
|
|
# create an empty KB that should be filled by calling from_disk
|
|
|
|
|
self.kb = KnowledgeBase(vocab=vocab)
|
|
|
|
|
else:
|
|
|
|
|
del cfg["kb"] # we don't want to duplicate its serialization
|
|
|
|
|
if not isinstance(self.kb, KnowledgeBase):
|
|
|
|
|
raise ValueError(Errors.E990.format(type=type(self.kb)))
|
2019-03-06 21:34:18 +03:00
|
|
|
|
self.cfg = dict(cfg)
|
2020-01-29 19:06:46 +03:00
|
|
|
|
self.distance = CosineDistance(normalize=False)
|
2020-06-12 03:03:23 +03:00
|
|
|
|
# how many neightbour sentences to take into account
|
|
|
|
|
self.n_sents = cfg.get("n_sents", 0)
|
2019-06-11 12:40:58 +03:00
|
|
|
|
|
2019-06-13 17:25:39 +03:00
|
|
|
|
def require_kb(self):
|
|
|
|
|
# Raise an error if the knowledge base is not initialized.
|
2020-05-20 12:41:12 +03:00
|
|
|
|
if len(self.kb) == 0:
|
2019-06-19 13:35:26 +03:00
|
|
|
|
raise ValueError(Errors.E139.format(name=self.name))
|
2019-06-13 17:25:39 +03:00
|
|
|
|
|
2019-11-11 19:35:27 +03:00
|
|
|
|
def begin_training(self, get_examples=lambda: [], pipeline=None, sgd=None, **kwargs):
|
2019-06-13 17:25:39 +03:00
|
|
|
|
self.require_kb()
|
2020-02-27 20:42:27 +03:00
|
|
|
|
nO = self.kb.entity_vector_length
|
|
|
|
|
self.set_output(nO)
|
2020-01-29 19:06:46 +03:00
|
|
|
|
self.model.initialize()
|
2019-06-18 01:05:47 +03:00
|
|
|
|
if sgd is None:
|
|
|
|
|
sgd = self.create_optimizer()
|
|
|
|
|
return sgd
|
|
|
|
|
|
2020-01-29 19:06:46 +03:00
|
|
|
|
def update(self, examples, state=None, set_annotations=False, drop=0.0, sgd=None, losses=None):
|
2019-06-13 17:25:39 +03:00
|
|
|
|
self.require_kb()
|
2019-06-14 16:55:26 +03:00
|
|
|
|
if losses is not None:
|
|
|
|
|
losses.setdefault(self.name, 0.0)
|
2019-11-11 19:35:27 +03:00
|
|
|
|
if not examples:
|
2019-06-14 16:55:26 +03:00
|
|
|
|
return 0
|
2019-10-14 13:28:53 +03:00
|
|
|
|
sentence_docs = []
|
2020-06-26 20:34:12 +03:00
|
|
|
|
try:
|
|
|
|
|
docs = [eg.predicted for eg in examples]
|
|
|
|
|
except AttributeError:
|
|
|
|
|
types = set([type(eg) for eg in examples])
|
2020-07-06 14:02:36 +03:00
|
|
|
|
raise TypeError(Errors.E978.format(name="EntityLinker", method="update", types=types))
|
2020-01-29 19:06:46 +03:00
|
|
|
|
if set_annotations:
|
|
|
|
|
# This seems simpler than other ways to get that exact output -- but
|
|
|
|
|
# it does run the model twice :(
|
|
|
|
|
predictions = self.model.predict(docs)
|
2020-06-12 03:03:23 +03:00
|
|
|
|
|
2020-06-26 20:34:12 +03:00
|
|
|
|
for eg in examples:
|
|
|
|
|
sentences = [s for s in eg.predicted.sents]
|
|
|
|
|
kb_ids = eg.get_aligned("ENT_KB_ID", as_string=True)
|
|
|
|
|
for ent in eg.predicted.ents:
|
|
|
|
|
kb_id = kb_ids[ent.start] # KB ID of the first token is the same as the whole span
|
|
|
|
|
if kb_id:
|
|
|
|
|
try:
|
|
|
|
|
# find the sentence in the list of sentences.
|
|
|
|
|
sent_index = sentences.index(ent.sent)
|
|
|
|
|
except AttributeError:
|
|
|
|
|
# Catch the exception when ent.sent is None and provide a user-friendly warning
|
|
|
|
|
raise RuntimeError(Errors.E030)
|
|
|
|
|
# get n previous sentences, if there are any
|
|
|
|
|
start_sentence = max(0, sent_index - self.n_sents)
|
|
|
|
|
|
|
|
|
|
# get n posterior sentences, or as many < n as there are
|
|
|
|
|
end_sentence = min(len(sentences) -1, sent_index + self.n_sents)
|
|
|
|
|
|
|
|
|
|
# get token positions
|
|
|
|
|
start_token = sentences[start_sentence].start
|
|
|
|
|
end_token = sentences[end_sentence].end
|
|
|
|
|
|
|
|
|
|
# append that span as a doc to training
|
|
|
|
|
sent_doc = eg.predicted[start_token:end_token].as_doc()
|
|
|
|
|
sentence_docs.append(sent_doc)
|
2020-01-29 19:06:46 +03:00
|
|
|
|
set_dropout_rate(self.model, drop)
|
2020-06-26 20:34:12 +03:00
|
|
|
|
if not sentence_docs:
|
|
|
|
|
warnings.warn(Warnings.W093.format(name="Entity Linker"))
|
|
|
|
|
return 0.0
|
2020-01-29 19:06:46 +03:00
|
|
|
|
sentence_encodings, bp_context = self.model.begin_update(sentence_docs)
|
2020-06-26 20:34:12 +03:00
|
|
|
|
loss, d_scores = self.get_similarity_loss(
|
|
|
|
|
scores=sentence_encodings,
|
|
|
|
|
examples=examples
|
|
|
|
|
)
|
2020-01-29 19:06:46 +03:00
|
|
|
|
bp_context(d_scores)
|
|
|
|
|
if sgd is not None:
|
|
|
|
|
self.model.finish_update(sgd)
|
2019-06-28 17:22:58 +03:00
|
|
|
|
|
2019-08-13 16:38:59 +03:00
|
|
|
|
if losses is not None:
|
|
|
|
|
losses[self.name] += loss
|
2020-01-29 19:06:46 +03:00
|
|
|
|
if set_annotations:
|
|
|
|
|
self.set_annotations(docs, predictions)
|
2019-08-13 16:38:59 +03:00
|
|
|
|
return loss
|
2019-06-07 16:55:10 +03:00
|
|
|
|
|
2020-06-26 20:34:12 +03:00
|
|
|
|
def get_similarity_loss(self, examples, scores):
|
2019-08-13 16:38:59 +03:00
|
|
|
|
entity_encodings = []
|
2020-06-26 20:34:12 +03:00
|
|
|
|
for eg in examples:
|
|
|
|
|
kb_ids = eg.get_aligned("ENT_KB_ID", as_string=True)
|
|
|
|
|
for ent in eg.predicted.ents:
|
|
|
|
|
kb_id = kb_ids[ent.start]
|
|
|
|
|
if kb_id:
|
|
|
|
|
entity_encoding = self.kb.get_vector(kb_id)
|
|
|
|
|
entity_encodings.append(entity_encoding)
|
2019-06-28 09:29:31 +03:00
|
|
|
|
|
2019-08-13 16:38:59 +03:00
|
|
|
|
entity_encodings = self.model.ops.asarray(entity_encodings, dtype="float32")
|
2019-06-28 09:29:31 +03:00
|
|
|
|
|
2019-08-13 16:38:59 +03:00
|
|
|
|
if scores.shape != entity_encodings.shape:
|
2019-11-11 19:35:27 +03:00
|
|
|
|
raise RuntimeError(Errors.E147.format(method="get_similarity_loss", msg="gold entities do not match up"))
|
2019-06-07 16:55:10 +03:00
|
|
|
|
|
2020-01-29 19:06:46 +03:00
|
|
|
|
gradients = self.distance.get_grad(scores, entity_encodings)
|
|
|
|
|
loss = self.distance.get_loss(scores, entity_encodings)
|
2019-08-13 16:38:59 +03:00
|
|
|
|
loss = loss / len(entity_encodings)
|
|
|
|
|
return loss, gradients
|
2019-06-03 22:32:54 +03:00
|
|
|
|
|
2019-11-11 19:35:27 +03:00
|
|
|
|
def get_loss(self, examples, scores):
|
2019-07-18 14:35:10 +03:00
|
|
|
|
cats = []
|
2020-06-26 20:34:12 +03:00
|
|
|
|
for eg in examples:
|
|
|
|
|
kb_ids = eg.get_aligned("ENT_KB_ID", as_string=True)
|
|
|
|
|
for ent in eg.predicted.ents:
|
|
|
|
|
kb_id = kb_ids[ent.start]
|
|
|
|
|
if kb_id:
|
|
|
|
|
cats.append([1.0])
|
2019-07-18 14:35:10 +03:00
|
|
|
|
|
|
|
|
|
cats = self.model.ops.asarray(cats, dtype="float32")
|
2019-07-23 12:52:48 +03:00
|
|
|
|
if len(scores) != len(cats):
|
|
|
|
|
raise RuntimeError(Errors.E147.format(method="get_loss", msg="gold entities do not match up"))
|
2019-07-18 14:35:10 +03:00
|
|
|
|
|
|
|
|
|
d_scores = (scores - cats)
|
2019-06-28 09:29:31 +03:00
|
|
|
|
loss = (d_scores ** 2).sum()
|
2019-07-18 14:35:10 +03:00
|
|
|
|
loss = loss / len(cats)
|
2019-06-28 09:29:31 +03:00
|
|
|
|
return loss, d_scores
|
|
|
|
|
|
2020-06-26 20:34:12 +03:00
|
|
|
|
def __call__(self, doc):
|
2019-07-19 15:47:36 +03:00
|
|
|
|
kb_ids, tensors = self.predict([doc])
|
|
|
|
|
self.set_annotations([doc], kb_ids, tensors=tensors)
|
2019-03-06 21:34:18 +03:00
|
|
|
|
return doc
|
|
|
|
|
|
2020-07-06 14:06:25 +03:00
|
|
|
|
def pipe(self, stream, batch_size=128):
|
2020-06-26 20:34:12 +03:00
|
|
|
|
for docs in util.minibatch(stream, size=batch_size):
|
2019-07-19 15:47:36 +03:00
|
|
|
|
kb_ids, tensors = self.predict(docs)
|
|
|
|
|
self.set_annotations(docs, kb_ids, tensors=tensors)
|
2020-06-26 20:34:12 +03:00
|
|
|
|
yield from docs
|
2019-03-06 21:34:18 +03:00
|
|
|
|
|
2019-06-03 22:32:54 +03:00
|
|
|
|
def predict(self, docs):
|
2019-07-19 13:36:15 +03:00
|
|
|
|
""" Return the KB IDs for each entity in each doc, including NIL if there is no prediction """
|
2019-06-13 17:25:39 +03:00
|
|
|
|
self.require_kb()
|
2019-07-19 13:36:15 +03:00
|
|
|
|
entity_count = 0
|
2019-06-24 11:55:04 +03:00
|
|
|
|
final_kb_ids = []
|
2019-07-19 15:47:36 +03:00
|
|
|
|
final_tensors = []
|
2019-06-12 14:37:05 +03:00
|
|
|
|
|
2019-06-14 16:55:26 +03:00
|
|
|
|
if not docs:
|
2019-07-23 15:23:58 +03:00
|
|
|
|
return final_kb_ids, final_tensors
|
2019-06-14 16:55:26 +03:00
|
|
|
|
|
|
|
|
|
if isinstance(docs, Doc):
|
|
|
|
|
docs = [docs]
|
|
|
|
|
|
|
|
|
|
for i, doc in enumerate(docs):
|
2020-06-12 03:03:23 +03:00
|
|
|
|
sentences = [s for s in doc.sents]
|
|
|
|
|
|
2019-06-14 16:55:26 +03:00
|
|
|
|
if len(doc) > 0:
|
2019-10-14 13:28:53 +03:00
|
|
|
|
# Looping through each sentence and each entity
|
2020-01-06 16:59:50 +03:00
|
|
|
|
# This may go wrong if there are entities across sentences - which shouldn't happen normally.
|
2020-06-20 22:47:23 +03:00
|
|
|
|
for sent_index, sent in enumerate(sentences):
|
2020-06-21 00:14:45 +03:00
|
|
|
|
if sent.ents:
|
|
|
|
|
# get n_neightbour sentences, clipped to the length of the document
|
|
|
|
|
start_sentence = max(0, sent_index - self.n_sents)
|
|
|
|
|
end_sentence = min(len(sentences) -1, sent_index + self.n_sents)
|
2019-10-14 13:28:53 +03:00
|
|
|
|
|
2020-06-21 00:14:45 +03:00
|
|
|
|
start_token = sentences[start_sentence].start
|
|
|
|
|
end_token = sentences[end_sentence].end
|
2019-10-14 13:28:53 +03:00
|
|
|
|
|
2020-06-21 00:14:45 +03:00
|
|
|
|
sent_doc = doc[start_token:end_token].as_doc()
|
|
|
|
|
# currently, the context is the same for each entity in a sentence (should be refined)
|
|
|
|
|
sentence_encoding = self.model.predict([sent_doc])[0]
|
|
|
|
|
xp = get_array_module(sentence_encoding)
|
|
|
|
|
sentence_encoding_t = sentence_encoding.T
|
|
|
|
|
sentence_norm = xp.linalg.norm(sentence_encoding_t)
|
|
|
|
|
|
|
|
|
|
for ent in sent.ents:
|
|
|
|
|
entity_count += 1
|
|
|
|
|
|
|
|
|
|
to_discard = self.cfg.get("labels_discard", [])
|
|
|
|
|
if to_discard and ent.label_ in to_discard:
|
|
|
|
|
# ignoring this entity - setting to NIL
|
|
|
|
|
final_kb_ids.append(self.NIL)
|
2019-10-14 13:28:53 +03:00
|
|
|
|
final_tensors.append(sentence_encoding)
|
|
|
|
|
|
|
|
|
|
else:
|
2020-06-21 00:14:45 +03:00
|
|
|
|
candidates = self.kb.get_candidates(ent.text)
|
|
|
|
|
if not candidates:
|
|
|
|
|
# no prediction possible for this entity - setting to NIL
|
|
|
|
|
final_kb_ids.append(self.NIL)
|
|
|
|
|
final_tensors.append(sentence_encoding)
|
|
|
|
|
|
|
|
|
|
elif len(candidates) == 1:
|
|
|
|
|
# shortcut for efficiency reasons: take the 1 candidate
|
|
|
|
|
|
|
|
|
|
# TODO: thresholding
|
|
|
|
|
final_kb_ids.append(candidates[0].entity_)
|
|
|
|
|
final_tensors.append(sentence_encoding)
|
|
|
|
|
|
|
|
|
|
else:
|
|
|
|
|
random.shuffle(candidates)
|
|
|
|
|
|
|
|
|
|
# this will set all prior probabilities to 0 if they should be excluded from the model
|
|
|
|
|
prior_probs = xp.asarray([c.prior_prob for c in candidates])
|
|
|
|
|
if not self.cfg.get("incl_prior", True):
|
|
|
|
|
prior_probs = xp.asarray([0.0 for c in candidates])
|
|
|
|
|
scores = prior_probs
|
|
|
|
|
|
|
|
|
|
# add in similarity from the context
|
|
|
|
|
if self.cfg.get("incl_context", True):
|
|
|
|
|
entity_encodings = xp.asarray([c.entity_vector for c in candidates])
|
|
|
|
|
entity_norm = xp.linalg.norm(entity_encodings, axis=1)
|
|
|
|
|
|
|
|
|
|
if len(entity_encodings) != len(prior_probs):
|
|
|
|
|
raise RuntimeError(Errors.E147.format(method="predict", msg="vectors not of equal length"))
|
|
|
|
|
|
|
|
|
|
# cosine similarity
|
|
|
|
|
sims = xp.dot(entity_encodings, sentence_encoding_t) / (sentence_norm * entity_norm)
|
|
|
|
|
if sims.shape != prior_probs.shape:
|
|
|
|
|
raise ValueError(Errors.E161)
|
|
|
|
|
scores = prior_probs + sims - (prior_probs*sims)
|
|
|
|
|
|
|
|
|
|
# TODO: thresholding
|
|
|
|
|
best_index = scores.argmax().item()
|
|
|
|
|
best_candidate = candidates[best_index]
|
|
|
|
|
final_kb_ids.append(best_candidate.entity_)
|
|
|
|
|
final_tensors.append(sentence_encoding)
|
2019-06-05 01:09:46 +03:00
|
|
|
|
|
2019-07-23 12:52:48 +03:00
|
|
|
|
if not (len(final_tensors) == len(final_kb_ids) == entity_count):
|
|
|
|
|
raise RuntimeError(Errors.E147.format(method="predict", msg="result variables not of equal length"))
|
2019-06-03 22:32:54 +03:00
|
|
|
|
|
2019-07-19 15:47:36 +03:00
|
|
|
|
return final_kb_ids, final_tensors
|
2019-07-19 13:36:15 +03:00
|
|
|
|
|
|
|
|
|
def set_annotations(self, docs, kb_ids, tensors=None):
|
2019-07-19 15:47:36 +03:00
|
|
|
|
count_ents = len([ent for doc in docs for ent in doc.ents])
|
2019-07-23 12:52:48 +03:00
|
|
|
|
if count_ents != len(kb_ids):
|
|
|
|
|
raise ValueError(Errors.E148.format(ents=count_ents, ids=len(kb_ids)))
|
2019-07-19 15:47:36 +03:00
|
|
|
|
|
2019-07-19 13:36:15 +03:00
|
|
|
|
i=0
|
|
|
|
|
for doc in docs:
|
|
|
|
|
for ent in doc.ents:
|
|
|
|
|
kb_id = kb_ids[i]
|
|
|
|
|
i += 1
|
|
|
|
|
for token in ent:
|
|
|
|
|
token.ent_kb_id_ = kb_id
|
2019-03-06 21:34:18 +03:00
|
|
|
|
|
2020-07-06 14:06:25 +03:00
|
|
|
|
def to_disk(self, path, exclude=tuple()):
|
2019-12-22 03:53:56 +03:00
|
|
|
|
serialize = {}
|
2020-03-06 16:42:23 +03:00
|
|
|
|
self.cfg["entity_width"] = self.kb.entity_vector_length
|
2019-06-13 17:25:39 +03:00
|
|
|
|
serialize["cfg"] = lambda p: srsly.write_json(p, self.cfg)
|
2019-07-03 16:00:42 +03:00
|
|
|
|
serialize["vocab"] = lambda p: self.vocab.to_disk(p)
|
2019-06-13 17:25:39 +03:00
|
|
|
|
serialize["kb"] = lambda p: self.kb.dump(p)
|
2020-06-20 16:52:00 +03:00
|
|
|
|
serialize["model"] = lambda p: self.model.to_disk(p)
|
2019-06-13 17:25:39 +03:00
|
|
|
|
util.to_disk(path, serialize, exclude)
|
|
|
|
|
|
2020-07-06 14:06:25 +03:00
|
|
|
|
def from_disk(self, path, exclude=tuple()):
|
2019-06-18 01:05:47 +03:00
|
|
|
|
def load_model(p):
|
2019-08-13 16:38:59 +03:00
|
|
|
|
try:
|
2019-07-24 12:27:34 +03:00
|
|
|
|
self.model.from_bytes(p.open("rb").read())
|
|
|
|
|
except AttributeError:
|
|
|
|
|
raise ValueError(Errors.E149)
|
2019-06-13 17:25:39 +03:00
|
|
|
|
|
2019-07-03 16:00:42 +03:00
|
|
|
|
def load_kb(p):
|
2020-05-20 12:41:12 +03:00
|
|
|
|
self.kb = KnowledgeBase(vocab=self.vocab, entity_vector_length=self.cfg["entity_width"])
|
|
|
|
|
self.kb.load_bulk(p)
|
2019-07-03 16:00:42 +03:00
|
|
|
|
|
2019-12-22 03:53:56 +03:00
|
|
|
|
deserialize = {}
|
2019-07-03 16:00:42 +03:00
|
|
|
|
deserialize["vocab"] = lambda p: self.vocab.from_disk(p)
|
2020-02-27 20:42:27 +03:00
|
|
|
|
deserialize["cfg"] = lambda p: self.cfg.update(_load_cfg(p))
|
2019-07-03 16:00:42 +03:00
|
|
|
|
deserialize["kb"] = load_kb
|
2019-06-18 01:05:47 +03:00
|
|
|
|
deserialize["model"] = load_model
|
2019-06-13 17:25:39 +03:00
|
|
|
|
util.from_disk(path, deserialize, exclude)
|
|
|
|
|
return self
|
|
|
|
|
|
2019-11-11 19:35:27 +03:00
|
|
|
|
def rehearse(self, examples, sgd=None, losses=None, **config):
|
2019-06-24 11:55:04 +03:00
|
|
|
|
raise NotImplementedError
|
2019-06-13 17:25:39 +03:00
|
|
|
|
|
|
|
|
|
def add_label(self, label):
|
2019-06-24 11:55:04 +03:00
|
|
|
|
raise NotImplementedError
|
2019-06-13 17:25:39 +03:00
|
|
|
|
|
|
|
|
|
|
2019-10-27 15:35:49 +03:00
|
|
|
|
@component("sentencizer", assigns=["token.is_sent_start", "doc.sents"])
|
2019-11-11 19:35:27 +03:00
|
|
|
|
class Sentencizer(Pipe):
|
2019-03-23 17:45:02 +03:00
|
|
|
|
"""Segment the Doc into sentences using a rule-based strategy.
|
|
|
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/sentencizer
|
|
|
|
|
"""
|
|
|
|
|
|
2019-09-14 16:25:48 +03:00
|
|
|
|
default_punct_chars = ['!', '.', '?', '։', '؟', '۔', '܀', '܁', '܂', '߹',
|
|
|
|
|
'।', '॥', '၊', '။', '።', '፧', '፨', '᙮', '᜵', '᜶', '᠃', '᠉', '᥄',
|
|
|
|
|
'᥅', '᪨', '᪩', '᪪', '᪫', '᭚', '᭛', '᭞', '᭟', '᰻', '᰼', '᱾', '᱿',
|
|
|
|
|
'‼', '‽', '⁇', '⁈', '⁉', '⸮', '⸼', '꓿', '꘎', '꘏', '꛳', '꛷', '꡶',
|
|
|
|
|
'꡷', '꣎', '꣏', '꤯', '꧈', '꧉', '꩝', '꩞', '꩟', '꫰', '꫱', '꯫', '﹒',
|
|
|
|
|
'﹖', '﹗', '!', '.', '?', '𐩖', '𐩗', '𑁇', '𑁈', '𑂾', '𑂿', '𑃀',
|
|
|
|
|
'𑃁', '𑅁', '𑅂', '𑅃', '𑇅', '𑇆', '𑇍', '𑇞', '𑇟', '𑈸', '𑈹', '𑈻', '𑈼',
|
|
|
|
|
'𑊩', '𑑋', '𑑌', '𑗂', '𑗃', '𑗉', '𑗊', '𑗋', '𑗌', '𑗍', '𑗎', '𑗏', '𑗐',
|
|
|
|
|
'𑗑', '𑗒', '𑗓', '𑗔', '𑗕', '𑗖', '𑗗', '𑙁', '𑙂', '𑜼', '𑜽', '𑜾', '𑩂',
|
2020-04-08 13:58:39 +03:00
|
|
|
|
'𑩃', '𑪛', '𑪜', '𑱁', '𑱂', '𖩮', '𖩯', '𖫵', '𖬷', '𖬸', '𖭄', '𛲟', '𝪈',
|
|
|
|
|
'。', '。']
|
2019-03-23 17:45:02 +03:00
|
|
|
|
|
|
|
|
|
def __init__(self, punct_chars=None, **kwargs):
|
|
|
|
|
"""Initialize the sentencizer.
|
|
|
|
|
|
|
|
|
|
punct_chars (list): Punctuation characters to split on. Will be
|
|
|
|
|
serialized with the nlp object.
|
|
|
|
|
RETURNS (Sentencizer): The sentencizer component.
|
|
|
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/sentencizer#init
|
|
|
|
|
"""
|
2019-09-14 16:25:48 +03:00
|
|
|
|
if punct_chars:
|
|
|
|
|
self.punct_chars = set(punct_chars)
|
|
|
|
|
else:
|
|
|
|
|
self.punct_chars = set(self.default_punct_chars)
|
2019-03-23 17:45:02 +03:00
|
|
|
|
|
2019-10-27 15:35:49 +03:00
|
|
|
|
@classmethod
|
2020-02-27 20:42:27 +03:00
|
|
|
|
def from_nlp(cls, nlp, model=None, **cfg):
|
2019-10-27 15:35:49 +03:00
|
|
|
|
return cls(**cfg)
|
|
|
|
|
|
2020-03-06 16:42:23 +03:00
|
|
|
|
def begin_training(
|
|
|
|
|
self, get_examples=lambda: [], pipeline=None, sgd=None, **kwargs
|
|
|
|
|
):
|
|
|
|
|
pass
|
|
|
|
|
|
2020-06-26 20:34:12 +03:00
|
|
|
|
def __call__(self, doc):
|
2019-03-23 17:45:02 +03:00
|
|
|
|
"""Apply the sentencizer to a Doc and set Token.is_sent_start.
|
|
|
|
|
|
2019-11-11 19:35:27 +03:00
|
|
|
|
example (Doc or Example): The document to process.
|
|
|
|
|
RETURNS (Doc or Example): The processed Doc or Example.
|
2019-03-23 17:45:02 +03:00
|
|
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/sentencizer#call
|
|
|
|
|
"""
|
|
|
|
|
start = 0
|
|
|
|
|
seen_period = False
|
|
|
|
|
for i, token in enumerate(doc):
|
|
|
|
|
is_in_punct_chars = token.text in self.punct_chars
|
|
|
|
|
token.is_sent_start = i == 0
|
|
|
|
|
if seen_period and not token.is_punct and not is_in_punct_chars:
|
|
|
|
|
doc[start].is_sent_start = True
|
|
|
|
|
start = token.i
|
|
|
|
|
seen_period = False
|
|
|
|
|
elif is_in_punct_chars:
|
|
|
|
|
seen_period = True
|
|
|
|
|
if start < len(doc):
|
|
|
|
|
doc[start].is_sent_start = True
|
|
|
|
|
return doc
|
|
|
|
|
|
2020-07-06 14:06:25 +03:00
|
|
|
|
def pipe(self, stream, batch_size=128):
|
2020-06-26 20:34:12 +03:00
|
|
|
|
for docs in util.minibatch(stream, size=batch_size):
|
2020-01-22 17:40:31 +03:00
|
|
|
|
predictions = self.predict(docs)
|
|
|
|
|
if isinstance(predictions, tuple) and len(tuple) == 2:
|
|
|
|
|
scores, tensors = predictions
|
|
|
|
|
self.set_annotations(docs, scores, tensors=tensors)
|
|
|
|
|
else:
|
|
|
|
|
self.set_annotations(docs, predictions)
|
2020-06-26 20:34:12 +03:00
|
|
|
|
yield from docs
|
2019-11-27 18:33:34 +03:00
|
|
|
|
|
|
|
|
|
def predict(self, docs):
|
|
|
|
|
"""Apply the pipeline's model to a batch of docs, without
|
|
|
|
|
modifying them.
|
|
|
|
|
"""
|
|
|
|
|
if not any(len(doc) for doc in docs):
|
|
|
|
|
# Handle cases where there are no tokens in any docs.
|
|
|
|
|
guesses = [[] for doc in docs]
|
|
|
|
|
return guesses
|
|
|
|
|
guesses = []
|
|
|
|
|
for doc in docs:
|
|
|
|
|
doc_guesses = [False] * len(doc)
|
2020-01-28 13:36:49 +03:00
|
|
|
|
if len(doc) > 0:
|
|
|
|
|
start = 0
|
|
|
|
|
seen_period = False
|
|
|
|
|
doc_guesses[0] = True
|
|
|
|
|
for i, token in enumerate(doc):
|
|
|
|
|
is_in_punct_chars = token.text in self.punct_chars
|
|
|
|
|
if seen_period and not token.is_punct and not is_in_punct_chars:
|
|
|
|
|
doc_guesses[start] = True
|
|
|
|
|
start = token.i
|
|
|
|
|
seen_period = False
|
|
|
|
|
elif is_in_punct_chars:
|
|
|
|
|
seen_period = True
|
|
|
|
|
if start < len(doc):
|
2019-11-27 18:33:34 +03:00
|
|
|
|
doc_guesses[start] = True
|
|
|
|
|
guesses.append(doc_guesses)
|
|
|
|
|
return guesses
|
|
|
|
|
|
|
|
|
|
def set_annotations(self, docs, batch_tag_ids, tensors=None):
|
|
|
|
|
if isinstance(docs, Doc):
|
|
|
|
|
docs = [docs]
|
|
|
|
|
cdef Doc doc
|
|
|
|
|
cdef int idx = 0
|
|
|
|
|
for i, doc in enumerate(docs):
|
|
|
|
|
doc_tag_ids = batch_tag_ids[i]
|
|
|
|
|
for j, tag_id in enumerate(doc_tag_ids):
|
|
|
|
|
# Don't clobber existing sentence boundaries
|
|
|
|
|
if doc.c[j].sent_start == 0:
|
|
|
|
|
if tag_id:
|
|
|
|
|
doc.c[j].sent_start = 1
|
|
|
|
|
else:
|
|
|
|
|
doc.c[j].sent_start = -1
|
|
|
|
|
|
2019-03-23 17:45:02 +03:00
|
|
|
|
def to_bytes(self, **kwargs):
|
|
|
|
|
"""Serialize the sentencizer to a bytestring.
|
|
|
|
|
|
|
|
|
|
RETURNS (bytes): The serialized object.
|
|
|
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/sentencizer#to_bytes
|
|
|
|
|
"""
|
2019-09-14 16:25:48 +03:00
|
|
|
|
return srsly.msgpack_dumps({"punct_chars": list(self.punct_chars)})
|
2019-03-23 17:45:02 +03:00
|
|
|
|
|
|
|
|
|
def from_bytes(self, bytes_data, **kwargs):
|
|
|
|
|
"""Load the sentencizer from a bytestring.
|
|
|
|
|
|
|
|
|
|
bytes_data (bytes): The data to load.
|
|
|
|
|
returns (Sentencizer): The loaded object.
|
|
|
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/sentencizer#from_bytes
|
|
|
|
|
"""
|
|
|
|
|
cfg = srsly.msgpack_loads(bytes_data)
|
2019-09-14 16:25:48 +03:00
|
|
|
|
self.punct_chars = set(cfg.get("punct_chars", self.default_punct_chars))
|
2019-03-23 17:45:02 +03:00
|
|
|
|
return self
|
|
|
|
|
|
|
|
|
|
def to_disk(self, path, exclude=tuple(), **kwargs):
|
|
|
|
|
"""Serialize the sentencizer to disk.
|
|
|
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/sentencizer#to_disk
|
|
|
|
|
"""
|
|
|
|
|
path = util.ensure_path(path)
|
|
|
|
|
path = path.with_suffix(".json")
|
2019-09-14 16:25:48 +03:00
|
|
|
|
srsly.write_json(path, {"punct_chars": list(self.punct_chars)})
|
2019-03-23 17:45:02 +03:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def from_disk(self, path, exclude=tuple(), **kwargs):
|
|
|
|
|
"""Load the sentencizer from disk.
|
|
|
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/sentencizer#from_disk
|
|
|
|
|
"""
|
|
|
|
|
path = util.ensure_path(path)
|
|
|
|
|
path = path.with_suffix(".json")
|
|
|
|
|
cfg = srsly.read_json(path)
|
2019-09-14 16:25:48 +03:00
|
|
|
|
self.punct_chars = set(cfg.get("punct_chars", self.default_punct_chars))
|
2019-03-23 17:45:02 +03:00
|
|
|
|
return self
|
|
|
|
|
|
2019-06-26 15:48:09 +03:00
|
|
|
|
|
2019-10-27 15:35:49 +03:00
|
|
|
|
# Cython classes can't be decorated, so we need to add the factories here
|
2020-05-19 17:20:03 +03:00
|
|
|
|
Language.factories["parser"] = lambda nlp, model, **cfg: parser_factory(nlp, model, **cfg)
|
|
|
|
|
Language.factories["ner"] = lambda nlp, model, **cfg: ner_factory(nlp, model, **cfg)
|
|
|
|
|
|
|
|
|
|
def parser_factory(nlp, model, **cfg):
|
2020-06-12 03:02:07 +03:00
|
|
|
|
default_config = {"learn_tokens": False, "min_action_freq": 30, "beam_width": 1, "beam_update_prob": 1.0}
|
2020-05-19 17:20:03 +03:00
|
|
|
|
if model is None:
|
|
|
|
|
model = default_parser()
|
|
|
|
|
warnings.warn(Warnings.W098.format(name="parser"))
|
2020-06-12 03:02:07 +03:00
|
|
|
|
for key, value in default_config.items():
|
|
|
|
|
if key not in cfg:
|
|
|
|
|
cfg[key] = value
|
2020-05-19 17:20:03 +03:00
|
|
|
|
return DependencyParser.from_nlp(nlp, model, **cfg)
|
|
|
|
|
|
|
|
|
|
def ner_factory(nlp, model, **cfg):
|
2020-06-12 03:02:07 +03:00
|
|
|
|
default_config = {"learn_tokens": False, "min_action_freq": 30, "beam_width": 1, "beam_update_prob": 1.0}
|
2020-05-19 17:20:03 +03:00
|
|
|
|
if model is None:
|
|
|
|
|
model = default_ner()
|
|
|
|
|
warnings.warn(Warnings.W098.format(name="ner"))
|
2020-06-12 03:02:07 +03:00
|
|
|
|
for key, value in default_config.items():
|
|
|
|
|
if key not in cfg:
|
|
|
|
|
cfg[key] = value
|
2020-05-19 17:20:03 +03:00
|
|
|
|
return EntityRecognizer.from_nlp(nlp, model, **cfg)
|
2019-10-27 15:35:49 +03:00
|
|
|
|
|
2020-06-02 00:38:48 +03:00
|
|
|
|
__all__ = ["Tagger", "DependencyParser", "EntityRecognizer", "TextCategorizer", "EntityLinker", "Sentencizer", "SentenceRecognizer"]
|