mirror of
				https://github.com/explosion/spaCy.git
				synced 2025-11-04 01:48:04 +03:00 
			
		
		
		
	* Update with WIP * Update with WIP * Update with pipeline serialization * Update types and pipe factories * Add deep merge, tidy up and add tests * Fix pipe creation from config * Don't validate default configs on load * Update spacy/language.py Co-authored-by: Ines Montani <ines@ines.io> * Adjust factory/component meta error * Clean up factory args and remove defaults * Add test for failing empty dict defaults * Update pipeline handling and methods * provide KB as registry function instead of as object * small change in test to make functionality more clear * update example script for EL configuration * Fix typo * Simplify test * Simplify test * splitting pipes.pyx into separate files * moving default configs to each component file * fix batch_size type * removing default values from component constructors where possible (TODO: test 4725) * skip instead of xfail * Add test for config -> nlp with multiple instances * pipeline.pipes -> pipeline.pipe * Tidy up, document, remove kwargs * small cleanup/generalization for Tok2VecListener * use DEFAULT_UPSTREAM field * revert to avoid circular imports * Fix tests * Replace deprecated arg * Make model dirs require config * fix pickling of keyword-only arguments in constructor * WIP: clean up and integrate full config * Add helper to handle function args more reliably Now also includes keyword-only args * Fix config composition and serialization * Improve config debugging and add visual diff * Remove unused defaults and fix type * Remove pipeline and factories from meta * Update spacy/default_config.cfg Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com> * Update spacy/default_config.cfg * small UX edits * avoid printing stack trace for debug CLI commands * Add support for language-specific factories * specify the section of the config which holds the model to debug * WIP: add Language.from_config * Update with language data refactor WIP * Auto-format * Add backwards-compat handling for Language.factories * Update morphologizer.pyx * Fix morphologizer * Update and simplify lemmatizers * Fix Japanese tests * Port over tagger changes * Fix Chinese and tests * Update to latest Thinc * WIP: xfail first Russian lemmatizer test * Fix component-specific overrides * fix nO for output layers in debug_model * Fix default value * Fix tests and don't pass objects in config * Fix deep merging * Fix lemma lookup data registry Only load the lookups if an entry is available in the registry (and if spacy-lookups-data is installed) * Add types * Add Vocab.from_config * Fix typo * Fix tests * Make config copying more elegant * Fix pipe analysis * Fix lemmatizers and is_base_form * WIP: move language defaults to config * Fix morphology type * Fix vocab * Remove comment * Update to latest Thinc * Add morph rules to config * Tidy up * Remove set_morphology option from tagger factory * Hack use_gpu * Move [pipeline] to top-level block and make [nlp.pipeline] list Allows separating component blocks from component order – otherwise, ordering the config would mean a changed component order, which is bad. Also allows initial config to define more components and not use all of them * Fix use_gpu and resume in CLI * Auto-format * Remove resume from config * Fix formatting and error * [pipeline] -> [components] * Fix types * Fix tagger test: requires set_morphology? Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com> Co-authored-by: svlandeg <sofie.vanlandeghem@gmail.com> Co-authored-by: Matthew Honnibal <honnibal+gh@gmail.com>
		
			
				
	
	
		
			178 lines
		
	
	
		
			7.1 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
			
		
		
	
	
			178 lines
		
	
	
		
			7.1 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
#!/usr/bin/env python
 | 
						|
# coding: utf8
 | 
						|
 | 
						|
"""Example of training spaCy's entity linker, starting off with a predefined
 | 
						|
knowledge base and corresponding vocab, and a blank English model.
 | 
						|
 | 
						|
For more details, see the documentation:
 | 
						|
* Training: https://spacy.io/usage/training
 | 
						|
* Entity Linking: https://spacy.io/usage/linguistic-features#entity-linking
 | 
						|
 | 
						|
Compatible with: spaCy v2.2.4
 | 
						|
Last tested with: v2.2.4
 | 
						|
"""
 | 
						|
from __future__ import unicode_literals, print_function
 | 
						|
 | 
						|
import plac
 | 
						|
import random
 | 
						|
from pathlib import Path
 | 
						|
import spacy
 | 
						|
 | 
						|
from spacy.gold import Example
 | 
						|
from spacy.pipeline import EntityRuler
 | 
						|
from spacy.util import minibatch, compounding
 | 
						|
 | 
						|
 | 
						|
