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...