TF-IDF 向量化

Python 的 Natural Language Processing(NLP)

Fouad Trad

Machine Learning Engineer

從 BoW 到 TF-IDF

  • BoW 將所有詞視為同等重要
  • TF-IDF 透過告訴你:
    • 一個詞在文件中出現的頻率
    • 該詞在整個語料中的重要性

 

顯示兩句的 BoW 表示:「I love this NLP course」與「I enjoyed this project.」

Python 的 Natural Language Processing(NLP)

TF-IDF

圖示 TF-IDF 是 TF 與 IDF 的乘積。

Python 的 Natural Language Processing(NLP)

TF-IDF

圖示 TF-IDF 是 TF 與 IDF 的乘積。

  • TF:Term Frequency(詞頻)
    • 詞在文件中出現的次數
Python 的 Natural Language Processing(NLP)

TF-IDF

圖示 TF-IDF 是 TF 與 IDF 的乘積。

  • TF:Term Frequency(詞頻)
    • 詞在文件中出現的次數
  • IDF:Inverse Document Frequency(逆文件頻率)
    • 詞在所有文件中有多罕見

 

  • 詞只在某一文件出現、不在其他文件出現 → 分數高
  • 詞在每份文件都出現 → 分數低
Python 的 Natural Language Processing(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 的 Natural Language Processing(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 sparse matrix of dtype 'float64'
    with 16 stored elements and shape (3, 9)>
Python 的 Natural Language Processing(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 的 Natural Language Processing(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 Scores Across Reviews") plt.xlabel("Terms") plt.ylabel("Documents") plt.show()

 

此資料集 TF-IDF 表示的熱度圖。

Python 的 Natural Language Processing(NLP)

與 BoW 比較

 

此資料集 BoW 表示的熱度圖。

 

此資料集 TF-IDF 表示的熱度圖。

Python 的 Natural Language Processing(NLP)

一起來練習吧!

Python 的 Natural Language Processing(NLP)

Preparing Video For Download...