Bag-of-Words モデルの構築

Pythonで学ぶNLPの特徴量エンジニアリング

Rounak Banik

Data Scientist

ML 用データ形式の要点

任意の ML アルゴリズムでは、

  • データは表形式であること
  • 学習特徴量は数値であること
Pythonで学ぶNLPの特徴量エンジニアリング

Bag-of-Words モデル

  • 単語トークンを抽出
  • 単語トークンの頻度を算出
  • 頻度とコーパス語彙から単語ベクトルを作成
Pythonで学ぶNLPの特徴量エンジニアリング

Bag-of-Words モデルの例

コーパス

"The lion is the king of the jungle"
"Lions have lifespans of a decade"
"The lion is an endangered species"
Pythonで学ぶNLPの特徴量エンジニアリング

Bag-of-Words モデルの例

語彙a, an, decade, endangered, have, is, jungle, king, lifespans, lion, Lions, of, species, the, The

"The lion is the king of the jungle"
[0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 2, 1]
"Lions have lifespans of a decade"
[1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0]
"The lion is an endangered species"
[0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1]
Pythonで学ぶNLPの特徴量エンジニアリング

テキスト前処理

  • Lions, lionlion
  • The, thethe
  • 句読点なし
  • ストップワードなし
  • 語彙が小さくなる
  • 次元削減で性能向上に寄与
Pythonで学ぶNLPの特徴量エンジニアリング

sklearn での Bag-of-Words モデル

corpus = pd.Series([
    'The lion is the king of the jungle',
    'Lions have lifespans of a decade',
    'The lion is an endangered species'
])
Pythonで学ぶNLPの特徴量エンジニアリング

sklearn での Bag-of-Words モデル

# Import CountVectorizer
from sklearn.feature_extraction.text import CountVectorizer

# Create CountVectorizer object vectorizer = CountVectorizer()
# Generate matrix of word vectors bow_matrix = vectorizer.fit_transform(corpus) print(bow_matrix.toarray())
array([[0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 3],
       [0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0],
       [1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1]], dtype=int64)
Pythonで学ぶNLPの特徴量エンジニアリング

練習しましょう!

Pythonで学ぶNLPの特徴量エンジニアリング

Preparing Video For Download...