What this is
What is a similarity score?
A similarity score is one number that says how alike two pieces of text are, computed by an AI system from their embeddings. An embedding is the list of numbers that gives a text a spot on a map of meaning. There are three common ways to turn two spots into a score: the angle between them (cosine), their product (dot product), or the straight-line gap (Euclidean distance). They put results in the same order only once every vector has been scaled to the same length. Even then, the number alone can mislead: under some embedding models, a score of 0.8 fits a near-duplicate and a stranger alike.
Why it matters: Every vector database and search library has a default metric, so you are choosing one whether you mean to or not, and the wrong one puts results in the wrong order without any error. And when a team argues over whether a similarity of 0.8 is a lot, the answer depends on the embedding model and has to be measured.
At a glance
Key takeaways
- Cosine compares direction only, the dot product compares direction and length together, and Euclidean distance measures the gap between the tips.
- On L2-normalized vectors all three give the same ranking, because ‖a − b‖² = 2 − 2cos.
- Use the metric the embedding model was trained with.
- A score means different things under different models, and many models crowd every score into a narrow band. Rank when you can; when you need a yes/no cut-off, measure it on labelled pairs for that model.
How it works, from scratch
Draw an arrow from the centre of the map of meaning to each text's spot. "How similar are these two texts?" then becomes "how alike are these two arrows?", and there are three ways to compare two arrows:
- Cosine similarity compares the direction they point and ignores how long they are, as two people pointing at the same mountain agree however long their arms are.
- Euclidean distance is the straight-line gap between the two arrow tips.
- Dot product mixes both: pointing the same way and being long both make it bigger.
Chapter 1
Three measures, worked by hand
Take three texts placed in three dimensions. Real models use 384 to 3,072 dimensions (numbers per vector), but the arithmetic is the same:
a = (1, 2, 2), b = (2, 1, 2), c = (2, −1, −2)
- Dot product: multiply position by position, then add. a·b = 1·2 + 2·1 + 2·2 = 8. a·c = 1·2 + 2·(−1) + 2·(−2) = −4.
- Length (the norm, written ‖a‖): square each number, add, and take the square root. ‖a‖ = √(1 + 4 + 4) = 3, and b and c also have length 3.
- Cosine: dot product divided by both lengths. cos(a, b) = 8 / (3·3) = 0.89. cos(a, c) = −4 / 9 = −0.44.
- Euclidean distance: subtract, square, add, square-root. ‖a − b‖ = √(1 + 1 + 0) = 1.41. ‖a − c‖ = √(1 + 9 + 16) = 5.10.
| Pair | Dot product | Lengths multiplied | Cosine | Distance | Reading |
|---|---|---|---|---|---|
| a, b | 8 | 9 | 0.89 | 1.41 | Very similar |
| a, c | −4 | 9 | −0.44 | 5.10 | Pointing away |
Cosine runs from −1 (opposite directions) through 0 (unrelated, at right angles) to 1 (same direction).
Figure 1 · Diagram
flowchart LR A["a = (1, 2, 2)"] --> D["dot product<br/>a·b = 8"] B["b = (2, 1, 2)"] --> D A --> NA["length ‖a‖ = 3"] B --> NB["length ‖b‖ = 3"] D --> COS["cosine = 8 / (3 × 3) = 0.89"] NA --> COS NB --> COS A --> SUB["difference a − b = (−1, 1, 0)"] B --> SUB SUB --> L2["distance = √2 = 1.41"]
In code: worked_example computes every number in the table, so you can
check your arithmetic against it. View source
Chapter 2
The three formulas
The formula and its symbols
Symbols
| Symbol | Meaning here | Shape / range |
|---|---|---|
| a, b | the two embedding vectors being compared | d numbers each |
| d | number of dimensions | 3 in the example; 384 to 3,072 in real models |
| i | which position (dimension) we're looking at | 1 to d |
| aᵢ | the i-th number in a | a real number |
| Σ | "add up", over i from 1 to d | |
| a · b | dot product: multiply matching positions and add | one number, any sign |
| ‖a‖ | length (norm) of a: √(Σ aᵢ²) | one number ≥ 0 |
| √ | square root | |
| cos(a, b) | cosine of the angle between a and b | −1 to 1 |
| ‖a − b‖ | Euclidean distance between the tips | ≥ 0; 0 means identical |
In words: the cosine of a and b is their dot product divided by the product of their lengths; the dot product adds up the products of matching positions; the distance is the square root of the summed squared differences.
New to Σ, ∂ or ‖x‖? The symbols reference decodes each one as a few lines of Python.
On the example: cos(a, b) = (1·2 + 2·1 + 2·2) / (3 · 3) = 8 / 9 = 0.89; ‖a − b‖ = √((1−2)² + (2−1)² + (2−2)²) = √2 = 1.41.
In Python:
import math
a, b = [1, 2, 2], [2, 1, 2]
# a · b = Σ a_i b_i
dot = sum(a_i * b_i for a_i, b_i in zip(a, b))
dot # → 8
# ‖a‖
norm_a = math.sqrt(sum(a_i ** 2 for a_i in a))
# ‖b‖
norm_b = math.sqrt(sum(b_i ** 2 for b_i in b))
norm_a, norm_b # → (3.0, 3.0)
# cos(a, b)
round(dot / (norm_a * norm_b), 2) # → 0.89
# ‖a - b‖
round(math.sqrt(sum((a_i - b_i) ** 2 for a_i, b_i in zip(a, b))), 2) # → 1.41
In code: cosine, dot and euclidean are one line of NumPy each, and
rank sorts a collection of documents from best match to worst under any
of the three. View source
Chapter 3
Normalize, and the three agree
The three measures disagree because the dot product and the distance see length and the cosine does not. Take length away and the disagreement goes with it. L2-normalizing a vector means dividing it by its own length, so that every arrow is trimmed to length 1. Then the only thing two arrows can differ in is direction, and "the tips are close together" says the same as "the arrows point the same way".
For example, a = (1, 0) and b = (0.6, 0.8) both have length 1 (0.6² + 0.8² = 0.36 + 0.64 = 1). Their cosine is 1·0.6 + 0·0.8 = 0.6. The squared distance is (1 − 0.6)² + (0 − 0.8)² = 0.16 + 0.64 = 0.8, and 2 − 2·0.6 is also 0.8.
The formula and its symbols
Symbols
| Symbol | Meaning here | Shape / range |
|---|---|---|
| ‖a − b‖² | squared distance between the tips | 0 to 4 for unit vectors |
| ‖a‖², ‖b‖² | squared lengths, both 1 after normalizing | 1 |
| a · b | dot product, equal to cosine for unit vectors | −1 to 1 |
| cos(a, b) | cosine similarity | −1 to 1 |
In words: for unit-length vectors, the squared distance is two minus twice the cosine, so the higher the cosine, the smaller the distance, always.
On the example: ‖a − b‖² = 1 + 1 − 2·0.6 = 0.8 = 2 − 2·0.6.
In Python:
# both length 1
a, b = [1, 0], [0.6, 0.8]
# for unit vectors, a · b is the cosine
cos = sum(a_i * b_i for a_i, b_i in zip(a, b))
# ‖a - b‖²
dist_sq = sum((a_i - b_i) ** 2 for a_i, b_i in zip(a, b))
# the two sides of the identity
round(dist_sq, 2), round(2 - 2 * cos, 2) # → (0.8, 0.8)
After normalizing, the dot product is the cosine, and the distance only ever falls as the cosine rises. So once vectors are L2-normalized, cosine, dot product and Euclidean distance give the same ranking.
Figure 2 · Interactive · computed from the lesson's code
Cosine similarity of two arrows
Try it: pick "Same direction, different lengths", then drag B's length. The dot product and the distance change, but the cosine stays at 1, because it only sees the angle. Drag an angle instead and watch the cosine slide from 1 through 0 to −1. Then switch on "Normalize to length 1": both arrows shrink to the unit circle, the dot product becomes the cosine, and the squared distance becomes 2 − 2 × cosine.
Figure 3 · Chart
All 400 random unit-vector pairs fall exactly on the line squared distance = 2 - 2 x cosine, so higher cosine always means smaller distance
Figure 4 · Diagram
flowchart TD
S{What was the model<br/>trained with?} -->|cosine| N[L2-normalize every vector<br/>once, at write time]
S -->|dot product| D{Does the vector length<br/>carry signal?}
D -->|yes, e.g. popularity| RAW[Keep raw vectors,<br/>rank by dot product]
D -->|no| N
N --> FAST[Rank by dot product:<br/>same order as cosine and L2,<br/>and the cheapest to compute]
In code: l2_normalize trims every row to length 1;
rankings_agree_after_normalizing ranks random documents by all three
metrics before and after normalizing; l2_identity_check returns both sides
of the identity for two random vectors. View source
Normalize in one place, when vectors are written. An index that holds some normalized vectors and some raw ones ranks them in the wrong order, and nothing reports an error. Use the metric the embedding model was trained with.
Chapter 4
When length carries signal
Normalizing throws length away, which costs nothing when length means nothing. Some models give it a meaning on purpose. A recommender can be trained so that popular items get longer arrows, which lets them win close contests. Cosine ignores that length; the dot product keeps it.
Take a query that points along (1, 0). A niche item, (0.99, 0.10), is almost perfectly aligned with it. A popular item, (0.95, 0.30) × 3 = (2.85, 0.90), is slightly off the query's direction but three times longer.
| Item | Cosine with query | Dot with query |
|---|---|---|
| niche (0.99, 0.10) | 0.99 / 0.995 = 0.995 | 0.99 |
| popular (2.85, 0.90) | 2.85 / 2.99 = 0.954 | 2.85 |
Cosine prefers the niche item; the dot product prefers the popular one.
Figure 5 · Chart
The short item points almost along the query and wins on cosine (0.99 vs 0.95); the item three times longer wins on dot product (2.85 vs 0.99)
Some retrieval and recommender models are trained with the raw dot product and store useful signal in the length. Normalizing their vectors "to be safe" throws that signal away.
Chapter 5
The curse of dimensionality
Every example so far had two or three dimensions, where the nearest point is clearly nearer than the rest. Embeddings have hundreds or thousands of dimensions, and there, for points scattered at random, that stops being true. Scatter 1,000 random points in a cube and measure their distances from a random spot. In 2 dimensions the nearest point is about 1/100th as far away as the farthest. In 1,000 dimensions it is about 90% as far, so every point is nearly the same distance away. This is the curse of dimensionality, and it is measured by the ratio of the nearest distance to the farthest:
The formula and its symbols
Symbols
| Symbol | Meaning here | Shape / range |
|---|---|---|
| q | the query point | d numbers |
| xⱼ | the j-th of the random points | d numbers each |
| j | which random point | 1 to 1,000 |
| min, max over j | the smallest / largest value across all the points | |
| ratio | nearest distance divided by farthest distance | 0 to 1; near 1 means "all equally far" |
In words: the ratio is the distance to the closest point divided by the distance to the farthest point.
On the example: a query at (0, 0) and three points at (1, 0), (0, 2) and (3, 4) are 1, 2 and 5 away, so the ratio is 1 / 5 = 0.2. With 1,000 random points the ratio is about 0.01 at d = 2 and about 0.9 at d = 1,000. The Python below draws its own random points, so it lands close to those numbers rather than on them: 0.02 and 0.9.
In Python:
import math, random
def ratio(q, xs):
# ‖q - x_j‖ for every j
dists = [math.dist(q, x_j) for x_j in xs]
# min over j ÷ max over j
return min(dists) / max(dists)
ratio((0, 0), [(1, 0), (0, 2), (3, 4)]) # → 0.2
random.seed(0)
for d in (2, 1000):
q = [random.random() for _ in range(d)]
xs = [[random.random() for _ in range(d)] for _ in range(1000)]
# one significant figure
print(d, f"{ratio(q, xs):.1g}") # → 2 0.02 1000 0.9
Figure 6 · Chart
The nearest-to-farthest distance ratio rises from about 0 in 2 dimensions to 0.8 at 200 and 0.92 at 2,000: random points become almost equidistant
In code: curse_of_dimensionality scatters the random points, measures
from a random query, and returns the nearest, farthest and ratio for each
dimension. View source
Exact nearest-neighbour search in high dimensions is slow and fragile, which is one reason vector search uses approximate indexes (Vector indexes). Real embeddings are not random: meaning puts them on a structure with far fewer dimensions, so nearest-neighbour search still works on them.
Chapter 6
Anisotropy: why every score looks like 0.8
Every vector leans the same way
Random points crowd together in distance. Real embeddings have a crowding problem of their own, in angle. Picture a stadium crowd all facing the stage. Ask whether two people in it face the same way and the answer is "roughly yes" for everyone, so the question tells you little. Many embedding models behave like that crowd: their vectors bunch into a narrow cone, so even unrelated texts get cosines of 0.7 or more. This lopsidedness is called anisotropy ("not the same in every direction").
To see what it does to the scores, build each vector as √3·m + n, where m is one direction every vector shares (the stage) and n is a unit-length direction of the text's own. For two unrelated texts the n parts are at right angles, so their dot product is (√3)² = 3, each length is √(3 + 1) = 2, and the cosine is 3 / (2 · 2) = 0.75. For paraphrases, whose own parts agree with cosine ρ, the cosine becomes 0.75 + 0.25·ρ: about 0.79 to 0.86. The whole difference between a stranger and a paraphrase lies between 0.75 and 0.86.
The formula and its symbols
Symbols
| Symbol | Meaning here | Shape / range |
|---|---|---|
| v, v₁, v₂ | an embedding vector | d numbers (768 here) |
| m | the shared direction every vector leans toward | unit vector |
| n | the text's own direction | unit vector |
| α (alpha) | how strongly every vector leans toward m | √3 here |
| β (beta) | how strongly each keeps its own direction | 1 here |
| ρ (rho) | cosine between the two texts' own directions | 0 unrelated; 0.15 to 0.45 for paraphrases |
In words: every vector is a big shared part plus a small personal part, so the cosine is mostly the shared part's weight, nudged up a little by how much the personal parts agree.
On the example: unrelated, ρ = 0: (3 + 0) / (3 + 1) = 0.75. A paraphrase with ρ = 0.4: (3 + 0.4) / 4 = 0.85.
In Python:
import math
alpha, beta = math.sqrt(3), 1
# shared direction; two unrelated own directions
m, n1, n2 = (1, 0, 0), (0, 1, 0), (0, 0, 1)
# v = α m + β n
v1 = [alpha * m_i + beta * n_i for m_i, n_i in zip(m, n1)]
v2 = [alpha * m_i + beta * n_i for m_i, n_i in zip(m, n2)]
dot = sum(a * b for a, b in zip(v1, v2))
# the cosine, measured directly
round(dot / (math.hypot(*v1) * math.hypot(*v2)), 2) # → 0.75
def cos_formula(rho):
return (alpha ** 2 + beta ** 2 * rho) / (alpha ** 2 + beta ** 2)
# unrelated, and a paraphrase
round(cos_formula(0), 2), round(cos_formula(0.4), 2) # → (0.75, 0.85)
Figure 7 · Chart
Raw cosines crowd paraphrases (0.76 to 0.87) and unrelated pairs (0.72 to 0.78) together; mean-centred, unrelated sit near 0 and paraphrases near 0.3
In code: anisotropic_embeddings builds the pairs as α·m + β·n,
pair_cosines scores each pair, and mean_center subtracts the average
vector to remove the shared direction. View source
Picking a threshold from labelled pairs
Ranking survives anisotropy: a shift shared by every score does not change which document is on top, so rank whenever you can. Some jobs need a yes/no cut-off instead: are these two texts duplicates, is this cached answer close enough, is there no good answer at all? When every score sits in one narrow band, a cut-off that is off by a few hundredths gives very different answers, so measure it. Label some pairs, score them, and choose the threshold with the best F1, the balance of precision (of the pairs called similar, how many were?) and recall (of the truly similar pairs, how many were caught?):
The formula and its symbols
Symbols
| Symbol | Meaning here | Range |
|---|---|---|
| P | precision: true matches ÷ everything called a match | 0 to 1 |
| R | recall: true matches found ÷ all true matches | 0 to 1 |
| F₁ | their harmonic mean; high only when both are high | 0 to 1 |
In words: F1 is twice the product of precision and recall, divided by their sum.
On a hand example: scores 0.9, 0.8, 0.7, 0.6 where the first two are true matches. Threshold 0.8 calls exactly those two matches: P = 2/2 = 1, R = 2/2 = 1, F₁ = 2·1·1 / 2 = 1.
In Python:
scores = [0.9, 0.8, 0.7, 0.6]
# the labels
is_match = [True, True, False, False]
# threshold 0.8
called = [s >= 0.8 for s in scores]
true_matches = sum(c and y for c, y in zip(called, is_match))
# precision
P = true_matches / sum(called)
# recall
R = true_matches / sum(is_match)
# F₁
2 * P * R / (P + R) # → 1.0
Figure 8 · Diagram
flowchart LR L[Sample a few hundred pairs<br/>from your own data] --> H[Label each:<br/>same meaning or not] H --> E[Score every pair<br/>with THIS model] E --> W[Sweep thresholds,<br/>compute precision, recall, F1] W --> P[Pick the threshold that fits<br/>your cost of each error] P --> V[Store it with the<br/>model version] V -->|model upgraded| E
Figure 9 · Chart
F1 on raw scores swings within a few hundredths: the calibrated threshold 0.776 reaches F1 0.99, while the guessed 0.80 drops to 0.87
In code: f1_curve computes F1 at every candidate threshold for this
plot; best_threshold returns the best one with its precision and recall. View source
Test yourself
4 questions
Answer each one out loud or on paper before you open it.
Question 1Q: When do cosine, dot product and Euclidean distance give the same ranking?Think it through, then reveal
When all vectors are L2-normalized: the dot product equals the cosine, and the squared distance equals 2 − 2cos, which always moves opposite to cosine.
Question 2Q: When would you deliberately use the raw dot product on unnormalized vectors?Think it through, then reveal
When the model was trained that way and encodes useful signal in the length (e.g. popularity or quality in some recommender and retrieval models). Normalizing would throw that signal away.
Question 3Q: Similarity scores all sit between 0.75 and 0.85. What's going on and how do you set a threshold?Think it through, then reveal
The model is anisotropic: its vectors share a dominant direction, so every pair looks similar and the real signal lives in a narrow band. Ranking still works. For a threshold, label a few hundred pairs from your own data, sweep the threshold, and pick the one that maximizes F1 (or matches your precision/recall needs). Optionally mean-center the vectors. Redo it for every model version.
Question 4Q: What is the curse of dimensionality for nearest-neighbour search?Think it through, then reveal
For random high-dimensional data, the nearest and farthest points are almost the same distance away, so "nearest" carries little information and exact search gets expensive. Real embeddings have structure, and approximate indexes trade a little recall for large speedups.
Primary sources
The papers behind this lesson
Proved that for broad families of random data, the nearest and farthest neighbours become equally far as dimension grows: the curse of dimensionality measured in this lesson.
The paperShowed that transformer embeddings occupy a narrow cone (anisotropy), which is why raw cosine scores bunch together.
The paperShowed that centering and whitening sentence embeddings spreads them back out and improves similarity quality.
The paperResearcher's shelf
Further reading
- Cosine similarity (Wikipedia): https://en.wikipedia.org/wiki/Cosine_similarity
- Beyer et al., When Is "Nearest Neighbor" Meaningful? (1999): https://doi.org/10.1007/3-540-49257-7_15
- Ethayarajh, How Contextual are Contextualized Word Representations? (anisotropy, 2019): https://arxiv.org/abs/1909.00512
- Su et al., Whitening Sentence Representations (2021): https://arxiv.org/abs/2103.15316
- sentence-transformers, semantic search and score functions: https://www.sbert.net/examples/applications/semantic-search/README.html
About this lesson. This is the illustrated edition of a lesson from the open-source AI Primer ↗. Its text, figures and numbers are generated from the Primer's source at commit f8b43d1, so the two always agree: the explanation, the code that builds it and the tests that prove it.