Embeddings and Cosine Similarity

Turn text into vectors and measure how close two vectors point. The closest document is the one RAG retrieves.

AI · intermediate · 8 min · 30 steps · free

What you'll learn

embeddings.py

import math

VOCAB = ['refund', 'money', 'back', 'ship', 'open']

def embed(text):
    words = text.lower().split()
    return [words.count(w) for w in VOCAB]

def cosine(a, b):
    size = math.hypot(*a) * math.hypot(*b)
    return math.sumprod(a, b) / size if size else 0.0

docs = ['refund money back', 'refund on shipping fees', 'shop is open daily']
query = embed('how do i get my money back refund')
scores = [round(cosine(query, embed(d)), 2) for d in docs]
best = docs[scores.index(max(scores))]
print(best, scores)

Step by step

  1. This brings in Python's built-in math module, so the program can use the functions it provides.
  2. A tiny vocabulary: each word gets one position in the vector.
  3. Python defines the function embed(). Its body does not run yet: it runs each time the function is called.
  4. Python defines the function cosine(). Its body does not run yet: it runs each time the function is called.
  5. docs is created and points to a new list: ['refund money back', 'refund on shipping fees', 'shop is open daily'].
  6. Python calls embed(), with text = 'how do i get my money back refund'. It gets its own names.
  7. words is created and points to a new list: ['how', 'do', 'i', 'get', 'my', 'money', 'back', 'refund'].
  8. The function returns [words.count(w) for w in VOCAB].
  9. The question becomes [1, 1, 1, 0, 0]: refund, money and back appear once each.
  10. Python calls embed(), with text = 'refund money back'. It gets its own names.
  11. words is created and points to a new list: ['refund', 'money', 'back'].
  12. The function returns [words.count(w) for w in VOCAB].
  13. cosine = (a · b) / (|a| × |b|): 1 when the vectors point the same way, 0 when they share nothing.
  14. size is the length of each vector multiplied together.
  15. The function returns math.sumprod(a, b) / size if size else 0.0.
  16. Python calls embed(), with text = 'refund on shipping fees'. It gets its own names. cosine() has finished, so its names are gone.
  17. words is created and points to a new list: ['refund', 'on', 'shipping', 'fees'].
  18. The function returns [words.count(w) for w in VOCAB].
  19. The second document shares only "refund".
  20. size is created with the value 1.73205.
  21. The function returns math.sumprod(a, b) / size if size else 0.0.
  22. Python calls embed(), with text = 'shop is open daily'. It gets its own names. cosine() has finished, so its names are gone.
  23. words is created and points to a new list: ['shop', 'is', 'open', 'daily'].
  24. The function returns [words.count(w) for w in VOCAB].
  25. Python calls cosine(), with a = [1, 1, 1, 0, 0] and b = [0, 0, 0, 0, 1]. It gets its own names. embed() has finished, so its names are gone.
  26. size is created with the value 1.73205.
  27. The function returns math.sumprod(a, b) / size if size else 0.0.
  28. cosine() has finished, so its names are gone. The value it returned, [1, 0.58, 0], is stored in scores.
  29. The highest score wins: this is the document RAG would put in the prompt.
  30. It prints refund money back [1.0, 0.58, 0.0].

Common mistakes

Best practices

Key takeaways

Check yourself

Two identical texts have cosine similarity?

Answer: 1

Why divide by the vector sizes?

Answer: So long documents do not win just for being long

More in Retrieval