spaCy EntityRuler

spaCyで学ぶNatural Language Processing

Azadeh Mobasher

Principal Data Scientist

spaCy EntityRuler

 

  • EntityRulerDocに固有表現を追加
  • 単体でもEntityRecognizerと併用でも可
  • 厳密一致のフレーズパターン(文字列):
{"label": "ORG", "pattern": "Microsoft"}
  • 1トークン=1辞書のトークンパターン(リスト):
{"label": "GPE", "pattern": [{"LOWER": "san"}, {"LOWER": "francisco"}]}
spaCyで学ぶNatural Language Processing

spaCy パイプラインに EntityRuler を追加

 

  • .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で学ぶNatural Language Processing

spaCy パイプラインに EntityRuler を追加

 

  • .entsEntityLinkerの結果が入る

 

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で学ぶNatural Language Processing

EntityRuler の実行例

 

  • spaCyの各コンポーネントと連携
  • 固有表現抽出器を強化

  • EntityRulerなしのspaCyモデル:

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で学ぶNatural Language Processing

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で学ぶNatural Language Processing

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で学ぶNatural Language Processing

練習しましょう!

spaCyで学ぶNatural Language Processing

Preparing Video For Download...