본문 바로가기

Python/AI 수학 with Python

[Python] 코사인 유사도 구현

< 참고 자료 >

벡터의 내적 표시

https://taichi1.tistory.com/19

 

[Python] 벡터의 내적 표시

numpy의 dot() 함수로 간단하게 구현을 할 수 있다. 또한, 각각의 요소를 곱한 후 더하는 방식으로도 구현을 할 수 있다. [In] import numpy as np a = np.array([1, 2, 3]) b = np.array([3, 2, 1]) print('------ dot() 함수 --

taichi1.tistory.com

Norm 구현

https://taichi1.tistory.com/20

 

[Python] Norm 구현

놈은 벡터의 크기를 나타내는 양이다. numpy의 linalg.norm() 함수를 이용해 다양한 놈을 구연할 수 있다. [In] import numpy as np a = np.array([1, -1, 1, -1]) print('----- L2놈 -----') print(np.linalg.norm(a)) # L2놈(디폴트)

taichi1.tistory.com

 

numpy의 dot() 함수와 norm() 함수를 이용해 코사인 유사도를 구할 수 있다.

[In]

# 코사인 유사도
import numpy as np

def cos_sim(vec_1, vec_2):
    return np.dot(vec_1, vec_2) / (np.linalg.norm(vec_1) * np.linalg.norm(vec_2))

a = np.array([2, 2, 2, 2])
b = np.array([1, 1, 1, 1])
c = np.array([0, 1, 0, 2])
d = np.array([-1, -1, -1, -1])

print('--- a와 b의 코사인 유사도 ---')
print(cos_sim(a,b))
print('--- a와 c의 코사인 유사도 ---')
print(cos_sim(a,c))
print('--- a와 d의 코사인 유사도 ---')
print(cos_sim(a,d))

[Out]

--- a와 b의 코사인 유사도 ---
1.0
--- a와 c의 코사인 유사도 ---
0.6708203932499369
--- a와 d의 코사인 유사도 ---
-1.0

a와 b는 방향이 일치하는 것을 알 수 있고, 반대로 a와 d는 방향이 반대인 것을 알 수 있다.