텍스트 기반 유사도

Python으로 추천 엔진 만들기

Rob O'Callaghan

Director of Data

명확한 속성 없이 작업하기

아마존의 상품 설명 예시.

Python으로 추천 엔진 만들기

TF-IDF (단어 빈도-역문서 빈도)

$$ \Large{\text{TF-IDF} = \frac{\frac{\text{Count of word occurrences}}{\text{Total words in document}}}{\log({\frac{\text{Number of docs word is in}}{\text{Total number of docs}}})}} $$

Python으로 추천 엔진 만들기

데이터 소개

book_summary_df:

Book Description
The Hobbit "Bilbo Baggins lives a simple life with his fellow hobbits in the shire..."
The Great Gatsby "Set in Jazz Age New York, the novel tells the tragic story of Jay ..."
A Game of Thrones "15 years have passed since Robert's rebellion, with a nine-year-long ..."
Macbeth "A brave Scottish general receives a prophecy from a trio of witches ..."
... ...
Python으로 추천 엔진 만들기

벡터라이저 인스턴스화

from sklearn.feature_extraction.text import TfidfVectorizer
tfidfvec = TfidfVectorizer(        ,           )
Python으로 추천 엔진 만들기

데이터 필터링

from sklearn.feature_extraction.text import TfidfVectorizer
tfidfvec = TfidfVectorizer(min_df=2,           )
Python으로 추천 엔진 만들기

데이터 필터링

from sklearn.feature_extraction.text import TfidfVectorizer
tfidfvec = TfidfVectorizer(min_df=2, max_df=0.7)
Python으로 추천 엔진 만들기

데이터 벡터화

vectorized_data = tfidfvec.fit_transform(book_summary_df['Descriptions'])

print(tfidfvec.get_feature_names)
['age', 'ancient', 'angry', 'brave', 'battle', 'fellow', 'game', 'general', ...]
print(vectorized_data.to_array())
[[0.21,      0.53,    0.41,    0.64,     0.01,     0.02,     ...
 [0.31,      0.00,    0.42,    0.03,     0.00,     0.73,     ...
 [...,        ...,     ...,     ...,      ...,      ...,     ...
Python으로 추천 엔진 만들기

데이터 정리

tfidf_df = pd.DataFrame(vectorized_data.toarray(),
                        columns=tfidfvec.get_feature_names())

tfidf_df.index = book_summary_df['Book']
print(tfidf_df)
                   | 'age'| 'ancient'| 'angry'| 'brave'| 'battle'| 'fellow'|...
|------------------|------|----------|--------|--------|---------|---------|...
| The Hobbit       |  0.21|      0.53|    0.41|    0.64|     0.01|     0.02|...
| The Great Gatsby |  0.31|      0.00|    0.42|    0.03|     0.00|     0.73|...
| A Game of Thrones|  0.61|      0.42|    0.77|    0.31|     0.83|     0.03|...
|               ...|   ...|       ...|     ...|     ...|      ...|      ...|...
Python으로 추천 엔진 만들기

코사인 유사도

코사인 거리: $$cos(\theta)=\frac{A.B }{||A||\cdot||B||}$$

Python으로 추천 엔진 만들기

코사인 유사도

from sklearn.metrics.pairwise import cosine_similarity

# 모든 항목 간 유사도 계산
cosine_similarity_array = cosine_similarity(tfidf_summary_df)
# 두 항목 간 유사도 계산
cosine_similarity(tfidf_df.loc['The Hobbit'].values.reshape(1, -1),
                  tfidf_df.loc['Macbeth'].values.reshape(1, -1))
Python으로 추천 엔진 만들기

연습해 봅시다!

Python으로 추천 엔진 만들기

Preparing Video For Download...