[핸즈온 추천시스템] TF-IDF란?

TF-IDF 에 대하여 알아보고, python을 활용해 직접 만들며 배워보도록 하겠습니다.

chrisjune
5 min readMay 31, 2023

용어정리

  • 도큐먼트는 문장으로, 키워드는 단어로 생각하면 이해가 쉽습니다.

정의

  • TF-IDF는 문장속 단어들이 얼마나 중요한지를 나타내는 통계 숫자값입니다.
  • 따라서 각 단어의 TF-IDF는 문장들에서 중요도를 배열 형태로 정의됩니다.

설명

df: document frequency

  • 해당 키워드가 전체 도큐먼트에서 존재하는지 유무의 합

idf: inverse of df

  • log(전체 도큐먼트 수 / df)

tf: term frequency

  • 해당 키워드가 각 도큐먼트에서 등장하는 빈도의 배열

tf-idf

  • tf 배열과 idf를 곱한 배열

실습(Python 으로 tf-idf 직접 계산)

from math import log10
# df: document frequency, 해당 키워드가 전체 도큐먼트에서 존재하는지 유무의 합
df_a = sum(["a" in d for d in data])
# idf: inverse of df, log(전체 도큐먼트 수 / df)
idf_a = log10(len(data)/df_a)
# tf: term frequency, 해당 키워드가 각 도큐먼트에서 등장하는 빈도의 배열
tf_a = [sum(["a" in i for i in d.split(" ")]) for d in data]
print(df_a, idf_a, tf_a)
# 1 0.47712125471966244 [2, 0, 0]

# tfidf: tf * idf
tfidf_a = [idf_a * i for i in tf_a]
print(tfidf_a)
# [0.9542425094393249, 0.0, 0.0]

실습(sklearn으로 tf-idf계산)
위의 계산을 을 쉽게 해주는게 scikit-learn 라이브러리에서 제공해주는 TfidfVectorizer 클래스입니다.

TfidfVectorizer에서는 기본적으로 도큐먼트의 토크나이징과 Stop word를 활용하여 의미가 적은 단어를 feature에서 제거합니다.

https://github.com/igorbrigadir/stopwords/blob/21fb2ef149216e3c8cac097975223604ae1e2310/en/scikitlearn.txt

data = [
"This is the first document",
"This document is the second document",
"And this is the third one",
"Is this the first document?",
"This is the fourth document",
"Another document, the fifth one",
"Yet another document, the sixth one",
"One more document, the seventh one",
"The last document, number eight",
"The final document, number nine"
]

df = pd.DataFrame(data, columns=['text'])
# 라이브러리 인스턴스화
from sklearn.feature_extraction.text import TfidfVectorizer
tfidf_vector = TfidfVectorizer()

# 데이터 임베딩
tfidf_matrix = tfidf_vector.fit_transform(df['text']).toarray()

# 임베딩된 데이터 피쳐명을 반환받음
tfidf_feature = tfidf_vector.get_feature_names_out()

# pd.DataFrame(tfidf_matrix, columns=tfidf_feature, index=df.index)
# tf-idf matrix를 활용하여 유사도 계산

from sklearn.metrics.pairwise import cosine_similarity
cos_df = pd.DataFrame(cosine_similarity(tfidf_matrix))

조금이라도 도움이 되셨으면 좋겠습니다. 감사합니다.

--

--