Sub topic 3
Measuring closeness: cosine similarity, dot product, and Euclidean distance
This chapter assumes you know basic Python, can compute a dot product and a vector length, and know that an embedding is a list of numbers representing a text. Here you will learn the three common ways to score how close two embeddings are, and how to pick one.
Three ways to compare vectors
Each metric answers a slightly different question about two vectors a and b.
- Dot product: multiply matching entries and add them up. It grows with both the angle agreement and the lengths of the vectors.
- Cosine similarity: the dot product divided by the product of the two lengths. It measures only the angle between the vectors. It ranges from -1 to 1.
- Euclidean distance: the straight-line distance between the two points. Smaller means closer, so it works in the opposite direction from the other two.
| Metric | Formula | Better when | Sensitive to length |
|---|---|---|---|
| Dot product | a · b | larger | yes |
| Cosine similarity | a · b / (‖a‖ ‖b‖) | larger | no |
| Euclidean distance | ‖a − b‖ | smaller | yes |
Cosine similarity in code
Cosine similarity compares direction and ignores length. A vector and a scaled copy of it score 1.0, and orthogonal vectors score 0.0.
import numpy as np
def cosine_similarity(a, b):
return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)))
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
c = np.array([-3.0, 0.0, 1.0]) # orthogonal to a (dot product is 0)
print(round(cosine_similarity(a, b), 3)) # 1.0
print(round(cosine_similarity(a, c), 3)) # 0.0Here b is twice as long as a, yet the score is still 1.0. The dot product of a and b is 28, while the dot product of a with itself is 14. The dot product rewards the longer vector, and cosine does not.
Why the metrics often agree
If every vector has length 1 (unit length), the three metrics rank results identically. Then the cosine similarity equals the dot product, because both lengths in the denominator are 1. The squared Euclidean distance becomes 2 - 2 * (a · b), so a higher dot product always means a smaller distance.
This is why many embedding libraries offer a normalization option. After normalizing, you can use the dot product, which is the cheapest of the three to compute and is a single matrix operation across a whole collection.
Choosing a metric
- Use the metric the embedding model was trained with. The model's documentation usually says which one.
- If the model outputs unit-length vectors, or you normalize them, use the dot product. The result is the same as cosine similarity.
- If vector length carries meaning, such as a model that encodes confidence or popularity in the length, use the dot product on the raw vectors.
- Use Euclidean distance when your index or tool only supports distance, and remember that lower is better.
Common errors
- Sorting in the wrong direction. Similarity scores are sorted high to low. Distances are sorted low to high.
- Mixing normalized and raw vectors. If documents are normalized but queries are not, dot-product scores are scaled by the query length. Rankings for a single query stay the same, but scores cannot be compared across queries.
- Dividing by zero. A vector of all zeros has length 0, so cosine similarity is undefined. Check for empty or failed inputs.
- Reading scores as probabilities. A cosine score of 0.7 does not mean 70% relevant. Scores depend on the model, so compare them only within one model.
Exercise
Two embeddings are both normalized to unit length. The dot product of a query with document A is 0.82, and with document B it is 0.64. Which document is closer to the query by cosine similarity, and which is closer by Euclidean distance?
Show answer
Document A is closer by both measures. For unit vectors, cosine similarity equals the dot product, so A scores 0.82 against 0.64. The squared Euclidean distance is 2 - 2 * (dot product), which is 0.36 for A and 0.72 for B. The smaller distance belongs to A.
Exercise
A vector x has length 5. You compute the dot product of x with a vector y and with 3 * y. How do the dot product and the cosine similarity change?
Show answer
The dot product triples, because it scales with the length of y. The cosine similarity does not change, because 3 * y points in the same direction as y and cosine ignores length.