Sub topic 3
Measuring closeness: cosine similarity, dot product, and Euclidean distance
This chapter assumes you know basic Python and NumPy, the dot product and vector length, and that an embedding is a vector that represents a text. You will learn the three standard ways to score how close two embeddings are, how they relate, and which one to pick.
Why you need a closeness score
Semantic search embeds a query and every document, then ranks documents by how close their vectors are to the query vector. The ranking depends on the score you choose. Three scores cover almost every system: cosine similarity, dot product, and Euclidean distance.
A score can be a similarity, where higher means closer, or a distance, where lower means closer. Mixing these up is a common source of reversed search results. This chapter labels each metric as one or the other.
The three metrics
Let a and b be two vectors with the same number of dimensions.
Dot product
The dot product multiplies matching components and sums them:
a · b = a₁b₁ + a₂b₂ + … + aₙbₙ
It is a similarity. It grows when the vectors point the same way, and it also grows with the length of either vector. Doubling the length of b doubles the score.
Cosine similarity
Cosine similarity divides the dot product by the product of the vector lengths:
cos(a, b) = (a · b) / (‖a‖ ‖b‖)
It is the cosine of the angle between the vectors, and it is a similarity. The range is −1 to 1. A score of 1 means the same direction, 0 means orthogonal (at a right angle), and −1 means opposite directions. Length cancels out, so only direction matters.
Cosine distance is defined as 1 − cos(a, b). Libraries often report this form. It is a distance, so lower means closer.
Euclidean distance
Euclidean distance is the straight-line distance between the two points:
‖a − b‖ = √((a₁−b₁)² + … + (aₙ−bₙ)²)
It is a distance. A value of 0 means identical vectors, and larger values mean farther apart. Both direction and length affect it. Many libraries also use the squared distance, which avoids the square root and gives the same ranking.
Computing all three
The vectors below are the same ones used in the chapter on embeddings: b is a scaled by 2, and c is orthogonal to a.
import numpy as np
def dot(a, b):
return float(np.dot(a, b))
def cosine_similarity(a, b):
return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)))
def euclidean(a, b):
return float(np.linalg.norm(a - 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
for name, other in [("b", b), ("c", c)]:
print(
f"a vs {name}: dot={dot(a, other):.3f} "
f"cosine={cosine_similarity(a, other):.3f} "
f"euclidean={euclidean(a, other):.3f}"
)The output is:
a vs b: dot=28.000 cosine=1.000 euclidean=3.742
a vs c: dot=0.000 cosine=0.000 euclidean=4.899Cosine says b is a perfect match for a, because it has the same direction. Euclidean distance says b is 3.742 away, because it is longer. The dot product is 28, a number with no fixed scale. You cannot tell from 28 alone whether that is high or low. Cosine always gives you a number between −1 and 1.
Why the metrics can disagree
The three metrics rank documents differently when vector lengths vary. Here a query points along the x-axis. Document x is long and points diagonally. Document y is short and points almost exactly along the query.
import numpy as np
q = np.array([1.0, 0.0])
docs = {
"x": np.array([3.0, 3.0]), # long, 45 degrees away from q
"y": np.array([1.0, 0.1]), # short, nearly parallel to q
}
for name, d in docs.items():
dot_score = np.dot(q, d)
cos_score = dot_score / (np.linalg.norm(q) * np.linalg.norm(d))
dist = np.linalg.norm(q - d)
print(f"{name}: dot={dot_score:.3f} cosine={cos_score:.3f} euclidean={dist:.3f}")The output is:
x: dot=3.000 cosine=0.707 euclidean=3.606
y: dot=1.000 cosine=0.995 euclidean=0.100The dot product ranks x first because x is long. Cosine and Euclidean distance rank y first. When vector length carries no meaning for your task, the dot product gives a misleading ranking.
Unit vectors make the metrics agree
A unit vector has length 1. If you divide every vector by its own length, a process called normalization, the three metrics become equivalent for ranking. For unit vectors:
- ‖a‖ = ‖b‖ = 1, so cos(a, b) = a · b. Cosine and dot product are the same number.
- ‖a − b‖² = ‖a‖² + ‖b‖² − 2(a · b) = 2 − 2 cos(a, b). Squared Euclidean distance is a decreasing function of cosine similarity.
The second identity means that sorting by smallest distance gives exactly the same order as sorting by largest cosine. You can check this numerically:
import numpy as np
rng = np.random.default_rng(42)
a = rng.standard_normal(384)
b = rng.standard_normal(384)
a /= np.linalg.norm(a) # scale to unit length
b /= np.linalg.norm(b)
cos = np.dot(a, b)
sq_dist = np.sum((a - b) ** 2)
print(np.isclose(sq_dist, 2 - 2 * cos)) # TrueThis is why the semantic search code in this tutorial encodes with normalize_embeddings=True and then scores with a plain matrix product. The dot product of unit vectors is cosine similarity, and a dot product is the fastest operation to run on a whole collection.
| Metric | Type | Range for unit vectors | Affected by vector length | Ranking on unit vectors |
|---|---|---|---|---|
| Dot product | Similarity | −1 to 1 | Yes | Same as cosine |
| Cosine similarity | Similarity | −1 to 1 | No | Reference |
| Cosine distance (1 − cos) | Distance | 0 to 2 | No | Reverse of cosine, so same order when sorted ascending |
| Euclidean distance | Distance | 0 to 2 | Yes | Same order as cosine distance |
Choosing a metric
In practice the answer is almost always the first branch. Embedding models are trained with a particular similarity in their loss function, and the model's documentation says which one it expects. Most popular text embedding models are trained for cosine similarity, and many of them output unit vectors already. Normalizing yourself is cheap and removes the question.
Some models are trained for the raw dot product, where length is part of the signal. Normalizing their output can change the ranking. Follow the model card in that case.
Edge cases and gotchas
- Zero vectors. A vector with length 0 makes cosine similarity divide by zero and return
nan. This can happen with empty input text in some pipelines. Filter these out or add a small constant to the denominator. - Typical score ranges. Cosine scores between embeddings of unrelated English sentences are often well above 0, such as 0.1 to 0.3, depending on the model. Do not treat a positive score as proof of relevance. Rank by score, and set any cutoff threshold by testing on your own data.
- Scores are not comparable across models. A cosine of 0.8 from one model can mean something quite different from 0.8 from another. Thresholds must be tuned per model.
- Distance versus similarity in libraries. Some libraries return cosine distance, and some return the inner product. Check whether a larger or smaller value means a better match before you sort.
- The dot product is not a true distance. A vector's dot product with itself is not necessarily the largest value in a collection, since a longer vector can score higher against it. Libraries describe this search as maximum inner product search. It matters when you pick an index type, which a later chapter covers.
- Floating-point error. Normalized float32 vectors can give a cosine slightly above 1, such as 1.0000001. Do not test for equality with 1. Use
np.isclose, or clip the value to the range −1 to 1 before passing it to something likearccos. - High dimensions. In hundreds of dimensions, most random vectors are nearly orthogonal and distances between points become similar to each other. Embedding models avoid this by placing related texts in a structured region, but it explains why raw scores often look compressed into a narrow band.
Summary
- Cosine similarity measures the angle between vectors and ignores length.
- The dot product combines angle and length. Euclidean distance also combines them, but as a distance.
- For unit vectors, the dot product equals cosine similarity, and squared Euclidean distance equals 2 − 2 × cosine, so all three give the same ranking.
- Follow the metric named in the model's documentation, and normalize when in doubt.
Exercise
Two embeddings u and v are both unit vectors, and their dot product is 0.8. What is their cosine similarity, and what is their Euclidean distance (to three decimals)? If you replaced v with 3v, how would the dot product, the cosine similarity, and the Euclidean distance change?
Show answer
For unit vectors the cosine similarity equals the dot product, so it is 0.8. Squared Euclidean distance is 2 − 2(0.8) = 0.4, so the distance is √0.4 ≈ 0.632. After replacing v with 3v, the dot product triples to 2.4. The cosine similarity stays at 0.8 because scaling does not change direction. The Euclidean distance changes because 3v is no longer a unit vector: ‖u − 3v‖² = 1 + 9 − 2(3)(0.8) = 5.2, so the distance is about 2.280.
Exercise
You search a collection with the dot product over unnormalized embeddings, and long documents keep ranking first even when they are off-topic. Give one fix that changes the vectors and one that changes only the scoring function.
Show answer
Changing the vectors: normalize every document and query embedding to unit length before indexing, so the dot product equals cosine similarity. Changing the scoring function: compute cosine similarity directly by dividing each dot product by the product of the two vector norms. Both remove the effect of vector length on the ranking.