Shikata Ga Nai

Private? There is no such things.

18. 自然言語処理(NLP)入門 〜テキストデータを扱う基本〜

Hello there, ('ω')ノ

自然言語処理とは?
テキストデータの基本操作(前処理)
単語のベクトル化(BoW, TF-IDF, Word2Vec)
感情分析(ポジティブ・ネガティブ分類)


📌 1. 自然言語処理(NLP)とは?

自然言語処理(NLP) とは、人間が話す言葉(テキスト)をコンピュータで処理し、意味を理解・解析する技術のことです。
例えば、以下のような処理が含まれます。

NLP技術 説明
トークン化(Tokenization) 文を単語に分割 "私は猫が好き" → ["私", "は", "猫", "が", "好き"]
ストップワード除去(Stopwords Removal) 意味のない単語を削除 "は", "が", "の" などを削除
ステミング(Stemming) 単語の語幹を統一 "running" → "run"
ベクトル化(Vectorization) テキストを数値に変換 BoW, TF-IDF, Word2Vec など
感情分析(Sentiment Analysis) テキストのポジ・ネガ判定 "この映画は最高!" → ポジティブ

テキストデータを適切に前処理し、機械学習に活かすことがNLPの第一歩!


📌 2. テキストデータの前処理

まずは、テキストデータを Python(NLTK, spaCy) を使って処理します!

✅ (1) 文章を単語に分割(トークン化)

import nltk
nltk.download('punkt')
from nltk.tokenize import word_tokenize

# サンプル文章
text = "I love cats, but I also like dogs!"

# トークン化(単語に分割)
tokens = word_tokenize(text)
print(tokens)

🔍 出力

['I', 'love', 'cats', ',', 'but', 'I', 'also', 'like', 'dogs', '!']

文章が単語ごとに分割される!
記号(, ! など)もトークンとして扱われる!


✅ (2) ストップワードの除去

ストップワード(Stopwords) とは、「は」「が」「の」など、意味を持たない単語のことです。

from nltk.corpus import stopwords
nltk.download('stopwords')

# ストップワードリスト(英語)
stop_words = set(stopwords.words('english'))

# ストップワードを除去
filtered_tokens = [word for word in tokens if word.lower() not in stop_words]
print(filtered_tokens)

🔍 出力

['love', 'cats', ',', 'also', 'like', 'dogs', '!']

"I", "but" などのストップワードが削除された!


✅ (3) ステミング(語幹処理)

ステミング(Stemming)は、単語を語幹(基本形) に変換する処理です。

from nltk.stem import PorterStemmer

stemmer = PorterStemmer()
stemmed_words = [stemmer.stem(word) for word in filtered_tokens]
print(stemmed_words)

🔍 出力

['love', 'cat', ',', 'also', 'like', 'dog', '!']

"cats" → "cat", "dogs" → "dog" になった!


📌 3. テキストのベクトル化(数値変換)

テキストデータはそのままでは機械学習に使えないため、数値ベクトルに変換 します。

✅ (1) BoW(Bag of Words)

BoW(単語の出現頻度をカウント)を使って、文章を数値化します。

from sklearn.feature_extraction.text import CountVectorizer

# サンプルテキスト
documents = ["I love cats", "I love dogs", "Cats and dogs are great!"]

# BoWを適用
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(documents)

# 単語ごとの特徴量を確認
print(vectorizer.get_feature_names_out())
print(X.toarray())

BoWは、単語の出現回数をベクトル化!
単語の意味は考慮されない(単語の順番や関係性は無視)


✅ (2) TF-IDF(重要な単語を強調)

TF-IDF(Term Frequency - Inverse Document Frequency)を使うと、よく出現する重要な単語に重みをつける ことができます。

from sklearn.feature_extraction.text import TfidfVectorizer

vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(documents)

# 単語ごとのTF-IDFスコアを確認
print(vectorizer.get_feature_names_out())
print(X.toarray())

TF-IDFは、よく出現する単語ほど重要視される!


📌 4. 感情分析(ポジティブ・ネガティブ判定)

最後に、簡単な 感情分析(Sentiment Analysis) を行ってみましょう!

✅ (1) 事前学習済みモデルを使う(TextBlob)

from textblob import TextBlob

# サンプル文章
text1 = "I love this movie! It is fantastic."
text2 = "This movie is terrible. I hate it."

# 感情分析
print(TextBlob(text1).sentiment.polarity)  # 1.0(ポジティブ)
print(TextBlob(text2).sentiment.polarity)  # -1.0(ネガティブ)

TextBlob を使うと、簡単にポジ・ネガ判定ができる!
スコアが正(+1.0 に近い)ならポジティブ、負(-1.0 に近い)ならネガティブ!


🎯 まとめ

NLPは、テキストデータを処理・解析する技術!
トークン化・ストップワード除去・ステミングで前処理を行う!
BoW・TF-IDF を使って、テキストを数値ベクトル化する!
TextBlob で簡単な感情分析が可能!

Best regards, (^^ゞ