Update draft of parser neural network model
Model is good, but code is messy. Currently requires Chainer, which may cause the build to fail on machines without a GPU.
Outline of the model:
We first predict context-sensitive vectors for each word in the input:
(embed_lower | embed_prefix | embed_suffix | embed_shape)
>> Maxout(token_width)
>> convolution ** 4
This convolutional layer is shared between the tagger and the parser. This prevents the parser from needing tag features.
To boost the representation, we make a "super tag" with POS, morphology and dependency label. The tagger predicts this
by adding a softmax layer onto the convolutional layer --- so, we're teaching the convolutional layer to give us a
representation that's one affine transform from this informative lexical information. This is obviously good for the
parser (which backprops to the convolutions too).
The parser model makes a state vector by concatenating the vector representations for its context tokens. Current
results suggest few context tokens works well. Maybe this is a bug.
The current context tokens:
* S0, S1, S2: Top three words on the stack
* B0, B1: First two words of the buffer
* S0L1, S0L2: Leftmost and second leftmost children of S0
* S0R1, S0R2: Rightmost and second rightmost children of S0
* S1L1, S1L2, S1R2, S1R, B0L1, B0L2: Likewise for S1 and B0
This makes the state vector quite long: 13*T, where T is the token vector width (128 is working well). Fortunately,
there's a way to structure the computation to save some expense (and make it more GPU friendly).
The parser typically visits 2*N states for a sentence of length N (although it may visit more, if it back-tracks
with a non-monotonic transition). A naive implementation would require 2*N (B, 13*T) @ (13*T, H) matrix multiplications
for a batch of size B. We can instead perform one (B*N, T) @ (T, 13*H) multiplication, to pre-compute the hidden
weights for each positional feature wrt the words in the batch. (Note that our token vectors come from the CNN
-- so we can't play this trick over the vocabulary. That's how Stanford's NN parser works --- and why its model
is so big.)
This pre-computation strategy allows a nice compromise between GPU-friendliness and implementation simplicity.
The CNN and the wide lower layer are computed on the GPU, and then the precomputed hidden weights are moved
to the CPU, before we start the transition-based parsing process. This makes a lot of things much easier.
We don't have to worry about variable-length batch sizes, and we don't have to implement the dynamic oracle
in CUDA to train.
Currently the parser's loss function is multilabel log loss, as the dynamic oracle allows multiple states to
be 0 cost. This is defined as:
(exp(score) / Z) - (exp(score) / gZ)
Where gZ is the sum of the scores assigned to gold classes. I'm very interested in regressing on the cost directly,
but so far this isn't working well.
Machinery is in place for beam-search, which has been working well for the linear model. Beam search should benefit
greatly from the pre-computation trick.
2017-05-13 00:09:15 +03:00
|
|
|
# cython: infer_types=True
|
|
|
|
# cython: profile=True
|
2017-04-15 13:05:47 +03:00
|
|
|
# coding: utf8
|
|
|
|
from __future__ import unicode_literals
|
|
|
|
|
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
|
2019-03-08 13:42:26 +03:00
|
|
|
from collections import OrderedDict
|
2017-10-27 21:29:08 +03:00
|
|
|
from thinc.api import chain
|
2018-12-01 16:41:24 +03:00
|
|
|
from thinc.v2v import Affine, Maxout, Softmax
|
|
|
|
from thinc.misc import LayerNorm
|
2019-06-10 22:25:26 +03:00
|
|
|
from thinc.neural.util import to_categorical
|
2019-06-26 14:53:10 +03:00
|
|
|
from thinc.neural.util import get_array_module
|
2019-06-03 22:32:54 +03:00
|
|
|
|
2019-06-07 21:40:41 +03:00
|
|
|
from .functions import merge_subtokens
|
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
|
|
|
|
2019-02-10 14:14:51 +03:00
|
|
|
from ..syntax import nonproj
|
|
|
|
from ..attrs import POS, ID
|
|
|
|
from ..parts_of_speech import X
|
2019-08-20 16:08:59 +03:00
|
|
|
from ..kb import KnowledgeBase
|
|
|
|
from .._ml import Tok2Vec, build_tagger_model, cosine, get_cossim_loss
|
2019-02-23 13:55:16 +03:00
|
|
|
from .._ml import build_text_classifier, build_simple_cnn_text_classifier
|
2019-06-03 22:32:54 +03:00
|
|
|
from .._ml import build_bow_text_classifier, build_nel_encoder
|
2019-02-10 14:14:51 +03:00
|
|
|
from .._ml import link_vectors_to_models, zero_init, flatten
|
|
|
|
from .._ml import masked_language_model, create_default_optimizer
|
|
|
|
from ..errors import Errors, TempErrors
|
|
|
|
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
|
|
|
|
def Model(cls, *shape, **kwargs):
|
2017-09-25 19:37:13 +03:00
|
|
|
"""Initialize a model for the pipe."""
|
2017-07-20 01:18:15 +03:00
|
|
|
raise NotImplementedError
|
|
|
|
|
|
|
|
def __init__(self, vocab, model=True, **cfg):
|
2017-09-25 19:37:13 +03:00
|
|
|
"""Create a new pipe instance."""
|
2017-07-20 01:18:15 +03:00
|
|
|
raise NotImplementedError
|
|
|
|
|
|
|
|
def __call__(self, 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
|
|
|
"""
|
2018-12-20 17:54:53 +03:00
|
|
|
self.require_model()
|
2019-08-01 18:29:01 +03:00
|
|
|
predictions = self.predict([doc])
|
|
|
|
if isinstance(predictions, tuple) and len(tuple) == 2:
|
|
|
|
scores, tensors = predictions
|
|
|
|
self.set_annotations([doc], scores, tensor=tensors)
|
|
|
|
else:
|
|
|
|
self.set_annotations([doc], predictions)
|
2017-07-20 01:18:15 +03:00
|
|
|
return doc
|
|
|
|
|
2018-12-20 17:54:53 +03:00
|
|
|
def require_model(self):
|
|
|
|
"""Raise an error if the component's model is not initialized."""
|
2019-02-10 14:14:51 +03:00
|
|
|
if getattr(self, "model", None) in (None, True, False):
|
2018-12-20 17:54:53 +03:00
|
|
|
raise ValueError(Errors.E109.format(name=self.name))
|
|
|
|
|
2017-07-20 01:18:15 +03:00
|
|
|
def pipe(self, stream, batch_size=128, n_threads=-1):
|
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
|
|
|
"""
|
2018-12-03 04:19:12 +03:00
|
|
|
for docs in util.minibatch(stream, size=batch_size):
|
2017-07-20 01:18:15 +03:00
|
|
|
docs = list(docs)
|
2019-07-28 18:56:11 +03:00
|
|
|
predictions = self.predict(docs)
|
|
|
|
if isinstance(predictions, tuple) and len(tuple) == 2:
|
|
|
|
scores, tensors = predictions
|
|
|
|
self.set_annotations(docs, scores, tensor=tensors)
|
|
|
|
else:
|
|
|
|
self.set_annotations(docs, predictions)
|
2017-07-20 01:18:15 +03:00
|
|
|
yield from docs
|
|
|
|
|
|
|
|
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
|
|
|
"""
|
2018-12-20 17:54:53 +03:00
|
|
|
self.require_model()
|
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-02-10 14:14:51 +03:00
|
|
|
def update(self, docs, golds, drop=0.0, sgd=None, losses=None):
|
2017-09-25 19:37:13 +03:00
|
|
|
"""Learn from a batch of documents and gold-standard information,
|
2017-09-25 17:20:49 +03:00
|
|
|
updating the pipe's model.
|
|
|
|
|
|
|
|
Delegates to predict() and get_loss().
|
2017-09-25 19:37:13 +03:00
|
|
|
"""
|
2019-07-28 18:54:11 +03:00
|
|
|
pass
|
2017-07-20 01:18:15 +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
|
|
|
def rehearse(self, docs, sgd=None, losses=None, **config):
|
|
|
|
pass
|
|
|
|
|
2017-07-20 01:18:15 +03:00
|
|
|
def get_loss(self, docs, golds, scores):
|
2017-09-25 19:37:13 +03:00
|
|
|
"""Find the loss and gradient of loss for the batch of
|
|
|
|
documents 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.
|
|
|
|
|
|
|
|
It's possible to extend pre-trained models with new labels,
|
|
|
|
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):
|
2019-02-10 14:14:51 +03:00
|
|
|
return create_default_optimizer(self.model.ops, **self.cfg.get("optimizer", {}))
|
2017-11-01 18:32:44 +03:00
|
|
|
|
2019-02-10 14:14:51 +03:00
|
|
|
def begin_training(
|
|
|
|
self, get_gold_tuples=lambda: [], pipeline=None, sgd=None, **kwargs
|
|
|
|
):
|
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."""
|
2017-07-20 01:18:15 +03:00
|
|
|
if self.model is True:
|
2017-09-25 17:20:49 +03:00
|
|
|
self.model = self.Model(**self.cfg)
|
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
|
|
|
|
|
|
|
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
|
|
|
|
|
2019-03-10 21:16:45 +03:00
|
|
|
def to_bytes(self, exclude=tuple(), **kwargs):
|
|
|
|
"""Serialize the pipe to a bytestring.
|
|
|
|
|
|
|
|
exclude (list): String names of serialization fields to exclude.
|
|
|
|
RETURNS (bytes): The serialized object.
|
|
|
|
"""
|
2017-10-10 04:58:12 +03:00
|
|
|
serialize = OrderedDict()
|
2019-02-10 14:14:51 +03:00
|
|
|
serialize["cfg"] = lambda: srsly.json_dumps(self.cfg)
|
2019-02-21 11:42:02 +03:00
|
|
|
if self.model not in (True, False, None):
|
2019-02-10 14:14:51 +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
|
2019-03-10 21:16:45 +03:00
|
|
|
exclude = util.get_serialization_exclude(serialize, exclude, kwargs)
|
2017-07-20 01:18:15 +03:00
|
|
|
return util.to_bytes(serialize, exclude)
|
|
|
|
|
2019-03-10 21:16:45 +03:00
|
|
|
def from_bytes(self, bytes_data, exclude=tuple(), **kwargs):
|
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):
|
2018-03-28 17:02:59 +03:00
|
|
|
# TODO: Remove this once we don't have to handle previous models
|
2019-02-10 14:14:51 +03:00
|
|
|
if self.cfg.get("pretrained_dims") and "pretrained_vectors" not in self.cfg:
|
|
|
|
self.cfg["pretrained_vectors"] = self.vocab.vectors.name
|
2017-09-02 16:17:20 +03:00
|
|
|
if self.model is True:
|
|
|
|
self.model = self.Model(**self.cfg)
|
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-03-10 21:16:45 +03:00
|
|
|
deserialize = OrderedDict()
|
|
|
|
deserialize["cfg"] = lambda b: self.cfg.update(srsly.json_loads(b))
|
2019-07-28 18:56:11 +03:00
|
|
|
if hasattr(self, "vocab"):
|
|
|
|
deserialize["vocab"] = lambda b: self.vocab.from_bytes(b)
|
2019-03-10 21:16:45 +03:00
|
|
|
deserialize["model"] = load_model
|
|
|
|
exclude = util.get_serialization_exclude(deserialize, exclude, kwargs)
|
2017-07-20 01:18:15 +03:00
|
|
|
util.from_bytes(bytes_data, deserialize, exclude)
|
|
|
|
return self
|
|
|
|
|
2019-03-10 21:16:45 +03:00
|
|
|
def to_disk(self, path, exclude=tuple(), **kwargs):
|
2017-09-25 19:37:13 +03:00
|
|
|
"""Serialize the pipe to disk."""
|
2017-10-10 04:58:12 +03:00
|
|
|
serialize = OrderedDict()
|
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)
|
2017-10-10 04:58:12 +03:00
|
|
|
if self.model not in (None, True, False):
|
2019-02-10 14:14:51 +03:00
|
|
|
serialize["model"] = lambda p: p.open("wb").write(self.model.to_bytes())
|
2019-03-10 21:16:45 +03:00
|
|
|
exclude = util.get_serialization_exclude(serialize, exclude, kwargs)
|
2017-07-20 01:18:15 +03:00
|
|
|
util.to_disk(path, serialize, exclude)
|
|
|
|
|
2019-03-10 21:16:45 +03:00
|
|
|
def from_disk(self, path, exclude=tuple(), **kwargs):
|
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):
|
2018-03-28 17:02:59 +03:00
|
|
|
# TODO: Remove this once we don't have to handle previous models
|
2019-02-10 14:14:51 +03:00
|
|
|
if self.cfg.get("pretrained_dims") and "pretrained_vectors" not in self.cfg:
|
|
|
|
self.cfg["pretrained_vectors"] = self.vocab.vectors.name
|
2017-09-02 16:17:20 +03:00
|
|
|
if self.model is True:
|
|
|
|
self.model = self.Model(**self.cfg)
|
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-03-10 21:16:45 +03:00
|
|
|
deserialize = OrderedDict()
|
|
|
|
deserialize["cfg"] = lambda p: self.cfg.update(_load_cfg(p))
|
|
|
|
deserialize["vocab"] = lambda p: self.vocab.from_disk(p)
|
|
|
|
deserialize["model"] = load_model
|
|
|
|
exclude = util.get_serialization_exclude(deserialize, exclude, kwargs)
|
2017-07-20 01:18:15 +03:00
|
|
|
util.from_disk(path, deserialize, exclude)
|
|
|
|
return self
|
|
|
|
|
|
|
|
|
2017-10-26 13:40:40 +03:00
|
|
|
class Tensorizer(Pipe):
|
2018-11-03 15:46:58 +03:00
|
|
|
"""Pre-train position-sensitive vectors for tokens."""
|
2019-02-10 14:14:51 +03:00
|
|
|
|
|
|
|
name = "tensorizer"
|
Update draft of parser neural network model
Model is good, but code is messy. Currently requires Chainer, which may cause the build to fail on machines without a GPU.
Outline of the model:
We first predict context-sensitive vectors for each word in the input:
(embed_lower | embed_prefix | embed_suffix | embed_shape)
>> Maxout(token_width)
>> convolution ** 4
This convolutional layer is shared between the tagger and the parser. This prevents the parser from needing tag features.
To boost the representation, we make a "super tag" with POS, morphology and dependency label. The tagger predicts this
by adding a softmax layer onto the convolutional layer --- so, we're teaching the convolutional layer to give us a
representation that's one affine transform from this informative lexical information. This is obviously good for the
parser (which backprops to the convolutions too).
The parser model makes a state vector by concatenating the vector representations for its context tokens. Current
results suggest few context tokens works well. Maybe this is a bug.
The current context tokens:
* S0, S1, S2: Top three words on the stack
* B0, B1: First two words of the buffer
* S0L1, S0L2: Leftmost and second leftmost children of S0
* S0R1, S0R2: Rightmost and second rightmost children of S0
* S1L1, S1L2, S1R2, S1R, B0L1, B0L2: Likewise for S1 and B0
This makes the state vector quite long: 13*T, where T is the token vector width (128 is working well). Fortunately,
there's a way to structure the computation to save some expense (and make it more GPU friendly).
The parser typically visits 2*N states for a sentence of length N (although it may visit more, if it back-tracks
with a non-monotonic transition). A naive implementation would require 2*N (B, 13*T) @ (13*T, H) matrix multiplications
for a batch of size B. We can instead perform one (B*N, T) @ (T, 13*H) multiplication, to pre-compute the hidden
weights for each positional feature wrt the words in the batch. (Note that our token vectors come from the CNN
-- so we can't play this trick over the vocabulary. That's how Stanford's NN parser works --- and why its model
is so big.)
This pre-computation strategy allows a nice compromise between GPU-friendliness and implementation simplicity.
The CNN and the wide lower layer are computed on the GPU, and then the precomputed hidden weights are moved
to the CPU, before we start the transition-based parsing process. This makes a lot of things much easier.
We don't have to worry about variable-length batch sizes, and we don't have to implement the dynamic oracle
in CUDA to train.
Currently the parser's loss function is multilabel log loss, as the dynamic oracle allows multiple states to
be 0 cost. This is defined as:
(exp(score) / Z) - (exp(score) / gZ)
Where gZ is the sum of the scores assigned to gold classes. I'm very interested in regressing on the cost directly,
but so far this isn't working well.
Machinery is in place for beam-search, which has been working well for the linear model. Beam search should benefit
greatly from the pre-computation trick.
2017-05-13 00:09:15 +03:00
|
|
|
|
2017-05-15 22:46:08 +03:00
|
|
|
@classmethod
|
2018-11-03 13:52:50 +03:00
|
|
|
def Model(cls, output_size=300, **cfg):
|
2017-05-19 01:00:02 +03:00
|
|
|
"""Create a new statistical model for the class.
|
|
|
|
|
|
|
|
width (int): Output size of the model.
|
|
|
|
embed_size (int): Number of vectors in the embedding table.
|
|
|
|
**cfg: Config parameters.
|
|
|
|
RETURNS (Model): A `thinc.neural.Model` or similar instance.
|
|
|
|
"""
|
2019-02-10 14:14:51 +03:00
|
|
|
input_size = util.env_opt("token_vector_width", cfg.get("input_size", 96))
|
2018-11-03 15:46:58 +03:00
|
|
|
return zero_init(Affine(output_size, input_size, drop_factor=0.0))
|
Update draft of parser neural network model
Model is good, but code is messy. Currently requires Chainer, which may cause the build to fail on machines without a GPU.
Outline of the model:
We first predict context-sensitive vectors for each word in the input:
(embed_lower | embed_prefix | embed_suffix | embed_shape)
>> Maxout(token_width)
>> convolution ** 4
This convolutional layer is shared between the tagger and the parser. This prevents the parser from needing tag features.
To boost the representation, we make a "super tag" with POS, morphology and dependency label. The tagger predicts this
by adding a softmax layer onto the convolutional layer --- so, we're teaching the convolutional layer to give us a
representation that's one affine transform from this informative lexical information. This is obviously good for the
parser (which backprops to the convolutions too).
The parser model makes a state vector by concatenating the vector representations for its context tokens. Current
results suggest few context tokens works well. Maybe this is a bug.
The current context tokens:
* S0, S1, S2: Top three words on the stack
* B0, B1: First two words of the buffer
* S0L1, S0L2: Leftmost and second leftmost children of S0
* S0R1, S0R2: Rightmost and second rightmost children of S0
* S1L1, S1L2, S1R2, S1R, B0L1, B0L2: Likewise for S1 and B0
This makes the state vector quite long: 13*T, where T is the token vector width (128 is working well). Fortunately,
there's a way to structure the computation to save some expense (and make it more GPU friendly).
The parser typically visits 2*N states for a sentence of length N (although it may visit more, if it back-tracks
with a non-monotonic transition). A naive implementation would require 2*N (B, 13*T) @ (13*T, H) matrix multiplications
for a batch of size B. We can instead perform one (B*N, T) @ (T, 13*H) multiplication, to pre-compute the hidden
weights for each positional feature wrt the words in the batch. (Note that our token vectors come from the CNN
-- so we can't play this trick over the vocabulary. That's how Stanford's NN parser works --- and why its model
is so big.)
This pre-computation strategy allows a nice compromise between GPU-friendliness and implementation simplicity.
The CNN and the wide lower layer are computed on the GPU, and then the precomputed hidden weights are moved
to the CPU, before we start the transition-based parsing process. This makes a lot of things much easier.
We don't have to worry about variable-length batch sizes, and we don't have to implement the dynamic oracle
in CUDA to train.
Currently the parser's loss function is multilabel log loss, as the dynamic oracle allows multiple states to
be 0 cost. This is defined as:
(exp(score) / Z) - (exp(score) / gZ)
Where gZ is the sum of the scores assigned to gold classes. I'm very interested in regressing on the cost directly,
but so far this isn't working well.
Machinery is in place for beam-search, which has been working well for the linear model. Beam search should benefit
greatly from the pre-computation trick.
2017-05-13 00:09:15 +03:00
|
|
|
|
2017-05-15 22:46:08 +03:00
|
|
|
def __init__(self, vocab, model=True, **cfg):
|
2017-05-19 01:00:02 +03:00
|
|
|
"""Construct a new statistical model. Weights are not allocated on
|
|
|
|
initialisation.
|
|
|
|
|
2017-10-27 21:29:08 +03:00
|
|
|
vocab (Vocab): A `Vocab` instance. The model must share the same
|
|
|
|
`Vocab` instance with the `Doc` objects it will process.
|
2019-06-28 09:29:31 +03:00
|
|
|
model (Model): A `Model` instance or `True` to allocate one later.
|
2017-05-19 01:00:02 +03:00
|
|
|
**cfg: Config parameters.
|
|
|
|
|
|
|
|
EXAMPLE:
|
|
|
|
>>> from spacy.pipeline import TokenVectorEncoder
|
|
|
|
>>> tok2vec = TokenVectorEncoder(nlp.vocab)
|
|
|
|
>>> tok2vec.model = tok2vec.Model(128, 5000)
|
|
|
|
"""
|
2017-05-15 22:46:08 +03:00
|
|
|
self.vocab = vocab
|
2017-05-18 12:29:51 +03:00
|
|
|
self.model = model
|
2017-11-03 22:20:26 +03:00
|
|
|
self.input_models = []
|
2017-07-23 01:52:47 +03:00
|
|
|
self.cfg = dict(cfg)
|
2019-02-10 14:14:51 +03:00
|
|
|
self.cfg.setdefault("cnn_maxout_pieces", 3)
|
2017-05-17 14:13:14 +03:00
|
|
|
|
2017-05-28 16:11:58 +03:00
|
|
|
def __call__(self, doc):
|
2017-05-19 01:00:02 +03:00
|
|
|
"""Add context-sensitive vectors to a `Doc`, e.g. from a CNN or LSTM
|
|
|
|
model. Vectors are set to the `Doc.tensor` attribute.
|
|
|
|
|
|
|
|
docs (Doc or iterable): One or more documents to add vectors to.
|
|
|
|
RETURNS (dict or None): Intermediate computations.
|
|
|
|
"""
|
2017-05-28 16:11:58 +03:00
|
|
|
tokvecses = self.predict([doc])
|
|
|
|
self.set_annotations([doc], tokvecses)
|
|
|
|
return doc
|
2017-05-16 17:17:30 +03:00
|
|
|
|
2017-05-18 16:30:59 +03:00
|
|
|
def pipe(self, stream, batch_size=128, n_threads=-1):
|
2017-05-19 01:00:02 +03:00
|
|
|
"""Process `Doc` objects as a stream.
|
|
|
|
|
|
|
|
stream (iterator): A sequence of `Doc` objects to process.
|
|
|
|
batch_size (int): Number of `Doc` objects to group.
|
2017-05-21 21:46:23 +03:00
|
|
|
YIELDS (iterator): A sequence of `Doc` objects, in order of input.
|
2017-05-19 01:00:02 +03:00
|
|
|
"""
|
2018-12-03 04:19:12 +03:00
|
|
|
for docs in util.minibatch(stream, size=batch_size):
|
2017-05-22 01:52:01 +03:00
|
|
|
docs = list(docs)
|
2017-11-03 22:20:26 +03:00
|
|
|
tensors = self.predict(docs)
|
|
|
|
self.set_annotations(docs, tensors)
|
2017-05-19 21:26:36 +03:00
|
|
|
yield from docs
|
2017-05-18 12:29:51 +03:00
|
|
|
|
2017-05-16 17:17:30 +03:00
|
|
|
def predict(self, docs):
|
2017-05-19 01:00:02 +03:00
|
|
|
"""Return a single tensor for a batch of documents.
|
|
|
|
|
|
|
|
docs (iterable): A sequence of `Doc` objects.
|
2017-10-27 21:29:08 +03:00
|
|
|
RETURNS (object): Vector representations for each token in the docs.
|
2017-05-19 01:00:02 +03:00
|
|
|
"""
|
2018-12-20 17:54:53 +03:00
|
|
|
self.require_model()
|
2017-11-03 22:20:26 +03:00
|
|
|
inputs = self.model.ops.flatten([doc.tensor for doc in docs])
|
|
|
|
outputs = self.model(inputs)
|
|
|
|
return self.model.ops.unflatten(outputs, [len(d) for d in docs])
|
2017-05-16 17:17:30 +03:00
|
|
|
|
2017-11-03 22:20:26 +03:00
|
|
|
def set_annotations(self, docs, tensors):
|
2017-05-19 01:00:02 +03:00
|
|
|
"""Set the tensor attribute for a batch of documents.
|
|
|
|
|
|
|
|
docs (iterable): A sequence of `Doc` objects.
|
2017-11-03 22:20:26 +03:00
|
|
|
tensors (object): Vector representation for each token in the docs.
|
2017-05-19 01:00:02 +03:00
|
|
|
"""
|
2017-11-03 22:20:26 +03:00
|
|
|
for doc, tensor in zip(docs, tensors):
|
2018-04-03 16:50:31 +03:00
|
|
|
if tensor.shape[0] != len(doc):
|
2019-03-08 13:42:26 +03:00
|
|
|
raise ValueError(Errors.E076.format(rows=tensor.shape[0], words=len(doc)))
|
2017-11-03 22:20:26 +03:00
|
|
|
doc.tensor = tensor
|
2017-05-17 13:04:50 +03:00
|
|
|
|
2019-02-10 14:14:51 +03:00
|
|
|
def update(self, docs, golds, state=None, drop=0.0, sgd=None, losses=None):
|
2017-05-19 01:00:02 +03:00
|
|
|
"""Update the model.
|
|
|
|
|
|
|
|
docs (iterable): A batch of `Doc` objects.
|
|
|
|
golds (iterable): A batch of `GoldParse` objects.
|
2019-05-17 18:44:11 +03:00
|
|
|
drop (float): The dropout rate.
|
2017-05-21 14:17:40 +03:00
|
|
|
sgd (callable): An optimizer.
|
2017-05-19 01:00:02 +03:00
|
|
|
RETURNS (dict): Results from the update.
|
|
|
|
"""
|
2018-12-20 17:54:53 +03:00
|
|
|
self.require_model()
|
2017-05-16 17:17:30 +03:00
|
|
|
if isinstance(docs, Doc):
|
|
|
|
docs = [docs]
|
2017-11-03 22:20:26 +03:00
|
|
|
inputs = []
|
|
|
|
bp_inputs = []
|
|
|
|
for tok2vec in self.input_models:
|
|
|
|
tensor, bp_tensor = tok2vec.begin_update(docs, drop=drop)
|
|
|
|
inputs.append(tensor)
|
|
|
|
bp_inputs.append(bp_tensor)
|
|
|
|
inputs = self.model.ops.xp.hstack(inputs)
|
|
|
|
scores, bp_scores = self.model.begin_update(inputs, drop=drop)
|
|
|
|
loss, d_scores = self.get_loss(docs, golds, scores)
|
|
|
|
d_inputs = bp_scores(d_scores, sgd=sgd)
|
|
|
|
d_inputs = self.model.ops.xp.split(d_inputs, len(self.input_models), axis=1)
|
2017-11-05 14:25:10 +03:00
|
|
|
for d_input, bp_input in zip(d_inputs, bp_inputs):
|
2017-11-03 22:20:26 +03:00
|
|
|
bp_input(d_input, sgd=sgd)
|
|
|
|
if losses is not None:
|
2019-02-10 14:14:51 +03:00
|
|
|
losses.setdefault(self.name, 0.0)
|
2017-11-03 22:20:26 +03:00
|
|
|
losses[self.name] += loss
|
|
|
|
return loss
|
|
|
|
|
|
|
|
def get_loss(self, docs, golds, prediction):
|
2018-11-03 13:52:50 +03:00
|
|
|
ids = self.model.ops.flatten([doc.to_array(ID).ravel() for doc in docs])
|
|
|
|
target = self.vocab.vectors.data[ids]
|
2018-11-03 13:53:22 +03:00
|
|
|
d_scores = (prediction - target) / prediction.shape[0]
|
2019-02-10 14:14:51 +03:00
|
|
|
loss = (d_scores ** 2).sum()
|
2017-11-03 22:20:26 +03:00
|
|
|
return loss, d_scores
|
2017-05-06 15:22:20 +03:00
|
|
|
|
2019-02-10 14:14:51 +03:00
|
|
|
def begin_training(self, gold_tuples=lambda: [], pipeline=None, sgd=None, **kwargs):
|
2017-11-06 16:26:26 +03:00
|
|
|
"""Allocate models, pre-process training data and acquire an
|
2017-05-19 01:00:02 +03:00
|
|
|
optimizer.
|
|
|
|
|
|
|
|
gold_tuples (iterable): Gold-standard training data.
|
|
|
|
pipeline (list): The pipeline the model is part of.
|
|
|
|
"""
|
2018-11-03 01:51:37 +03:00
|
|
|
if pipeline is not None:
|
|
|
|
for name, model in pipeline:
|
2019-02-10 14:14:51 +03:00
|
|
|
if getattr(model, "tok2vec", None):
|
2018-11-03 01:51:37 +03:00
|
|
|
self.input_models.append(model.tok2vec)
|
2017-05-18 12:29:51 +03:00
|
|
|
if self.model is True:
|
2017-09-21 03:15:49 +03:00
|
|
|
self.model = self.Model(**self.cfg)
|
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-18 12:29:51 +03:00
|
|
|
|
2017-05-29 02:37:57 +03:00
|
|
|
|
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
|
|
|
|
"""
|
|
|
|
|
|
|
|
name = "tagger"
|
2017-10-27 21:29:08 +03:00
|
|
|
|
2017-07-23 01:52:47 +03:00
|
|
|
def __init__(self, vocab, model=True, **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
|
2017-11-08 14:10:49 +03:00
|
|
|
self.cfg = OrderedDict(sorted(cfg.items()))
|
2019-03-08 13:42:26 +03:00
|
|
|
self.cfg.setdefault("cnn_maxout_pieces", 2)
|
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
|
|
|
|
2017-11-03 22:20:26 +03:00
|
|
|
@property
|
|
|
|
def tok2vec(self):
|
|
|
|
if self.model in (None, True, False):
|
|
|
|
return None
|
|
|
|
else:
|
|
|
|
return chain(self.model.tok2vec, flatten)
|
|
|
|
|
2017-05-19 21:26:36 +03:00
|
|
|
def __call__(self, doc):
|
2017-11-03 13:20:05 +03:00
|
|
|
tags, tokvecs = self.predict([doc])
|
|
|
|
self.set_annotations([doc], tags, tensors=tokvecs)
|
2017-05-28 16:11:58 +03:00
|
|
|
return doc
|
2017-05-16 17:17:30 +03:00
|
|
|
|
|
|
|
def pipe(self, stream, batch_size=128, n_threads=-1):
|
2018-12-03 04:19:12 +03:00
|
|
|
for docs in util.minibatch(stream, size=batch_size):
|
2017-08-18 23:02:35 +03:00
|
|
|
docs = list(docs)
|
2017-11-03 13:20:05 +03:00
|
|
|
tag_ids, tokvecs = self.predict(docs)
|
|
|
|
self.set_annotations(docs, tag_ids, tensors=tokvecs)
|
2017-05-19 21:26:36 +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-12-20 17:54:53 +03:00
|
|
|
self.require_model()
|
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)
|
2018-06-29 17:05:40 +03:00
|
|
|
guesses = [self.model.ops.allocate((0, n_labels)) for doc in docs]
|
|
|
|
tokvecs = self.model.ops.allocate((0, self.model.tok2vec.nO))
|
|
|
|
return guesses, tokvecs
|
2017-11-03 13:20:05 +03:00
|
|
|
tokvecs = self.model.tok2vec(docs)
|
|
|
|
scores = self.model.softmax(tokvecs)
|
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)
|
2017-11-03 13:20:05 +03:00
|
|
|
return guesses, tokvecs
|
2017-05-16 17:17:30 +03:00
|
|
|
|
2017-11-03 13:20:05 +03:00
|
|
|
def set_annotations(self, docs, batch_tag_ids, tensors=None):
|
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
|
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
|
|
|
|
if doc.c[j].tag == 0 and doc.c[j].pos == 0:
|
2017-11-06 14:36:05 +03:00
|
|
|
# Don't clobber preset lemmas
|
|
|
|
lemma = doc.c[j].lemma
|
2017-11-01 23:10:45 +03:00
|
|
|
vocab.morphology.assign_tag_id(&doc.c[j], tag_id)
|
2017-11-06 18:56:19 +03:00
|
|
|
if lemma != 0 and lemma != doc.c[j].lex.orth:
|
2017-11-06 14:36:05 +03:00
|
|
|
doc.c[j].lemma = lemma
|
2017-05-08 15:53:45 +03:00
|
|
|
idx += 1
|
2018-06-29 20:21:38 +03:00
|
|
|
if tensors is not None and len(tensors):
|
2017-11-05 17:34:40 +03:00
|
|
|
if isinstance(doc.tensor, numpy.ndarray) \
|
|
|
|
and not isinstance(tensors[i], numpy.ndarray):
|
|
|
|
doc.extend_tensor(tensors[i].get())
|
|
|
|
else:
|
|
|
|
doc.extend_tensor(tensors[i])
|
2018-04-10 17:14:52 +03:00
|
|
|
doc.is_tagged = True
|
2017-05-08 15:53:45 +03:00
|
|
|
|
2017-09-21 15:59:48 +03:00
|
|
|
def update(self, docs, golds, drop=0., sgd=None, losses=None):
|
2018-12-20 17:54:53 +03:00
|
|
|
self.require_model()
|
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
|
|
|
|
2017-09-21 15:59:48 +03:00
|
|
|
tag_scores, bp_tag_scores = self.model.begin_update(docs, drop=drop)
|
2017-05-16 17:17:30 +03:00
|
|
|
loss, d_tag_scores = self.get_loss(docs, golds, tag_scores)
|
2017-09-23 03:58:06 +03:00
|
|
|
bp_tag_scores(d_tag_scores, sgd=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
|
2017-05-16 17:17:30 +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
|
|
|
def rehearse(self, docs, drop=0., sgd=None, losses=None):
|
|
|
|
"""Perform a 'rehearsal' update, where we try to match the output of
|
|
|
|
an initial model.
|
|
|
|
"""
|
|
|
|
if self._rehearsal_model is None:
|
|
|
|
return
|
|
|
|
guesses, backprop = self.model.begin_update(docs, drop=drop)
|
|
|
|
target = self._rehearsal_model(docs)
|
|
|
|
gradient = guesses - target
|
|
|
|
backprop(gradient, sgd=sgd)
|
|
|
|
if losses is not None:
|
|
|
|
losses.setdefault(self.name, 0.0)
|
|
|
|
losses[self.name] += (gradient**2).sum()
|
|
|
|
|
2017-05-16 17:17:30 +03:00
|
|
|
def get_loss(self, docs, golds, scores):
|
2017-05-20 21:23:05 +03:00
|
|
|
scores = self.model.ops.flatten(scores)
|
2017-11-01 21:27:49 +03:00
|
|
|
tag_index = {tag: i for i, tag in enumerate(self.labels)}
|
2017-05-18 12:29:51 +03:00
|
|
|
cdef int idx = 0
|
2019-03-08 13:42:26 +03:00
|
|
|
correct = numpy.zeros((scores.shape[0],), dtype="i")
|
2017-05-19 21:26:36 +03:00
|
|
|
guesses = scores.argmax(axis=1)
|
2019-03-08 13:42:26 +03:00
|
|
|
known_labels = numpy.ones((scores.shape[0], 1), dtype="f")
|
Update draft of parser neural network model
Model is good, but code is messy. Currently requires Chainer, which may cause the build to fail on machines without a GPU.
Outline of the model:
We first predict context-sensitive vectors for each word in the input:
(embed_lower | embed_prefix | embed_suffix | embed_shape)
>> Maxout(token_width)
>> convolution ** 4
This convolutional layer is shared between the tagger and the parser. This prevents the parser from needing tag features.
To boost the representation, we make a "super tag" with POS, morphology and dependency label. The tagger predicts this
by adding a softmax layer onto the convolutional layer --- so, we're teaching the convolutional layer to give us a
representation that's one affine transform from this informative lexical information. This is obviously good for the
parser (which backprops to the convolutions too).
The parser model makes a state vector by concatenating the vector representations for its context tokens. Current
results suggest few context tokens works well. Maybe this is a bug.
The current context tokens:
* S0, S1, S2: Top three words on the stack
* B0, B1: First two words of the buffer
* S0L1, S0L2: Leftmost and second leftmost children of S0
* S0R1, S0R2: Rightmost and second rightmost children of S0
* S1L1, S1L2, S1R2, S1R, B0L1, B0L2: Likewise for S1 and B0
This makes the state vector quite long: 13*T, where T is the token vector width (128 is working well). Fortunately,
there's a way to structure the computation to save some expense (and make it more GPU friendly).
The parser typically visits 2*N states for a sentence of length N (although it may visit more, if it back-tracks
with a non-monotonic transition). A naive implementation would require 2*N (B, 13*T) @ (13*T, H) matrix multiplications
for a batch of size B. We can instead perform one (B*N, T) @ (T, 13*H) multiplication, to pre-compute the hidden
weights for each positional feature wrt the words in the batch. (Note that our token vectors come from the CNN
-- so we can't play this trick over the vocabulary. That's how Stanford's NN parser works --- and why its model
is so big.)
This pre-computation strategy allows a nice compromise between GPU-friendliness and implementation simplicity.
The CNN and the wide lower layer are computed on the GPU, and then the precomputed hidden weights are moved
to the CPU, before we start the transition-based parsing process. This makes a lot of things much easier.
We don't have to worry about variable-length batch sizes, and we don't have to implement the dynamic oracle
in CUDA to train.
Currently the parser's loss function is multilabel log loss, as the dynamic oracle allows multiple states to
be 0 cost. This is defined as:
(exp(score) / Z) - (exp(score) / gZ)
Where gZ is the sum of the scores assigned to gold classes. I'm very interested in regressing on the cost directly,
but so far this isn't working well.
Machinery is in place for beam-search, which has been working well for the linear model. Beam search should benefit
greatly from the pre-computation trick.
2017-05-13 00:09:15 +03:00
|
|
|
for gold in golds:
|
|
|
|
for tag in gold.tags:
|
2017-05-19 21:26:36 +03:00
|
|
|
if tag is None:
|
|
|
|
correct[idx] = guesses[idx]
|
2018-06-25 23:00:51 +03:00
|
|
|
elif tag in tag_index:
|
2017-05-19 21:26:36 +03:00
|
|
|
correct[idx] = tag_index[tag]
|
2018-06-25 23:00:51 +03:00
|
|
|
else:
|
2018-06-25 23:24:54 +03:00
|
|
|
correct[idx] = 0
|
|
|
|
known_labels[idx] = 0.
|
Update draft of parser neural network model
Model is good, but code is messy. Currently requires Chainer, which may cause the build to fail on machines without a GPU.
Outline of the model:
We first predict context-sensitive vectors for each word in the input:
(embed_lower | embed_prefix | embed_suffix | embed_shape)
>> Maxout(token_width)
>> convolution ** 4
This convolutional layer is shared between the tagger and the parser. This prevents the parser from needing tag features.
To boost the representation, we make a "super tag" with POS, morphology and dependency label. The tagger predicts this
by adding a softmax layer onto the convolutional layer --- so, we're teaching the convolutional layer to give us a
representation that's one affine transform from this informative lexical information. This is obviously good for the
parser (which backprops to the convolutions too).
The parser model makes a state vector by concatenating the vector representations for its context tokens. Current
results suggest few context tokens works well. Maybe this is a bug.
The current context tokens:
* S0, S1, S2: Top three words on the stack
* B0, B1: First two words of the buffer
* S0L1, S0L2: Leftmost and second leftmost children of S0
* S0R1, S0R2: Rightmost and second rightmost children of S0
* S1L1, S1L2, S1R2, S1R, B0L1, B0L2: Likewise for S1 and B0
This makes the state vector quite long: 13*T, where T is the token vector width (128 is working well). Fortunately,
there's a way to structure the computation to save some expense (and make it more GPU friendly).
The parser typically visits 2*N states for a sentence of length N (although it may visit more, if it back-tracks
with a non-monotonic transition). A naive implementation would require 2*N (B, 13*T) @ (13*T, H) matrix multiplications
for a batch of size B. We can instead perform one (B*N, T) @ (T, 13*H) multiplication, to pre-compute the hidden
weights for each positional feature wrt the words in the batch. (Note that our token vectors come from the CNN
-- so we can't play this trick over the vocabulary. That's how Stanford's NN parser works --- and why its model
is so big.)
This pre-computation strategy allows a nice compromise between GPU-friendliness and implementation simplicity.
The CNN and the wide lower layer are computed on the GPU, and then the precomputed hidden weights are moved
to the CPU, before we start the transition-based parsing process. This makes a lot of things much easier.
We don't have to worry about variable-length batch sizes, and we don't have to implement the dynamic oracle
in CUDA to train.
Currently the parser's loss function is multilabel log loss, as the dynamic oracle allows multiple states to
be 0 cost. This is defined as:
(exp(score) / Z) - (exp(score) / gZ)
Where gZ is the sum of the scores assigned to gold classes. I'm very interested in regressing on the cost directly,
but so far this isn't working well.
Machinery is in place for beam-search, which has been working well for the linear model. Beam search should benefit
greatly from the pre-computation trick.
2017-05-13 00:09:15 +03:00
|
|
|
idx += 1
|
2019-03-08 13:42:26 +03:00
|
|
|
correct = self.model.ops.xp.array(correct, dtype="i")
|
Update draft of parser neural network model
Model is good, but code is messy. Currently requires Chainer, which may cause the build to fail on machines without a GPU.
Outline of the model:
We first predict context-sensitive vectors for each word in the input:
(embed_lower | embed_prefix | embed_suffix | embed_shape)
>> Maxout(token_width)
>> convolution ** 4
This convolutional layer is shared between the tagger and the parser. This prevents the parser from needing tag features.
To boost the representation, we make a "super tag" with POS, morphology and dependency label. The tagger predicts this
by adding a softmax layer onto the convolutional layer --- so, we're teaching the convolutional layer to give us a
representation that's one affine transform from this informative lexical information. This is obviously good for the
parser (which backprops to the convolutions too).
The parser model makes a state vector by concatenating the vector representations for its context tokens. Current
results suggest few context tokens works well. Maybe this is a bug.
The current context tokens:
* S0, S1, S2: Top three words on the stack
* B0, B1: First two words of the buffer
* S0L1, S0L2: Leftmost and second leftmost children of S0
* S0R1, S0R2: Rightmost and second rightmost children of S0
* S1L1, S1L2, S1R2, S1R, B0L1, B0L2: Likewise for S1 and B0
This makes the state vector quite long: 13*T, where T is the token vector width (128 is working well). Fortunately,
there's a way to structure the computation to save some expense (and make it more GPU friendly).
The parser typically visits 2*N states for a sentence of length N (although it may visit more, if it back-tracks
with a non-monotonic transition). A naive implementation would require 2*N (B, 13*T) @ (13*T, H) matrix multiplications
for a batch of size B. We can instead perform one (B*N, T) @ (T, 13*H) multiplication, to pre-compute the hidden
weights for each positional feature wrt the words in the batch. (Note that our token vectors come from the CNN
-- so we can't play this trick over the vocabulary. That's how Stanford's NN parser works --- and why its model
is so big.)
This pre-computation strategy allows a nice compromise between GPU-friendliness and implementation simplicity.
The CNN and the wide lower layer are computed on the GPU, and then the precomputed hidden weights are moved
to the CPU, before we start the transition-based parsing process. This makes a lot of things much easier.
We don't have to worry about variable-length batch sizes, and we don't have to implement the dynamic oracle
in CUDA to train.
Currently the parser's loss function is multilabel log loss, as the dynamic oracle allows multiple states to
be 0 cost. This is defined as:
(exp(score) / Z) - (exp(score) / gZ)
Where gZ is the sum of the scores assigned to gold classes. I'm very interested in regressing on the cost directly,
but so far this isn't working well.
Machinery is in place for beam-search, which has been working well for the linear model. Beam search should benefit
greatly from the pre-computation trick.
2017-05-13 00:09:15 +03:00
|
|
|
d_scores = scores - to_categorical(correct, nb_classes=scores.shape[1])
|
2018-09-13 15:14:38 +03:00
|
|
|
d_scores *= self.model.ops.asarray(known_labels)
|
2017-05-18 12:29:51 +03:00
|
|
|
loss = (d_scores**2).sum()
|
2017-05-20 21:23:05 +03:00
|
|
|
d_scores = self.model.ops.unflatten(d_scores, [len(d) for d in docs])
|
2017-05-18 16:30:59 +03:00
|
|
|
return float(loss), d_scores
|
2016-10-16 02:47:12 +03:00
|
|
|
|
2018-03-27 12:39:59 +03:00
|
|
|
def begin_training(self, get_gold_tuples=lambda: [], pipeline=None, sgd=None,
|
2018-02-12 12:18:39 +03:00
|
|
|
**kwargs):
|
2017-05-18 16:30:59 +03:00
|
|
|
orig_tag_map = dict(self.vocab.morphology.tag_map)
|
2017-11-08 14:10:49 +03:00
|
|
|
new_tag_map = OrderedDict()
|
2018-03-27 12:39:59 +03:00
|
|
|
for raw_text, annots_brackets in get_gold_tuples():
|
2017-05-17 13:04:50 +03:00
|
|
|
for annots, brackets in annots_brackets:
|
|
|
|
ids, words, tags, heads, deps, ents = annots
|
|
|
|
for tag in tags:
|
2017-05-18 16:30:59 +03:00
|
|
|
if tag in orig_tag_map:
|
|
|
|
new_tag_map[tag] = orig_tag_map[tag]
|
|
|
|
else:
|
|
|
|
new_tag_map[tag] = {POS: X}
|
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:
|
|
|
|
vocab.morphology = Morphology(vocab.strings, new_tag_map,
|
2017-06-05 00:34:32 +03:00
|
|
|
vocab.morphology.lemmatizer,
|
|
|
|
exc=vocab.morphology.exc)
|
2019-03-08 13:42:26 +03:00
|
|
|
self.cfg["pretrained_vectors"] = kwargs.get("pretrained_vectors")
|
2017-05-29 21:23:47 +03:00
|
|
|
if self.model is True:
|
2019-03-08 13:42:26 +03:00
|
|
|
for hp in ["token_vector_width", "conv_depth"]:
|
2018-12-18 02:08:31 +03:00
|
|
|
if hp in kwargs:
|
|
|
|
self.cfg[hp] = kwargs[hp]
|
2017-09-21 21:07:26 +03:00
|
|
|
self.model = self.Model(self.vocab.morphology.n_tags, **self.cfg)
|
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
|
|
|
|
|
|
|
@classmethod
|
2017-09-23 03:58:06 +03:00
|
|
|
def Model(cls, n_tags, **cfg):
|
2019-03-08 13:42:26 +03:00
|
|
|
if cfg.get("pretrained_dims") and not cfg.get("pretrained_vectors"):
|
2018-04-03 22:40:29 +03:00
|
|
|
raise ValueError(TempErrors.T008)
|
2017-09-23 03:58:06 +03:00
|
|
|
return build_tagger_model(n_tags, **cfg)
|
2017-09-16 20:46:02 +03:00
|
|
|
|
2017-11-01 23:49:24 +03:00
|
|
|
def add_label(self, label, values=None):
|
2017-11-01 18:32:44 +03:00
|
|
|
if label in self.labels:
|
|
|
|
return 0
|
2017-11-01 23:49:24 +03:00
|
|
|
if self.model not in (True, False, None):
|
|
|
|
# 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
|
|
|
|
|
2019-03-10 21:16:45 +03:00
|
|
|
def to_bytes(self, exclude=tuple(), **kwargs):
|
2017-10-10 04:58:12 +03:00
|
|
|
serialize = OrderedDict()
|
2019-02-21 11:42:02 +03:00
|
|
|
if self.model not in (None, True, False):
|
2019-03-08 13:42:26 +03:00
|
|
|
serialize["model"] = self.model.to_bytes
|
|
|
|
serialize["vocab"] = self.vocab.to_bytes
|
|
|
|
serialize["cfg"] = lambda: srsly.json_dumps(self.cfg)
|
2017-11-08 15:08:48 +03:00
|
|
|
tag_map = OrderedDict(sorted(self.vocab.morphology.tag_map.items()))
|
2019-03-08 13:42:26 +03:00
|
|
|
serialize["tag_map"] = lambda: srsly.msgpack_dumps(tag_map)
|
2019-03-10 21:16:45 +03:00
|
|
|
exclude = util.get_serialization_exclude(serialize, exclude, kwargs)
|
2017-05-29 11:14:20 +03:00
|
|
|
return util.to_bytes(serialize, exclude)
|
|
|
|
|
2019-03-10 21:16:45 +03:00
|
|
|
def from_bytes(self, bytes_data, exclude=tuple(), **kwargs):
|
2017-05-29 21:23:47 +03:00
|
|
|
def load_model(b):
|
2018-03-28 17:02:59 +03:00
|
|
|
# TODO: Remove this once we don't have to handle previous models
|
2019-03-08 13:42:26 +03:00
|
|
|
if self.cfg.get("pretrained_dims") and "pretrained_vectors" not in self.cfg:
|
|
|
|
self.cfg["pretrained_vectors"] = self.vocab.vectors.name
|
2017-05-29 21:23:47 +03:00
|
|
|
if self.model is True:
|
2017-10-27 21:29:08 +03:00
|
|
|
token_vector_width = util.env_opt(
|
2019-03-08 13:42:26 +03:00
|
|
|
"token_vector_width",
|
|
|
|
self.cfg.get("token_vector_width", 96))
|
|
|
|
self.model = self.Model(self.vocab.morphology.n_tags, **self.cfg)
|
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
|
|
|
|
2017-05-30 01:53:06 +03:00
|
|
|
deserialize = OrderedDict((
|
2019-03-08 13:42:26 +03:00
|
|
|
("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-30 01:53:06 +03:00
|
|
|
))
|
2019-03-10 21:16:45 +03:00
|
|
|
exclude = util.get_serialization_exclude(deserialize, exclude, kwargs)
|
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
|
|
|
|
|
2019-03-10 21:16:45 +03:00
|
|
|
def to_disk(self, path, exclude=tuple(), **kwargs):
|
2017-11-08 15:08:48 +03:00
|
|
|
tag_map = OrderedDict(sorted(self.vocab.morphology.tag_map.items()))
|
2017-06-01 20:18:36 +03:00
|
|
|
serialize = OrderedDict((
|
2019-03-10 21:16:45 +03:00
|
|
|
("vocab", lambda p: self.vocab.to_disk(p)),
|
|
|
|
("tag_map", lambda p: srsly.write_msgpack(p, tag_map)),
|
|
|
|
("model", lambda p: p.open("wb").write(self.model.to_bytes())),
|
|
|
|
("cfg", lambda p: srsly.write_json(p, self.cfg))
|
2017-06-01 20:18:36 +03:00
|
|
|
))
|
2019-03-10 21:16:45 +03:00
|
|
|
exclude = util.get_serialization_exclude(serialize, exclude, kwargs)
|
2017-05-29 12:45:45 +03:00
|
|
|
util.to_disk(path, serialize, exclude)
|
|
|
|
|
2019-03-10 21:16:45 +03:00
|
|
|
def from_disk(self, path, exclude=tuple(), **kwargs):
|
2017-06-01 20:18:36 +03:00
|
|
|
def load_model(p):
|
2018-03-28 17:02:59 +03:00
|
|
|
# TODO: Remove this once we don't have to handle previous models
|
2019-03-08 13:42:26 +03:00
|
|
|
if self.cfg.get("pretrained_dims") and "pretrained_vectors" not in self.cfg:
|
|
|
|
self.cfg["pretrained_vectors"] = self.vocab.vectors.name
|
2017-06-01 20:18:36 +03:00
|
|
|
if self.model is True:
|
2017-09-21 21:07:26 +03:00
|
|
|
self.model = self.Model(self.vocab.morphology.n_tags, **self.cfg)
|
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
|
|
|
|
|
|
|
deserialize = OrderedDict((
|
2019-03-08 13:42:26 +03:00
|
|
|
("cfg", lambda p: self.cfg.update(_load_cfg(p))),
|
|
|
|
("vocab", lambda p: self.vocab.from_disk(p)),
|
|
|
|
("tag_map", load_tag_map),
|
|
|
|
("model", load_model),
|
2017-06-01 20:18:36 +03:00
|
|
|
))
|
2019-03-10 21:16:45 +03:00
|
|
|
exclude = util.get_serialization_exclude(deserialize, exclude, kwargs)
|
2017-05-29 12:45:45 +03:00
|
|
|
util.from_disk(path, deserialize, exclude)
|
|
|
|
return self
|
2017-05-29 11:14:20 +03:00
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
name = "nn_labeller"
|
2017-10-27 21:29:08 +03:00
|
|
|
|
2017-09-26 13:42:52 +03:00
|
|
|
def __init__(self, vocab, model=True, target='dep_tag_offset', **cfg):
|
2017-05-22 01:52:30 +03:00
|
|
|
self.vocab = vocab
|
|
|
|
self.model = model
|
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)
|
2019-03-08 13:42:26 +03:00
|
|
|
self.cfg.setdefault("cnn_maxout_pieces", 2)
|
2017-07-23 01:52:47 +03:00
|
|
|
|
|
|
|
@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
|
|
|
|
|
2018-03-27 12:39:59 +03:00
|
|
|
def begin_training(self, get_gold_tuples=lambda: [], pipeline=None, tok2vec=None,
|
2018-02-12 12:18:39 +03:00
|
|
|
sgd=None, **kwargs):
|
2018-03-27 12:39:59 +03:00
|
|
|
gold_tuples = nonproj.preprocess_training_data(get_gold_tuples())
|
2017-05-22 01:52:30 +03:00
|
|
|
for raw_text, annots_brackets in gold_tuples:
|
|
|
|
for annots, brackets in annots_brackets:
|
|
|
|
ids, words, tags, heads, deps, ents = annots
|
2017-09-26 13:42:52 +03:00
|
|
|
for i in range(len(ids)):
|
|
|
|
label = self.make_label(i, words, tags, heads, deps, ents)
|
|
|
|
if label is not None and label not in self.labels:
|
|
|
|
self.labels[label] = len(self.labels)
|
2017-05-29 21:23:47 +03:00
|
|
|
if self.model is True:
|
2019-03-08 13:42:26 +03:00
|
|
|
token_vector_width = util.env_opt("token_vector_width")
|
2018-01-21 21:21:34 +03:00
|
|
|
self.model = self.Model(len(self.labels), tok2vec=tok2vec)
|
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
|
|
|
|
|
|
|
@classmethod
|
2017-09-26 13:42:52 +03:00
|
|
|
def Model(cls, n_tags, tok2vec=None, **cfg):
|
2019-03-08 13:42:26 +03:00
|
|
|
token_vector_width = util.env_opt("token_vector_width", 96)
|
2018-12-01 16:41:24 +03:00
|
|
|
softmax = Softmax(n_tags, token_vector_width*2)
|
2018-01-21 21:21:34 +03:00
|
|
|
model = chain(
|
|
|
|
tok2vec,
|
2018-12-01 16:41:24 +03:00
|
|
|
LayerNorm(Maxout(token_vector_width*2, token_vector_width, pieces=3)),
|
2018-01-21 21:21:34 +03:00
|
|
|
softmax
|
|
|
|
)
|
|
|
|
model.tok2vec = tok2vec
|
|
|
|
model.softmax = softmax
|
|
|
|
return model
|
|
|
|
|
|
|
|
def predict(self, docs):
|
2018-12-20 17:54:53 +03:00
|
|
|
self.require_model()
|
2018-01-21 21:21:34 +03:00
|
|
|
tokvecs = self.model.tok2vec(docs)
|
|
|
|
scores = self.model.softmax(tokvecs)
|
|
|
|
return tokvecs, scores
|
2017-09-16 20:46:02 +03:00
|
|
|
|
2017-05-22 01:52:30 +03:00
|
|
|
def get_loss(self, docs, golds, scores):
|
2018-04-03 16:50:31 +03:00
|
|
|
if len(docs) != len(golds):
|
2019-03-08 13:42:26 +03:00
|
|
|
raise ValueError(Errors.E077.format(value="loss", n_docs=len(docs),
|
2018-04-03 16:50:31 +03:00
|
|
|
n_golds=len(golds)))
|
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)
|
2018-02-17 20:41:18 +03:00
|
|
|
for i, gold in enumerate(golds):
|
|
|
|
for j in range(len(docs[i])):
|
|
|
|
# Handes alignment for tokenization differences
|
2018-03-27 20:23:02 +03:00
|
|
|
label = self.make_label(j, gold.words, gold.tags,
|
2018-02-17 20:41:18 +03:00
|
|
|
gold.heads, gold.labels, gold.ents)
|
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")
|
2017-05-22 01:52:30 +03:00
|
|
|
d_scores = scores - to_categorical(correct, nb_classes=scores.shape[1])
|
|
|
|
loss = (d_scores**2).sum()
|
|
|
|
return float(loss), d_scores
|
|
|
|
|
2017-09-26 13:42:52 +03:00
|
|
|
@staticmethod
|
|
|
|
def make_dep(i, words, tags, heads, deps, ents):
|
|
|
|
if deps[i] is None or heads[i] is None:
|
|
|
|
return None
|
|
|
|
return deps[i]
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def make_tag(i, words, tags, heads, deps, ents):
|
|
|
|
return tags[i]
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def make_ent(i, words, tags, heads, deps, ents):
|
|
|
|
if ents is None:
|
|
|
|
return None
|
|
|
|
return ents[i]
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def make_dep_tag_offset(i, words, tags, heads, deps, ents):
|
|
|
|
if deps[i] is None or heads[i] is None:
|
|
|
|
return None
|
|
|
|
offset = heads[i] - i
|
|
|
|
offset = min(offset, 2)
|
|
|
|
offset = max(offset, -2)
|
2019-03-08 13:42:26 +03:00
|
|
|
return "%s-%s:%d" % (deps[i], tags[i], offset)
|
2017-09-26 13:42:52 +03:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def make_ent_tag(i, words, tags, heads, deps, ents):
|
|
|
|
if ents is None or ents[i] is None:
|
|
|
|
return None
|
|
|
|
else:
|
2019-03-08 13:42:26 +03:00
|
|
|
return "%s-%s" % (tags[i], ents[i])
|
2017-09-26 13:42:52 +03:00
|
|
|
|
2018-03-27 20:23:02 +03:00
|
|
|
@staticmethod
|
|
|
|
def make_sent_start(target, words, tags, heads, deps, ents, cache=True, _cache={}):
|
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)
|
|
|
|
|
|
|
|
The implementation of this method uses an internal cache that relies
|
|
|
|
on the identity of the heads array, to avoid requiring a new piece
|
|
|
|
of gold data. You can pass cache=False if you know the cache will
|
|
|
|
do the wrong thing.
|
2019-03-08 13:42:26 +03:00
|
|
|
"""
|
2018-03-27 20:23:02 +03:00
|
|
|
assert len(words) == len(heads)
|
|
|
|
assert target < len(words), (target, len(words))
|
|
|
|
if cache:
|
|
|
|
if id(heads) in _cache:
|
|
|
|
return _cache[id(heads)][target]
|
|
|
|
else:
|
|
|
|
for key in list(_cache.keys()):
|
|
|
|
_cache.pop(key)
|
2019-03-08 13:42:26 +03:00
|
|
|
sent_tags = ["I-SENT"] * len(words)
|
2018-03-27 20:23:02 +03:00
|
|
|
_cache[id(heads)] = sent_tags
|
|
|
|
else:
|
2019-03-08 13:42:26 +03:00
|
|
|
sent_tags = ["I-SENT"] * len(words)
|
2018-03-27 20:23:02 +03:00
|
|
|
|
|
|
|
def _find_root(child):
|
|
|
|
seen = set([child])
|
|
|
|
while child is not None and heads[child] != child:
|
|
|
|
seen.add(child)
|
|
|
|
child = heads[child]
|
|
|
|
return child
|
|
|
|
|
|
|
|
sentences = {}
|
|
|
|
for i in range(len(words)):
|
|
|
|
root = _find_root(i)
|
|
|
|
if root is None:
|
|
|
|
sent_tags[i] = None
|
|
|
|
else:
|
|
|
|
sentences.setdefault(root, []).append(i)
|
|
|
|
for root, span in sorted(sentences.items()):
|
|
|
|
if len(span) == 1:
|
2019-03-08 13:42:26 +03:00
|
|
|
sent_tags[span[0]] = "U-SENT"
|
2018-03-27 20:23:02 +03:00
|
|
|
else:
|
2019-03-08 13:42:26 +03:00
|
|
|
sent_tags[span[0]] = "B-SENT"
|
|
|
|
sent_tags[span[-1]] = "L-SENT"
|
2018-03-27 20:23:02 +03:00
|
|
|
return sent_tags[target]
|
|
|
|
|
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):
|
|
|
|
@classmethod
|
|
|
|
def Model(cls, vocab, tok2vec, **cfg):
|
|
|
|
output_size = vocab.vectors.data.shape[1]
|
|
|
|
output_layer = chain(
|
|
|
|
LayerNorm(Maxout(output_size, tok2vec.nO, pieces=3)),
|
|
|
|
zero_init(Affine(output_size, output_size, drop_factor=0.0))
|
|
|
|
)
|
|
|
|
model = chain(tok2vec, output_layer)
|
|
|
|
model = masked_language_model(vocab, model)
|
|
|
|
model.tok2vec = tok2vec
|
|
|
|
model.output_layer = output_layer
|
|
|
|
return model
|
|
|
|
|
|
|
|
def __init__(self, vocab, model=True, **cfg):
|
|
|
|
self.vocab = vocab
|
|
|
|
self.model = model
|
|
|
|
self.cfg = cfg
|
|
|
|
|
|
|
|
def set_annotations(self, docs, dep_ids, tensors=None):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def begin_training(self, get_gold_tuples=lambda: [], pipeline=None,
|
|
|
|
tok2vec=None, sgd=None, **kwargs):
|
|
|
|
link_vectors_to_models(self.vocab)
|
|
|
|
if self.model is True:
|
|
|
|
self.model = self.Model(self.vocab, tok2vec)
|
|
|
|
X = self.model.ops.allocate((5, self.model.tok2vec.nO))
|
|
|
|
self.model.output_layer.begin_training(X)
|
|
|
|
if sgd is None:
|
|
|
|
sgd = self.create_optimizer()
|
|
|
|
return sgd
|
|
|
|
|
|
|
|
def predict(self, docs):
|
2018-12-20 17:54:53 +03:00
|
|
|
self.require_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
|
|
|
tokvecs = self.model.tok2vec(docs)
|
|
|
|
vectors = self.model.output_layer(tokvecs)
|
|
|
|
return tokvecs, vectors
|
|
|
|
|
|
|
|
def get_loss(self, docs, vectors, prediction):
|
|
|
|
# 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.
|
|
|
|
ids = self.model.ops.flatten([doc.to_array(ID).ravel() for doc in docs])
|
|
|
|
target = vectors[ids]
|
|
|
|
gradient = (prediction - target) / prediction.shape[0]
|
|
|
|
loss = (gradient**2).sum()
|
|
|
|
return float(loss), gradient
|
2019-02-05 14:32:20 +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
|
|
|
def update(self, docs, golds, drop=0., sgd=None, losses=None):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def rehearse(self, docs, drop=0., sgd=None, losses=None):
|
2018-12-20 17:54:53 +03:00
|
|
|
self.require_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
|
|
|
if losses is not None and self.name not in losses:
|
|
|
|
losses[self.name] = 0.
|
|
|
|
predictions, bp_predictions = self.model.begin_update(docs, drop=drop)
|
|
|
|
loss, d_predictions = self.get_loss(docs, self.vocab.vectors.data, predictions)
|
|
|
|
bp_predictions(d_predictions, sgd=sgd)
|
|
|
|
|
|
|
|
if losses is not None:
|
|
|
|
losses[self.name] += loss
|
|
|
|
|
|
|
|
|
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
|
|
|
|
"""
|
2017-07-22 02:14:07 +03:00
|
|
|
name = 'textcat'
|
2017-06-05 16:40:03 +03:00
|
|
|
|
2017-07-20 01:18:15 +03:00
|
|
|
@classmethod
|
2019-02-05 14:33:47 +03:00
|
|
|
def Model(cls, nr_class=1, **cfg):
|
2018-12-10 16:37:39 +03:00
|
|
|
embed_size = util.env_opt("embed_size", 2000)
|
|
|
|
if "token_vector_width" in cfg:
|
|
|
|
token_vector_width = cfg["token_vector_width"]
|
|
|
|
else:
|
|
|
|
token_vector_width = util.env_opt("token_vector_width", 96)
|
2019-03-08 13:42:26 +03:00
|
|
|
if cfg.get("architecture") == "simple_cnn":
|
2019-02-23 13:55:16 +03:00
|
|
|
tok2vec = Tok2Vec(token_vector_width, embed_size, **cfg)
|
|
|
|
return build_simple_cnn_text_classifier(tok2vec, nr_class, **cfg)
|
2019-03-23 18:44:44 +03:00
|
|
|
elif cfg.get("architecture") == "bow":
|
|
|
|
return build_bow_text_classifier(nr_class, **cfg)
|
2019-02-23 13:55:16 +03:00
|
|
|
else:
|
|
|
|
return build_text_classifier(nr_class, **cfg)
|
2017-06-05 16:40:03 +03:00
|
|
|
|
2018-11-03 01:51:37 +03:00
|
|
|
@property
|
|
|
|
def tok2vec(self):
|
|
|
|
if self.model in (None, True, False):
|
|
|
|
return None
|
|
|
|
else:
|
2018-12-10 16:37:39 +03:00
|
|
|
return self.model.tok2vec
|
2018-11-03 01:51:37 +03:00
|
|
|
|
2017-07-20 01:18:15 +03:00
|
|
|
def __init__(self, vocab, model=True, **cfg):
|
|
|
|
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
|
|
|
|
2017-07-20 01:18:15 +03:00
|
|
|
def __call__(self, doc):
|
2017-11-03 13:20:05 +03:00
|
|
|
scores, tensors = self.predict([doc])
|
|
|
|
self.set_annotations([doc], scores, tensors=tensors)
|
2017-07-20 01:18:15 +03:00
|
|
|
return doc
|
2017-06-05 16:40:03 +03:00
|
|
|
|
2017-07-20 01:18:15 +03:00
|
|
|
def pipe(self, stream, batch_size=128, n_threads=-1):
|
2018-12-03 04:19:12 +03:00
|
|
|
for docs in util.minibatch(stream, size=batch_size):
|
2017-07-20 01:18:15 +03:00
|
|
|
docs = list(docs)
|
2017-11-03 13:20:05 +03:00
|
|
|
scores, tensors = self.predict(docs)
|
|
|
|
self.set_annotations(docs, scores, tensors=tensors)
|
2017-07-20 01:18:15 +03:00
|
|
|
yield from docs
|
|
|
|
|
|
|
|
def predict(self, docs):
|
2018-12-20 17:54:53 +03:00
|
|
|
self.require_model()
|
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
|
|
|
|
|
2017-07-20 01:18:15 +03:00
|
|
|
scores = self.model(docs)
|
|
|
|
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])
|
|
|
|
|
2017-09-21 15:59:48 +03:00
|
|
|
def update(self, docs, golds, state=None, drop=0., sgd=None, losses=None):
|
2019-07-10 20:39:38 +03:00
|
|
|
self.require_model()
|
2017-07-20 01:18:15 +03:00
|
|
|
scores, bp_scores = self.model.begin_update(docs, drop=drop)
|
|
|
|
loss, d_scores = self.get_loss(docs, golds, scores)
|
2017-09-21 15:59:48 +03:00
|
|
|
bp_scores(d_scores, sgd=sgd)
|
2017-07-20 01:18:15 +03:00
|
|
|
if losses is not None:
|
|
|
|
losses.setdefault(self.name, 0.0)
|
|
|
|
losses[self.name] += loss
|
|
|
|
|
💫 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 rehearse(self, docs, drop=0., sgd=None, losses=None):
|
|
|
|
if self._rehearsal_model is None:
|
|
|
|
return
|
|
|
|
scores, bp_scores = self.model.begin_update(docs, drop=drop)
|
|
|
|
target = self._rehearsal_model(docs)
|
|
|
|
gradient = scores - target
|
|
|
|
bp_scores(gradient, sgd=sgd)
|
|
|
|
if losses is not None:
|
|
|
|
losses.setdefault(self.name, 0.0)
|
|
|
|
losses[self.name] += (gradient**2).sum()
|
|
|
|
|
2017-07-20 01:18:15 +03:00
|
|
|
def get_loss(self, docs, golds, scores):
|
2019-03-08 13:42:26 +03:00
|
|
|
truths = numpy.zeros((len(golds), len(self.labels)), dtype="f")
|
|
|
|
not_missing = numpy.ones((len(golds), len(self.labels)), dtype="f")
|
2017-07-20 01:18:15 +03:00
|
|
|
for i, gold in enumerate(golds):
|
|
|
|
for j, label in enumerate(self.labels):
|
2017-10-06 02:43:02 +03:00
|
|
|
if label in gold.cats:
|
|
|
|
truths[i, j] = gold.cats[label]
|
|
|
|
else:
|
|
|
|
not_missing[i, j] = 0.
|
2017-07-20 01:18:15 +03:00
|
|
|
truths = self.model.ops.asarray(truths)
|
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):
|
|
|
|
if label in self.labels:
|
|
|
|
return 0
|
2017-11-01 19:06:43 +03:00
|
|
|
if self.model not in (None, True, False):
|
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]
|
|
|
|
# larger = Affine(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
|
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-03-08 13:42:26 +03:00
|
|
|
def begin_training(self, get_gold_tuples=lambda: [], pipeline=None, sgd=None, **kwargs):
|
2017-06-05 16:40:03 +03:00
|
|
|
if self.model is True:
|
2019-03-08 13:42:26 +03:00
|
|
|
self.cfg["pretrained_vectors"] = kwargs.get("pretrained_vectors")
|
2019-07-10 20:39:38 +03:00
|
|
|
self.require_labels()
|
2018-04-29 16:48:53 +03:00
|
|
|
self.model = self.Model(len(self.labels), **self.cfg)
|
2017-09-22 17:38:22 +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-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
|
|
|
|
"""
|
|
|
|
|
|
|
|
name = "parser"
|
2017-05-16 12:21:59 +03:00
|
|
|
TransitionSystem = ArcEager
|
|
|
|
|
2017-10-07 03:00:47 +03:00
|
|
|
@property
|
|
|
|
def postprocesses(self):
|
2019-07-09 22:50:30 +03:00
|
|
|
return [nonproj.deprojectivize]
|
2018-03-27 20:23:02 +03:00
|
|
|
|
2018-01-21 21:37:02 +03:00
|
|
|
def add_multitask_objective(self, target):
|
2019-03-08 13:42:26 +03:00
|
|
|
if target == "cloze":
|
💫 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
|
|
|
cloze = ClozeMultitask(self.vocab)
|
|
|
|
self._multitasks.append(cloze)
|
|
|
|
else:
|
|
|
|
labeller = MultitaskObjective(self.vocab, target=target)
|
|
|
|
self._multitasks.append(labeller)
|
2017-10-07 03:00:47 +03:00
|
|
|
|
2018-03-27 12:39:59 +03:00
|
|
|
def init_multitask_objectives(self, get_gold_tuples, pipeline, sgd=None, **cfg):
|
2018-01-21 21:37:02 +03:00
|
|
|
for labeller in self._multitasks:
|
2018-09-13 15:08:55 +03:00
|
|
|
tok2vec = self.model.tok2vec
|
2018-03-27 12:39:59 +03:00
|
|
|
labeller.begin_training(get_gold_tuples, pipeline=pipeline,
|
2017-11-06 16:26:26 +03:00
|
|
|
tok2vec=tok2vec, sgd=sgd)
|
2017-09-26 13:42:52 +03:00
|
|
|
|
2017-05-27 23:46:06 +03:00
|
|
|
def __reduce__(self):
|
2019-03-08 13:42:26 +03:00
|
|
|
return (DependencyParser, (self.vocab, self.moves, self.model), None, None)
|
2017-05-27 23:46:06 +03:00
|
|
|
|
2019-02-14 22:03:19 +03:00
|
|
|
@property
|
|
|
|
def labels(self):
|
|
|
|
# Get the labels from the model by looking at the available moves
|
|
|
|
return tuple(set(move.split("-")[1] for move in self.move_names))
|
|
|
|
|
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"
|
2017-05-16 12:21:59 +03:00
|
|
|
TransitionSystem = BiluoPushDown
|
2017-05-17 13:04:50 +03:00
|
|
|
nr_feature = 6
|
2018-03-27 20:23:02 +03:00
|
|
|
|
2018-01-21 21:37:02 +03:00
|
|
|
def add_multitask_objective(self, target):
|
2019-02-10 14:14:51 +03:00
|
|
|
if target == "cloze":
|
💫 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
|
|
|
cloze = ClozeMultitask(self.vocab)
|
|
|
|
self._multitasks.append(cloze)
|
|
|
|
else:
|
|
|
|
labeller = MultitaskObjective(self.vocab, target=target)
|
|
|
|
self._multitasks.append(labeller)
|
2017-05-17 13:04:50 +03:00
|
|
|
|
2018-03-27 12:39:59 +03:00
|
|
|
def init_multitask_objectives(self, get_gold_tuples, pipeline, sgd=None, **cfg):
|
2018-01-21 21:37:02 +03:00
|
|
|
for labeller in self._multitasks:
|
2018-09-13 15:08:55 +03:00
|
|
|
tok2vec = self.model.tok2vec
|
2018-03-27 12:39:59 +03:00
|
|
|
labeller.begin_training(get_gold_tuples, pipeline=pipeline,
|
2017-10-27 21:29:08 +03:00
|
|
|
tok2vec=tok2vec)
|
2017-08-18 23:02:35 +03:00
|
|
|
|
2017-05-27 23:46:06 +03:00
|
|
|
def __reduce__(self):
|
2017-10-27 21:29:08 +03:00
|
|
|
return (EntityRecognizer, (self.vocab, self.moves, self.model),
|
|
|
|
None, None)
|
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-02-14 22:03:19 +03:00
|
|
|
return tuple(set(move.split("-")[1] for move in self.move_names
|
|
|
|
if move[0] in ("B", "I", "L", "U")))
|
2018-11-18 02:06:26 +03:00
|
|
|
|
2017-03-15 17:27:41 +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-03-22 15:55:10 +03:00
|
|
|
name = 'entity_linker'
|
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
|
|
|
|
|
|
|
@classmethod
|
2019-06-03 22:32:54 +03:00
|
|
|
def Model(cls, **cfg):
|
|
|
|
embed_width = cfg.get("embed_width", 300)
|
2019-06-18 14:20:40 +03:00
|
|
|
hidden_width = cfg.get("hidden_width", 128)
|
2019-06-29 15:52:36 +03:00
|
|
|
type_to_int = cfg.get("type_to_int", dict())
|
2019-06-03 22:32:54 +03:00
|
|
|
|
2019-06-29 15:52:36 +03:00
|
|
|
model = build_nel_encoder(embed_width=embed_width, hidden_width=hidden_width, ner_types=len(type_to_int), **cfg)
|
2019-06-18 01:05:47 +03:00
|
|
|
return model
|
2019-06-03 22:32:54 +03:00
|
|
|
|
2019-07-03 16:00:42 +03:00
|
|
|
def __init__(self, vocab, **cfg):
|
|
|
|
self.vocab = vocab
|
2019-06-18 01:05:47 +03:00
|
|
|
self.model = True
|
2019-06-13 17:25:39 +03:00
|
|
|
self.kb = None
|
2019-03-06 21:34:18 +03:00
|
|
|
self.cfg = dict(cfg)
|
2019-06-11 12:40:58 +03:00
|
|
|
|
2019-06-13 17:25:39 +03:00
|
|
|
def set_kb(self, kb):
|
|
|
|
self.kb = kb
|
2019-06-03 22:32:54 +03:00
|
|
|
|
|
|
|
def require_model(self):
|
2019-06-11 12:40:58 +03:00
|
|
|
# Raise an error if the component's model is not initialized.
|
2019-06-18 01:05:47 +03:00
|
|
|
if getattr(self, "model", None) in (None, True, False):
|
2019-06-03 22:32:54 +03:00
|
|
|
raise ValueError(Errors.E109.format(name=self.name))
|
|
|
|
|
2019-06-13 17:25:39 +03:00
|
|
|
def require_kb(self):
|
|
|
|
# Raise an error if the knowledge base is not initialized.
|
|
|
|
if getattr(self, "kb", None) in (None, True, False):
|
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-06-03 22:32:54 +03:00
|
|
|
def begin_training(self, get_gold_tuples=lambda: [], pipeline=None, sgd=None, **kwargs):
|
2019-06-13 17:25:39 +03:00
|
|
|
self.require_kb()
|
|
|
|
self.cfg["entity_width"] = self.kb.entity_vector_length
|
|
|
|
|
2019-06-18 01:05:47 +03:00
|
|
|
if self.model is True:
|
|
|
|
self.model = self.Model(**self.cfg)
|
|
|
|
|
|
|
|
if sgd is None:
|
|
|
|
sgd = self.create_optimizer()
|
2019-07-03 14:35:36 +03:00
|
|
|
|
2019-06-18 01:05:47 +03:00
|
|
|
return sgd
|
|
|
|
|
2019-06-03 22:32:54 +03:00
|
|
|
def update(self, docs, golds, state=None, drop=0.0, sgd=None, losses=None):
|
|
|
|
self.require_model()
|
2019-06-13 17:25:39 +03:00
|
|
|
self.require_kb()
|
2019-06-03 22:32:54 +03:00
|
|
|
|
2019-06-14 16:55:26 +03:00
|
|
|
if losses is not None:
|
|
|
|
losses.setdefault(self.name, 0.0)
|
|
|
|
|
|
|
|
if not docs or not golds:
|
|
|
|
return 0
|
|
|
|
|
2019-06-07 13:58:42 +03:00
|
|
|
if len(docs) != len(golds):
|
2019-06-07 14:54:45 +03:00
|
|
|
raise ValueError(Errors.E077.format(value="EL training", n_docs=len(docs),
|
2019-06-07 13:58:42 +03:00
|
|
|
n_golds=len(golds)))
|
|
|
|
|
2019-06-07 14:54:45 +03:00
|
|
|
if isinstance(docs, Doc):
|
|
|
|
docs = [docs]
|
|
|
|
golds = [golds]
|
|
|
|
|
2019-06-24 11:55:04 +03:00
|
|
|
context_docs = []
|
2019-07-03 14:35:36 +03:00
|
|
|
|
2019-06-07 14:54:45 +03:00
|
|
|
for doc, gold in zip(docs, golds):
|
2019-06-29 15:52:36 +03:00
|
|
|
ents_by_offset = dict()
|
|
|
|
for ent in doc.ents:
|
2019-07-22 16:08:17 +03:00
|
|
|
ents_by_offset["{}_{}".format(ent.start_char, ent.end_char)] = ent
|
2019-07-19 13:36:15 +03:00
|
|
|
for entity, kb_dict in gold.links.items():
|
|
|
|
start, end = entity
|
2019-06-14 16:55:26 +03:00
|
|
|
mention = doc.text[start:end]
|
2019-07-23 12:52:48 +03:00
|
|
|
|
2019-08-13 16:38:59 +03:00
|
|
|
for kb_id, value in kb_dict.items():
|
|
|
|
# Currently only training on the positive instances
|
|
|
|
if value:
|
|
|
|
context_docs.append(doc)
|
2019-07-18 11:22:24 +03:00
|
|
|
|
2019-08-13 16:38:59 +03:00
|
|
|
context_encodings, bp_context = self.model.begin_update(context_docs, drop=drop)
|
|
|
|
loss, d_scores = self.get_similarity_loss(scores=context_encodings, golds=golds, docs=None)
|
|
|
|
bp_context(d_scores, sgd=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
|
|
|
|
return loss
|
2019-06-07 16:55:10 +03:00
|
|
|
|
2019-08-13 16:38:59 +03:00
|
|
|
def get_similarity_loss(self, docs, golds, scores):
|
|
|
|
entity_encodings = []
|
|
|
|
for gold in golds:
|
|
|
|
for entity, kb_dict in gold.links.items():
|
|
|
|
for kb_id, value in kb_dict.items():
|
|
|
|
# this loss function assumes we're only using positive examples
|
|
|
|
if value:
|
|
|
|
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:
|
|
|
|
raise RuntimeError(Errors.E147.format(method="get_loss", msg="gold entities do not match up"))
|
2019-06-07 16:55:10 +03:00
|
|
|
|
2019-08-13 16:38:59 +03:00
|
|
|
loss, gradients = get_cossim_loss(yh=scores, y=entity_encodings)
|
|
|
|
loss = loss / len(entity_encodings)
|
|
|
|
return loss, gradients
|
2019-06-03 22:32:54 +03:00
|
|
|
|
2019-07-15 18:36:43 +03:00
|
|
|
def get_loss(self, docs, golds, scores):
|
2019-07-18 14:35:10 +03:00
|
|
|
cats = []
|
|
|
|
for gold in golds:
|
2019-07-19 13:36:15 +03:00
|
|
|
for entity, kb_dict in gold.links.items():
|
|
|
|
for kb_id, value in kb_dict.items():
|
|
|
|
cats.append([value])
|
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
|
|
|
|
|
2019-03-06 21:34:18 +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
|
|
|
|
|
|
|
|
def pipe(self, stream, batch_size=128, n_threads=-1):
|
|
|
|
for docs in util.minibatch(stream, size=batch_size):
|
|
|
|
docs = list(docs)
|
2019-07-19 15:47:36 +03:00
|
|
|
kb_ids, tensors = self.predict(docs)
|
|
|
|
self.set_annotations(docs, kb_ids, tensors=tensors)
|
2019-03-06 21:34:18 +03:00
|
|
|
yield from docs
|
|
|
|
|
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-03 22:32:54 +03:00
|
|
|
self.require_model()
|
2019-06-13 17:25:39 +03:00
|
|
|
self.require_kb()
|
2019-06-12 14:37:05 +03:00
|
|
|
|
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]
|
|
|
|
|
2019-08-13 16:38:59 +03:00
|
|
|
context_encodings = self.model(docs)
|
2019-06-26 14:53:10 +03:00
|
|
|
xp = get_array_module(context_encodings)
|
|
|
|
|
2019-06-14 16:55:26 +03:00
|
|
|
for i, doc in enumerate(docs):
|
|
|
|
if len(doc) > 0:
|
2019-07-19 15:47:36 +03:00
|
|
|
# currently, the context is the same for each entity in a sentence (should be refined)
|
2019-06-26 14:53:10 +03:00
|
|
|
context_encoding = context_encodings[i]
|
2019-08-13 16:38:59 +03:00
|
|
|
context_enc_t = context_encoding.T
|
|
|
|
norm_1 = xp.linalg.norm(context_enc_t)
|
2019-06-14 16:55:26 +03:00
|
|
|
for ent in doc.ents:
|
2019-07-19 13:36:15 +03:00
|
|
|
entity_count += 1
|
2019-06-29 15:52:36 +03:00
|
|
|
|
2019-06-18 19:38:09 +03:00
|
|
|
candidates = self.kb.get_candidates(ent.text)
|
2019-07-19 13:36:15 +03:00
|
|
|
if not candidates:
|
|
|
|
final_kb_ids.append(self.NIL) # no prediction possible for this entity
|
2019-07-19 15:47:36 +03:00
|
|
|
final_tensors.append(context_encoding)
|
2019-07-19 13:36:15 +03:00
|
|
|
else:
|
2019-06-28 09:29:31 +03:00
|
|
|
random.shuffle(candidates)
|
2019-06-28 17:22:58 +03:00
|
|
|
|
2019-08-13 16:38:59 +03:00
|
|
|
# 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])
|
2019-06-28 17:22:58 +03:00
|
|
|
scores = prior_probs
|
|
|
|
|
2019-08-13 16:38:59 +03:00
|
|
|
# add in similarity from the context
|
|
|
|
if self.cfg.get("incl_context", True):
|
2019-06-28 17:22:58 +03:00
|
|
|
entity_encodings = xp.asarray([c.entity_vector for c in candidates])
|
2019-08-13 16:38:59 +03:00
|
|
|
norm_2 = xp.linalg.norm(entity_encodings, axis=1)
|
|
|
|
|
2019-07-23 12:52:48 +03:00
|
|
|
if len(entity_encodings) != len(prior_probs):
|
|
|
|
raise RuntimeError(Errors.E147.format(method="predict", msg="vectors not of equal length"))
|
|
|
|
|
2019-08-13 16:38:59 +03:00
|
|
|
# cosine similarity
|
|
|
|
sims = xp.dot(entity_encodings, context_enc_t) / (norm_1 * norm_2)
|
|
|
|
scores = prior_probs + sims - (prior_probs*sims)
|
2019-06-18 19:38:09 +03:00
|
|
|
|
|
|
|
# TODO: thresholding
|
2019-06-28 09:29:31 +03:00
|
|
|
best_index = scores.argmax()
|
2019-06-18 19:38:09 +03:00
|
|
|
best_candidate = candidates[best_index]
|
|
|
|
final_kb_ids.append(best_candidate.entity_)
|
2019-07-19 15:47:36 +03:00
|
|
|
final_tensors.append(context_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
|
|
|
|
2019-06-13 17:25:39 +03:00
|
|
|
def to_disk(self, path, exclude=tuple(), **kwargs):
|
|
|
|
serialize = OrderedDict()
|
|
|
|
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)
|
2019-06-18 01:05:47 +03:00
|
|
|
if self.model not in (None, True, False):
|
|
|
|
serialize["model"] = lambda p: p.open("wb").write(self.model.to_bytes())
|
2019-06-13 17:25:39 +03:00
|
|
|
exclude = util.get_serialization_exclude(serialize, exclude, kwargs)
|
|
|
|
util.to_disk(path, serialize, exclude)
|
|
|
|
|
|
|
|
def from_disk(self, path, exclude=tuple(), **kwargs):
|
2019-06-18 01:05:47 +03:00
|
|
|
def load_model(p):
|
2019-07-24 12:27:34 +03:00
|
|
|
if self.model is True:
|
2019-06-18 01:05:47 +03:00
|
|
|
self.model = self.Model(**self.cfg)
|
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):
|
|
|
|
kb = KnowledgeBase(vocab=self.vocab, entity_vector_length=self.cfg["entity_width"])
|
|
|
|
kb.load_bulk(p)
|
|
|
|
self.set_kb(kb)
|
|
|
|
|
2019-06-13 17:25:39 +03:00
|
|
|
deserialize = OrderedDict()
|
|
|
|
deserialize["cfg"] = lambda p: self.cfg.update(_load_cfg(p))
|
2019-07-03 16:00:42 +03:00
|
|
|
deserialize["vocab"] = lambda p: self.vocab.from_disk(p)
|
|
|
|
deserialize["kb"] = load_kb
|
2019-06-18 01:05:47 +03:00
|
|
|
deserialize["model"] = load_model
|
2019-06-13 17:25:39 +03:00
|
|
|
exclude = util.get_serialization_exclude(deserialize, exclude, kwargs)
|
|
|
|
util.from_disk(path, deserialize, exclude)
|
|
|
|
return self
|
|
|
|
|
|
|
|
def rehearse(self, docs, 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-03-23 17:45:02 +03:00
|
|
|
class Sentencizer(object):
|
|
|
|
"""Segment the Doc into sentences using a rule-based strategy.
|
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/sentencizer
|
|
|
|
"""
|
|
|
|
|
|
|
|
name = "sentencizer"
|
|
|
|
default_punct_chars = [".", "!", "?"]
|
|
|
|
|
|
|
|
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
|
|
|
|
"""
|
|
|
|
self.punct_chars = punct_chars or self.default_punct_chars
|
|
|
|
|
|
|
|
def __call__(self, doc):
|
|
|
|
"""Apply the sentencizer to a Doc and set Token.is_sent_start.
|
|
|
|
|
|
|
|
doc (Doc): The document to process.
|
|
|
|
RETURNS (Doc): The processed Doc.
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
def to_bytes(self, **kwargs):
|
|
|
|
"""Serialize the sentencizer to a bytestring.
|
|
|
|
|
|
|
|
RETURNS (bytes): The serialized object.
|
|
|
|
|
|
|
|
DOCS: https://spacy.io/api/sentencizer#to_bytes
|
|
|
|
"""
|
|
|
|
return srsly.msgpack_dumps({"punct_chars": self.punct_chars})
|
|
|
|
|
|
|
|
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)
|
|
|
|
self.punct_chars = cfg.get("punct_chars", self.default_punct_chars)
|
|
|
|
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")
|
|
|
|
srsly.write_json(path, {"punct_chars": self.punct_chars})
|
|
|
|
|
|
|
|
|
|
|
|
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)
|
|
|
|
self.punct_chars = cfg.get("punct_chars", self.default_punct_chars)
|
|
|
|
return self
|
|
|
|
|
2019-06-26 15:48:09 +03:00
|
|
|
|
2019-03-26 13:00:02 +03:00
|
|
|
__all__ = ["Tagger", "DependencyParser", "EntityRecognizer", "Tensorizer", "TextCategorizer", "EntityLinker", "Sentencizer"]
|