書き起こしテキストでの固有表現抽出

Pythonで学ぶ音声言語処理

Daniel Bourke

Machine Learning Engineer/YouTube Creator

spaCy のインストール

# spaCy をインストール
$ pip install spacy
# spaCy 言語モデルをダウンロード
$ python -m spacy download en_core_web_sm
Pythonで学ぶ音声言語処理

spaCy を使う

import spacy

# spaCy 言語モデルを読み込む nlp = spacy.load("en_core_web_sm")
# spaCy の doc を作成
doc = nlp("I'd like to talk about a smartphone I ordered on July 31st from your 
Sydney store, my order number is 40939440. I spoke to Georgia about it last week.")
Pythonで学ぶ音声言語処理

spaCy のトークン

# トークンと位置を表示
for token in doc:
  print(token.text, token.idx)
I 0
'd 1
like 4
to 9
talk 12
about 17
a 23
smartphone 25...
Pythonで学ぶ音声言語処理

spaCy の文単位

# 文を表示
for sentences in doc.sents:
  print(sentence)
I'd like to talk about a smartphone I ordered on July 31st from your Sydney store, 
my order number is 4093829.
I spoke to one of your customer service team, Georgia, yesterday.
Pythonで学ぶ音声言語処理

spaCy の固有表現

spaCy の主な組み込み固有表現:

  • PERSON 人物(架空の人物を含む)。
  • ORG 企業・機関など。
  • GPE 国・都市・州。
  • PRODUCT 物体・乗り物・食品など(サービスは除く)。
  • DATE 日付・期間(絶対/相対)。
  • TIME 1日より短い時刻。
  • MONEY 金額(通貨単位を含む)。
  • CARDINAL 他の型に当てはまらない数詞。
Pythonで学ぶ音声言語処理

spaCy の固有表現

# doc 内の固有表現を抽出
for entity in doc.ents:
  print(entity.text, entity.label_)
July 31st DATE
Sydney GPE
4093829 CARDINAL
one CARDINAL
Georgia GPE
yesterday DATE
Pythonで学ぶ音声言語処理

カスタム固有表現

# EntityRuler クラスをインポート
from spacy.pipeline import EntityRuler
# spaCy のパイプラインを確認
print(nlp.pipeline)
[('tagger', <spacy.pipeline.pipes.Tagger at 0x1c3aa8a470>),
 ('parser', <spacy.pipeline.pipes.DependencyParser at 0x1c3bb60588>),
 ('ner', <spacy.pipeline.pipes.EntityRecognizer at 0x1c3bb605e8>)]
Pythonで学ぶ音声言語処理

パイプラインの変更

# EntityRuler を作成
ruler = EntityRuler(nlp)
# トークンパターンを追加
ruler.add_patterns([{"label":"PRODUCT", "pattern": "smartphone"}])
# ルールを ner の前に追加
nlp.add_pipe(ruler, before="ner")
# 変更後のパイプラインを確認
nlp.pipeline
Pythonで学ぶ音声言語処理

パイプラインの変更

[('tagger', <spacy.pipeline.pipes.Tagger at 0x1c1f9c9b38>),
 ('parser', <spacy.pipeline.pipes.DependencyParser at 0x1c3c9cba08>),
 ('entity_ruler', <spacy.pipeline.entityruler.EntityRuler at 0x1c1d834b70>),
 ('ner', <spacy.pipeline.pipes.EntityRecognizer at 0x1c3c9cba68>)]
Pythonで学ぶ音声言語処理

新しいパイプラインのテスト

# 新しい固有表現ルールをテスト
for entity in doc.ents:
    print(entity.text, entity.label_)
smartphone PRODUCT
July 31st DATE
Sydney GPE
4093829 CARDINAL
one CARDINAL
Georgia GPE
yesterday DATE
Pythonで学ぶ音声言語処理

Let's rocket and practice spaCy!

Pythonで学ぶ音声言語処理

Preparing Video For Download...