|
| 1 | +from spacy.training.example import Example |
| 2 | +from spacy.util import make_tempdir |
| 3 | +from spacy import util |
| 4 | +from thinc.api import Config |
| 5 | + |
| 6 | + |
| 7 | +TRAIN_DATA = [ |
| 8 | + ("I'm so happy.", {"cats": {"POSITIVE": 1.0, "NEGATIVE": 0.0}}), |
| 9 | + ("I'm so angry", {"cats": {"POSITIVE": 0.0, "NEGATIVE": 1.0}}), |
| 10 | +] |
| 11 | + |
| 12 | + |
| 13 | +cfg_string = """ |
| 14 | + [nlp] |
| 15 | + lang = "en" |
| 16 | + pipeline = ["transformer","textcat"] |
| 17 | +
|
| 18 | + [components] |
| 19 | +
|
| 20 | + [components.textcat] |
| 21 | + factory = "textcat" |
| 22 | +
|
| 23 | + [components.textcat.model] |
| 24 | + @architectures = "spacy.TextCatEnsemble.v2" |
| 25 | +
|
| 26 | + [components.textcat.model.tok2vec] |
| 27 | + @architectures = "spacy-transformers.TransformerListener.v1" |
| 28 | + grad_factor = 1.0 |
| 29 | +
|
| 30 | + [components.textcat.model.tok2vec.pooling] |
| 31 | + @layers = "reduce_mean.v1" |
| 32 | +
|
| 33 | + [components.transformer] |
| 34 | + factory = "transformer" |
| 35 | + """ |
| 36 | + |
| 37 | + |
| 38 | +def test_transformer_pipeline_textcat(): |
| 39 | + """Test that a pipeline with just a transformer+textcat runs and trains properly. |
| 40 | + This used to throw an error because of shape inference issues - |
| 41 | + cf https://github.com/explosion/spaCy/issues/6401""" |
| 42 | + orig_config = Config().from_str(cfg_string) |
| 43 | + nlp = util.load_model_from_config(orig_config, auto_fill=True, validate=True) |
| 44 | + assert nlp.pipe_names == ["transformer", "textcat"] |
| 45 | + train_examples = [] |
| 46 | + |
| 47 | + for text, annotations in TRAIN_DATA: |
| 48 | + train_examples.append(Example.from_dict(nlp.make_doc(text), annotations)) |
| 49 | + optimizer = nlp.initialize(get_examples=lambda: train_examples) |
| 50 | + |
| 51 | + for i in range(2): |
| 52 | + losses = {} |
| 53 | + nlp.update(train_examples, sgd=optimizer, losses=losses) |
| 54 | + |
| 55 | + doc = nlp("We're interested at underwater basket weaving.") |
| 56 | + cats1 = doc.cats |
| 57 | + |
| 58 | + # ensure IO goes OK |
| 59 | + with make_tempdir() as d: |
| 60 | + file_path = d / "trained_nlp" |
| 61 | + nlp.to_disk(file_path) |
| 62 | + nlp2 = util.load_model_from_path(file_path) |
| 63 | + doc2 = nlp2("We're interested at underwater basket weaving.") |
| 64 | + cats2 = doc2.cats |
| 65 | + assert cats1 == cats2 |
0 commit comments