【レベル1:文トークン化(Sentence Tokenization)】
文章を文に分割
“Hello. How are you?” → [“Hello.”, “How are you?”]
【レベル2:単語トークン化(Word Tokenization)】
文を単語に分割
“I love NLP” → [“I”, “love”, “NLP”]
【レベル3:サブワードトークン化(Subword Tokenization)】
単語をさらに小さい単位に分割
“unhappiness” → [“un”, “happi”, “ness”]
3-3. 文トークン化の実装
📝 文トークン化とは?
長い文章を、個別の文に分割する処理です。
ピリオド、感嘆符、疑問符などで文を区切ります。
NLTKライブラリを使って文トークン化を行います。
Google Colabでは、最初に必要なデータをダウンロードする必要があります。
# 文トークン化のコード
import nltk
# 必要なデータをダウンロード(初回のみ実行)
# ‘punkt’ は文分割に必要なデータ
nltk.download(‘punkt’)
# サンプルテキスト
text = “Hello. How are you? I’m fine! Thanks for asking.”
# sent_tokenize() で文に分割
sentences = nltk.sent_tokenize(text)
print(“元のテキスト:”)
print(text)
print(“\n文トークン化後:”)
for i, sent in enumerate(sentences):
print(f” 文{i+1}: {sent}”)
実行結果:
元のテキスト:
Hello. How are you? I’m fine! Thanks for asking.
文トークン化後:
文1: Hello.
文2: How are you?
文3: I’m fine!
文4: Thanks for asking.
3-4. 単語トークン化の実装
📝 単語トークン化とは?
文を単語単位に分割する処理です。
英語の場合、基本的にスペースで区切ります。
NLTKを使った単語トークン化
# 単語トークン化のコード(NLTK)
import nltk
nltk.download(‘punkt’) # 初回のみ
text = “Natural language processing is amazing!”
# word_tokenize() で単語に分割
tokens = nltk.word_tokenize(text)
print(“元のテキスト:”, text)
print(“トークン:”, tokens)
print(“トークン数:”, len(tokens))
実行結果:
元のテキスト: Natural language processing is amazing!
トークン: [‘Natural’, ‘language’, ‘processing’, ‘is’, ‘amazing’, ‘!’]
トークン数: 6
【英語のストップワード例】
冠詞: a, an, the
be動詞: is, are, was, were, be, been
前置詞: in, on, at, to, for, of, with
接続詞: and, or, but
代名詞: I, you, he, she, it, they, we
【日本語のストップワード例】
助詞: は、が、を、に、で、の、と、も、や
助動詞: です、ます、た、だ
接続詞: そして、また、しかし
4-2. なぜストップワードを除去するのか?
【例文】
“This is a great introduction to NLP”
【ストップワードを含む場合】
トークン: [“this”, “is”, “a”, “great”, “introduction”, “to”, “nlp”]
→ 7単語すべてを処理する必要がある
【ストップワード除去後】
トークン: [“great”, “introduction”, “nlp”]
→ 重要な3単語だけを処理すれば良い
メリット:
・処理する単語数が減る → 計算が速くなる
・ノイズが減る → モデルの精度が上がることがある
# ストップワード除去の実装
text = “This is a great introduction to natural language processing”
# 1. トークン化(小文字に変換)
tokens = word_tokenize(text.lower())
print(“トークン化後:”, tokens)
# 2. ストップワード除去
# リスト内包表記で、ストップワードに含まれない単語だけを残す
filtered_tokens = [word for word in tokens if word not in stop_words]
print(“除去後:”, filtered_tokens)
実行結果:
【レマ化結果】
running (v) → run
ran (v) → run
better (a) → good
geese (n) → goose
studies (v) → study
💡 品詞(pos)の指定が重要
レマ化では品詞を指定すると精度が上がります:
pos='v':動詞(verb)
pos='n':名詞(noun)
pos='a':形容詞(adjective)
pos='r':副詞(adverb)
5-4. ステミング vs レマ化の比較
項目
ステミング
レマ化
手法
ルールベース(語尾削除)
辞書ベース(正しい変換)
速度
高速
やや遅い
精度
低い(不正確な場合あり)
高い(正しい基本形)
出力
語幹(意味不明な場合あり)
正しい単語
“easily”の結果
“easili” ✗
“easily” or “easy” ✓
“ran”の結果
“ran” ✗
“run” ✓
💡 どちらを使うべき?
ステミングを選ぶ場合:
処理速度を重視する
大量のデータを処理する
単純な検索システムを作る
レマ化を選ぶ場合:
精度を重視する
意味解析が重要
感情分析や質問応答を行う
🛠️ 6. 実装:前処理パイプラインの完成
これまで学んだ前処理を組み合わせて、完全なパイプラインを作成します。
6-1. NLTK vs spaCyの比較
項目
NLTK
spaCy
対象
教育・研究向け
実務・プロダクション向け
速度
やや遅い
非常に高速
学習コスト
初心者に優しい
やや高い
機能
アルゴリズム多数
深層学習ベース
推奨用途
学習、実験
本番システム
6-2. NLTKで前処理パイプラインを作成
NLTKを使った完全な前処理関数を作成します。
コードを段階的に解説します。
ステップ1:必要なライブラリのインポートとダウンロード
# NLTKの前処理パイプライン – Part 1
import nltk
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize
import string
# 必要なデータをダウンロード(初回のみ)
nltk.download(‘punkt’)
nltk.download(‘stopwords’)
nltk.download(‘wordnet’)
nltk.download(‘omw-1.4’)
ステップ2:前処理関数の定義
# NLTKの前処理パイプライン – Part 2
def preprocess_text_nltk(text):
“””
NLTKを使ったテキスト前処理関数
処理内容:
1. 小文字化
2. トークン化
3. 句読点の除去
4. ストップワードの除去
5. レマ化
“””
# 1. 小文字化
# すべての文字を小文字に変換して統一
text = text.lower()
# 2. トークン化
# 文を単語のリストに分割
tokens = word_tokenize(text)
# 3. 句読点とストップワードの除去
# string.punctuation: すべての句読点
# stopwords.words(‘english’): 英語のストップワード
stop_words = set(stopwords.words(‘english’))
tokens = [token for token in tokens
if token not in string.punctuation
and token not in stop_words]
# 4. レマ化
# 各単語を基本形に変換
lemmatizer = WordNetLemmatizer()
tokens = [lemmatizer.lemmatize(token, pos=’v’) for token in tokens]
return tokens
ステップ3:動作テスト
# NLTKの前処理パイプライン – Part 3(テスト)
# テスト用のテキスト
sample_text = “Running through the beautiful woods, I saw many amazing trees!”
# 前処理を実行
result = preprocess_text_nltk(sample_text)
print(“【入力テキスト】”)
print(sample_text)
print(“\n【前処理後】”)
print(result)
実行結果:
【入力テキスト】
Running through the beautiful woods, I saw many amazing trees!
【前処理後】
[‘run’, ‘beautiful’, ‘wood’, ‘see’, ‘many’, ‘amaze’, ‘tree’]
6-3. spaCyで前処理パイプラインを作成
spaCyを使うと、より簡潔に前処理を記述できます。
# spaCyの前処理パイプライン
import spacy
# 英語モデルをロード
# 初回は以下のコマンドでダウンロードが必要:
# !python -m spacy download en_core_web_sm
nlp = spacy.load(‘en_core_web_sm’)
def preprocess_text_spacy(text):
“””
spaCyを使ったテキスト前処理関数
spaCyは1回の処理で以下を同時に行う:
– トークン化
– 品詞タグ付け
– レマ化
– ストップワード判定
“””
# テキストを処理(全ての解析が自動的に行われる)
doc = nlp(text)
# 各トークンについて:
# – token.lemma_: レマ化された形
# – token.is_stop: ストップワードかどうか
# – token.is_punct: 句読点かどうか
# – token.is_space: 空白かどうか
tokens = [token.lemma_.lower() for token in doc
if not token.is_stop
and not token.is_punct
and not token.is_space]
return tokens
# テスト
sample_text = “Running through the beautiful woods, I saw many amazing trees!”
result = preprocess_text_spacy(sample_text)
print(“【入力テキスト】”)
print(sample_text)
print(“\n【前処理後(spaCy)】”)
print(result)
実行結果:
【入力テキスト】
Running through the beautiful woods, I saw many amazing trees!
【前処理後(spaCy)】
[‘run’, ‘beautiful’, ‘wood’, ‘see’, ‘amazing’, ‘tree’]