spaCy EntityRuler

Natural Language Processing con spaCy

Azadeh Mobasher

Principal Data Scientist

spaCy EntityRuler

 

  • EntityRuler aggiunge entità nominate a un contenitore Doc
  • Può essere usato da solo o insieme a EntityRecognizer
  • Pattern di frasi per entità per corrispondenze esatte di stringhe (string):
{"label": "ORG", "pattern": "Microsoft"}
  • Pattern di token per entità con un dizionario per ciascun token (list):
{"label": "GPE", "pattern": [{"LOWER": "san"}, {"LOWER": "francisco"}]}
Natural Language Processing con spaCy

Aggiungere EntityRuler alla pipeline di spaCy

 

  • Con il metodo .add_pipe()
  • L'elenco di pattern si aggiunge con .add_patterns()

 

nlp = spacy.blank("en")
entity_ruler = nlp.add_pipe("entity_ruler")
patterns = [{"label": "ORG", "pattern": "Microsoft"},
            {"label": "GPE", "pattern": [{"LOWER": "san"}, {"LOWER": "francisco"}]}]
entity_ruler.add_patterns(patterns)
Natural Language Processing con spaCy

Aggiungere EntityRuler alla pipeline di spaCy

 

  • .ents contiene i risultati di un componente EntityLinker

 

doc = nlp("Microsoft is hiring software developer in San Francisco.")
print([(ent.text, ent.label_) for ent in doc.ents])
[("Microsoft", "ORG"), ("San Francisco", "GPE")]
Natural Language Processing con spaCy

EntityRuler in azione

 

  • Si integra con i componenti della pipeline spaCy
  • Migliora il riconoscitore di entità nominate

  • Modello spaCy senza EntityRuler:

nlp = spacy.load("en_core_web_sm")

doc = nlp("Manhattan associates is a company in the U.S.")
print([(ent.text, ent.label_) for ent in doc.ents])
>>> [("Manhattan", "GPE"), ("U.S.", "GPE")]
Natural Language Processing con spaCy

EntityRuler in azione

 

  • EntityRuler aggiunto dopo il componente ner esistente:
nlp = spacy.load("en_core_web_sm")
ruler = nlp.add_pipe("entity_ruler", after='ner')
patterns = [{"label": "ORG", "pattern": [{"lower": "manhattan"}, {"lower": "associates"}]}]
ruler.add_patterns(patterns)

doc = nlp("Manhattan associates is a company in the U.S.")
print([(ent.text, ent.label_) for ent in doc.ents])
>>> [("Manhattan", "GPE"), ("U.S.", "GPE")]
Natural Language Processing con spaCy

EntityRuler in azione

 

  • EntityRuler aggiunto prima del componente ner esistente:
nlp = spacy.load("en_core_web_sm")
ruler = nlp.add_pipe("entity_ruler", before='ner')
patterns = [{"label": "ORG", "pattern": [{"lower": "manhattan"}, {"lower": "associates"}]}]
ruler.add_patterns(patterns)

doc = nlp("Manhattan associates is a company in the U.S.")
print([(ent.text, ent.label_) for ent in doc.ents])
>>> [("Manhattan associates", "ORG"), ("U.S.", "GPE")]
Natural Language Processing con spaCy

Esercitiamoci!

Natural Language Processing con spaCy

Preparing Video For Download...