728x90
1.코사인 유사도
두 벡터 간의 유사도를 측정하는 방법으로, 두 벡터의 방향이 얼마나 유사한지를 나타낸다.
코사인 유사도는 벡터의 크기(길이)에는 영향을 받지 않으며, 오로지 벡터 간의 각도에 따라 유사도를 계산한다.
코사인 유사도가 높다면 두 문서의 유사도가 높다는것을 의미한다.
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from numpy import dot
from numpy.linalg import norm
def cos_sim(A, B):
return dot(A, B)/(norm(A)*norm(B))
corpus = [
"hello my name is hello hello",
"my name is John",
"hello John my name"
]
#TF-IDF
tfidfv = TfidfVectorizer().fit(corpus)
tfidfArr=tfidfv.transform(corpus).toarray()
print(tfidfArr)
print(tfidfv.vocabulary_)
#cos_sim 유사도
print("유사도:",cos_sim(tfidfArr[0],tfidfArr[1]))
#결과
[[0.89617418 0.29872473 0. 0.2319864 0.2319864 ]
[0. 0.55847784 0.55847784 0.43370786 0.43370786]
[0.55847784 0. 0.55847784 0.43370786 0.43370786]]
{'hello': 0, 'my': 3, 'name': 4, 'is': 1, 'john': 2}
유사도: 0.3680597872639026
728x90
'AI' 카테고리의 다른 글
[AI] 머신 러닝(Machine Learning) 용어 (2) | 2024.12.27 |
---|---|
[AI] Bag of Words (1) | 2024.12.27 |
[AI] 국소 표현(Local Representation),분산 표현(Distributed Representation) (0) | 2024.12.27 |