2017-10-26 12:24:12 +00:00
|
|
|
#!/usr/bin/env python
|
|
|
|
# coding: utf8
|
2017-10-31 23:43:22 +00:00
|
|
|
"""Example of training spaCy's named entity recognizer, starting off with an
|
2017-10-26 12:24:12 +00:00
|
|
|
existing model or a blank model.
|
|
|
|
|
|
|
|
For more details, see the documentation:
|
2017-11-07 11:00:43 +00:00
|
|
|
* Training: https://spacy.io/usage/training
|
|
|
|
* NER: https://spacy.io/usage/linguistic-features#named-entities
|
2017-10-26 12:24:12 +00:00
|
|
|
|
2017-11-07 00:22:30 +00:00
|
|
|
Compatible with: spaCy v2.0.0+
|
2017-10-26 12:24:12 +00:00
|
|
|
"""
|
2016-10-16 19:34:57 +00:00
|
|
|
from __future__ import unicode_literals, print_function
|
2017-06-01 10:47:18 +00:00
|
|
|
|
2017-10-26 14:10:56 +00:00
|
|
|
import plac
|
2016-10-16 19:34:57 +00:00
|
|
|
import random
|
2017-10-26 12:24:12 +00:00
|
|
|
from pathlib import Path
|
|
|
|
import spacy
|
2018-10-09 23:40:29 +00:00
|
|
|
from spacy.util import minibatch, compounding
|
2016-10-16 19:34:57 +00:00
|
|
|
|
2017-01-27 11:27:10 +00:00
|
|
|
|
2017-10-26 12:24:12 +00:00
|
|
|
# training data
|
|
|
|
TRAIN_DATA = [
|
2017-11-06 22:14:04 +00:00
|
|
|
('Who is Shaka Khan?', {
|
|
|
|
'entities': [(7, 17, 'PERSON')]
|
|
|
|
}),
|
|
|
|
('I like London and Berlin.', {
|
|
|
|
'entities': [(7, 13, 'LOC'), (18, 24, 'LOC')]
|
|
|
|
})
|
2017-10-26 12:24:12 +00:00
|
|
|
]
|
|
|
|
|
|
|
|
|
2017-10-26 14:10:56 +00:00
|
|
|
@plac.annotations(
|
|
|
|
model=("Model name. Defaults to blank 'en' model.", "option", "m", str),
|
|
|
|
output_dir=("Optional output directory", "option", "o", Path),
|
|
|
|
n_iter=("Number of training iterations", "option", "n", int))
|
2017-10-26 12:24:12 +00:00
|
|
|
def main(model=None, output_dir=None, n_iter=100):
|
2017-10-26 14:10:56 +00:00
|
|
|
"""Load the model, set up the pipeline and train the entity recognizer."""
|
2017-10-26 12:24:12 +00:00
|
|
|
if model is not None:
|
|
|
|
nlp = spacy.load(model) # load existing spaCy model
|
|
|
|
print("Loaded model '%s'" % model)
|
|
|
|
else:
|
|
|
|
nlp = spacy.blank('en') # create blank Language class
|
|
|
|
print("Created blank 'en' model")
|
|
|
|
|
|
|
|
# create the built-in pipeline components and add them to the pipeline
|
2017-10-26 13:15:08 +00:00
|
|
|
# nlp.create_pipe works for built-ins that are registered with spaCy
|
2017-10-26 12:24:12 +00:00
|
|
|
if 'ner' not in nlp.pipe_names:
|
|
|
|
ner = nlp.create_pipe('ner')
|
|
|
|
nlp.add_pipe(ner, last=True)
|
2017-11-06 22:14:04 +00:00
|
|
|
# otherwise, get it so we can add labels
|
|
|
|
else:
|
|
|
|
ner = nlp.get_pipe('ner')
|
2017-10-26 12:24:12 +00:00
|
|
|
|
2017-11-06 22:14:04 +00:00
|
|
|
# add labels
|
|
|
|
for _, annotations in TRAIN_DATA:
|
|
|
|
for ent in annotations.get('entities'):
|
|
|
|
ner.add_label(ent[2])
|
2017-10-26 12:24:12 +00:00
|
|
|
|
|
|
|
# get names of other pipes to disable them during training
|
|
|
|
other_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'ner']
|
2017-10-26 22:31:30 +00:00
|
|
|
with nlp.disable_pipes(*other_pipes): # only train NER
|
2017-11-06 22:14:04 +00:00
|
|
|
optimizer = nlp.begin_training()
|
2017-10-26 12:24:12 +00:00
|
|
|
for itn in range(n_iter):
|
|
|
|
random.shuffle(TRAIN_DATA)
|
|
|
|
losses = {}
|
2018-10-09 23:40:29 +00:00
|
|
|
# batch up the examples using spaCy's minibatch
|
|
|
|
batches = minibatch(TRAIN_DATA, size=compounding(4., 32., 1.001))
|
|
|
|
for batch in batches:
|
|
|
|
texts, annotations = zip(*batch)
|
2017-10-26 12:24:12 +00:00
|
|
|
nlp.update(
|
2018-10-09 23:40:29 +00:00
|
|
|
texts, # batch of texts
|
|
|
|
annotations, # batch of annotations
|
2017-11-06 22:14:04 +00:00
|
|
|
drop=0.5, # dropout - make it harder to memorise data
|
|
|
|
sgd=optimizer, # callable to update weights
|
2017-10-26 12:24:12 +00:00
|
|
|
losses=losses)
|
2018-10-09 23:40:29 +00:00
|
|
|
print('Losses', losses)
|
2017-10-26 12:24:12 +00:00
|
|
|
|
|
|
|
# test the trained model
|
|
|
|
for text, _ in TRAIN_DATA:
|
|
|
|
doc = nlp(text)
|
|
|
|
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])
|
|
|
|
|
|
|
|
# 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 13:15:08 +00:00
|
|
|
nlp2 = spacy.load(output_dir)
|
2017-10-26 12:24:12 +00:00
|
|
|
for text, _ in TRAIN_DATA:
|
2017-10-26 13:15:08 +00:00
|
|
|
doc = nlp2(text)
|
2017-10-26 12:24:12 +00: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])
|
|
|
|
|
|
|
|
|
2016-10-16 19:34:57 +00:00
|
|
|
if __name__ == '__main__':
|
2017-05-31 11:42:12 +00:00
|
|
|
plac.call(main)
|
2017-11-06 22:14:04 +00: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)]
|