Cosine Similarity: The Math Behind Semantic Search

Semantic search and RAG rank results by cosine similarity — but what does that actually measure? Build it from the dot product, see the geometry, write it in ten lines of Python, and check it against scikit-learn’s own numbers.

Open any explanation of semantic search, embeddings, or RAG and you’ll hit the same sentence: “we compare the embeddings using cosine similarity.” It’s said the way people say “we hashed the password” — as if the meaning is obvious.

It isn’t obvious, and it’s also not complicated. Cosine similarity is one line of arithmetic you can do by hand, and once you’ve done it once, a large part of how retrieval works stops being mysterious. This tutorial builds it from the dot product, shows the geometry, implements it in ten lines of dependency-free Python, and then checks that implementation against scikit-learn’s own published numbers — so you finish holding something you’ve verified rather than something you’ve been told.

Prerequisites

  • Python 3.8+ if you want to run the code. No libraries — the example is pure standard library, no network, no API keys.
  • Comfort with lists of numbers. No linear-algebra course required; we build the two pieces we need.

Step 1: the dot product measures agreement

An embedding is just a list of numbers — a vector. Take two of them, multiply them position by position, and add up the results. That’s the dot product:

a = [4, 4]
b = [7, 2]

a · b = (4 × 7) + (4 × 2) = 28 + 8 = 36

Notice what that sum rewards. When two vectors are large in the same positions, the products are large and positive, and the total climbs. When one is positive where the other is negative, that term subtracts. When they’re busy in completely different positions, the products are near zero and so is the total.

So the dot product already measures a kind of agreement. It has one problem: it also measures size. Double every number in a and the dot product doubles too, even though a still points in exactly the same direction — still “means” the same thing. A long document vector would beat a short one on sheer magnitude.

Step 2: divide the size out

The fix is to divide by how long each vector is. A vector’s length (its norm, written ‖a‖) comes straight from Pythagoras — square the components, sum, take the square root:

‖a‖ = √(4² + 4²) = √32  ≈ 5.66
‖b‖ = √(7² + 2²) = √53  ≈ 7.28

Divide the dot product by both lengths and you have cosine similarity:

cos(a, b) = (a · b) / (‖a‖ × ‖b‖)
          = 36 / (5.66 × 7.28)
          = 36 / 41.18
          ≈ 0.874

That formula is not a convention we invented for this tutorial. It is the definition scikit-learn documents for cosine_similarity: K(X, Y) = <X, Y> / (||X||*||Y||) — the normalized dot product of X and Y.

Step 3: what you just computed is an angle

Dividing by both lengths does something geometrically specific: it turns the dot product into the cosine of the angle between the two vectors. That’s the whole name.

Cosine similarity is the cosine of the angle between two vectors Two vectors a and b drawn from the origin on 2-D axes. The angle theta between them is marked with an arc. A dashed vector 2a, twice as long as a and pointing the same way, sits along a’s line and makes the same angle with b — so cosine similarity, cos theta equals 0.87 for both, is unchanged by length. dimension 1 dimension 2 2a = [7, 7] a = [4, 4] b = [7, 2] θ cos θ = (a · b) / (‖a‖ ‖b‖) = 36 / (5.66 × 7.28) ≈ 0.87 2a is twice as long as a, but points the same way — so cos θ is still 0.87. Direction carries the meaning. Length does not.
Cosine similarity reads the angle. Doubling a vector’s length leaves the score untouched.

This is the intuition worth keeping:

If the vectors…The angle is…Cosine similarity is…
point the same way0°1
are at right angles (unrelated)90°0
point in opposite directions180°−1

And the property that makes it useful for search: length doesn’t matter, only direction does. In the diagram above, 2a is twice as long as a, yet it scores identically against b, because it points the same way. A 3,000-word article and a two-sentence summary of it can land in nearly the same direction — and cosine similarity says so, while a raw dot product would favour whichever vector happened to be bigger.

Step 4: ten lines of Python

Here’s the entire thing, no libraries:

from math import sqrt

def dot(a, b):
    return sum(ai * bi for ai, bi in zip(a, b))

