Bag-of-Words 表現

Pythonで学ぶ自然言語処理(NLP)

Fouad Trad

Machine Learning Engineer

NLP ワークフローの復習

全体のワークフロー図。第3章と第4章が transformers ライブラリに焦点。

Pythonで学ぶ自然言語処理(NLP)

Bag-of-Words (BoW)

  • 文字列を数値で表す基礎手法
  • 各単語の出現回数で表現する
  • 単語を「袋」に入れて数えるだけ
  • 文法や順序は無視

テキストの単語を袋に入れ、単語の出現回数を数える図。

Pythonで学ぶ自然言語処理(NLP)

BoW の例

2つの文「I love NLP」と「I love machine learning.」を示す画像。

Pythonで学ぶ自然言語処理(NLP)

BoW の例

文から得た語彙: I, love, NLP, machine, learning を示す画像。

  • すべてのユニークな単語で語彙を作成
Pythonで学ぶ自然言語処理(NLP)

BoW の例

定義した語彙に従い、各文の単語数から特徴ベクトルを作る画像。

  • すべてのユニークな単語で語彙を作成
  • 語彙中の各単語の出現回数を数える
Pythonで学ぶ自然言語処理(NLP)

コードで見る BoW

reviews = ["I loved the movie. It was amazing!",
           "The movie was okay.",
           "I hated the movie. It was boring."]

def preprocess(text):
text = text.lower()
tokens = word_tokenize(text)
tokens = [word for word in tokens if word not in string.punctuation]
return " ".join(tokens)
cleaned_reviews = [preprocess(review) for review in reviews]
print(cleaned_reviews)
['i loved the movie it was amazing', 
 'the movie was okay', 
 'i hated the movie it was boring']
Pythonで学ぶ自然言語処理(NLP)

コードで見る BoW

from sklearn.feature_extraction.text import CountVectorizer


vectorizer = CountVectorizer()
vectorizer.fit(cleaned_reviews)
print(vectorizer.get_feature_names_out())
['amazing' 'boring' 'hated' 'it' 'loved' 'movie' 'okay' 'the' 'was']
Pythonで学ぶ自然言語処理(NLP)

BoW の出力

X = vectorizer.transform(cleaned_reviews)

# OR X = vectorizer.fit_transform(cleaned_reviews)
print(X)
<Compressed Sparse Row sparse matrix of dtype 'int64'
    with 16 stored elements and shape (3, 9)>

疎行列: ほとんどがゼロの表

Pythonで学ぶ自然言語処理(NLP)

BoW の出力

print(X.toarray())
[[1 0 0 1 1 1 0 1 1]
 [0 0 0 0 0 1 1 1 1]
 [0 1 1 1 0 1 0 1 1]]
print(vectorizer.get_feature_names_out())
['amazing' 'boring' 'hated' 'it' 'loved' 'movie' 'okay' 'the' 'was']
Pythonで学ぶ自然言語処理(NLP)

単語頻度

import numpy as np

word_counts = np.sum(X.toarray(), axis=0)
words = vectorizer.get_feature_names_out()
import matplotlib.pyplot as plt

plt.bar(words, word_counts)
plt.title("Word Frequencies in Movie Reviews")
plt.xlabel("Words") plt.ylabel("Frequency") plt.show()

ストップワードが最頻となる、単語と出現回数の棒グラフ。

Pythonで学ぶ自然言語処理(NLP)

練習してみましょう!

Pythonで学ぶ自然言語処理(NLP)

Preparing Video For Download...