Sub topic 2
Measuring similarity: cosine, dot product and Euclidean distance
This chapter assumes you can read basic Python with NumPy, know what a dot product is, and have a general idea of what an embedding is. Here you will learn the three common ways to score how close two vectors are, and how to pick one for a given embedding model.
The three metrics
Every vector search needs a rule for "close". Three rules cover most systems.
- Euclidean distance (L2) is the straight-line distance between two points. Smaller means more similar.
- Dot product multiplies matching components and adds them up. Larger means more similar.
- Cosine similarity is the dot product divided by the product of the two vector lengths. It measures the angle between vectors and ignores their length. It ranges from -1 to 1, and larger means more similar.
import numpy as np
a = np.array([1.0, 2.0, 3.0])
b = np.array([2.0, 4.0, 6.0]) # same direction as a, twice as long
l2 = np.linalg.norm(a - b)
dot = a @ b
cosine = dot / (np.linalg.norm(a) * np.linalg.norm(b))
print(f"L2 distance: {l2:.3f}")
print(f"dot product: {dot:.3f}")
print(f"cosine: {cosine:.3f}")The two vectors point the same way, so cosine is 1.0. Their L2 distance is still about 3.74 because they differ in length. This is the key difference: cosine ignores length, while L2 and the dot product do not.
Normalization makes them agree
If every vector has length 1 (is normalized), the three metrics rank results in the same order. For unit vectors, the squared L2 distance equals 2 - 2 × (dot product), and the dot product equals cosine similarity. A smaller L2 distance therefore always means a larger dot product.
import numpy as np
rng = np.random.default_rng(1)
vectors = rng.normal(size=(500, 32))
query = rng.normal(size=32)
unit = lambda x: x / np.linalg.norm(x, axis=-1, keepdims=True)
v, q = unit(vectors), unit(query)
by_dot = np.argsort(-(v @ q))[:5]
by_l2 = np.argsort(np.linalg.norm(v - q, axis=1))[:5]
print(by_dot, by_l2, (by_dot == by_l2).all())The script prints True. Normalizing once at write time lets you use the dot product, which is the cheapest of the three to compute, and still get cosine rankings.
Choosing a metric
| Situation | Metric | Reason |
|---|---|---|
| Model documentation says "cosine" or outputs unit-length vectors | Cosine or dot product | Same ranking, dot product is faster |
| Model trained with a dot-product objective, vector length carries meaning (for example, popularity in a recommender) | Dot product | Normalizing would discard that signal |
| Features are coordinates where absolute distance matters (for example, image descriptors) | Euclidean | Matches how the model was trained |
The simplest rule is to use the metric the embedding model was trained with. Its documentation usually says which one.
Common errors
- Mixing metrics between index and query. An index built for L2 and queried as if it were cosine returns plausible but wrong results, and nothing raises an error.
- Forgetting that distance and similarity point opposite ways. Cosine similarity is sorted descending, while L2 distance is sorted ascending. pgvector's
<=>operator returns cosine distance, which is 1 minus cosine similarity, so it sorts ascending. - Using the dot product on unnormalized vectors by accident. Long vectors win regardless of direction.
- Normalizing a zero vector. The length is 0, so the division produces NaN values. Check for empty or all-zero inputs.
Exercise
Your embedding model returns vectors of varying length, and its documentation says to compare them with cosine similarity. You want to use a fast dot-product index. What do you do, and why does it work?
Show answer
Normalize every vector to length 1 before inserting it, and normalize each query too. For unit vectors the dot product equals cosine similarity, so the dot-product index returns the same ranking that cosine would.
Exercise
Vectors a = [3, 0] and b = [1, 0] are compared. Which metric says they are identical, and which says they differ?
Show answer
Cosine similarity says they are identical (1.0) because they point in the same direction. Euclidean distance says they differ (distance 2), and the dot product (3) also depends on their lengths.