TF-IDF 向量化

Python 中的自然语言处理(NLP)

Fouad Trad

Machine Learning Engineer

从 BoW 到 TF-IDF

  • BoW 将所有词视为同等重要
  • TF-IDF 通过指出以下内容来改进:
    • 词在文档中出现的频次
    • 该词在语料中有多有意义

 

两句"我爱这门 NLP 课程""我喜欢这个项目"的 BoW 表示。

Python 中的自然语言处理(NLP)

TF-IDF

图示:TF-IDF 是 TF 与 IDF 的乘积。

Python 中的自然语言处理(NLP)

TF-IDF

图示:TF-IDF 是 TF 与 IDF 的乘积。

  • TF:词频(Term Frequency)
    • 某词在文档中出现的次数
Python 中的自然语言处理(NLP)

TF-IDF

图示:TF-IDF 是 TF 与 IDF 的乘积。

  • TF:词频(Term Frequency)
    • 某词在文档中出现的次数
  • IDF:逆文档频率(Inverse Document Frequency)
    • 该词在所有文档中有多罕见

 

  • 词只在一篇文档中出现而不在其他文档中出现 → 分数高
  • 词在每篇文档中都出现 → 分数低
Python 中的自然语言处理(NLP)

TF-IDF:代码示例

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

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)

TF-IDF:代码示例

from sklearn.feature_extraction.text import TfidfVectorizer

vectorizer = TfidfVectorizer()
tfidf_matrix = vectorizer.fit_transform(cleaned_reviews)
print(tfidf_matrix)
<Compressed Sparse Row 稀疏矩阵,dtype 为 'float64'
    含 16 个存储元素,形状为 (3, 9)>
Python 中的自然语言处理(NLP)

TF-IDF 输出

print(tfidf_matrix.toarray())
[[0.52523431 0.         0.         0.39945423 0.52523431 0.31021184   0.         0.31021184 0.31021184]
 [0.         0.         0.         0.         0.         0.41285857   0.69903033 0.41285857 0.41285857]
 [0.         0.52523431 0.52523431 0.39945423 0.         0.31021184   0.         0.31021184 0.31021184]]
vectorizer.get_feature_names_out()
['amazing' 'boring' 'hated' 'it' 'loved' 'movie' 'okay' 'the' 'was']
Python 中的自然语言处理(NLP)

热力图可视化分数

import pandas as pd

df_tfidf = pd.DataFrame(

tfidf_matrix.toarray(),
columns=vectorizer.get_feature_names_out() )
import seaborn as sns
import matplotlib.pyplot as plt

sns.heatmap(df_tfidf, annot=True)
plt.title("不同评论的 TF-IDF 分数") plt.xlabel("术语") plt.ylabel("文档") plt.show()

 

数据集的 TF-IDF 表示的热力图。

Python 中的自然语言处理(NLP)

与 BoW 对比

 

数据集的 BoW 表示的热力图。

 

数据集的 TF-IDF 表示的热力图。

Python 中的自然语言处理(NLP)

让我们来练习!

Python 中的自然语言处理(NLP)

Preparing Video For Download...