C.W.K.
Stream
Lesson 03 of 06 · published

Cosine, Euclidean, Dot Product

~22 min · math, metrics

Level 0Scout
0 XP0/41 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

가까움을 재는 세 가지 방법

텍스트가 벡터가 되면 "얼마나 비슷해?" 는 "거리를 어떻게 재?" 로 바뀌어. 프로덕션에서 보는 답은 셋, 잘못 고르면 retrieval 품질이 조용히 떨어져.

Cosine similarity (텍스트 기본값)

두 벡터의 각도를 잼. 같은 방향 = 1, 반대 = -1, 직각 = 0. magnitude 무시해 — 문서 길이가 유사도에 bias 안 주게 하고 싶을 때 정확히 이게 필요해.

Euclidean distance (L2)

고차원 공간의 직선 거리. 작을수록 가까움. magnitude 가 의미를 가질 때 (frequency-weighted vector, normalize 안 한 이미지 임베딩) 유용.

Dot product (내적)

각도와 magnitude 한 숫자에 합쳐서. 단위 벡터에서는 cosine 과 같지만 normalize 가 없어서 GPU 에서 더 빨라. 추천 시스템에서 magnitude 로 인기도/중요도를 인코딩하려고 일부러 dot product 쓰기도 해.

요즘 텍스트 임베딩 모델은 거의 다 단위 벡터 출력

OpenAI, Voyage, Cohere, BGE, 대부분의 sentence-transformers 모델은 이미 L2 정규화된 벡터를 내. cosine, dot product, Euclidean 거리의 monotonic 함수가 다 같은 ranking 을 줘 — 본인 vector store 가 가장 효율적으로 지원하는 거 골라. 가정하기 전에 모델 카드 한 번 읽어.

Code

NumPy 로 세 메트릭·python
import numpy as np

def cosine(a, b):
    return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))

def euclidean(a, b):
    return np.linalg.norm(a - b)

def dot(a, b):
    return np.dot(a, b)

a = np.array([1.0, 0.0, 0.0])
b = np.array([0.9, 0.4, 0.0])
print('cosine    ', cosine(a, b))     # ~0.913
print('euclidean ', euclidean(a, b))  # 0.412
print('dot       ', dot(a, b))        # 0.9
본인 모델이 단위 벡터 내는지 확인·python
norms = np.linalg.norm(vecs, axis=1)
assert np.allclose(norms, 1.0, atol=1e-3), '임베딩이 L2 정규화 안 돼있음'

External links

Exercise

아무 sentence pair 5쌍 (관련 3, 무관 2) 으로. cosine, Euclidean, dot product 를 raw 와 L2 정규화 벡터 양쪽에서 계산. 단위 벡터에서는 세 메트릭 ranking 이 일치하는지 표로 확인.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.