def norm(a):
    return sqrt(dot(a, a))

def cosine_similarity(a, b):
    """cos(a, b) in [-1, 1]. Returns 0.0 if either vector is all-zero (undefined)."""
    na, nb = norm(a), norm(b)
    if na == 0.0 or nb == 0.0:
        return 0.0
    return dot(a, b) / (na * nb)

The zero-vector guard matters: an all-zero vector has no direction, so the angle is undefined and the formula would divide by zero. Returning 0.0 matches what scikit-learn’s published example shows for an all-zero row.

Step 5: check it against the reference

“It looks right” is not verification. scikit-learn’s documentation includes a worked example with printed output, which makes an excellent test oracle — if our from-scratch function reproduces those numbers, it implements the same definition.

The documented example (consulted 2026-08-04, scikit-learn 1.9.0):

X = [[0, 0, 0], [1, 1, 1]]
Y = [[1, 0, 0], [1, 1, 0]]

cosine_similarity(X, Y) == [[0.   , 0.   ],
                            [0.577, 0.816]]

You can confirm the interesting cells by hand before running anything:

  • [1,1,1] · [1,0,0] = 1, lengths √3 and 1, so 1 / 1.732 ≈ 0.577. ✓
  • [1,1,1] · [1,1,0] = 2, lengths √3 and √2, so 2 / 2.449 ≈ 0.816. ✓

The accompanying example directory runs exactly that comparison, plus the identical / orthogonal / opposite / zero-vector cases:

bash verify.sh

Output:

All cosine-similarity checks passed (matches scikit-learn's published example).
--- demo ---
doc 1: 1.000
doc 0: 0.707
doc 2: 0.000

No network, no installs, no API keys — so this runs in CI and stays green.

Look again at the last three lines of output. That’s a rank function: one query vector, three document vectors, sorted by cosine similarity.

def rank(query, documents):
    """Return (index, score) pairs sorted by similarity to `query`, best first."""
    scored = [(i, cosine_similarity(query, d)) for i, d in enumerate(documents)]
    return sorted(scored, key=lambda p: p[1], reverse=True)

Strip the infrastructure away and that is what a vector database does when you search. Semantic search is:

  1. Turn the query into a vector (that’s the embedding model’s job).
  2. Turn every document into a vector, once, ahead of time.
  3. Rank documents by cosine similarity to the query vector.
  4. Return the top few.

Retrieval-augmented generation adds one step: paste those top few into the prompt. Everything a production system adds on top — approximate-nearest-neighbour indexes, sharding, filtering, re-ranking — exists to do step 3 fast over millions of vectors, not to do something different. The scoring is the arithmetic you just did by hand.

What cosine similarity does not tell you

Practical judgement, not maths, from here on:

  • It scores direction, not distance. Two vectors can sit far apart in the space and still score 1.0 if they point the same way. That’s usually what you want for text; it’s not automatically what you want for every kind of vector.
  • It cannot rescue bad embeddings. Cosine similarity faithfully compares whatever the embedding model produced. If the model doesn’t capture your domain’s meaning, the ranking will be confidently wrong — and the similarity score will look just as healthy. Evaluate the retrieval, not the formula.
  • Scores are not probabilities and don’t transfer between models. 0.82 from one embedding model means nothing about 0.82 from another. Threshold by measuring your own results, not by copying a number from a blog post.
  • If your vectors are already L2-normalized — many embedding APIs return unit vectors — then every norm is 1, and cosine similarity reduces to a plain dot product. scikit-learn’s documentation makes the same point: on L2-normalized data, cosine_similarity is equivalent to the linear kernel. That’s why production systems often store normalized vectors and use the cheaper dot product.
  • Out of scope here: how embedding models are trained, approximate-nearest- neighbour indexes, and choosing a vector database. Those are separate tutorials — this one is the piece they all assume you already have.

Next step

You now have the primitive that retrieval is built on, verified against a reference implementation rather than taken on faith. The rest of the Foundations tutorials build the same way: one idea, drawn, derived, and checked.

If that’s how you like to learn, the next one lands in your inbox — get the next Foundations tutorial by email.

Sources