build spacy custom ner model stackoverflow

Solutions on MaxInterview for build spacy custom ner model stackoverflow by the best coders in the world

showing results for - "build spacy custom ner model stackoverflow"
Samantha
21 May 2018
1def main(model=None, output_dir=r'model', n_iter=100):
2    """Load the model, set up the pipeline and train the entity recognizer."""
3    if model is not None:
4        nlp = spacy.load(model)  # load existing spaCy model
5        print("Loaded model '%s'" % model)
6    else:
7        nlp = spacy.blank("en")  # create blank Language class
8        print("Created blank 'en' model")
9
10    # create the built-in pipeline components and add them to the pipeline
11    # nlp.create_pipe works for built-ins that are registered with spaCy
12    if "ner" not in nlp.pipe_names:
13        ner = nlp.create_pipe("ner")
14        nlp.add_pipe(ner, last=True)
15    # otherwise, get it so we can add labels
16    else:
17        ner = nlp.get_pipe("ner")
18
19    # add labels
20    for _, annotations in TRAIN_DATA:
21        for ent in annotations.get("entities"):
22            ner.add_label(ent[2])
23
24    # get names of other pipes to disable them during training
25    other_pipes = [pipe for pipe in nlp.pipe_names if pipe != "ner"]
26    with nlp.disable_pipes(*other_pipes):  # only train NER
27        # reset and initialize the weights randomly – but only if we're
28        # training a new model
29        if model is None:
30            nlp.begin_training()
31        for itn in range(n_iter):
32            random.shuffle(TRAIN_DATA)
33            losses = {}
34            # batch up the examples using spaCy's minibatch
35            batches = minibatch(TRAIN_DATA, size=compounding(4.0, 32.0, 1.001))
36            for batch in batches:
37                texts, annotations = zip(*batch)
38                nlp.update(
39                    texts,  # batch of texts
40                    annotations,  # batch of annotations
41                    drop=0.5,  # dropout - make it harder to memorise data
42                    losses=losses,
43                )
44            print("Losses", losses)
45
46    # test the trained model
47    for text, _ in TRAIN_DATA:
48        doc = nlp(text)
49        print("Entities", [(ent.text, ent.label_) for ent in doc.ents])
50        print("Tokens", [(t.text, t.ent_type_, t.ent_iob) for t in doc])
51
52    # save model to output directory
53    if output_dir is not None:
54        output_dir = Path(output_dir)
55        if not output_dir.exists():
56            output_dir.mkdir()
57        nlp.to_disk(output_dir)
58        print("Saved model to", output_dir)
59