Cosine, Dot Product or Euclidean Distance: Why Three Measures Pick Three Winners, and the One Fix
One question, four help articles, three measures: cosine picks Reset password, dot product picks Delete account, Euclidean distance picks Change email. Work each one out by hand in NumPy, see why length misleads, then normalise to length 1 and watch all three agree, on toy vectors and on all-MiniLM-L6-v2.
What you will learn
- Compute cosine similarity, dot product and Euclidean distance with NumPy
- See why the three measures can rank the same articles differently
- Normalise vectors to length 1 so all three measures agree
- Check which measure a real embedding model is built for
Before you start
- What an Embedding Actually Is
- Basic NumPy arrays
A question comes in. Which document is the closest one? There are three popular ways to measure that: cosine similarity, the dot product and Euclidean distance. And here's the interesting part: they don't always agree.
This is the retrieve step of a RAG system, where we pick the pieces closest to the question. The measure decides which piece the model gets to read, so it is worth seeing exactly how each one behaves. If you are new to embeddings, start with What an Embedding Actually Is.
Every text is an arrow from the centre
Think of a compass. Every text becomes an arrow from the centre. A user types I forgot my password, and that question is the vector [4, 3]. Four help articles become arrows too. Real embeddings have hundreds of numbers, but two let us draw them:
"""Rank four help articles for one question with three similarity measures."""
import numpy as np
# Two numbers per text keep the picture drawable (real embeddings have hundreds).
QUESTION = np.array([4.0, 3.0]) # "I forgot my password"
ARTICLES = {
"Reset password": np.array([2.0, 1.5]),
"Change email": np.array([5.0, 5.0]),
"Billing invoices": np.array([1.0, 5.0]),
"Delete account": np.array([8.0, 2.0]),
}
Reset password points the same way as the question, just shorter. Change email leans up a little. Billing invoices leans up much more. Delete account is long and almost flat. An arrow gives us two things to compare: direction and length.
Cosine: do the arrows point the same way?
def cosine(a, b):
return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))
Cosine asks one simple thing: do the two arrows point the same way? Let's run it by hand for the question and Billing invoices:
a @ bmultiplies the numbers pair by pair and adds them: 4 × 1 + 3 × 5 = 19.- The lengths: the question is 5, Billing invoices is about 5.1. Multiplied, about 25.5.
- 19 / 25.5 = 0.745, which is an angle of 41.8 degrees.
Reset password sits right on top of the question: 0 degrees, cosine 1.000. Change email is only 8.1 degrees apart, 0.990. Delete account is 22.8 degrees away, 0.922. Dividing by both lengths cancels the length, so only the angle is left.
Dot product: direction times length
def dot(a, b):
return float(a @ b)
The dot product mixes direction and length. It equals the question's length, times the article's length, times the cosine. Reset password has a short arrow, 2.5 long, so it only gets 12.5. Change email gets 35, Billing invoices 19. Delete account leans away, but its arrow is 8.25 long, so it gets 4 × 8 + 3 × 2 = 38, the highest. Nothing here divides by the length, so big numbers win. A long arrow can win even when it points away.
Euclidean distance: a ruler between the tips
def euclidean(a, b):
return float(np.linalg.norm(a - b))
Take a ruler and measure between the two tips. Question minus Change email is [-1, -2], and the length of that gap is 2.24: close. Question minus Delete account is [-4, 1], 4.12: far. Reset password points the same way but its tip is further off, 2.50. For distance, smaller means closer. For cosine and dot, bigger means closer. The ruler measures where the tips land, so length matters here too.
Same data, three winners
python 01_three_measures.py
Raw vectors
article cosine dot distance
Reset password 1.000 12.50 2.50
Change email 0.990 35.00 2.24
Billing invoices 0.745 19.00 3.61
Delete account 0.922 38.00 4.12
Cosine picks Reset password. Dot product picks Delete account. Distance picks Change email. Same question, same articles, three different winners, and a search system needs one answer.
The fix: give every arrow length 1
def unit(v):
return v / np.linalg.norm(v)
unit divides a vector by its own length. The question [4, 3] divided by 5 becomes [0.8, 0.6], exactly length 1. Every article goes through the same line. Ours are all longer than 1, so they shrink (an arrow shorter than 1 would stretch). Now every tip sits on the same circle. That step is called normalising, and once the length is gone, only direction is left:
Normalised to length 1
article cosine dot distance
Reset password 1.000 1.00 0.00
Change email 0.990 0.99 0.14
Billing invoices 0.745 0.75 0.71
Delete account 0.922 0.92 0.40
Reset password now leads every column, with a distance of zero. And look at the cosine column: it didn't change at all. Cosine never cared about length. On unit vectors, cosine and dot are the same number, and distance gives the same order.
The same on a real model
Now a real embedding model, all-MiniLM-L6-v2, which gives 384 numbers per text and runs on your own computer. Note normalize_embeddings=True:
"""The same three measures on real embeddings (free local model, no API key)."""
import sys
import numpy as np
from sentence_transformers import SentenceTransformer
MODEL = "all-MiniLM-L6-v2" # 384 numbers per text (Hugging Face model card)
ARTICLES = ["Reset password", "Change email", "Billing invoices", "Delete account"]
def rank(question):
model = SentenceTransformer(MODEL)
q = model.encode(question, normalize_embeddings=True)
vecs = model.encode(ARTICLES, normalize_embeddings=True)
rows = []
for name, v in zip(ARTICLES, vecs):
cos = float(q @ v / (np.linalg.norm(q) * np.linalg.norm(v)))
rows.append((name, cos, float(q @ v), float(np.linalg.norm(q - v)), float(np.linalg.norm(v))))
return rows, float(np.linalg.norm(q))
question: "I forgot my password" (length 1.00)
article cosine dot distance length
Reset password 0.754 0.754 0.701 1.00
Delete account 0.476 0.476 1.024 1.00
Change email 0.320 0.320 1.166 1.00
Billing invoices 0.007 0.007 1.409 1.00
same ranking for all three: True
The question comes back at length 1.00, and so does every article, so cosine and dot are the same number. Reset password wins with 0.754, and all three give the same ranking. Ask my bill is wrong with the same script and Billing invoices comes first at 0.435, again with one ranking for all three. So check your model's documentation, and use the measure it was built for.
Common mistakes
- Using the dot product on vectors that aren't normalised. Long vectors win just for being long, as Delete account did with 38.
- Sorting distance the wrong way. For Euclidean distance the smallest number is the best match; for cosine and dot it's the biggest.
- Normalising the documents but not the question (or the other way round). Both sides need length 1 for the measures to agree.
- Picking a measure by habit. Your model card or vector database setting says which measure the vectors were made for.
Quick recap
| Measure | What it compares | Closer means | Raw winner here |
|---|---|---|---|
| Cosine | Direction only | Bigger | Reset password (1.000) |
| Dot product | Direction times length | Bigger | Delete account (38.00) |
| Euclidean distance | Gap between the tips | Smaller | Change email (2.24) |
Any of them, after unit() | Direction only | - | Reset password, all three |
To score a whole collection at once and keep the top k, see Similarity Search: Finding the Closest Vectors.
Try it yourself
Multiply the question by three, QUESTION = np.array([12.0, 9.0]), and run 01_three_measures.py again. Before you run it, guess: which columns move, and which one stays exactly the same?
Related course on Udemy
Become an AI Engineer: LLMs, RAG, Agents and MCP
Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)Related posts
What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
A customer types "I cannot log in" and keyword search finds nothing, although a password-reset article exists. Turn meaning into numbers by hand, find the nearest point with math.dist, build a three-topic toy embedder that finds the right article at 1.00, and watch it score 0.00 on "I can't get into my account".
The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
Ingest, chunk, embed, store, retrieve, rerank and generate, in one Python file. Follow one question through a 26-chunk employee handbook to an answer that cites its source.
Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
Ask one question of a whole collection of vectors: which items are closest to this one? Normalise, score every row with one matrix multiply, keep the top k or everything above a threshold, and check it with NearestNeighbors.
Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
A smart model has never read your company's files, and they change every month. Three ways to give it the facts: paste everything, fine-tune, or retrieve only the right pieces. Follow a refund-policy question through all three and see why RAG wins when documents change.