spaCy EntityRuler

使用 spaCy 的自然语言处理

Azadeh Mobasher

Principal Data Scientist

spaCy EntityRuler

 

  • EntityRulerDoc 容器添加命名实体
  • 可单独使用或与 EntityRecognizer 结合
  • 用于精确字符串匹配的"短语实体模式"(string):
{"label": "ORG", "pattern": "Microsoft"}
  • "词元实体模式",每个字典描述一个词元(list):
{"label": "GPE", "pattern": [{"LOWER": "san"}, {"LOWER": "francisco"}]}
使用 spaCy 的自然语言处理

将 EntityRuler 添加到 spaCy 流水线

 

  • 使用 .add_pipe() 方法
  • 使用 .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)
使用 spaCy 的自然语言处理

将 EntityRuler 添加到 spaCy 流水线

 

  • .ents 存储 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')]
使用 spaCy 的自然语言处理

EntityRuler 实战

 

  • spaCy 流水线组件集成
  • 增强命名实体识别

  • 不含 EntityRulerspaCy 模型:

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')]
使用 spaCy 的自然语言处理

EntityRuler 实战

 

  • 在现有 ner 组件之后添加 EntityRuler
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')]
使用 spaCy 的自然语言处理

EntityRuler 实战

 

  • 在现有 ner 组件之前添加 EntityRuler
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')]
使用 spaCy 的自然语言处理

Passons à la pratique !

使用 spaCy 的自然语言处理

Preparing Video For Download...