Sub topic 1
From Data to Vectors: What Embeddings Are
Prerequisites
Assume you know basic Python, vectors, dot products, and the purpose of machine-learning embeddings.
From Data to Vectors
An embedding is a numeric vector that represents an item, such as text, an image, or a product. An embedding model maps similar items to nearby points in a high-dimensional space.
For example, a model may convert each sentence into a vector with 768 floating-point values. The values do not usually have direct human meanings. Their pattern captures features learned from training data.
A vector database stores these vectors with their source data and metadata. Given a query vector, it finds stored vectors that are most similar.
Measuring Similarity
A similarity metric assigns a score to two vectors. The correct choice depends on how the embedding model was trained and normalized.
| Metric | Meaning | Common choice |
|---|---|---|
| Cosine similarity | Compares direction, ignoring vector length | Normalized text embeddings |
| Dot product | Combines direction and magnitude | Models trained for inner-product search |
| Euclidean distance | Measures straight-line distance | Models where geometric distance matters |
Cosine similarity ranges from -1 to 1. A larger value means more similar. Euclidean distance works in the opposite direction: a smaller value means more similar. If vectors are normalized to length one, maximizing dot product gives the same ordering as cosine similarity.
Exact Nearest Neighbor Search
Exact nearest neighbor search compares a query with every stored vector. This brute-force approach is simple and provides the correct baseline.
import numpy as np
rng = np.random.default_rng(0)
vectors = rng.normal(size=(1000, 64)).astype("float32")
query = rng.normal(size=64).astype("float32")
def normalize(x):
return x / np.linalg.norm(x, axis=-1, keepdims=True)
scores = normalize(vectors) @ normalize(query)
top5 = np.argsort(-scores)[:5]
print(top5, scores[top5])Why Exact Search Stops Scaling
With N stored vectors of dimension D, brute-force search needs about N × D comparisons per query. Larger collections increase latency and memory traffic. Repeating this for many users can also exhaust CPU capacity.
Approximate nearest neighbor indexes reduce the work by examining only promising candidates. They may miss some true neighbors, so later chapters measure this trade-off as recall, the fraction of correct neighbors returned.
Exercise
Why can normalized dot product be used for cosine similarity?
Show answer
Normalization gives every vector length one, so the dot product equals the cosine of the angle between the vectors.