Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

In this topic

AI Engineering
  • The AI Stack in One Picture: Six Layers Every AI Product Is Built From
  • Tokenization: What an LLM Actually Sees When You Type
  • LLM Tokens, Context Windows and Cost: What One Question Really Costs
  • What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
  • Structured LLM Output with Pydantic: Describe the Shape Once, Check Every Reply
  • Temperature, Top-p and Sampling: Why the Same Prompt Gives a Different Answer
  • Open vs Closed LLMs: Cost, Control, Privacy and Capability, Decided per Workload
  • Streaming and Error Handling for LLM Calls: Show the First Word Early, Retry Politely, Fail Calmly
  • Practice: Build a CLI Chat Tool with Memory, Commands, Error Handling and a History Cap
  • Explicit Criteria vs Vague Prompts: Turn Every Adjective Into a Check a Script Can Run
  • Few-Shot Prompting Done Right: How Many Examples, How Different, What Order, and the Leak That Lies
  • Prompt Caching: Keep the Start of Every Request Identical and Pay for the Long Part Once
  • Prompt Versioning and Testing in a Repo: Prompt Files, a Registry, a Hash per Answer and Tests That Gate
  • Context Engineering: What Belongs in the Context Window, Turn by Turn
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
  • The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
  • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
  • Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
  • Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations
  • Chunking Strategies for RAG: Fixed Size, Sentences or Headings, Measured on One Handbook
  • Vector Databases Hands-On: The Same Search in Chroma and pgvector
  • RAG Prompt Assembly and Citations: Number the Blocks, Fit a Token Budget, Check Every Claim
  • Hybrid Search: BM25 Plus Dense Embeddings, Merged With Reciprocal Rank Fusion
  • Reranking With a Cross-Encoder: When the Second Pass Helps, and When It Doesn't
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Choosing a Vector Index: Flat, HNSW or IVF-PQ, a Memory Estimate, and Filters That Starve Small Customers
  • Citations and Abstention in RAG: What a Citation Proves, and When the Right Answer Is "It's Not in the Documents"
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Cosine, Dot Product or Euclidean Distance: Why Three Measures Pick Three Winners, and the One Fix
  • Choosing an Embedding Model: Dimension, Context Length, Domain and Cost, Tested on Your Own Questions
  • Loading and Parsing Real Documents for RAG: PDF Headers, Wrapped Lines, Tables and HTML Chrome, Scored
  • Where Naive RAG Fails: Five Ways the Simplest Retriever Hands the Model the Wrong Pages
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table
  • Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph
  • LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways
  • Human-in-the-Loop and Checkpointing in LangGraph: interrupt, a SQLite Save Slot and Command(resume=...)
  • Multi-Agent Patterns: Hub and Spoke in LangGraph, With Short Briefs, Owned Tools and a Retry the Hub Decides
  • A Research Agent in LangGraph: Plan, Search, Read, Write, and a Check Node That Rejects Citations Nobody Read
  • Workflow or Agent: Decide Who Picks the Next Step, Then Let the Constraints Choose the Design
  • Custom Agent Loops and Harnesses: A Dispatch Table, an Approval Hold, Error Results and a Turn Budget
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  • From ML Metrics to LLM Evals: Same Ruler, New Targets
  • Why You Cannot Ship an LLM Feature Without an Eval: Five Parts, Three Graders, One Tiny Eval
  • Building a Golden Dataset for LLM Evals: Cases, a Schema, a Coverage Table and a Seeded Split
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Regression Testing an LLM Bot in CI: A Golden Set, Two pytest Gates and GitHub Actions
  • Testing a RAG Bot Before It Ships: Slices, a Release Gate per Slice, and the Week After
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • LLM-as-Judge: Write a Rubric, Check Every Verdict, and Trust the Grader Only After Kappa Says So
  • RAGAS and Custom Evals: Framework Faithfulness Plus Your Own Citation and Required-Fact Checks, Behind One Gate
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
  • Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
  • Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
  • A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
  • Caching for AI Apps: Four Layers, What Goes in Each Key, and How a Delete Travels
  • Semantic Caching: Why a Similarity Threshold Can't Stop Confident Wrong Answers
  • LLM Model Routing: Rules, a Classifier or a Cascade, Judged on Cost per Win and Every Topic
  • Cutting p95 and Cost in Half for an LLM App: Read the Bill, Match the Lever, Guard Success
  • Observability and Tracing for LLM Apps: A Span per Stage, Redaction First, Bad Traces Become Tests
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Design a Multi-Tenant RAG Assistant, Part 1: Requirements, Rough Numbers and a Contract
  • Design a Multi-Tenant RAG Assistant, Part 2: Tenant Isolation, a Scoped Cache and Walking an Outage
  • A 500 MB PDF Takes 50 s to Answer, Get It to 2 s: Measure First, Then Promise Per Path
  • A 500 MB PDF From 50 s to 2 s, the Fast Path: Queue, Status, Streaming and an Acceptance Test That Fails
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • Prompt Injection, Jailbreaks and Untrusted Input: Label What Comes In, Gate What Goes Out
  • Injection Exposure Review for an Agent: Map Inputs, Data and Effects, Layer Every Path, Retest the Job
  • Data Leakage and PII in LLM Apps: Redact, Minimize, Log Safely and Count Every Place
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Claude API Keys: Keep the Key on a Server Proxy, One Key per Environment, Rotate and Scope It
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. Retrieval and RAG

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.

Chaand Sheikh

·27 November 2026Retrieval and RAG

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.

The question and four articles as arrows question [4, 3] Reset password [2, 1.5] Change email [5, 5] Billing invoices [1, 5] Delete account [8, 2] Winner by measure (raw) cosine: Reset password dot: Delete account distance: Change email
Same question, same four articles, three different winners. Drawn from the vectors in 01_three_measures.py.

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 @ b multiplies 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.

Normalising puts every tip on the same circle Raw: length changes the winner → Length 1: only direction is left Reset password cosine, dot, distance: Reset password
Dividing each vector by its length moves every tip onto the unit circle; then all three measures rank the articles the same way.

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

MeasureWhat it comparesCloser meansRaw winner here
CosineDirection onlyBiggerReset password (1.000)
Dot productDirection times lengthBiggerDelete account (38.00)
Euclidean distanceGap between the tipsSmallerChange 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?

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in AI Engineering · 30 of 79

Previous
Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
Next post
Choosing an Embedding Model: Dimension, Context Length, Domain and Cost, Tested on Your Own Questions

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.

On this page

  • Every text is an arrow from the centre
  • Cosine: do the arrows point the same way?
  • Dot product: direction times length
  • Euclidean distance: a ruler between the tips
  • Same data, three winners
  • The fix: give every arrow length 1
  • The same on a real model
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.