构建 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 特征工程

词频-逆文档频率

  • 与词频成正比
  • 与其出现的文档数成反比
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...