Sub topic 1
From data to vectors: what embeddings are
Prerequisites
This chapter assumes you can read basic Python, know what a vector and a dot product are, and have a general idea of what a machine learning model does. You do not need to know how to train a model.
What an embedding is
An embedding is a list of numbers, a vector, that a model produces for a piece of data such as a sentence, an image, or a product. The model is trained so that items with similar meaning end up with vectors that are close together. Items with unrelated meaning end up far apart.
This turns a fuzzy question ("which documents are about the same thing?") into a geometric one ("which vectors are nearest?"). A vector database exists to answer that second question quickly.
The vector length is the model's dimension. Common text models produce 384, 768, 1024, or 1536 numbers per item. Every vector from one model has the same length, and the individual numbers have no meaning on their own. Only the distances and angles between vectors carry information.
A worked example
The sketch below uses a toy embedding function so that it runs without downloading a model. It hashes words into a small vector. Real models learn meaning, but the way you use the output is the same.
import numpy as np
DIM = 16
def toy_embed(text: str) -> np.ndarray:
"""Bag-of-words hashing embedding. For illustration only."""
v = np.zeros(DIM, dtype="float32")
for word in text.lower().split():
v[hash(word) % DIM] += 1.0
return v / (np.linalg.norm(v) or 1.0)
docs = [
"the cat sat on the mat",
"a cat lay on a mat",
"stock markets fell sharply today",
]
vectors = np.stack([toy_embed(d) for d in docs])
query = toy_embed("cat on the mat")
scores = vectors @ query
for doc, score in sorted(zip(docs, scores), key=lambda p: -p[1]):
print(f"{score:.2f} {doc}")The two cat sentences score higher than the finance sentence because they share words. A trained model goes further: "kitten resting on a rug" would also land near the cat sentences even with no shared words. That is the reason to use learned embeddings instead of keyword matching.
Python randomizes hash for strings between runs, so exact scores can differ from run to run. The ranking is what matters here.
Using a real model
With the sentence-transformers library, the same pattern looks like this:
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2")
vecs = model.encode(
["The cat sat on the mat.", "A kitten rests on a rug."],
normalize_embeddings=True,
)
print(vecs.shape) # (2, 384)
print(float(vecs[0] @ vecs[1]))The normalize_embeddings=True option scales each vector to length 1. Whether you should normalize depends on how the model was trained, which the next chapter covers.
Common errors
- Mixing models. Vectors from different models live in different spaces, even when they have the same dimension. Comparing them gives meaningless scores. Index and query with the same model and version.
- Changing the model without re-embedding. Upgrading a model means re-embedding the whole collection and rebuilding the index.
- Ignoring input limits. Models truncate or reject text beyond a maximum length. Long documents must be split into chunks before embedding.
- Treating dimensions as features. Coordinate 17 does not mean "is about animals". Do not inspect or filter on single coordinates.
- Expecting exact meaning. Embeddings capture similarity as the training data defined it. A model trained on general web text may rank domain-specific terms poorly.
Why this matters for the rest of the tutorial
Everything that follows works on vectors only. Similarity metrics decide what "close" means, and indexes decide how to find close vectors without checking all of them. The quality of the results is limited first by the embedding model, so it is worth testing the model on your own data before you tune anything else.
Exercise
You embed your documents with model A (768 dimensions). Later, a teammate embeds new queries with model B, which also has 768 dimensions. The code runs without errors. Why are the search results still unreliable, and what is the fix?
Show answer
A vector's coordinates only make sense within the space of the model that produced it. Model B's 768 numbers are arranged differently from model A's, so distances between the two sets of vectors do not reflect meaning, even though the shapes match and nothing raises an error. The fix is to embed queries and documents with the same model and version, and to re-embed and re-index the documents if you switch models.