Workspace IndexMath › Day 19

Dot Product, Norm, Cosine Similarity TODO

Math · Day 19 / 52 · September — Linear Algebra (Day 18-26)

Concept

The dot product of two vectors is defined as the sum of the products of corresponding components, and geometrically it equals the product of the two vectors' magnitudes times the cosine of the angle between them. A norm is a function measuring vector magnitude: the L2 norm is the square root of the dot product of a vector with itself, L1 is the sum of the absolute values of the components, and L∞ is the maximum absolute value. The Cauchy-Schwarz inequality says the absolute value of the dot product never exceeds the product of the two norms, which is exactly why dividing the dot product by the two norms always gives a value between -1 and 1, making cosine similarity well-defined. Cosine similarity ignores vector magnitude and compares direction only, so it's used instead of Euclidean distance when you want to exclude differences in document length or scale. A dot product of zero means orthogonality, which is the starting point for concepts like projection and least squares.

Practical problems like embedding search, similarity ranking, and how results change depending on whether you normalize, ultimately come down to which norm you're measuring with and whether you normalized magnitude.

Code & Formula

# 내적·노름·코사인 유사도 — L1/L2/L∞ 노름, 코사인 유사도, 코시-슈바르츠 부등식을 확인한다.

import numpy as np

u = np.array([3.0, 4.0, 0.0])
v = np.array([1.0, 2.0, 2.0])

dot = np.dot(u, v)
print(f"u={u}, v={v}")
print(f"내적 u·v = {dot}")

l1 = np.linalg.norm(u, 1)
l2 = np.linalg.norm(u, 2)
linf = np.linalg.norm(u, np.inf)
print(f"\nu의 노름: L1={l1}, L2={l2}, L∞={linf}")

cos_sim = dot / (np.linalg.norm(u) * np.linalg.norm(v))
print(f"\n코사인 유사도 cos(u,v) = {cos_sim:.4f}")

# 코시-슈바르츠: |u·v| <= ||u|| * ||v||  → 이 부등식 덕분에 cos_sim이 항상 [-1, 1] 안에 있다
cauchy_schwarz_bound = np.linalg.norm(u) * np.linalg.norm(v)
print(f"|u·v| = {abs(dot):.4f}  <=  ||u||*||v|| = {cauchy_schwarz_bound:.4f} ? {abs(dot) <= cauchy_schwarz_bound}")

# 크기가 다른 두 벡터라도 방향이 같으면 코사인 유사도는 1
w = u * 10  # u와 방향은 같고 크기만 10배
print(f"\nw = 10*u 의 코사인 유사도(u,w) = {np.dot(u, w) / (np.linalg.norm(u) * np.linalg.norm(w)):.4f} → 스케일 무시, 방향만 비교")

Exercise

For the same dataset, implement Euclidean-distance nearest neighbors and cosine-similarity nearest neighbors separately, and check how the results change before and after normalizing vectors to unit norm.

Practical Connection

This is used directly when clustering similar wallets by on-chain address behavior vectors or wiring up log/document search, and more generally it underlies predictive models like least squares and regression.

If you study this on a given day, add a note link and a ✅ to this line in the source curriculum (docs/knowledge/math-50-curriculum.md) and this spot will lead straight to the note body. You can also write directly on this page — but regenerating overwrites it, so it's safer to keep anything you want to save as markdown under docs/algorithms/.


한국어

내적·노름·코사인 유사도 TODO

Math · Day 19 / 52 · 9월 — 선형대수 (Day 18–26)

개념

두 벡터의 내적은 대응 성분의 곱의 합으로 정의되며, 기하적으로는 두 벡터 크기의 곱에 사잇각의 코사인을 곱한 값과 같다. 노름은 벡터의 크기를 재는 함수로, L2 노름은 자기 자신과의 내적의 제곱근이고 L1은 성분 절댓값의 합, L∞는 최대 절댓값이다. 코시-슈바르츠 부등식은 내적의 절댓값이 두 노름의 곱을 넘지 못한다고 말하며, 이 덕분에 내적을 두 노름으로 나눈 값이 항상 -1과 1 사이에 있어 코사인 유사도가 잘 정의된다. 코사인 유사도는 벡터의 크기를 무시하고 방향만 비교하므로, 문서 길이나 스케일 차이를 배제하고 싶을 때 유클리드 거리 대신 쓴다. 내적이 0이면 직교이며, 이는 사영과 최소제곱 같은 개념의 출발점이다.

임베딩 검색, 유사도 랭킹, 정규화 여부에 따른 결과 차이 같은 실무 문제는 결국 '어떤 노름으로 재고 크기를 정규화했는가'로 갈린다.

코드 · 수식

# 내적·노름·코사인 유사도 — L1/L2/L∞ 노름, 코사인 유사도, 코시-슈바르츠 부등식을 확인한다.

import numpy as np

u = np.array([3.0, 4.0, 0.0])
v = np.array([1.0, 2.0, 2.0])

dot = np.dot(u, v)
print(f"u={u}, v={v}")
print(f"내적 u·v = {dot}")

l1 = np.linalg.norm(u, 1)
l2 = np.linalg.norm(u, 2)
linf = np.linalg.norm(u, np.inf)
print(f"\nu의 노름: L1={l1}, L2={l2}, L∞={linf}")

cos_sim = dot / (np.linalg.norm(u) * np.linalg.norm(v))
print(f"\n코사인 유사도 cos(u,v) = {cos_sim:.4f}")

# 코시-슈바르츠: |u·v| <= ||u|| * ||v||  → 이 부등식 덕분에 cos_sim이 항상 [-1, 1] 안에 있다
cauchy_schwarz_bound = np.linalg.norm(u) * np.linalg.norm(v)
print(f"|u·v| = {abs(dot):.4f}  <=  ||u||*||v|| = {cauchy_schwarz_bound:.4f} ? {abs(dot) <= cauchy_schwarz_bound}")

# 크기가 다른 두 벡터라도 방향이 같으면 코사인 유사도는 1
w = u * 10  # u와 방향은 같고 크기만 10배
print(f"\nw = 10*u 의 코사인 유사도(u,w) = {np.dot(u, w) / (np.linalg.norm(u) * np.linalg.norm(w)):.4f} → 스케일 무시, 방향만 비교")

연습

같은 데이터에 대해 유클리드 거리 기반 최근접 이웃과 코사인 유사도 기반 최근접 이웃을 각각 구현해, 벡터를 단위 노름으로 정규화하기 전후로 결과가 어떻게 바뀌는지 확인하라.

실무 · Verex 연결

온체인 주소 행동 벡터로 유사 지갑을 묶거나 로그·문서 검색을 붙일 때 직접 쓰이고, 더 일반적으로는 최소제곱·회귀 같은 예측 모델의 기반 연산이다.

공부한 날 원본 커리큘럼(docs/knowledge/math-50-curriculum.md)의 이 줄에 노트 링크와 ✅ 를 붙이면, 이 자리는 노트 본문으로 바로 이어집니다. 노트 없이 이 페이지에 바로 적어도 됩니다 — 다만 다시 생성하면 덮어쓰이므로, 남길 글은 docs/algorithms/ 의 마크다운으로 쓰는 편이 안전합니다.

← 18. 벡터·행렬·행렬곱·역행렬20. 유한체 GF(p) 위 선형대수 (12월 다리, 스레드 A) →