코사인 유사도

Python으로 배우는 NLP 피처 엔지니어링

Rounak Banik

Data Scientist

코사인 유사도

1 이미지 출처 techninpink.com
Python으로 배우는 NLP 피처 엔지니어링

내적

두 벡터를 가정합시다.

$$V = (v_1, v_2, \cdots, v_n), W = (w_1, w_2, \cdots, w_n)$$

V와 W의 내적은 다음과 같습니다.

$$V \cdot W = (v_1 \times w_1) + (v_2 \times w_2) + \cdots + (v_n \times w_n) $$

예:

$$A = (4, 7, 1) \; , \; B = (5, 2, 3)$$

$$A \cdot B = (4 \times 5) + (7 \times 2) + \cdots (1 \times 3)$$

$$= 20 + 14 + 3 = 37 \color{white}{A \cdot B d}$$

$$$$

Python으로 배우는 NLP 피처 엔지니어링

벡터의 크기

임의의 벡터에 대해,

$$V = (v_1, v_2, \cdots, v_n)$$

크기는 다음과 같이 정의합니다.

$$||\mathbf{V}|| = \sqrt{(v_1)^{2} + (v_2)^{2} + ... + (v_n)^{2}} $$

예:

$$A = (4, 7, 1) \; , \; B = (5, 2, 3)$$

$$||\mathbf{A}|| = \sqrt{(4)^{2} + (7)^{2} + (1)^{2}} $$

$$ \color{white}{filler} = \sqrt{16 + 49 + 1} = \sqrt{66}$$

$$

Python으로 배우는 NLP 피처 엔지니어링

코사인 점수

벡터 A와 B 사이의 각도

$$A: (4, 7, 1)$$

$$B: (5, 2, 3)$$

코사인 점수,

$$cos(A,B) = \frac{A \cdot B}{|A| \cdot |B|}$$

$$\color{white}{fillers lorem}= \frac{37}{\sqrt{66} \times \sqrt{38}}$$

$$\color{white}{fillers l}= 0.7388$$

Python으로 배우는 NLP 피처 엔지니어링

코사인 점수: 핵심 포인트

  • -1과 1 사이의 값
  • NLP에서는 0과 1 사이
  • 문서 길이에 강건함
Python으로 배우는 NLP 피처 엔지니어링

scikit-learn으로 구현

# Import the cosine_similarity
from sklearn.metrics.pairwise import cosine_similarity
# Define two 3-dimensional vectors A and B
A = (4,7,1)
B = (5,2,3)

# Compute the cosine score of A and B
score = cosine_similarity([A], [B])

# Print the cosine score
print(score)
array([[ 0.73881883]])
Python으로 배우는 NLP 피처 엔지니어링

연습해 봅시다!

Python으로 배우는 NLP 피처 엔지니어링

Preparing Video For Download...