TF-IDF vectorization

การประมวลผลภาษาธรรมชาติ (NLP) ด้วย Python

Fouad Trad

Machine Learning Engineer

จาก BoW สู่ TF-IDF

  • BoW ถือว่าคำทุกคำมีความสำคัญเท่ากัน
  • TF-IDF แก้ปัญหานี้โดยบอกว่า:
    • คำนั้นปรากฏบ่อยแค่ไหนในเอกสาร
    • คำนั้นมีความหมายเพียงใดในภาพรวมของคอลเลกชัน

 

ภาพแสดงการแทนค่าแบบ BoW ของสองประโยค: 'I love this NLP course' และ 'I enjoyed this project.'

การประมวลผลภาษาธรรมชาติ (NLP) ด้วย Python

TF-IDF

ภาพแสดงว่า TF-IDF คือผลคูณของ TF และ IDF

การประมวลผลภาษาธรรมชาติ (NLP) ด้วย Python

TF-IDF

ภาพแสดงว่า TF-IDF คือผลคูณของ TF และ IDF

  • TF: Term Frequency
    • จำนวนครั้งที่คำปรากฏในเอกสาร
การประมวลผลภาษาธรรมชาติ (NLP) ด้วย Python

TF-IDF

ภาพแสดงว่า TF-IDF คือผลคูณของ TF และ IDF

  • TF: Term Frequency
    • จำนวนครั้งที่คำปรากฏในเอกสาร
  • IDF: Inverse Document Frequency
    • ความหายากของคำนั้นในเอกสารทั้งหมด

 

  • คำปรากฏในเอกสารเดียว ไม่พบในเอกสารอื่น → คะแนนสูง
  • คำปรากฏในทุกเอกสาร → คะแนนต่ำ
การประมวลผลภาษาธรรมชาติ (NLP) ด้วย Python

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']
การประมวลผลภาษาธรรมชาติ (NLP) ด้วย Python

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)>
การประมวลผลภาษาธรรมชาติ (NLP) ด้วย Python

ผลลัพธ์ 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']
การประมวลผลภาษาธรรมชาติ (NLP) ด้วย Python

แสดงคะแนนเป็น Heatmap

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()

 

Heatmap แสดงการแทนค่าแบบ TF-IDF ของชุดข้อมูล

การประมวลผลภาษาธรรมชาติ (NLP) ด้วย Python

เปรียบเทียบกับ BoW

 

Heatmap แสดงการแทนค่าแบบ BoW ของชุดข้อมูล

 

Heatmap แสดงการแทนค่าแบบ TF-IDF ของชุดข้อมูล

การประมวลผลภาษาธรรมชาติ (NLP) ด้วย Python

มาฝึกกันเถอะ!

การประมวลผลภาษาธรรมชาติ (NLP) ด้วย Python

Preparing Video For Download...