2017-10-26 15:24:12 +03:00
|
|
|
|
#!/usr/bin/env python
|
|
|
|
|
# coding: utf8
|
2017-11-01 02:43:22 +03:00
|
|
|
|
"""Example of training spaCy's named entity recognizer, starting off with an
|
2017-10-26 15:24:12 +03:00
|
|
|
|
existing model or a blank model.
|
|
|
|
|
|
|
|
|
|
For more details, see the documentation:
|
2017-11-07 14:00:43 +03:00
|
|
|
|
* Training: https://spacy.io/usage/training
|
|
|
|
|
* NER: https://spacy.io/usage/linguistic-features#named-entities
|
2017-10-26 15:24:12 +03:00
|
|
|
|
|
2017-11-07 03:22:30 +03:00
|
|
|
|
Compatible with: spaCy v2.0.0+
|
2020-05-19 17:01:18 +03:00
|
|
|
|
Last tested with: v2.2.4
|
2017-10-26 15:24:12 +03:00
|
|
|
|
"""
|
2016-10-16 22:34:57 +03:00
|
|
|
|
from __future__ import unicode_literals, print_function
|
2017-06-01 13:47:18 +03:00
|
|
|
|
|
2017-10-26 17:10:56 +03:00
|
|
|
|
import plac
|
2016-10-16 22:34:57 +03:00
|
|
|
|
import random
|
2020-05-19 17:01:18 +03:00
|
|
|
|
import warnings
|
2017-10-26 15:24:12 +03:00
|
|
|
|
from pathlib import Path
|
|
|
|
|
import spacy
|
2020-07-06 14:02:36 +03:00
|
|
|
|
from spacy.gold import Example
|
2018-10-10 02:40:29 +03:00
|
|
|
|
from spacy.util import minibatch, compounding
|
2016-10-16 22:34:57 +03:00
|
|
|
|
|
2017-01-27 14:27:10 +03:00
|
|
|
|
|
2017-10-26 15:24:12 +03:00
|
|
|
|
# training data
|
|
|
|
|
TRAIN_DATA = [
|
2018-12-17 15:44:38 +03:00
|
|
|
|
("Who is Shaka Khan?", {"entities": [(7, 17, "PERSON")]}),
|
|
|
|
|
("I like London and Berlin.", {"entities": [(7, 13, "LOC"), (18, 24, "LOC")]}),
|
2017-10-26 15:24:12 +03:00
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
|
2017-10-26 17:10:56 +03:00
|
|
|
|
@plac.annotations(
|
|
|
|
|
model=("Model name. Defaults to blank 'en' model.", "option", "m", str),
|
|
|
|
|
output_dir=("Optional output directory", "option", "o", Path),
|
2018-12-17 15:44:38 +03:00
|
|
|
|
n_iter=("Number of training iterations", "option", "n", int),
|
|
|
|
|
)
|
2017-10-26 15:24:12 +03:00
|
|
|
|
def main(model=None, output_dir=None, n_iter=100):
|
2017-10-26 17:10:56 +03:00
|
|
|
|
"""Load the model, set up the pipeline and train the entity recognizer."""
|
2017-10-26 15:24:12 +03:00
|
|
|
|
if model is not None:
|
|
|
|
|
nlp = spacy.load(model) # load existing spaCy model
|
|
|
|
|
print("Loaded model '%s'" % model)
|
|
|
|
|
else:
|
2018-12-17 15:44:38 +03:00
|
|
|
|
nlp = spacy.blank("en") # create blank Language class
|
2017-10-26 15:24:12 +03:00
|
|
|
|
print("Created blank 'en' model")
|
|
|
|
|
|
|
|
|
|
# create the built-in pipeline components and add them to the pipeline
|
2017-10-26 16:15:08 +03:00
|
|
|
|
# nlp.create_pipe works for built-ins that are registered with spaCy
|
2020-05-18 23:23:33 +03:00
|
|
|
|
if "simple_ner" not in nlp.pipe_names:
|
|
|
|
|
ner = nlp.create_pipe("simple_ner")
|
2017-10-26 15:24:12 +03:00
|
|
|
|
nlp.add_pipe(ner, last=True)
|
2017-11-07 01:14:04 +03:00
|
|
|
|
# otherwise, get it so we can add labels
|
|
|
|
|
else:
|
2020-05-18 23:23:33 +03:00
|
|
|
|
ner = nlp.get_pipe("simple_ner")
|
2017-10-26 15:24:12 +03:00
|
|
|
|
|
2020-07-06 14:02:36 +03:00
|
|
|
|
# add labels and create Example objects
|
|
|
|
|
train_examples = []
|
|
|
|
|
for text, annotations in TRAIN_DATA:
|
|
|
|
|
train_examples.append(Example.from_dict(nlp.make_doc(text), annotations))
|
2018-12-17 15:44:38 +03:00
|
|
|
|
for ent in annotations.get("entities"):
|
2020-05-18 23:23:33 +03:00
|
|
|
|
print("Add label", ent[2])
|
2017-11-07 01:14:04 +03:00
|
|
|
|
ner.add_label(ent[2])
|
2017-10-26 15:24:12 +03:00
|
|
|
|
|
2020-06-29 15:33:00 +03:00
|
|
|
|
with nlp.select_pipes(enable="simple_ner") and warnings.catch_warnings():
|
2020-05-19 17:01:18 +03:00
|
|
|
|
# show warnings for misaligned entity spans once
|
2020-05-21 19:39:06 +03:00
|
|
|
|
warnings.filterwarnings("once", category=UserWarning, module="spacy")
|
2020-05-19 17:01:18 +03:00
|
|
|
|
|
2018-12-17 15:45:28 +03:00
|
|
|
|
# reset and initialize the weights randomly – but only if we're
|
|
|
|
|
# training a new model
|
|
|
|
|
if model is None:
|
|
|
|
|
nlp.begin_training()
|
2020-05-21 19:39:06 +03:00
|
|
|
|
print(
|
|
|
|
|
"Transitions", list(enumerate(nlp.get_pipe("simple_ner").get_tag_names()))
|
|
|
|
|
)
|
2017-10-26 15:24:12 +03:00
|
|
|
|
for itn in range(n_iter):
|
2020-07-06 14:02:36 +03:00
|
|
|
|
random.shuffle(train_examples)
|
2017-10-26 15:24:12 +03:00
|
|
|
|
losses = {}
|
2018-10-10 02:40:29 +03:00
|
|
|
|
# batch up the examples using spaCy's minibatch
|
2020-07-06 14:02:36 +03:00
|
|
|
|
batches = minibatch(train_examples, size=compounding(4.0, 32.0, 1.001))
|
2018-10-10 02:40:29 +03:00
|
|
|
|
for batch in batches:
|
2017-10-26 15:24:12 +03:00
|
|
|
|
nlp.update(
|
2019-11-11 19:35:27 +03:00
|
|
|
|
batch,
|
2020-05-18 23:23:33 +03:00
|
|
|
|
drop=0.0, # dropout - make it harder to memorise data
|
2018-12-17 15:44:38 +03:00
|
|
|
|
losses=losses,
|
|
|
|
|
)
|
|
|
|
|
print("Losses", losses)
|
2017-10-26 15:24:12 +03:00
|
|
|
|
|
|
|
|
|
# test the trained model
|
|
|
|
|
for text, _ in TRAIN_DATA:
|
|
|
|
|
doc = nlp(text)
|
2018-12-17 15:44:38 +03:00
|
|
|
|
print("Entities", [(ent.text, ent.label_) for ent in doc.ents])
|
|
|
|
|
print("Tokens", [(t.text, t.ent_type_, t.ent_iob) for t in doc])
|
2017-10-26 15:24:12 +03:00
|
|
|
|
|
|
|
|
|
# save model to output directory
|
|
|
|
|
if output_dir is not None:
|
|
|
|
|
output_dir = Path(output_dir)
|
|
|
|
|
if not output_dir.exists():
|
|
|
|
|
output_dir.mkdir()
|
|
|
|
|
nlp.to_disk(output_dir)
|
|
|
|
|
print("Saved model to", output_dir)
|
|
|
|
|
|
|
|
|
|
# test the saved model
|
|
|
|
|
print("Loading from", output_dir)
|
2017-10-26 16:15:08 +03:00
|
|
|
|
nlp2 = spacy.load(output_dir)
|
2017-10-26 15:24:12 +03:00
|
|
|
|
for text, _ in TRAIN_DATA:
|
2017-10-26 16:15:08 +03:00
|
|
|
|
doc = nlp2(text)
|
2018-12-17 15:44:38 +03:00
|
|
|
|
print("Entities", [(ent.text, ent.label_) for ent in doc.ents])
|
|
|
|
|
print("Tokens", [(t.text, t.ent_type_, t.ent_iob) for t in doc])
|
2017-10-26 15:24:12 +03:00
|
|
|
|
|
|
|
|
|
|
2018-12-17 15:44:38 +03:00
|
|
|
|
if __name__ == "__main__":
|
2017-05-31 14:42:12 +03:00
|
|
|
|
plac.call(main)
|
2017-11-07 01:14:04 +03:00
|
|
|
|
|
|
|
|
|
# Expected output:
|
|
|
|
|
# Entities [('Shaka Khan', 'PERSON')]
|
|
|
|
|
# Tokens [('Who', '', 2), ('is', '', 2), ('Shaka', 'PERSON', 3),
|
|
|
|
|
# ('Khan', 'PERSON', 1), ('?', '', 2)]
|
|
|
|
|
# Entities [('London', 'LOC'), ('Berlin', 'LOC')]
|
|
|
|
|
# Tokens [('I', '', 2), ('like', '', 2), ('London', 'LOC', 3),
|
|
|
|
|
# ('and', '', 2), ('Berlin', 'LOC', 3), ('.', '', 2)]
|