tf-idf 文書ベクトルの構築

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

Rounak Banik

Data Scientist

n-gram モデリング

  • 次元の重みは、その次元に対応する語の頻度に依存
    • 文書内に human が5回出現
    • human に対応する次元の重みは 5
Pythonで学ぶNLPの特徴量エンジニアリング

動機

  • 一部の語は全ての文書で非常によく出現
  • 宇宙に関するコーパス
    • ある文書では jupiteruniverse が各20回出現
    • jupiter は他文書では稀、universe は一般的
    • 排他性から jupiter に高い重みを付与
Pythonで学ぶNLPの特徴量エンジニアリング

応用

  • ストップワードの自動検出
  • 検索
  • レコメンダシステム
  • 一部の予測モデリングで性能向上
Pythonで学ぶNLPの特徴量エンジニアリング

TF-IDF(単語頻度—逆文書頻度)

  • 語頻度に比例
  • 出現する文書数に反比例
Pythonで学ぶNLPの特徴量エンジニアリング

数式

$$\red{w_{i,j}} = tf_{i,j} \cdot \log\left(\frac{N}{df_{i}}\right) $$

$$\red{w_{i,j}} \rightarrow \text{語 } i \text{ の文書 } j \text{ における重み}$$

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

数式

$$w_{i,j} = \red{tf_{i,j}} \cdot \log\left(\frac{N}{df_{i}}\right) $$

$$w_{i,j} \rightarrow \text{語 } i \text{ の文書 } j \text{ における重み}$$

$$\red{tf_{i,j}} \rightarrow \text{語 } i \text{ の文書 } j \text{ における出現頻度} $$

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

数式

$$w_{i,j} = tf_{i,j} \cdot \red{\log\left(\frac{N}{df_{i}}\right)} $$

$$w_{i,j} \rightarrow \text{語 } i \text{ の文書 } j \text{ における重み}$$

$$tf_{i,j} \rightarrow \text{語 } i \text{ の文書 } j \text{ における出現頻度} $$

$$\red{N} \rightarrow \text{コーパス内の文書数} $$

$$\red{df_{i}} \rightarrow \text{語 } i \text{ を含む文書数}$$

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

数式

$$w_{i,j} = tf_{i,j} \cdot \log\left(\frac{N}{df_{i}}\right) $$

$$w_{i,j} \rightarrow \text{語 } i \text{ の文書 } j \text{ における重み}$$

$$tf_{i,j} \rightarrow term \; frequency \; of \; term \; i \; in \; document \; j $$

$$N \rightarrow number \; of \; documents \; in \; the \; corpus $$

$$df_{i} \rightarrow number \; of \; documents \; cotaining \; term \; i$$

例:

$\red{w_{library, document}} = 5 \cdot log(\frac{20}{8}) \approx 2 $

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

scikit-learn での tf-idf

# Import TfidfVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer

# Create TfidfVectorizer object vectorizer = TfidfVectorizer()
# Generate matrix of word vectors tfidf_matrix = vectorizer.fit_transform(corpus) print(tfidf_matrix.toarray())
[[0.         0.         0.         0.         0.25434658 0.33443519
  0.33443519 0.         0.25434658 0.         0.25434658 0.
  0.76303975]
 [0.         0.46735098 0.         0.46735098 0.         0.
  0.         0.46735098 0.         0.46735098 0.35543247 0.
  0.        ]
...
Pythonで学ぶNLPの特徴量エンジニアリング

Passons à la pratique !

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

Preparing Video For Download...