Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

build spacy custom ner model stackoverflow

def main(model=None, output_dir=r'model', n_iter=100):
    """Load the model, set up the pipeline and train the entity recognizer."""
    if model is not None:
        nlp = spacy.load(model)  # load existing spaCy model
        print("Loaded model '%s'" % model)
    else:
        nlp = spacy.blank("en")  # create blank Language class
        print("Created blank 'en' model")

    # create the built-in pipeline components and add them to the pipeline
    # nlp.create_pipe works for built-ins that are registered with spaCy
    if "ner" not in nlp.pipe_names:
        ner = nlp.create_pipe("ner")
        nlp.add_pipe(ner, last=True)
    # otherwise, get it so we can add labels
    else:
        ner = nlp.get_pipe("ner")

    # add labels
    for _, annotations in TRAIN_DATA:
        for ent in annotations.get("entities"):
            ner.add_label(ent[2])

    # get names of other pipes to disable them during training
    other_pipes = [pipe for pipe in nlp.pipe_names if pipe != "ner"]
    with nlp.disable_pipes(*other_pipes):  # only train NER
        # reset and initialize the weights randomly – but only if we're
        # training a new model
        if model is None:
            nlp.begin_training()
        for itn in range(n_iter):
            random.shuffle(TRAIN_DATA)
            losses = {}
            # batch up the examples using spaCy's minibatch
            batches = minibatch(TRAIN_DATA, size=compounding(4.0, 32.0, 1.001))
            for batch in batches:
                texts, annotations = zip(*batch)
                nlp.update(
                    texts,  # batch of texts
                    annotations,  # batch of annotations
                    drop=0.5,  # dropout - make it harder to memorise data
                    losses=losses,
                )
            print("Losses", losses)

    # test the trained model
    for text, _ in TRAIN_DATA:
        doc = nlp(text)
        print("Entities", [(ent.text, ent.label_) for ent in doc.ents])
        print("Tokens", [(t.text, t.ent_type_, t.ent_iob) for t in doc])

    # 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("Saved model to", output_dir)
Comment

PREVIOUS NEXT
Code Example
Python :: assert len(lex) < self.bucket_specs[-1][1] 
Python :: python: separate lines including the period or excalamtion mark and print it to the prompt.. 
Python :: pandas filter and change value 
Python :: python collections counter 
Python :: how to shutdown your computer using python 
Python :: how to get words from a string in python 
Python :: python calling dynamic function on object 
Python :: convert string array to integer python 
Python :: replace space with _ in pandas 
Python :: python extraer primer elemento lista 
Python :: how to run a .exe through python 
Python :: pandas replace values in column based on condition 
Python :: python twilio certificate error 
Python :: how to display speechmarks in python string 
Python :: python dir all files 
Python :: python format float as currency 
Python :: pandas decimal places 
Python :: matplotlib draw a line between two points 
Python :: how to make pyautogui search a region of the screen 
Python :: sheebang python 
Python :: get wav file in dir 
Python :: python beep 
Python :: Replace empty string and "records with only spaces" with npnan pandas 
Python :: dataframe groupby to dictionary 
Python :: python check if character before character in alphabet 
Python :: pandas normalize groupby 
Python :: how to create an empty 2d list in python 
Python :: python console command 
Python :: remove all rows where one ccolumns egale to nan 
Python :: how to check for duplicates in a column in python 
ADD CONTENT
Topic
Content
Source link
Name
9+4 =