2018-07-25 00:38:44 +03:00
|
|
|
import pytest
|
|
|
|
import random
|
|
|
|
import numpy.random
|
2020-07-06 14:06:25 +03:00
|
|
|
from thinc.api import fix_random_seed
|
2020-02-27 20:42:27 +03:00
|
|
|
from spacy import util
|
|
|
|
from spacy.lang.en import English
|
2018-07-25 00:38:44 +03:00
|
|
|
from spacy.language import Language
|
|
|
|
from spacy.pipeline import TextCategorizer
|
|
|
|
from spacy.tokens import Doc
|
2020-07-22 14:42:59 +03:00
|
|
|
from spacy.pipeline.tok2vec import DEFAULT_TOK2VEC_MODEL
|
2017-11-07 00:04:29 +03:00
|
|
|
|
2020-03-29 20:40:36 +03:00
|
|
|
from ..util import make_tempdir
|
2020-06-26 20:34:12 +03:00
|
|
|
from ...gold import Example
|
2020-03-29 20:40:36 +03:00
|
|
|
|
2020-07-06 14:06:25 +03:00
|
|
|
|
2020-01-29 19:06:46 +03:00
|
|
|
TRAIN_DATA = [
|
|
|
|
("I'm so happy.", {"cats": {"POSITIVE": 1.0, "NEGATIVE": 0.0}}),
|
|
|
|
("I'm so angry", {"cats": {"POSITIVE": 0.0, "NEGATIVE": 1.0}}),
|
|
|
|
]
|
|
|
|
|
2017-11-07 03:25:54 +03:00
|
|
|
|
2018-08-15 17:56:55 +03:00
|
|
|
@pytest.mark.skip(reason="Test is flakey when run with others")
|
2017-11-07 00:04:29 +03:00
|
|
|
def test_simple_train():
|
|
|
|
nlp = Language()
|
2020-07-22 14:42:59 +03:00
|
|
|
textcat = nlp.add_pipe("textcat")
|
|
|
|
textcat.add_label("answer")
|
2017-11-07 00:04:29 +03:00
|
|
|
nlp.begin_training()
|
|
|
|
for i in range(5):
|
2018-11-27 03:09:36 +03:00
|
|
|
for text, answer in [
|
|
|
|
("aaaa", 1.0),
|
|
|
|
("bbbb", 0),
|
|
|
|
("aa", 1.0),
|
|
|
|
("bbbbbbbbb", 0.0),
|
|
|
|
("aaaaaa", 1),
|
|
|
|
]:
|
2019-11-11 19:35:27 +03:00
|
|
|
nlp.update((text, {"cats": {"answer": answer}}))
|
2018-11-27 03:09:36 +03:00
|
|
|
doc = nlp("aaa")
|
|
|
|
assert "answer" in doc.cats
|
|
|
|
assert doc.cats["answer"] >= 0.5
|
2018-07-25 00:38:44 +03:00
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.skip(reason="Test is flakey when run with others")
|
|
|
|
def test_textcat_learns_multilabel():
|
|
|
|
random.seed(5)
|
|
|
|
numpy.random.seed(5)
|
|
|
|
docs = []
|
|
|
|
nlp = Language()
|
2018-11-27 03:09:36 +03:00
|
|
|
letters = ["a", "b", "c"]
|
2018-07-25 00:38:44 +03:00
|
|
|
for w1 in letters:
|
|
|
|
for w2 in letters:
|
2018-11-27 03:09:36 +03:00
|
|
|
cats = {letter: float(w2 == letter) for letter in letters}
|
|
|
|
docs.append((Doc(nlp.vocab, words=["d"] * 3 + [w1, w2] + ["d"] * 3), cats))
|
2018-07-25 00:38:44 +03:00
|
|
|
random.shuffle(docs)
|
2020-06-26 20:34:12 +03:00
|
|
|
textcat = TextCategorizer(nlp.vocab, width=8)
|
2018-07-25 00:38:44 +03:00
|
|
|
for letter in letters:
|
2020-06-26 20:34:12 +03:00
|
|
|
textcat.add_label(letter)
|
|
|
|
optimizer = textcat.begin_training()
|
2018-07-25 00:38:44 +03:00
|
|
|
for i in range(30):
|
|
|
|
losses = {}
|
2020-06-26 20:34:12 +03:00
|
|
|
examples = [Example.from_dict(doc, {"cats": cats}) for doc, cat in docs]
|
|
|
|
textcat.update(examples, sgd=optimizer, losses=losses)
|
2018-07-25 00:38:44 +03:00
|
|
|
random.shuffle(docs)
|
|
|
|
for w1 in letters:
|
|
|
|
for w2 in letters:
|
2018-11-27 03:09:36 +03:00
|
|
|
doc = Doc(nlp.vocab, words=["d"] * 3 + [w1, w2] + ["d"] * 3)
|
|
|
|
truth = {letter: w2 == letter for letter in letters}
|
2020-06-26 20:34:12 +03:00
|
|
|
textcat(doc)
|
2018-07-25 00:38:44 +03:00
|
|
|
for cat, score in doc.cats.items():
|
|
|
|
if not truth[cat]:
|
|
|
|
assert score < 0.5
|
|
|
|
else:
|
|
|
|
assert score > 0.5
|
2019-11-21 18:24:10 +03:00
|
|
|
|
|
|
|
|
|
|
|
def test_label_types():
|
|
|
|
nlp = Language()
|
2020-07-22 14:42:59 +03:00
|
|
|
textcat = nlp.add_pipe("textcat")
|
|
|
|
textcat.add_label("answer")
|
2019-11-21 18:24:10 +03:00
|
|
|
with pytest.raises(ValueError):
|
2020-07-22 14:42:59 +03:00
|
|
|
textcat.add_label(9)
|
2020-01-29 19:06:46 +03:00
|
|
|
|
|
|
|
|
2020-02-27 20:42:27 +03:00
|
|
|
def test_overfitting_IO():
|
2020-01-29 19:06:46 +03:00
|
|
|
# Simple test to try and quickly overfit the textcat component - ensuring the ML models work correctly
|
2020-04-02 15:46:32 +03:00
|
|
|
fix_random_seed(0)
|
2020-02-27 20:42:27 +03:00
|
|
|
nlp = English()
|
2020-07-22 14:42:59 +03:00
|
|
|
textcat = nlp.add_pipe("textcat")
|
Refactor the Scorer to improve flexibility (#5731)
* Refactor the Scorer to improve flexibility
Refactor the `Scorer` to improve flexibility for arbitrary pipeline
components.
* Individual pipeline components provide their own `evaluate` methods
that score a list of `Example`s and return a dictionary of scores
* `Scorer` is initialized either:
* with a provided pipeline containing components to be scored
* with a default pipeline containing the built-in statistical
components (senter, tagger, morphologizer, parser, ner)
* `Scorer.score` evaluates a list of `Example`s and returns a dictionary
of scores referring to the scores provided by the components in the
pipeline
Significant differences:
* `tags_acc` is renamed to `tag_acc` to be consistent with `token_acc`
and the new `morph_acc`, `pos_acc`, and `lemma_acc`
* Scoring is no longer cumulative: `Scorer.score` scores a list of
examples rather than a single example and does not retain any state
about previously scored examples
* PRF values in the returned scores are no longer multiplied by 100
* Add kwargs to Morphologizer.evaluate
* Create generalized scoring methods in Scorer
* Generalized static scoring methods are added to `Scorer`
* Methods require an attribute (either on Token or Doc) that is
used to key the returned scores
Naming differences:
* `uas`, `las`, and `las_per_type` in the scores dict are renamed to
`dep_uas`, `dep_las`, and `dep_las_per_type`
Scoring differences:
* `Doc.sents` is now scored as spans rather than on sentence-initial
token positions so that `Doc.sents` and `Doc.ents` can be scored with
the same method (this lowers scores since a single incorrect sentence
start results in two incorrect spans)
* Simplify / extend hasattr check for eval method
* Add hasattr check to tokenizer scoring
* Simplify to hasattr check for component scoring
* Reset Example alignment if docs are set
Reset the Example alignment if either doc is set in case the
tokenization has changed.
* Add PRF tokenization scoring for tokens as spans
Add PRF scores for tokens as character spans. The scores are:
* token_acc: # correct tokens / # gold tokens
* token_p/r/f: PRF for (token.idx, token.idx + len(token))
* Add docstring to Scorer.score_tokenization
* Rename component.evaluate() to component.score()
* Update Scorer API docs
* Update scoring for positive_label in textcat
* Fix TextCategorizer.score kwargs
* Update Language.evaluate docs
* Update score names in default config
2020-07-25 13:53:02 +03:00
|
|
|
# Set exclusive labels
|
|
|
|
textcat.model.attrs["multi_label"] = False
|
2020-07-06 14:02:36 +03:00
|
|
|
train_examples = []
|
|
|
|
for text, annotations in TRAIN_DATA:
|
|
|
|
train_examples.append(Example.from_dict(nlp.make_doc(text), annotations))
|
2020-01-29 19:06:46 +03:00
|
|
|
for label, value in annotations.get("cats").items():
|
|
|
|
textcat.add_label(label)
|
|
|
|
optimizer = nlp.begin_training()
|
|
|
|
|
|
|
|
for i in range(50):
|
|
|
|
losses = {}
|
2020-07-06 14:02:36 +03:00
|
|
|
nlp.update(train_examples, sgd=optimizer, losses=losses)
|
2020-02-27 20:42:27 +03:00
|
|
|
assert losses["textcat"] < 0.01
|
2020-01-29 19:06:46 +03:00
|
|
|
|
|
|
|
# test the trained model
|
|
|
|
test_text = "I am happy."
|
|
|
|
doc = nlp(test_text)
|
|
|
|
cats = doc.cats
|
2020-02-27 20:42:27 +03:00
|
|
|
# note that by default, exclusive_classes = false so we need a bigger error margin
|
2020-01-29 19:06:46 +03:00
|
|
|
assert cats["POSITIVE"] > 0.9
|
2020-02-27 20:42:27 +03:00
|
|
|
assert cats["POSITIVE"] + cats["NEGATIVE"] == pytest.approx(1.0, 0.1)
|
|
|
|
|
|
|
|
# Also test the results are still the same after IO
|
|
|
|
with make_tempdir() as tmp_dir:
|
|
|
|
nlp.to_disk(tmp_dir)
|
|
|
|
nlp2 = util.load_model_from_path(tmp_dir)
|
|
|
|
doc2 = nlp2(test_text)
|
|
|
|
cats2 = doc2.cats
|
|
|
|
assert cats2["POSITIVE"] > 0.9
|
|
|
|
assert cats2["POSITIVE"] + cats2["NEGATIVE"] == pytest.approx(1.0, 0.1)
|
2020-03-29 20:40:36 +03:00
|
|
|
|
Refactor the Scorer to improve flexibility (#5731)
* Refactor the Scorer to improve flexibility
Refactor the `Scorer` to improve flexibility for arbitrary pipeline
components.
* Individual pipeline components provide their own `evaluate` methods
that score a list of `Example`s and return a dictionary of scores
* `Scorer` is initialized either:
* with a provided pipeline containing components to be scored
* with a default pipeline containing the built-in statistical
components (senter, tagger, morphologizer, parser, ner)
* `Scorer.score` evaluates a list of `Example`s and returns a dictionary
of scores referring to the scores provided by the components in the
pipeline
Significant differences:
* `tags_acc` is renamed to `tag_acc` to be consistent with `token_acc`
and the new `morph_acc`, `pos_acc`, and `lemma_acc`
* Scoring is no longer cumulative: `Scorer.score` scores a list of
examples rather than a single example and does not retain any state
about previously scored examples
* PRF values in the returned scores are no longer multiplied by 100
* Add kwargs to Morphologizer.evaluate
* Create generalized scoring methods in Scorer
* Generalized static scoring methods are added to `Scorer`
* Methods require an attribute (either on Token or Doc) that is
used to key the returned scores
Naming differences:
* `uas`, `las`, and `las_per_type` in the scores dict are renamed to
`dep_uas`, `dep_las`, and `dep_las_per_type`
Scoring differences:
* `Doc.sents` is now scored as spans rather than on sentence-initial
token positions so that `Doc.sents` and `Doc.ents` can be scored with
the same method (this lowers scores since a single incorrect sentence
start results in two incorrect spans)
* Simplify / extend hasattr check for eval method
* Add hasattr check to tokenizer scoring
* Simplify to hasattr check for component scoring
* Reset Example alignment if docs are set
Reset the Example alignment if either doc is set in case the
tokenization has changed.
* Add PRF tokenization scoring for tokens as spans
Add PRF scores for tokens as character spans. The scores are:
* token_acc: # correct tokens / # gold tokens
* token_p/r/f: PRF for (token.idx, token.idx + len(token))
* Add docstring to Scorer.score_tokenization
* Rename component.evaluate() to component.score()
* Update Scorer API docs
* Update scoring for positive_label in textcat
* Fix TextCategorizer.score kwargs
* Update Language.evaluate docs
* Update score names in default config
2020-07-25 13:53:02 +03:00
|
|
|
# Test scoring
|
2020-07-25 16:01:15 +03:00
|
|
|
scores = nlp.evaluate(
|
|
|
|
train_examples, component_cfg={"scorer": {"positive_label": "POSITIVE"}}
|
|
|
|
)
|
Refactor the Scorer to improve flexibility (#5731)
* Refactor the Scorer to improve flexibility
Refactor the `Scorer` to improve flexibility for arbitrary pipeline
components.
* Individual pipeline components provide their own `evaluate` methods
that score a list of `Example`s and return a dictionary of scores
* `Scorer` is initialized either:
* with a provided pipeline containing components to be scored
* with a default pipeline containing the built-in statistical
components (senter, tagger, morphologizer, parser, ner)
* `Scorer.score` evaluates a list of `Example`s and returns a dictionary
of scores referring to the scores provided by the components in the
pipeline
Significant differences:
* `tags_acc` is renamed to `tag_acc` to be consistent with `token_acc`
and the new `morph_acc`, `pos_acc`, and `lemma_acc`
* Scoring is no longer cumulative: `Scorer.score` scores a list of
examples rather than a single example and does not retain any state
about previously scored examples
* PRF values in the returned scores are no longer multiplied by 100
* Add kwargs to Morphologizer.evaluate
* Create generalized scoring methods in Scorer
* Generalized static scoring methods are added to `Scorer`
* Methods require an attribute (either on Token or Doc) that is
used to key the returned scores
Naming differences:
* `uas`, `las`, and `las_per_type` in the scores dict are renamed to
`dep_uas`, `dep_las`, and `dep_las_per_type`
Scoring differences:
* `Doc.sents` is now scored as spans rather than on sentence-initial
token positions so that `Doc.sents` and `Doc.ents` can be scored with
the same method (this lowers scores since a single incorrect sentence
start results in two incorrect spans)
* Simplify / extend hasattr check for eval method
* Add hasattr check to tokenizer scoring
* Simplify to hasattr check for component scoring
* Reset Example alignment if docs are set
Reset the Example alignment if either doc is set in case the
tokenization has changed.
* Add PRF tokenization scoring for tokens as spans
Add PRF scores for tokens as character spans. The scores are:
* token_acc: # correct tokens / # gold tokens
* token_p/r/f: PRF for (token.idx, token.idx + len(token))
* Add docstring to Scorer.score_tokenization
* Rename component.evaluate() to component.score()
* Update Scorer API docs
* Update scoring for positive_label in textcat
* Fix TextCategorizer.score kwargs
* Update Language.evaluate docs
* Update score names in default config
2020-07-25 13:53:02 +03:00
|
|
|
assert scores["cats_f"] == 1.0
|
2020-07-27 12:17:52 +03:00
|
|
|
assert scores["cats_score"] == 1.0
|
|
|
|
assert "cats_score_desc" in scores
|
Refactor the Scorer to improve flexibility (#5731)
* Refactor the Scorer to improve flexibility
Refactor the `Scorer` to improve flexibility for arbitrary pipeline
components.
* Individual pipeline components provide their own `evaluate` methods
that score a list of `Example`s and return a dictionary of scores
* `Scorer` is initialized either:
* with a provided pipeline containing components to be scored
* with a default pipeline containing the built-in statistical
components (senter, tagger, morphologizer, parser, ner)
* `Scorer.score` evaluates a list of `Example`s and returns a dictionary
of scores referring to the scores provided by the components in the
pipeline
Significant differences:
* `tags_acc` is renamed to `tag_acc` to be consistent with `token_acc`
and the new `morph_acc`, `pos_acc`, and `lemma_acc`
* Scoring is no longer cumulative: `Scorer.score` scores a list of
examples rather than a single example and does not retain any state
about previously scored examples
* PRF values in the returned scores are no longer multiplied by 100
* Add kwargs to Morphologizer.evaluate
* Create generalized scoring methods in Scorer
* Generalized static scoring methods are added to `Scorer`
* Methods require an attribute (either on Token or Doc) that is
used to key the returned scores
Naming differences:
* `uas`, `las`, and `las_per_type` in the scores dict are renamed to
`dep_uas`, `dep_las`, and `dep_las_per_type`
Scoring differences:
* `Doc.sents` is now scored as spans rather than on sentence-initial
token positions so that `Doc.sents` and `Doc.ents` can be scored with
the same method (this lowers scores since a single incorrect sentence
start results in two incorrect spans)
* Simplify / extend hasattr check for eval method
* Add hasattr check to tokenizer scoring
* Simplify to hasattr check for component scoring
* Reset Example alignment if docs are set
Reset the Example alignment if either doc is set in case the
tokenization has changed.
* Add PRF tokenization scoring for tokens as spans
Add PRF scores for tokens as character spans. The scores are:
* token_acc: # correct tokens / # gold tokens
* token_p/r/f: PRF for (token.idx, token.idx + len(token))
* Add docstring to Scorer.score_tokenization
* Rename component.evaluate() to component.score()
* Update Scorer API docs
* Update scoring for positive_label in textcat
* Fix TextCategorizer.score kwargs
* Update Language.evaluate docs
* Update score names in default config
2020-07-25 13:53:02 +03:00
|
|
|
|
2020-03-29 20:40:36 +03:00
|
|
|
|
|
|
|
# fmt: off
|
|
|
|
@pytest.mark.parametrize(
|
|
|
|
"textcat_config",
|
|
|
|
[
|
|
|
|
{"@architectures": "spacy.TextCatBOW.v1", "exclusive_classes": False, "ngram_size": 1, "no_output_layer": False},
|
|
|
|
{"@architectures": "spacy.TextCatBOW.v1", "exclusive_classes": True, "ngram_size": 4, "no_output_layer": False},
|
|
|
|
{"@architectures": "spacy.TextCatBOW.v1", "exclusive_classes": False, "ngram_size": 3, "no_output_layer": True},
|
|
|
|
{"@architectures": "spacy.TextCatBOW.v1", "exclusive_classes": True, "ngram_size": 2, "no_output_layer": True},
|
2020-07-26 16:11:43 +03:00
|
|
|
{"@architectures": "spacy.TextCatEnsemble.v1", "exclusive_classes": False, "ngram_size": 1, "pretrained_vectors": False, "width": 64, "conv_depth": 2, "embed_size": 2000, "window_size": 2, "dropout": None},
|
|
|
|
{"@architectures": "spacy.TextCatEnsemble.v1", "exclusive_classes": True, "ngram_size": 5, "pretrained_vectors": False, "width": 128, "conv_depth": 2, "embed_size": 2000, "window_size": 1, "dropout": None},
|
|
|
|
{"@architectures": "spacy.TextCatEnsemble.v1", "exclusive_classes": True, "ngram_size": 2, "pretrained_vectors": False, "width": 32, "conv_depth": 3, "embed_size": 500, "window_size": 3, "dropout": None},
|
2020-07-22 14:42:59 +03:00
|
|
|
{"@architectures": "spacy.TextCatCNN.v1", "tok2vec": DEFAULT_TOK2VEC_MODEL, "exclusive_classes": True},
|
|
|
|
{"@architectures": "spacy.TextCatCNN.v1", "tok2vec": DEFAULT_TOK2VEC_MODEL, "exclusive_classes": False},
|
2020-03-29 20:40:36 +03:00
|
|
|
],
|
|
|
|
)
|
|
|
|
# fmt: on
|
|
|
|
def test_textcat_configs(textcat_config):
|
|
|
|
pipe_config = {"model": textcat_config}
|
|
|
|
nlp = English()
|
2020-07-22 14:42:59 +03:00
|
|
|
textcat = nlp.add_pipe("textcat", config=pipe_config)
|
2020-07-06 14:02:36 +03:00
|
|
|
train_examples = []
|
|
|
|
for text, annotations in TRAIN_DATA:
|
|
|
|
train_examples.append(Example.from_dict(nlp.make_doc(text), annotations))
|
2020-03-29 20:40:36 +03:00
|
|
|
for label, value in annotations.get("cats").items():
|
|
|
|
textcat.add_label(label)
|
|
|
|
optimizer = nlp.begin_training()
|
|
|
|
for i in range(5):
|
|
|
|
losses = {}
|
2020-07-06 14:02:36 +03:00
|
|
|
nlp.update(train_examples, sgd=optimizer, losses=losses)
|