2017-10-27 01:32:19 +03:00
|
|
|
#!/usr/bin/env python
|
|
|
|
# coding: utf8
|
2018-04-29 03:06:46 +03:00
|
|
|
"""Train a convolutional neural network text classifier on the
|
2017-10-27 01:32:19 +03:00
|
|
|
IMDB dataset, using the TextCategorizer component. The dataset will be loaded
|
2020-03-29 20:40:36 +03:00
|
|
|
automatically via the package `ml_datasets`. The model is added to
|
2017-11-01 02:43:22 +03:00
|
|
|
spacy.pipeline, and predictions are available via `doc.cats`. For more details,
|
|
|
|
see the documentation:
|
2017-11-07 14:00:43 +03:00
|
|
|
* Training: https://spacy.io/usage/training
|
2017-10-27 01:32:19 +03:00
|
|
|
|
2020-03-29 20:40:36 +03:00
|
|
|
Compatible with: spaCy v3.0.0+
|
2017-10-27 01:32:19 +03:00
|
|
|
"""
|
|
|
|
from __future__ import unicode_literals, print_function
|
2020-01-29 19:06:46 +03:00
|
|
|
|
2017-07-22 21:15:32 +03:00
|
|
|
import plac
|
|
|
|
import random
|
2017-10-27 01:32:19 +03:00
|
|
|
from pathlib import Path
|
2020-03-29 20:40:36 +03:00
|
|
|
from ml_datasets import loaders
|
2017-07-22 21:15:32 +03:00
|
|
|
|
2017-10-27 01:32:19 +03:00
|
|
|
import spacy
|
2020-03-29 20:40:36 +03:00
|
|
|
from spacy import util
|
2017-11-07 02:22:43 +03:00
|
|
|
from spacy.util import minibatch, compounding
|
2020-06-26 20:34:12 +03:00
|
|
|
from spacy.gold import Example
|
2020-07-27 17:48:21 +03:00
|
|
|
from thinc.api import Config
|
2017-07-22 21:15:32 +03:00
|
|
|
|
2017-10-04 16:12:28 +03:00
|
|
|
|
2017-10-27 01:32:19 +03:00
|
|
|
@plac.annotations(
|
2020-03-29 20:40:36 +03:00
|
|
|
config_path=("Path to config file", "positional", None, Path),
|
2017-10-27 01:32:19 +03:00
|
|
|
output_dir=("Optional output directory", "option", "o", Path),
|
2017-11-01 19:09:22 +03:00
|
|
|
n_texts=("Number of texts to train from", "option", "t", int),
|
2018-12-02 06:26:26 +03:00
|
|
|
n_iter=("Number of training iterations", "option", "n", int),
|
2019-08-31 14:39:31 +03:00
|
|
|
init_tok2vec=("Pretrained tok2vec weights", "option", "t2v", Path),
|
2020-03-29 20:40:36 +03:00
|
|
|
dataset=("Dataset to train on (default: imdb)", "option", "d", str),
|
|
|
|
threshold=("Min. number of instances for a given label (default 20)", "option", "m", int)
|
2018-12-02 06:26:26 +03:00
|
|
|
)
|
2020-03-29 20:40:36 +03:00
|
|
|
def main(config_path, output_dir=None, n_iter=20, n_texts=2000, init_tok2vec=None, dataset="imdb", threshold=20):
|
|
|
|
if not config_path or not config_path.exists():
|
|
|
|
raise ValueError(f"Config file not found at {config_path}")
|
|
|
|
|
|
|
|
spacy.util.fix_random_seed()
|
2019-01-11 05:02:18 +03:00
|
|
|
if output_dir is not None:
|
|
|
|
output_dir = Path(output_dir)
|
|
|
|
if not output_dir.exists():
|
|
|
|
output_dir.mkdir()
|
|
|
|
|
2020-03-29 20:40:36 +03:00
|
|
|
print(f"Loading nlp model from {config_path}")
|
2020-07-27 17:48:21 +03:00
|
|
|
nlp_config = Config().from_disk(config_path)
|
2020-07-27 18:50:12 +03:00
|
|
|
nlp, _ = util.load_model_from_config(nlp_config, auto_fill=True)
|
2017-10-27 01:32:19 +03:00
|
|
|
|
2020-03-29 20:40:36 +03:00
|
|
|
# ensure the nlp object was defined with a textcat component
|
2018-12-02 06:26:26 +03:00
|
|
|
if "textcat" not in nlp.pipe_names:
|
2020-03-29 20:40:36 +03:00
|
|
|
raise ValueError(f"The nlp definition in the config does not contain a textcat component")
|
2017-10-27 01:32:19 +03:00
|
|
|
|
2020-03-29 20:40:36 +03:00
|
|
|
textcat = nlp.get_pipe("textcat")
|
2017-10-27 01:32:19 +03:00
|
|
|
|
2020-03-29 20:40:36 +03:00
|
|
|
# load the dataset
|
|
|
|
print(f"Loading dataset {dataset} ...")
|
|
|
|
(train_texts, train_cats), (dev_texts, dev_cats) = load_data(dataset=dataset, threshold=threshold, limit=n_texts)
|
2018-12-02 06:26:26 +03:00
|
|
|
print(
|
|
|
|
"Using {} examples ({} training, {} evaluation)".format(
|
|
|
|
n_texts, len(train_texts), len(dev_texts)
|
|
|
|
)
|
|
|
|
)
|
2020-03-29 20:40:36 +03:00
|
|
|
train_examples = []
|
|
|
|
for text, cats in zip(train_texts, train_cats):
|
|
|
|
doc = nlp.make_doc(text)
|
2020-06-26 20:34:12 +03:00
|
|
|
example = Example.from_dict(doc, {"cats": cats})
|
2020-03-29 20:40:36 +03:00
|
|
|
for cat in cats:
|
|
|
|
textcat.add_label(cat)
|
2020-06-26 20:34:12 +03:00
|
|
|
train_examples.append(example)
|
2017-10-27 01:32:19 +03:00
|
|
|
|
2020-05-18 23:27:10 +03:00
|
|
|
with nlp.select_pipes(enable="textcat"): # only train textcat
|
2017-11-01 15:14:31 +03:00
|
|
|
optimizer = nlp.begin_training()
|
2019-03-21 01:05:11 +03:00
|
|
|
if init_tok2vec is not None:
|
|
|
|
with init_tok2vec.open("rb") as file_:
|
2020-02-27 20:42:27 +03:00
|
|
|
textcat.model.get_ref("tok2vec").from_bytes(file_.read())
|
2017-10-27 01:32:19 +03:00
|
|
|
print("Training the model...")
|
2018-12-02 06:26:26 +03:00
|
|
|
print("{:^5}\t{:^5}\t{:^5}\t{:^5}".format("LOSS", "P", "R", "F"))
|
2019-03-22 18:10:11 +03:00
|
|
|
batch_sizes = compounding(4.0, 32.0, 1.001)
|
2017-10-27 01:32:19 +03:00
|
|
|
for i in range(n_iter):
|
|
|
|
losses = {}
|
|
|
|
# batch up the examples using spaCy's minibatch
|
2020-03-29 20:40:36 +03:00
|
|
|
random.shuffle(train_examples)
|
|
|
|
batches = minibatch(train_examples, size=batch_sizes)
|
2017-10-27 01:32:19 +03:00
|
|
|
for batch in batches:
|
2019-11-11 19:35:27 +03:00
|
|
|
nlp.update(batch, sgd=optimizer, drop=0.2, losses=losses)
|
2017-10-27 01:32:19 +03:00
|
|
|
with textcat.model.use_params(optimizer.averages):
|
|
|
|
# evaluate on the dev data split off in load_data()
|
|
|
|
scores = evaluate(nlp.tokenizer, textcat, dev_texts, dev_cats)
|
2018-12-02 06:26:26 +03:00
|
|
|
print(
|
|
|
|
"{0:.3f}\t{1:.3f}\t{2:.3f}\t{3:.3f}".format( # print a simple table
|
|
|
|
losses["textcat"],
|
|
|
|
scores["textcat_p"],
|
|
|
|
scores["textcat_r"],
|
|
|
|
scores["textcat_f"],
|
|
|
|
)
|
|
|
|
)
|
2017-10-27 01:32:19 +03:00
|
|
|
|
2020-03-29 20:40:36 +03:00
|
|
|
# test the trained model (only makes sense for sentiment analysis)
|
2017-10-27 01:32:19 +03:00
|
|
|
test_text = "This movie sucked"
|
|
|
|
doc = nlp(test_text)
|
|
|
|
print(test_text, doc.cats)
|
|
|
|
|
|
|
|
if output_dir is not None:
|
2018-12-08 15:27:05 +03:00
|
|
|
with nlp.use_params(optimizer.averages):
|
|
|
|
nlp.to_disk(output_dir)
|
2017-10-27 01:32:19 +03:00
|
|
|
print("Saved model to", output_dir)
|
|
|
|
|
|
|
|
# test the saved model
|
|
|
|
print("Loading from", output_dir)
|
|
|
|
nlp2 = spacy.load(output_dir)
|
|
|
|
doc2 = nlp2(test_text)
|
|
|
|
print(test_text, doc2.cats)
|
|
|
|
|
|
|
|
|
2020-03-29 20:40:36 +03:00
|
|
|
def load_data(dataset, threshold, limit=0, split=0.8):
|
|
|
|
"""Load data from the provided dataset."""
|
2017-10-27 01:32:19 +03:00
|
|
|
# Partition off part of the train data for evaluation
|
2020-03-29 20:40:36 +03:00
|
|
|
data_loader = loaders.get(dataset)
|
|
|
|
train_data, _ = data_loader(limit=int(limit/split))
|
2017-10-27 01:32:19 +03:00
|
|
|
random.shuffle(train_data)
|
|
|
|
texts, labels = zip(*train_data)
|
2020-03-29 20:40:36 +03:00
|
|
|
|
2020-06-12 03:02:07 +03:00
|
|
|
unique_labels = set()
|
|
|
|
for label_set in labels:
|
|
|
|
if isinstance(label_set, int) or isinstance(label_set, str):
|
|
|
|
unique_labels.add(label_set)
|
|
|
|
elif isinstance(label_set, list) or isinstance(label_set, set):
|
|
|
|
unique_labels.update(label_set)
|
|
|
|
unique_labels = sorted(unique_labels)
|
2020-03-29 20:40:36 +03:00
|
|
|
print(f"# of unique_labels: {len(unique_labels)}")
|
|
|
|
|
|
|
|
count_values_train = dict()
|
|
|
|
for text, annot_list in train_data:
|
2020-06-12 03:02:07 +03:00
|
|
|
if isinstance(annot_list, int) or isinstance(annot_list, str):
|
|
|
|
count_values_train[annot_list] = count_values_train.get(annot_list, 0) + 1
|
|
|
|
else:
|
|
|
|
for annot in annot_list:
|
|
|
|
count_values_train[annot] = count_values_train.get(annot, 0) + 1
|
2020-03-29 20:40:36 +03:00
|
|
|
for value, count in sorted(count_values_train.items(), key=lambda item: item[1]):
|
|
|
|
if count < threshold:
|
|
|
|
unique_labels.remove(value)
|
|
|
|
|
|
|
|
print(f"# of unique_labels after filtering with threshold {threshold}: {len(unique_labels)}")
|
|
|
|
|
|
|
|
if unique_labels == {0, 1}:
|
|
|
|
cats = [{"POSITIVE": bool(y), "NEGATIVE": not bool(y)} for y in labels]
|
|
|
|
else:
|
|
|
|
cats = []
|
|
|
|
for y in labels:
|
2020-06-12 03:02:07 +03:00
|
|
|
if isinstance(y, str) or isinstance(y, int):
|
2020-03-29 20:40:36 +03:00
|
|
|
cats.append({str(label): (label == y) for label in unique_labels})
|
|
|
|
elif isinstance(y, set):
|
|
|
|
cats.append({str(label): (label in y) for label in unique_labels})
|
|
|
|
else:
|
|
|
|
raise ValueError(f"Unrecognised type of labels: {type(y)}")
|
|
|
|
|
2017-10-27 01:32:19 +03:00
|
|
|
split = int(len(train_data) * split)
|
|
|
|
return (texts[:split], cats[:split]), (texts[split:], cats[split:])
|
2017-07-22 21:15:32 +03:00
|
|
|
|
|
|
|
|
|
|
|
def evaluate(tokenizer, textcat, texts, cats):
|
|
|
|
docs = (tokenizer(text) for text in texts)
|
2018-12-10 16:37:39 +03:00
|
|
|
tp = 0.0 # True positives
|
2017-10-27 01:32:19 +03:00
|
|
|
fp = 1e-8 # False positives
|
|
|
|
fn = 1e-8 # False negatives
|
2018-12-10 16:37:39 +03:00
|
|
|
tn = 0.0 # True negatives
|
2017-07-22 21:15:32 +03:00
|
|
|
for i, doc in enumerate(textcat.pipe(docs)):
|
|
|
|
gold = cats[i]
|
|
|
|
for label, score in doc.cats.items():
|
2017-10-06 02:43:02 +03:00
|
|
|
if label not in gold:
|
|
|
|
continue
|
2018-12-10 16:37:39 +03:00
|
|
|
if label == "NEGATIVE":
|
|
|
|
continue
|
2017-10-06 02:43:02 +03:00
|
|
|
if score >= 0.5 and gold[label] >= 0.5:
|
2018-12-02 06:26:26 +03:00
|
|
|
tp += 1.0
|
2017-10-06 02:43:02 +03:00
|
|
|
elif score >= 0.5 and gold[label] < 0.5:
|
2018-12-02 06:26:26 +03:00
|
|
|
fp += 1.0
|
2017-10-06 02:43:02 +03:00
|
|
|
elif score < 0.5 and gold[label] < 0.5:
|
2017-07-22 21:15:32 +03:00
|
|
|
tn += 1
|
2017-10-06 02:43:02 +03:00
|
|
|
elif score < 0.5 and gold[label] >= 0.5:
|
2017-07-22 21:15:32 +03:00
|
|
|
fn += 1
|
2017-10-27 01:32:19 +03:00
|
|
|
precision = tp / (tp + fp)
|
2017-07-22 21:15:32 +03:00
|
|
|
recall = tp / (tp + fn)
|
2019-03-16 16:15:49 +03:00
|
|
|
if (precision + recall) == 0:
|
2019-02-23 14:45:41 +03:00
|
|
|
f_score = 0.0
|
|
|
|
else:
|
|
|
|
f_score = 2 * (precision * recall) / (precision + recall)
|
2018-12-02 06:26:26 +03:00
|
|
|
return {"textcat_p": precision, "textcat_r": recall, "textcat_f": f_score}
|
2017-07-23 01:34:12 +03:00
|
|
|
|
2017-07-22 21:15:32 +03:00
|
|
|
|
2018-12-02 06:26:26 +03:00
|
|
|
if __name__ == "__main__":
|
2017-07-22 21:15:32 +03:00
|
|
|
plac.call(main)
|