AI Hints
Home›RAG Tutorial›Embeddings
RAG · Lesson 27 of 120

Cosine Similarity

How close two meanings are.

⏱ 2 min read▶ Video at 26:52🎓 Free
Watch this lesson in the RAG courseWatch on YouTube ↗Full RAG course

To compare two embeddings, we measure the angle between them. That's cosine similarity. A score near one means very similar. Near zero means unrelated. With normalised vectors, it's just a dot product.

Cosine Similarity
From the video: Cosine Similarity
  • Angle between vectors
  • Near 1: similar
  • Near 0: unrelated

Comparing meanings

We embed a question, and two sentences from our help centre. The at sign multiplies vectors, giving the cosine similarity. Run it. The battery sentence scores far higher than the opening hours, even though it shares almost no words with the question.

cosine.pypython
from sentence_transformers import SentenceTransformer

model = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")
q, a, b = model.encode([
    "How many hours until my e-bike is full again?",
    "The Volt 500 battery charges fully in about 4 hours.",
    "York is open Monday to Saturday, 9am to 5:30pm.",
], normalize_embeddings=True)

print("question vs battery:", round(float(q @ a), 2))
print("question vs hours:  ", round(float(q @ b), 2))
Output
question vs battery: 0.35
question vs hours:   0.18

Reading scores

Scores depend on the model, so compare them, don't treat them as percentages. What matters is the ranking, which chunk scores highest for a question. That ranking is the heart of vector search.

keyvalue
Near 1very similar
Near 0unrelated
Comparedon't read as %
Rankingwhat matters

Summary

Cosine similarity measures how close two meanings are. With normalised vectors, it's a dot product. Next, searching the whole help centre by meaning.

Key takeaways
  • q @ a
  • Higher is closer
  • Rank by score
Next up: Searching by Meaning — the whole index