空の spaCy モデルでの EntityRuler
EntityRuler を使うと、doc.ents にエンティティを追加できます。これは、固有表現認識の spaCy パイプラインコンポーネントである EntityRecognizer と組み合わせて精度を高めることも、単体で使ってルールベースのみの固有表現認識システムを実装することもできます。この演習では、空の英語の spaCy モデルに EntityRuler コンポーネントを追加し、与えられた text に対してルールベースのみで固有表現を分類する練習をします。
spaCy パッケージはすでにインポート済みで、空の英語 spaCy モデルが nlp として用意されています。小文字の openai と microsoft を ORG として分類するための patterns のリストも用意されています。
この演習はコースの一部です
spaCyで学ぶNatural Language Processing
演習の手順
- パイプラインに
EntityRulerコンポーネントを作成して追加します。 - 与えられたパターンを
EntityRulerコンポーネントに追加します。 - 与えられた
textをモデルに通して、対応するDocコンテナを作成します。 Docコンテナ内のすべてのエンティティについて、(エンティティのテキスト, 種類)のタプルを出力します。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
nlp = spacy.blank("en")
patterns = [{"label": "ORG", "pattern": [{"LOWER": "openai"}]},
{"label": "ORG", "pattern": [{"LOWER": "microsoft"}]}]
text = "OpenAI has joined forces with Microsoft."
# Add EntityRuler component to the model
entity_ruler = nlp.____("entity_ruler")
# Add given patterns to the EntityRuler component
entity_ruler.____(____)
# Run the model on a given text
doc = nlp(____)
# Print entities text and type for all entities in the Doc container
print([(ent.____, ent.____) for ent in doc.____])