2017-03-23 13:08:41 +03:00
|
|
|
# coding: utf8
|
|
|
|
from __future__ import unicode_literals, division, print_function
|
|
|
|
|
2017-05-22 13:28:58 +03:00
|
|
|
import plac
|
2017-03-23 13:08:41 +03:00
|
|
|
import json
|
2017-04-23 23:27:10 +03:00
|
|
|
from collections import defaultdict
|
2017-05-16 17:17:30 +03:00
|
|
|
import cytoolz
|
2017-05-17 13:04:50 +03:00
|
|
|
from pathlib import Path
|
|
|
|
import dill
|
2017-05-21 17:07:06 +03:00
|
|
|
import tqdm
|
2017-05-22 12:47:14 +03:00
|
|
|
from thinc.neural.optimizers import linear_decay
|
2017-05-23 11:06:53 +03:00
|
|
|
from timeit import default_timer as timer
|
2017-03-23 13:08:41 +03:00
|
|
|
|
2017-05-17 13:04:50 +03:00
|
|
|
from ..tokens.doc import Doc
|
2017-03-23 13:08:41 +03:00
|
|
|
from ..scorer import Scorer
|
|
|
|
from ..gold import GoldParse, merge_sents
|
2017-05-21 17:07:06 +03:00
|
|
|
from ..gold import GoldCorpus
|
2017-05-08 00:25:29 +03:00
|
|
|
from ..util import prints
|
2017-03-23 13:08:41 +03:00
|
|
|
from .. import util
|
2017-05-18 12:36:53 +03:00
|
|
|
from .. import displacy
|
2017-03-23 13:08:41 +03:00
|
|
|
|
|
|
|
|
2017-05-22 13:28:58 +03:00
|
|
|
@plac.annotations(
|
|
|
|
lang=("model language", "positional", None, str),
|
|
|
|
output_dir=("output directory to store model in", "positional", None, str),
|
|
|
|
train_data=("location of JSON-formatted training data", "positional", None, str),
|
|
|
|
dev_data=("location of JSON-formatted development data (optional)", "positional", None, str),
|
|
|
|
n_iter=("number of iterations", "option", "n", int),
|
|
|
|
n_sents=("number of sentences", "option", "ns", int),
|
|
|
|
use_gpu=("Use GPU", "flag", "G", bool),
|
|
|
|
no_tagger=("Don't train tagger", "flag", "T", bool),
|
|
|
|
no_parser=("Don't train parser", "flag", "P", bool),
|
|
|
|
no_entities=("Don't train NER", "flag", "N", bool)
|
|
|
|
)
|
2017-05-22 14:13:39 +03:00
|
|
|
def train(_, lang, output_dir, train_data, dev_data, n_iter=20, n_sents=0,
|
|
|
|
use_gpu=False, no_tagger=False, no_parser=False, no_entities=False):
|
2017-05-22 13:28:58 +03:00
|
|
|
"""Train a model. Expects data in spaCy's JSON format."""
|
|
|
|
n_sents = n_sents or None
|
2017-05-08 00:25:29 +03:00
|
|
|
output_path = util.ensure_path(output_dir)
|
|
|
|
train_path = util.ensure_path(train_data)
|
|
|
|
dev_path = util.ensure_path(dev_data)
|
|
|
|
if not output_path.exists():
|
2017-05-22 13:28:58 +03:00
|
|
|
prints(output_path, title="Output directory not found", exits=1)
|
2017-05-08 00:25:29 +03:00
|
|
|
if not train_path.exists():
|
2017-05-22 13:28:58 +03:00
|
|
|
prints(train_path, title="Training data not found", exits=1)
|
2017-05-08 00:25:29 +03:00
|
|
|
if dev_path and not dev_path.exists():
|
2017-05-22 13:28:58 +03:00
|
|
|
prints(dev_path, title="Development data not found", exits=1)
|
2017-03-23 13:08:41 +03:00
|
|
|
|
2017-05-22 13:28:58 +03:00
|
|
|
lang_class = util.get_lang_class(lang)
|
2017-03-23 13:08:41 +03:00
|
|
|
|
2017-05-21 17:07:06 +03:00
|
|
|
pipeline = ['token_vectors', 'tags', 'dependencies', 'entities']
|
|
|
|
if no_tagger and 'tags' in pipeline: pipeline.remove('tags')
|
|
|
|
if no_parser and 'dependencies' in pipeline: pipeline.remove('dependencies')
|
|
|
|
if no_entities and 'entities' in pipeline: pipeline.remove('entities')
|
2017-03-23 13:08:41 +03:00
|
|
|
|
2017-05-21 17:07:06 +03:00
|
|
|
nlp = lang_class(pipeline=pipeline)
|
2017-05-22 18:41:39 +03:00
|
|
|
corpus = GoldCorpus(train_path, dev_path, limit=n_sents)
|
2017-03-23 13:08:41 +03:00
|
|
|
|
2017-05-21 17:07:06 +03:00
|
|
|
dropout = util.env_opt('dropout', 0.0)
|
2017-05-22 12:47:14 +03:00
|
|
|
dropout_decay = util.env_opt('dropout_decay', 0.0)
|
2017-05-22 18:41:39 +03:00
|
|
|
orig_dropout = dropout
|
2017-03-23 13:08:41 +03:00
|
|
|
|
2017-05-21 17:07:06 +03:00
|
|
|
optimizer = nlp.begin_training(lambda: corpus.train_tuples, use_gpu=use_gpu)
|
|
|
|
n_train_docs = corpus.count_train()
|
2017-05-22 12:47:14 +03:00
|
|
|
batch_size = float(util.env_opt('min_batch_size', 4))
|
|
|
|
max_batch_size = util.env_opt('max_batch_size', 64)
|
|
|
|
batch_accel = util.env_opt('batch_accel', 1.001)
|
2017-05-22 18:41:39 +03:00
|
|
|
print("Itn.\tDep. Loss\tUAS\tNER P.\tNER R.\tNER F.\tTag %\tToken %")
|
2017-05-21 17:07:06 +03:00
|
|
|
for i in range(n_iter):
|
|
|
|
with tqdm.tqdm(total=n_train_docs) as pbar:
|
2017-05-25 04:10:20 +03:00
|
|
|
train_docs = corpus.train_docs(nlp, shuffle=i, projectivize=True,
|
|
|
|
gold_preproc=False)
|
|
|
|
losses = {}
|
2017-05-22 12:47:14 +03:00
|
|
|
idx = 0
|
|
|
|
while idx < n_train_docs:
|
|
|
|
batch = list(cytoolz.take(int(batch_size), train_docs))
|
|
|
|
if not batch:
|
|
|
|
break
|
2017-05-21 17:07:06 +03:00
|
|
|
docs, golds = zip(*batch)
|
2017-05-25 04:10:20 +03:00
|
|
|
nlp.update(docs, golds, drop=dropout, sgd=optimizer, losses=losses)
|
2017-05-21 17:07:06 +03:00
|
|
|
pbar.update(len(docs))
|
2017-05-22 12:47:14 +03:00
|
|
|
idx += len(docs)
|
|
|
|
batch_size *= batch_accel
|
2017-05-22 18:41:39 +03:00
|
|
|
batch_size = min(batch_size, max_batch_size)
|
|
|
|
dropout = linear_decay(orig_dropout, dropout_decay, i*n_train_docs+idx)
|
2017-05-22 01:49:46 +03:00
|
|
|
with nlp.use_params(optimizer.averages):
|
2017-05-23 11:06:53 +03:00
|
|
|
start = timer()
|
2017-05-25 04:10:20 +03:00
|
|
|
scorer = nlp.evaluate(corpus.dev_docs(nlp, gold_preproc=False))
|
2017-05-23 11:06:53 +03:00
|
|
|
end = timer()
|
|
|
|
n_words = scorer.tokens.tp + scorer.tokens.fn
|
|
|
|
assert n_words != 0
|
|
|
|
wps = n_words / (end-start)
|
2017-05-25 04:10:20 +03:00
|
|
|
print_progress(i, losses, scorer.scores, wps=wps)
|
2017-05-17 13:04:50 +03:00
|
|
|
with (output_path / 'model.bin').open('wb') as file_:
|
2017-05-22 12:47:14 +03:00
|
|
|
with nlp.use_params(optimizer.averages):
|
|
|
|
dill.dump(nlp, file_, -1)
|
2017-05-20 02:15:50 +03:00
|
|
|
|
|
|
|
|
|
|
|
def _render_parses(i, to_render):
|
|
|
|
to_render[0].user_data['title'] = "Batch %d" % i
|
|
|
|
with Path('/tmp/entities.html').open('w') as file_:
|
|
|
|
html = displacy.render(to_render[:5], style='ent', page=True)
|
|
|
|
file_.write(html)
|
|
|
|
with Path('/tmp/parses.html').open('w') as file_:
|
|
|
|
html = displacy.render(to_render[:5], style='dep', page=True)
|
|
|
|
file_.write(html)
|
2017-03-23 13:08:41 +03:00
|
|
|
|
|
|
|
|
2017-05-23 11:06:53 +03:00
|
|
|
def print_progress(itn, losses, dev_scores, wps=0.0):
|
2017-05-16 17:17:30 +03:00
|
|
|
scores = {}
|
2017-05-22 18:41:39 +03:00
|
|
|
for col in ['dep_loss', 'tag_loss', 'uas', 'tags_acc', 'token_acc',
|
2017-05-23 11:06:53 +03:00
|
|
|
'ents_p', 'ents_r', 'ents_f', 'wps']:
|
2017-05-16 17:17:30 +03:00
|
|
|
scores[col] = 0.0
|
2017-05-25 04:10:20 +03:00
|
|
|
scores['dep_loss'] = losses.get('parser', 0.0)
|
|
|
|
scores['tag_loss'] = losses.get('tagger', 0.0)
|
2017-05-16 17:17:30 +03:00
|
|
|
scores.update(dev_scores)
|
2017-05-25 04:10:20 +03:00
|
|
|
scores['wps'] = wps
|
2017-05-22 18:41:39 +03:00
|
|
|
tpl = '\t'.join((
|
|
|
|
'{:d}',
|
|
|
|
'{dep_loss:.3f}',
|
|
|
|
'{tag_loss:.3f}',
|
|
|
|
'{uas:.3f}',
|
|
|
|
'{ents_p:.3f}',
|
|
|
|
'{ents_r:.3f}',
|
|
|
|
'{ents_f:.3f}',
|
|
|
|
'{tags_acc:.3f}',
|
2017-05-23 11:06:53 +03:00
|
|
|
'{token_acc:.3f}',
|
|
|
|
'{wps:.1f}'))
|
2017-05-16 17:17:30 +03:00
|
|
|
print(tpl.format(itn, **scores))
|
2017-03-23 13:08:41 +03:00
|
|
|
|
|
|
|
|
|
|
|
def print_results(scorer):
|
2017-03-26 15:16:52 +03:00
|
|
|
results = {
|
|
|
|
'TOK': '%.2f' % scorer.token_acc,
|
|
|
|
'POS': '%.2f' % scorer.tags_acc,
|
|
|
|
'UAS': '%.2f' % scorer.uas,
|
|
|
|
'LAS': '%.2f' % scorer.las,
|
|
|
|
'NER P': '%.2f' % scorer.ents_p,
|
|
|
|
'NER R': '%.2f' % scorer.ents_r,
|
|
|
|
'NER F': '%.2f' % scorer.ents_f}
|
2017-03-23 13:08:41 +03:00
|
|
|
util.print_table(results, title="Results")
|