Embeddings and similarity: cosine similarity by hand
RAG & Vector Search · 10 questions
Short notes
Key idea
An embedding turns text into a vector so that texts with similar meaning end up close together. Cosine similarity measures closeness by the angle between vectors: 1 means the same direction, 0 means unrelated.
Syntax
import numpy as np
def cosine(a, b):
return a @ b / (np.linalg.norm(a) * np.linalg.norm(b))
q = embed("how do I get my money back")
d = embed("Refunds are paid within 5 working days")
cosine(q, d) # high, though no words are shared
- Embed questions and documents with the same model.
- Normalised vectors (length 1): cosine = dot product.
Example
By hand: a = (1, 2, 2), b = (2, 1, 2). Dot = 2 + 2 + 4 = 8; lengths 3 and 3; cosine = 8/9 ≈ 0.89. Very similar directions.
Traps
- Mixing embedding models makes similarities meaningless.
- Similar isn't the same as correct: "refunds are allowed" and "refunds are not allowed" embed close together.
- Embeddings are weak on exact codes and numbers (order IDs, part numbers); add keyword search.
- Scores aren't comparable across models; pick thresholds per model.
Want the full lesson with step-by-step examples, a project and a certificate? RAG & Vector Search course, ₹180 →
- Question 1easy
What is a text embedding?
- Question 2medium
Documents were embedded with model A. You switch to model B for questions only. What happens?
- Question 3easy
What does this print?
import numpy as np a = np.array([0.6, 0.8]) b = np.array([0.8, 0.6]) print(round(float(a @ b), 2))
- Question 4medium
The practice embedding only matches shared words. What does this print?
from practice_llm import embed, cosine print(round(cosine(embed("reimbursement please"), embed("Refunds go back to the way you paid")), 2)) - Question 5medium
Why do RAG systems use embedding models rather than plain keyword matching?
Embeddings and similarity: cosine similarity by hand
Embeddings and similarity: cosine similarity by hand
Embeddings and similarity: cosine similarity by hand
Embeddings and similarity: cosine similarity by hand
Embeddings and similarity: cosine similarity by hand
5 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.