AI Foundations for Developers COURSE·LESSON 29 OF 410 completed

Embeddings and Vector Similarity

Encode meaning for comparison

An embedding model maps an item, such as a sentence, to a vector. Training encourages useful relationships under a particular objective. Queries about “getting my money back” may become close to a passage containing “refund,” even without identical wording.

Different embedding models define different spaces. Do not compare document vectors from one model with query vectors from another unless the system explicitly supports that pairing. Some retrievers intentionally use separately trained query and document encoders; their compatibility comes from training, not matching dimensions alone.

Cosine similarity by hand

Cosine similarity is dot(a,b)/(norm(a)×norm(b)). It compares direction, making vector length irrelevant to that score. For nonzero real vectors the mathematical range is -1 to 1. Many real embedding datasets occupy a narrower range; do not assume a universal “good” threshold.

python
import math

def cosine(a, b):
    if len(a) != len(b):
        raise ValueError("Mismatched dimensions")
    na = math.sqrt(sum(x*x for x in a))
    nb = math.sqrt(sum(x*x for x in b))
    if na == 0 or nb == 0:
        return 0.0
    return sum(x*y for x, y in zip(a, b)) / (na * nb)

query = [1, 0]
documents = {"refund": [0.9, 0.1], "password": [0.1, 0.9]}
for name, vector in documents.items():
    print(name, round(cosine(query, vector), 3))
# refund 0.994
# password 0.11

The vectors are illustrative, not outputs of a trained encoder. Run in the Python compiler.

Indexing and retrieval

For a small collection, compare a query against every vector. At scale, approximate nearest-neighbor indexes trade exactness for speed and memory. Evaluate retrieval recall at your configured settings rather than assuming approximate search always returns the exact nearest items.

Save embedding model/version, chunk ID, document version, tenant permissions, and source metadata with the index. Changing embedding models usually requires re-embedding the corpus and rebuilding compatible indexes.

Checkpoint with answers

Does similarity prove that a passage answers the question? No. Similar wording or topic can still omit the required fact.

Why might exact product codes need keyword search? Semantic encoders can blur distinctions between similar strings; lexical search preserves exact matching well.

Exercise: Both vectors have 768 numbers but come from unrelated models. Are they comparable? Answer: not reliably. Dimension equality is insufficient.

Learn at your own pace0 / 41 lessons complete