def sample_train_data():
 | 
						|
    train_data = []
 | 
						|
 | 
						|
    # Q2146908 (Russ Cochran): American golfer
 | 
						|
    # Q7381115 (Russ Cochran): publisher
 | 
						|
 | 
						|
    text_1 = "Russ Cochran his reprints include EC Comics."
 | 
						|
    dict_1 = {(0, 12): {"Q7381115": 1.0, "Q2146908": 0.0}}
 | 
						|
    train_data.append((text_1, {"links": dict_1}))
 | 
						|
 | 
						|
    text_2 = "Russ Cochran has been publishing comic art."
 | 
						|
    dict_2 = {(0, 12): {"Q7381115": 1.0, "Q2146908": 0.0}}
 | 
						|
    train_data.append((text_2, {"links": dict_2}))
 | 
						|
 | 
						|
    text_3 = "Russ Cochran captured his first major title with his son as caddie."
 | 
						|
    dict_3 = {(0, 12): {"Q7381115": 0.0, "Q2146908": 1.0}}
 | 
						|
    train_data.append((text_3, {"links": dict_3}))
 | 
						|
 | 
						|
    text_4 = "Russ Cochran was a member of University of Kentucky's golf team."
 | 
						|
    dict_4 = {(0, 12): {"Q7381115": 0.0, "Q2146908": 1.0}}
 | 
						|
    train_data.append((text_4, {"links": dict_4}))
 | 
						|
 | 
						|
    return train_data
 | 
						|
 | 
						|
 | 
						|
# training data
 | 
						|
TRAIN_DATA = sample_train_data()
 | 
						|
 | 
						|
 | 
						|
@plac.annotations(
 | 
						|
    kb_path=("Path to the knowledge base", "positional", None, Path),
 | 
						|
    vocab_path=("Path to the vocab for the kb", "positional", None, Path),
 | 
						|
    output_dir=("Optional output directory", "option", "o", Path),
 | 
						|
    n_iter=("Number of training iterations", "option", "n", int),
 | 
						|
)
 | 
						|
def main(kb_path, vocab_path, output_dir=None, n_iter=50):
 | 
						|
    """Create a blank model with the specified vocab, set up the pipeline and train the entity linker.
 | 
						|
    The `vocab` should be the one used during creation of the KB."""
 | 
						|
    # create blank English model with correct vocab
 | 
						|
    nlp = spacy.blank("en")
 | 
						|
    nlp.vocab.from_disk(vocab_path)
 | 
						|
    nlp.vocab.vectors.name = "spacy_pretrained_vectors"
 | 
						|
    print("Created blank 'en' model with vocab from '%s'" % vocab_path)
 | 
						|
 | 
						|
    # Add a sentencizer component. Alternatively, add a dependency parser for higher accuracy.
 | 
						|
    nlp.add_pipe(nlp.create_pipe("sentencizer"))
 | 
						|
 | 
						|
    # Add a custom component to recognize "Russ Cochran" as an entity for the example training data.
 | 
						|
    # Note that in a realistic application, an actual NER algorithm should be used instead.
 | 
						|
    ruler = EntityRuler(nlp)
 | 
						|
    patterns = [
 | 
						|
        {"label": "PERSON", "pattern": [{"LOWER": "russ"}, {"LOWER": "cochran"}]}
 | 
						|
    ]
 | 
						|
    ruler.add_patterns(patterns)
 | 
						|
    nlp.add_pipe(ruler)
 | 
						|
 | 
						|
    # Create the Entity Linker component and add it to the pipeline.
 | 
						|
    if "entity_linker" not in nlp.pipe_names:
 | 
						|
        print("Loading Knowledge Base from '%s'" % kb_path)
 | 
						|
        cfg = {
 | 
						|
            "kb": {
 | 
						|
                "@assets": "spacy.KBFromFile.v1",
 | 
						|
                "vocab_path": vocab_path,
 | 
						|
                "kb_path": kb_path,
 | 
						|
            },
 | 
						|
            # use only the predicted EL score and not the prior probability (for demo purposes)
 | 
						|
            "incl_prior": False,
 | 
						|
        }
 | 
						|
        entity_linker = nlp.create_pipe("entity_linker", cfg)
 | 
						|
        nlp.add_pipe(entity_linker, last=True)
 | 
						|
 | 
						|
    # Convert the texts to docs to make sure we have doc.ents set for the training examples.
 | 
						|
    # Also ensure that the annotated examples correspond to known identifiers in the knowledge base.
 | 
						|
    kb_ids = nlp.get_pipe("entity_linker").kb.get_entity_strings()
 | 
						|
    train_examples = []
 | 
						|
    for text, annotation in TRAIN_DATA:
 | 
						|
        with nlp.select_pipes(disable="entity_linker"):
 | 
						|
            doc = nlp(text)
 | 
						|
        annotation_clean = annotation
 | 
						|
        for offset, kb_id_dict in annotation["links"].items():
 | 
						|
            new_dict = {}
 | 
						|
            for kb_id, value in kb_id_dict.items():
 | 
						|
                if kb_id in kb_ids:
 | 
						|
                    new_dict[kb_id] = value
 | 
						|
                else:
 | 
						|
                    print(
 | 
						|
                        "Removed", kb_id, "from training because it is not in the KB."
 | 
						|
                    )
 | 
						|
            annotation_clean["links"][offset] = new_dict
 | 
						|
        train_examples.append(Example.from_dict(doc, annotation_clean))
 | 
						|
 | 
						|
    with nlp.select_pipes(enable="entity_linker"):  # only train entity linker
 | 
						|
        # reset and initialize the weights randomly
 | 
						|
        optimizer = nlp.begin_training()
 | 
						|
 | 
						|
        for itn in range(n_iter):
 | 
						|
            random.shuffle(train_examples)
 | 
						|
            losses = {}
 | 
						|
            # batch up the examples using spaCy's minibatch
 | 
						|
            batches = minibatch(train_examples, size=compounding(4.0, 32.0, 1.001))
 | 
						|
            for batch in batches:
 | 
						|
                nlp.update(
 | 
						|
                    batch,
 | 
						|
                    drop=0.2,  # dropout - make it harder to memorise data
 | 
						|
                    losses=losses,
 | 
						|
                    sgd=optimizer,
 | 
						|
                )
 | 
						|
            print(itn, "Losses", losses)
 | 
						|
 | 
						|
    # test the trained model
 | 
						|
    _apply_model(nlp)
 | 
						|
 | 
						|
    # save model to output directory
 | 
						|
    if output_dir is not None:
 | 
						|
        output_dir = Path(output_dir)
 | 
						|
        if not output_dir.exists():
 | 
						|
            output_dir.mkdir()
 | 
						|
        nlp.to_disk(output_dir)
 | 
						|
        print()
 | 
						|
        print("Saved model to", output_dir)
 | 
						|
 | 
						|
        # test the saved model
 | 
						|
        print("Loading from", output_dir)
 | 
						|
        nlp2 = spacy.load(output_dir)
 | 
						|
        _apply_model(nlp2)
 | 
						|
 | 
						|
 | 
						|
