建立 tf-idf 文件向量

Python 中文本特徵工程

Rounak Banik

Data Scientist

n-gram 建模

  • 各維度權重取決於該詞在該維度的出現頻率。
    • 文件中 human 出現 5 次。
    • 對應 human 的維度權重為 5
Python 中文本特徵工程

動機

  • 有些詞在所有文件中都很常見。
  • 主題為宇宙的文件語料庫。
    • 其中一份文件中 jupiteruniverse 各出現 20 次。
    • jupiter 在其他文件中很少見,universe 很常見。
    • 因為較具排他性,給 jupiter 較高權重。
Python 中文本特徵工程

應用

  • 自動偵測停用詞
  • 搜尋
  • 推薦系統
  • 在部分預測模型中表現更佳
Python 中文本特徵工程

詞頻-逆文件頻率(tf-idf)

  • 與詞頻成正比
  • 與其出現在多少文件中成反比
Python 中文本特徵工程

數學公式

$$\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 中文本特徵工程

數學公式

$$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 中文本特徵工程

數學公式

$$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 中文本特徵工程

數學公式

$$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 中文本特徵工程

使用 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 中文本特徵工程

一起來練習吧!

Python 中文本特徵工程

Preparing Video For Download...