from sklearn.feature_extraction.text import TfidfVectorizer
doc_list = ['if you take the blue pill, the story ends',
'if you take the red pill, you stay in Wonderland',
'if you take the red pill, I show you how deep the rabbit hole goes']
tfidf_vect_simple = TfidfVectorizer()
feature_vect_simple = tfidf_vect_simple.fit_transform(doc_list)
print(feature_vect_simple.shape) #문장 3개, 피쳐 18개
print(type(feature_vect_simple))
[Out]
(3, 18) #문서 3개, 총 단어의 개수(중복 제거) 18개
<class 'scipy.sparse._csr.csr_matrix'>
[In] 희소행렬을 밀집행렬로 변화한 후 array로 변환
add check point! <희소 표현(Sparse Representation)> 문장을 벡터로 나타낼 때 대부분의 값이 0인 희소행렬 개념 이용 -> 표현하고자 하는 단어 1, 나머지 0 설정 단어의 수가 늘어나면 차원도 커지는 문제점 존재 <희소 행렬(Sparse Matrix)> 희소 행렬은 행렬의 원소 중에 많은 항들이 '0'으로 구성되어 있는 행렬로 실제 사용하지 않는 메모리 공간으로 인해 메모리 낭비가 발생하게 됨 희소 행렬을 가지고 learning 할시 잘 되지 않을 가능성이 있기에 NLP에서 사용하는 word/sentence embedding 등과 같이 차원 축소 과정으 통해 데이터를 밀집(dense)하게 만들 필요성이 존재함 <밀집 표현(Dense Representation)> 단어의 개수와 상관없이 사용자가 차원 값을 설정하기 때문에 차원 축소의 장점이 있음 특정 단어를 표현하기 위해 여러 특성을 고려하여 각 요소에 대한 정보가 실수로 표현됨
#앞에 정의한 cos_similarity() 함수의 인자인 array로 만들기 위해 밀집행렬로 변환 후 다시 배열로 변환해야 함
#TFidfVectorizer로 transform()한 결과는 희소행렬(Sparese Matrix)이므로 밀집행렬(Dense Matrix)로 변환
feature_vect_dense = feature_vect_simple.todense()
#첫번째 문장과 두번째 문장의 feature vector 추출한 후 1차원으로 변환
#첫번째 문장의 벡터
#np.array(feature_vect_dense[0]) ---> 2차원
#np.array(feature_vect_dense[0]).reshape(-1,) -----> 1차원
vect1 = np.array(feature_vect_dense[0]).reshape(-1,)
vect2 = np.array(feature_vect_dense[1]).reshape(-1,)
vect3 = np.array(feature_vect_dense[2]).reshape(-1,)
#첫번째 문장과 두번째 문장의 feature vector로 두개 문장의 Cosine 유사도 추출
similarity_simple = cos_similarity(vect1, vect2)
print('문장1, 문장 2 Cosine 유사도 : {0:.3f}'.format(similarity_simple))
#첫번째 문장과 세번째 문장의 feature vector로 두개 문장의 Cosine 유사도 추출
similarity_simple = cos_similarity(vect1, vect3)
print('문장1, 문서 3 Cosine 유사도 : {0:.3f}'.format(similarity_simple))
#두번째 문장과 세번째 문장의 feature vector로 두개 문장의 Cosine 유사도 추출
similarity_simple = cos_similarity(vect2, vect3)
print('문장2, 문장 3 Cosine 유사도 : {0:.3f}'.format(similarity_simple))
[Out]
문장1, 문장 2 Cosine 유사도 : 0.402
문장1, 문장 3 Cosine 유사도 : 0.404
문장2, 문장 3 Cosine 유사도 : 0.456
사이킷런의 cosine_similarity()함수를 이용하여 비교
[In]
from sklearn.metrics.pairwise import cosine_similarity
similarity_simple_pair = cosine_similarity(feature_vect_simple[0],
feature_vect_simple)
print(similarity_simple_pair)
# 1,1 / 1,2 / 1,3 문장 비교
from sklearn.metrics.pairwise import cosine_similarity
# cluster_label=2인 데이터는 호텔로 클러스터링된 데이터 DF에서 해당 Index를 추출
hotel_indexes = document_df[document_df['cluster_label']==2].index
print('호텔로 클러스터링 된 문서들의 DataFrame Index:', hotel_indexes)
# 호텔로 클러스터링된 데이터 중 첫번째 문서를 추출하여 파일명 표시.
comparison_docname = document_df.iloc[hotel_indexes[0]]['filename']
print('##### 비교 기준 문서명 ',comparison_docname,' 와 타 문서 유사도######')
''' document_df에서 추출한 Index 객체를 feature_vect로 입력하여 호텔 클러스터링된 feature_vect 추출
이를 이용하여 호텔로 클러스터링된 문서 중 첫번째 문서와 다른 문서간의 코사인 유사도 측정.'''
similarity_pair = cosine_similarity(feature_vect[hotel_indexes[0]] , feature_vect[hotel_indexes])
print(similarity_pair)
[Out]
호텔로 클러스터링 된 문서들의 DataFrame Index: Int64Index([1, 13, 14, 15, 20, 21, 24, 28, 30, 31, 32, 38, 39, 40, 45, 46], dtype='int64')
##### 비교 기준 문서명 bathroom_bestwestern_hotel_sfo 와 타 문서 유사도######
[[1. 0.0430688 0.05221059 0.06189595 0.05846178 0.06193118
0.03638665 0.11742762 0.38038865 0.32619948 0.51442299 0.11282857
0.13989623 0.1386783 0.09518068 0.07049362]]
문서 간 유사도 시각화
[In]
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
# argsort()를 이용 첫번째 문서와 타 문서간 유사도가 큰 순으로 정렬한 인덱스 반환하되 자기 자신은 제외.
sorted_index = similarity_pair.argsort()[:,::-1]
sorted_index = sorted_index[:, 1:]
print(sorted_index)
# 유사도가 큰 순으로 hotel_indexes를 추출하여 재 정렬.
print(hotel_indexes)
hotel_sorted_indexes = hotel_indexes[sorted_index.reshape(-1,)]
# 유사도가 큰 순으로 유사도 값을 재정렬하되 자기 자신은 제외
hotel_1_sim_value = np.sort(similarity_pair.reshape(-1,))[::-1]
hotel_1_sim_value = hotel_1_sim_value[1:]
# 유사도가 큰 순으로 정렬된 Index와 유사도값을 이용하여 파일명과 유사도값을 Seaborn 막대 그래프로 시각화
hotel_1_sim_df = pd.DataFrame()
hotel_1_sim_df['filename'] = document_df.iloc[hotel_sorted_indexes]['filename']
hotel_1_sim_df['similarity'] = hotel_1_sim_value
sns.barplot(x='similarity', y='filename',data=hotel_1_sim_df)
plt.title(comparison_docname)