def _apply_model(nlp):
 | 
						|
    for text, annotation in TRAIN_DATA:
 | 
						|
        # apply the entity linker which will now make predictions for the 'Russ Cochran' entities
 | 
						|
        doc = nlp(text)
 | 
						|
        print()
 | 
						|
        print("Entities", [(ent.text, ent.label_, ent.kb_id_) for ent in doc.ents])
 | 
						|
        print("Tokens", [(t.text, t.ent_type_, t.ent_kb_id_) for t in doc])
 | 
						|
 | 
						|
 | 
						|
if __name__ == "__main__":
 | 
						|
    plac.call(main)
 | 
						|
 | 
						|
    # Expected output (can be shuffled):
 | 
						|
 | 
						|
    # Entities[('Russ Cochran', 'PERSON', 'Q7381115')]
 | 
						|
    # Tokens[('Russ', 'PERSON', 'Q7381115'), ('Cochran', 'PERSON', 'Q7381115'), ("his", '', ''), ('reprints', '', ''), ('include', '', ''), ('The', '', ''), ('Complete', '', ''), ('EC', '', ''), ('Library', '', ''), ('.', '', '')]
 | 
						|
 | 
						|
    # Entities[('Russ Cochran', 'PERSON', 'Q7381115')]
 | 
						|
    # Tokens[('Russ', 'PERSON', 'Q7381115'), ('Cochran', 'PERSON', 'Q7381115'), ('has', '', ''), ('been', '', ''), ('publishing', '', ''), ('comic', '', ''), ('art', '', ''), ('.', '', '')]
 | 
						|
 | 
						|
    # Entities[('Russ Cochran', 'PERSON', 'Q2146908')]
 | 
						|
    # Tokens[('Russ', 'PERSON', 'Q2146908'), ('Cochran', 'PERSON', 'Q2146908'), ('captured', '', ''), ('his', '', ''), ('first', '', ''), ('major', '', ''), ('title', '', ''), ('with', '', ''), ('his', '', ''), ('son', '', ''), ('as', '', ''), ('caddie', '', ''), ('.', '', '')]
 | 
						|
 | 
						|
    # Entities[('Russ Cochran', 'PERSON', 'Q2146908')]
 | 
						|
    # Tokens[('Russ', 'PERSON', 'Q2146908'), ('Cochran', 'PERSON', 'Q2146908'), ('was', '', ''), ('a', '', ''), ('member', '', ''), ('of', '', ''), ('University', '', ''), ('of', '', ''), ('Kentucky', '', ''), ("'s", '', ''), ('golf', '', ''), ('team', '', ''), ('.', '', '')]
 |