Skip to content
AgenticAIWiki
  1. Learn
  2. Part 1
  3. 4. Embeddings and semantic search
  4. 4.2

Lesson 4.2 · 2 of 10 · 4 min read · Reviewed 24 Nov 2026

Similarity: cosine and dot product

By the end, you can

  • Compare cosine similarity and dot product.
  • Interpret similarity scores sensibly.

Cosine similarity

The cosine of the angle between two vectors:

cos(a, b) = (a . b) / (|a| x |b|)

 1.0  same direction (very similar)
 0.0  at right angles (unrelated)
-1.0  opposite

It ignores length and looks only at direction.

Dot product

a . b = a1*b1 + a2*b2 + ... + an*bn

Bigger when vectors point the same way and are long. Many embedding models output normalised vectors (length 1), and then the dot product equals cosine similarityCosine similarity: A measure of how similar two vectors are, based on the angle between them, from -1 to 1. and is cheaper to compute.

Euclidean distance

Straight-line distance between points. For normalised vectors, ranking by distance gives the same order as ranking by cosine.

Reading scores

  • Scores depend on the embedding modelEmbedding model: A model trained to turn text (or images) into embeddings for search and comparison, rather than to generate text.. A 0.8 in one model isn’t the same as 0.8 in another.
  • Real scores bunch in a narrow band. EmbeddingEmbedding: A list of numbers (a vector) that represents the meaning of a piece of text, so similar meanings land close together. vectors don’t spread evenly in every direction, so with many models even unrelated sentences score around 0.6 to 0.8, and near-duplicates 0.9 or more. The “0 means unrelated” line above is geometry, not what you’ll see.
  • Use them to rank, and set thresholds only after checking examples from your data.
  • Use the measure the embedding model’s docs recommend.

A small example

query: "return worn shoes"
  0.83  "Footwear may be returned within 30 days if unworn"
  0.79  "Worn footwear is accepted only if faulty"
  0.41  "Shipping takes 3 to 5 days"

Both footwear passages rank above shipping; the exact numbers matter less than the order.

Key points

  • Cosine similarity measures the angle between two vectors: 1 means same direction. In theory 0 means unrelated, but real embedding models put unrelated texts well above 0.
  • Dot product also grows with vector length; for normalised vectors, it equals cosine similarity.
  • Scores are relative: compare them within one model and task, rather than trusting a fixed cut-off.
Hands-on labRuns in the Playground

Compare cosine, dot product and distance

Implement the three similarity measures and see when they agree and when they don't.

You will have: A table of scores and rankings for one query under cosine, dot product and L2 distance, before and after normalising.

Steps

  1. Run the starter and read the three empty ranking lines.
  2. Write dot(), cosine() and l2() from their formulas.
  3. Rank the documents three ways and note that the long 'faq' vector wins on dot product.
  4. Normalise every vector to length 1 and rank again.
  5. Explain in one sentence why the three rankings now agree.

Done when

  • Raw vectors: dot product ranks 'faq' first, cosine ranks 'returns' first.
  • After normalising, all three rankings are identical.
  • The script prints both sets of rankings.

Open in the Playground No API key needed.

Starter code (Python)
import math

query = [0.9, 0.1, 0.0]
docs = {"returns": [0.8, 0.2, 0.1], "shipping": [0.3, 0.9, 0.1], "faq": [2.0, 1.5, 1.5]}

def dot(a, b):
    return 0.0  # TODO: sum of a[i] * b[i]

def length(a):
    return math.sqrt(sum(x * x for x in a))

def cosine(a, b):
    return 0.0  # TODO: dot divided by the two lengths

def l2(a, b):
    return 0.0  # TODO: square root of the summed squared differences

def rankings(q, ds):
    by_dot = sorted(ds, key=lambda k: -dot(q, ds[k]))
    by_cos = sorted(ds, key=lambda k: -cosine(q, ds[k]))
    by_l2 = sorted(ds, key=lambda k: l2(q, ds[k]))
    return by_dot, by_cos, by_l2

print("raw:", rankings(query, docs))
# TODO: normalise query and every doc to length 1, then print the rankings again
Show a solution
import math

query = [0.9, 0.1, 0.0]
docs = {"returns": [0.8, 0.2, 0.1], "shipping": [0.3, 0.9, 0.1], "faq": [2.0, 1.5, 1.5]}

def dot(a, b):
    return sum(x * y for x, y in zip(a, b))

def length(a):
    return math.sqrt(sum(x * x for x in a))

def cosine(a, b):
    return dot(a, b) / (length(a) * length(b))

def l2(a, b):
    return math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b)))

def unit(a):
    return [x / length(a) for x in a]

def rankings(q, ds):
    by_dot = sorted(ds, key=lambda k: -dot(q, ds[k]))
    by_cos = sorted(ds, key=lambda k: -cosine(q, ds[k]))
    by_l2 = sorted(ds, key=lambda k: l2(q, ds[k]))
    return by_dot, by_cos, by_l2

for k, v in docs.items():
    print(f"{k:9} dot={dot(query, v):.2f} cos={cosine(query, v):.2f} l2={l2(query, v):.2f}")
d, c, e = rankings(query, docs)
print("raw dot:", d, "cos:", c, "l2:", e)
d, c, e = rankings(unit(query), {k: unit(v) for k, v in docs.items()})
print("normalised dot:", d, "cos:", c, "l2:", e)
print("all agree:", d == c == e)
Quick checkTwo embeddings have been normalised to length 1. How do their dot product and cosine similarity compare?
How sure are you?
Pick an answer and how sure you are