spaCy の基本

spaCyで学ぶNatural Language Processing

Azadeh Mobasher

Principal Data Scientist

spaCy の NLP パイプライン

import spacy

nlp = spacy.load("en_core_web_sm")
doc = nlp("Here's my spaCy pipeline.")
  • spaCy をインポート
  • spacy.load()Language クラスの nlp を取得
    • Language オブジェクトはテキスト処理パイプライン
  • 任意のテキストに nlp() を適用して Doc コンテナを得る
spaCyで学ぶNatural Language Processing

spaCy の NLP パイプライン

 

spaCyLanguage クラスで以下の処理を行います:

spaCy Language pipeline

spaCyで学ぶNatural Language Processing

spaCy のコンテナオブジェクト

  • spaCy にはテキストを表す複数のデータ構造があります:

 

Name Description
Doc テキストの言語注釈にアクセスするためのコンテナ
Span Doc の一部スライス
Token 個々のトークン(単語、句読点、空白など)
spaCyで学ぶNatural Language Processing

パイプラインのコンポーネント

  • spaCy の言語処理パイプラインは、読み込むモデルとその機能に依存します。

 

Component Name Description
Tokenizer Tokenizer テキストをトークンに分割し Doc を作成
Tagger Tagger 品詞タグを付与
Lemmatizer Lemmatizer 単語を基本形に正規化
EntityRecognizer NER 固有表現を検出してラベル付け
spaCyで学ぶNatural Language Processing

パイプラインのコンポーネント

 

  • 各コンポーネントは固有の機能でテキストを処理

    • Language
    • DependencyParser
    • Sentencizer
spaCyで学ぶNatural Language Processing

トークン化

  • 常に最初に実行される処理
  • 以降の処理はトークンを前提とする
  • トークンは単語・数値・句読点など
import spacy
nlp = spacy.load("en_core_web_sm")

doc = nlp("Tokenization splits a sentence into its tokens.")

print([token.text for token in doc])
['Tokenization', 'splits', 'a', 'sentence', 'into', 'its', 'tokens', '.']
spaCyで学ぶNatural Language Processing

文分割

  • トークン化より複雑
  • DependencyParser コンポーネントの一部
import spacy
nlp = spacy.load("en_core_web_sm")

text = "We are learning NLP. This course introduces spaCy."
doc = nlp(text)

for sent in doc.sents: print(sent.text)
We are learning NLP.
This course introduces spaCy.
spaCyで学ぶNatural Language Processing

レンマ化(Lemmatization)

  • Lemme(レンマ)はトークンの基本形
  • eatsate のレンマは eat
  • 言語モデルの精度を向上
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("We are seeing her after one year.")

print([(token.text, token.lemma_) for token in doc])
[('We', 'we'), ('are', 'be'), ('seeing', 'see'), ('her', 'she'), 
('after', 'after'), ('one', 'one'), ('year', 'year'), ('.', '.')]
spaCyで学ぶNatural Language Processing

練習しましょう!

spaCyで学ぶNatural Language Processing

Preparing Video For Download...