Cosine Similarity
Comparing vector direction instead of magnitude — why it's the better similarity metric.
By the end of this chapter, you'll be able to:
- Explain why raw dot products are misled by vector length
- Compute cosine similarity by hand for small vectors
- Recognize when direction, not magnitude, is what actually matters
The Dot Product chapter ended with a warning: dot product mixes together direction and magnitude, so it can grow simply because a vector got longer, not because it became more related to anything. Cosine similarity fixes that by dividing the magnitude back out.
The formula
The numerator is the familiar dot product. The denominator is the product of each vector's magnitude (its length) — dividing by it cancels out scale entirely, leaving a number between and that depends only on the angle between the two vectors.
Seeing why this matters
Look at A and B above: B is just A scaled by 2 — same direction,
twice as long. Their dot product tells two very different stories depending on
which formula you use:
import numpy as np
A = np.array([3, 4])
B = np.array([6, 8]) # same direction as A, scaled by 2
D = np.array([4, -3]) # perpendicular to A
print(A @ B) # 50 (raw dot product)
print(A @ A) # 25 (A compared to itself)
norm_A = np.linalg.norm(A) # 5.0
norm_B = np.linalg.norm(B) # 10.0
cos_AB = (A @ B) / (norm_A * norm_B)
print(cos_AB) # 1.0 — perfectly aligned
cos_AD = (A @ D) / (norm_A * np.linalg.norm(D))
print(cos_AD) # 0.0 — perpendicularA @ B (50) is larger than A @ A (25) — the raw dot product makes it look like
B is "more related" to A than A is to itself, purely because B is longer.
Cosine similarity sees through that: cos(A, B) = 1.0, correctly identifying that
they point in exactly the same direction — the maximum possible similarity, tied
with A compared to itself.
Meanwhile A and D (drawn at a right angle above) have cos(A, D) = 0: zero
directional relationship, regardless of either vector's length.
Reading the range
Cosine similarity of 1 means identical direction. 0 means perpendicular — no
relationship. -1 means exactly opposite directions. Unlike a raw dot product, this
scale means the same thing no matter how long the underlying vectors are.
Check your understanding
1. A = [3, 4] and B = [6, 8]. What is cos(A, B)?
2. Why is cosine similarity generally preferred over raw dot product for comparing embeddings?