Welcome to this SysSeder introduction to vector embeddings and cosine similarity.
Vector representations appear in retrieval, recommendation and other machine-learning systems. This article studies a small mathematical building block, not the whole practice of data science or a claim about current hiring requirements.
But here is the secret: underneath the fancy marketing buzzwords of modern AI lies a bedrock of fundamental mathematics. When we talk about vector databases, embeddings, and semantic search, we are actually talking about linear algebra and geometry.
We can make the mathematics concrete by implementing vector operations and cosine similarity in plain Python. The code is educational and unexecuted, not a replacement for tested numerical libraries.
Why vector mathematics matters for retrieval
Before we write any code, let's address the "why." Why do we represent data as vectors in a high-dimensional space?
Exact numerical and string comparisons such as 5 > 3 and "apple" == "apple" differ from semantic retrieval. A substring pattern like LIKE "%feline companion%" does not by itself match the different words “domestic cat”; these phrases may be related without being identical in every context.
An embedding represents data as a numerical vector. Training may encourage some useful relations to correspond to proximity, but the result depends on the model, objective and metric; closeness does not automatically establish semantic equivalence.
As a deliberately hand-designed toy, let two coordinates stand for “feline” and “domestic” on a 0–1 scale. These are invented features, not learned embeddings or biological measurements:
- Lion:
[0.9, 0.1](Highly feline, not domestic) - House Cat:
[0.95, 0.95](Highly feline, highly domestic) - Golden Retriever:
[0.1, 0.9](Not feline, highly domestic)
Geometry compares these chosen coordinates. Whether the resulting ranking captures a useful relation must be evaluated; cosine and Euclidean distance need not produce the same order.
The Math: Cosine Similarity vs. Euclidean Distance
Two common comparison measures are Euclidean distance and cosine similarity. Cosine similarity is not itself a distance; the often-used cosine distance is one minus that similarity.
Euclidean Distance
Euclidean distance measures straight-line separation and is sensitive to vector scale. That can be desirable or undesirable depending on the representation and task; it is not an inherent flaw.
In an unnormalized word-count representation, repeating the same word distribution can increase vector magnitude without changing direction. Learned embeddings are different: their norms need not grow with document length, and many systems normalize them.
Cosine Similarity
For nonzero vectors, cosine similarity is the cosine of their angle, not the angle itself. Multiplying either vector by a positive scale leaves the similarity unchanged; a negative scale reverses its direction.
For nonzero vectors A and B of equal dimension, the formula is:
A · B
Cosine Similarity = -------
||A|| ||B||
Let's break that down into developer terms:
- A · B (The Dot Product): We multiply corresponding elements of vector A and vector B, and sum the results.
- ||A|| and ||B|| (The Norms/Magnitudes): The length of each vector, calculated by squaring each element, summing them, and taking the square root.
For finite real nonzero vectors, the mathematical value lies between -1 and 1. Floating-point arithmetic introduces rounding; a zero vector has no defined direction.
- 1: Same direction; this does not prove identical meanings.
- 0: Orthogonal vectors in this representation, not necessarily unrelated real-world concepts.
- -1: Opposite vector directions, not automatically linguistic antonyms.
Implementing Cosine Similarity from Scratch
Now that we understand the math, let's write some code. We won't use NumPy or PyTorch here. Writing this in plain Python will help cement how the math translates to code loops.
import math
def checked_vector(vector):
values = tuple(float(x) for x in vector)
if not values or not all(math.isfinite(x) for x in values):
raise ValueError("Vectors must be nonempty and finite")
return values
def dot_product(vector_a, vector_b):
a, b = checked_vector(vector_a), checked_vector(vector_b)
if len(a) != len(b):
raise ValueError("Vectors must have the same dimension")
return math.fsum(x * y for x, y in zip(a, b))
def magnitude(vector):
return math.hypot(*checked_vector(vector))
def cosine_similarity(vector_a, vector_b):
a, b = checked_vector(vector_a), checked_vector(vector_b)
if len(a) != len(b):
raise ValueError("Vectors must have the same dimension")
mag_a, mag_b = math.hypot(*a), math.hypot(*b)
if not math.isfinite(mag_a) or not math.isfinite(mag_b):
raise ValueError("Norm exceeds this implementation's numeric range")
if mag_a == 0 or mag_b == 0:
raise ValueError("Cosine is undefined for a zero vector")
# Normalize before multiplication to reduce avoidable intermediate overflow.
value = math.fsum((x / mag_a) * (y / mag_b) for x, y in zip(a, b))
return max(-1.0, min(1.0, value)) # Clamp tiny floating-point excursions.
# Illustrative hand-assigned coordinates, not model output or executed tests.
vector_a = [0.9, 0.8] # Label: Cat
vector_b = [0.85, 0.85] # Label: Kitten
vector_c = [0.1, 0.05] # Label: Space Shuttle; label does not determine direction.
print(f"Similarity (Cat, Kitten): {cosine_similarity(vector_a, vector_b):.4f}")
print(f"Similarity (Cat, Space Shuttle): {cosine_similarity(vector_a, vector_c):.4f}")
No script was executed. Substituting the coordinates into the formula gives these exact symbolic comparisons, rather than the original incorrect decimal output:
cos(A, B) = 1.7 / sqrt(2.9)
cos(A, C) = 0.13 / sqrt(0.018125)
The “Space Shuttle” label cannot make its invented vector point away from the “Cat” vector. Positive coordinates keep angles below 90 degrees, but do not alone force high similarity. More dimensions do not automatically yield better semantic separation; the representation and training matter.
A miniature ranking demonstration with hand-designed vectors
The corpus below uses four invented topic features and manually assigned query vectors. It demonstrates ranking mechanics only: no text embedding API or learned model processes either query.
# A mock database of articles with 4-dimensional embeddings.
# Dimensions represent: [Tech, Cooking, Sports, Space]
documents = [
{
"title": "How to deploy a Docker container to AWS",
"embedding": [0.95, 0.05, 0.01, 0.1] # High Tech
},
{
"title": "The ultimate sourdough bread recipe",
"embedding": [0.02, 0.98, 0.05, 0.01] # High Cooking
},
{
"title": "Understanding the James Webb Space Telescope",
"embedding": [0.4, 0.01, 0.05, 0.95] # Medium Tech, High Space
},
{
"title": "World Cup qualifiers: tactics and analysis",
"embedding": [0.05, 0.1, 0.95, 0.02] # High Sports
}
]
def search(query_vector, corpus, top_n=2):
if not isinstance(top_n, int) or top_n < 1:
raise ValueError("top_n must be a positive integer")
results = []
for doc in corpus:
score = cosine_similarity(query_vector, doc["embedding"])
results.append((doc["title"], score))
# Sort results by similarity score in descending order
results.sort(key=lambda x: x[1], reverse=True)
return results[:top_n]
# Scenario: User searches for "Kubernetes hosting and cloud orchestration"
# Hand-assigned toy query vector; no model or text encoder:
query_tech = [0.88, 0.02, 0.02, 0.2]
print("--- Search Results for 'Cloud Tech' ---")
for title, score in search(query_tech, documents):
print(f"[{score:.4f}] {title}")
# Scenario: User searches for "NASA Mars mission updates"
# Hand-assigned toy query vector; no model or text encoder:
query_space = [0.2, 0.0, 0.0, 0.9]
print("\n--- Search Results for 'Mars Mission' ---")
for title, score in search(query_space, documents):
print(f"[{score:.4f}] {title}")
The manually assigned coordinates are designed to rank the Docker article before the telescope article for the cloud query, and the telescope article before the Docker article for the space query. This is an explanatory order, not captured output or a semantic-quality test. The following indices refer to the zero-based document list.
cloud_query_order = [0, 2]
space_query_order = [2, 0]
The mapping was supplied by the author through the toy coordinates. The search function compares numbers and never reads the query text; a real semantic-search system requires a consistent encoder and evaluation.
Scale Challenges: Enter Vector Databases
You might ask: if this is so simple, why use infrastructure such as Pinecone, Milvus, Qdrant or pgvector?
For N documents of dimension d, this direct comparison costs O(Nd), followed here by O(N log N) sorting. Calling the scan O(N) assumes d is fixed and ignores the explicit full sort. This is an analysis of the supplied loops and full comparison sort, not a benchmark; CPython documents its adaptive merge-based sorting implementation.
Large exhaustive scans can be costly, but elapsed time depends on implementation, hardware, vector dimension and batching. This article provides no millisecond benchmark or universal viability threshold.
Approximate-nearest-neighbor indexes can trade recall against search work. HNSW is a hierarchical graph method; trees and quantization are other families, not synonyms for it. Its paper reports logarithmic scaling in its setting, not a universal O(log N) worst-case guarantee for all vector searches. Measure recall, latency, memory and build/update cost on your data.
Conclusion
Vector arithmetic explains one part of retrieval. It does not by itself explain model training or establish that geometric similarity represents the meaning needed by an application. Keep the representation, metric and evaluation separate.
These building blocks help you inspect a similarity calculation. A vector database or LLM pipeline may use different metrics, normalization and indexing, which must be checked separately.
What about you? Are you working on integrating AI, semantic search, or RAG systems into your stack? Have you run into scaling issues with vector queries? Let’s talk about it in the comments below!
Until next time, happy coding!
Primary documentation
- Normalized dot-product definition; similarity is geometric rather than semantic truth.
- Cosine distance is1 minus normalized dot product.
- math.hypot, fsum and isfinite APIs for illustrative numerical safeguards.
- Original HNSW hierarchical graph and reported logarithmic scaling, not universal guarantees.
- Text count/vector representations and normalization differ from unqualified semantic claims.
- Primary CPython design notes describe adaptive stable merge sorting; O(Nd) scan plus worst-case comparison-sort O(N log N) is author analysis of the provided example.