Vector Norms, Distances, Dot Products & Cosine Similarity
Measure length, distance, and directional alignment — the geometric core of KNN, Lasso/Ridge, RAG search, and Transformer attention
Dot Products & Cosine Similarity ARE the engine behind RAG search, Recommendations, Attention, and L1/L2 Regularization!
Every vector database (Pinecone, pgvector, FAISS) retrieves RAG documents by Cosine Similarity, and every Transformer Attention head starts with Q · Kᵀ dot products!
Understanding L1 (diamond) vs. L2 (circle) norms instantly explains why Lasso zeroes out irrelevant features while Ridge smoothly shrinks correlated ones.
Implementing Cosine Similarity Top-K retrieval and L2 normalization without NaN division-by-zero is one of the most frequent GenAI coding interview tasks.
In a RAG search engine, Doc A mentions 'AI' 2 times and 'Python' 2 times ([2, 2]). Doc B is 10× longer and mentions 'AI' 20 times and 'Python' 20 times ([20, 20]). What is their Cosine Similarity?
- Compute L1 (Manhattan), L2 (Euclidean), and L∞ (Max) norms by hand and explain their unit-ball geometry.
- Calculate Euclidean vs. Manhattan distances between feature vectors (and why feature scaling is mandatory).
- Compute dot products algebraically (Σ a_i b_i) and interpret them geometrically via orthogonal projection shadows.
- Use unit vectors, Cauchy–Schwarz, and Cosine Similarity — and know exactly when to pick Cosine vs. Dot Product vs. L2 in ML & RAG.
Once you know how to represent data as vectors, the next question every ML algorithm asks is: "How big is this vector, and how similar are these two vectors?" Answering that question cleanly gives you norms (vector length), distances (KNN & clustering), dot products (projections & neural layers), and cosine similarity (semantic search & RAG).
1. Vector Norms: Three Ways to Measure Length (L₁, L₂, L∞)
Imagine standing at the corner of 1st Ave & 1st St, and your favorite coffee shop is 4 blocks East and 3 blocks North ([4, 3]). How far away is it? Depends on how you travel!
- By NYC Taxi (must follow street grids):
4 + 3 = 7 blocks(L1 Norm!). - By Helicopter (straight diagonal line):
√(4² + 3²) = 5 blocks(L2 Norm!).
Click any intersection on the city grid below to feel L1 vs. L2 norms instantly!
A norm assigns a non-negative length to any vector . Every valid norm obeys 3 common-sense rules:
- Non-negativity: , and .
- Scaling: (doubling a vector doubles its length).
- Triangle Inequality: (a straight shortcut is never longer than a detour!).
The family of norms is defined as :
| Norm | Formula | Intuition | ML & Deep Learning Role |
|---|---|---|---|
| (Manhattan) | $|\mathbf{x}|1 = \sum{i=1}^d | x_i | $ |
| (Euclidean) | Straight-line Pythagorean length | Ridge / Weight Decay, MSE, gradient clipping, embedding normalization | |
| (Max) | $|\mathbf{x}|_\infty = \max_i | x_i | $ |
Worked Example 1 — Computing All 3 Norms by Hand
Take the simple 2D vector :
- norm:
- norm: (classic 3-4-5 right triangle!)
- norm:
Notice a universal ordering you can always check: ()!
Unit Vectors (Pure Direction, Length = 1)
To strip away a vector's length and keep only its direction, divide by its norm: For , its unit vector is . Check its length: !
Click any intersection on this city map! A taxi MUST drive along streets (L1 Norm = |x| + |y|), while a helicopter flies straight diagonally (L2 Norm = √(x² + y²)).
Compute the L1 norm, L2 norm, L∞ norm, and unit vector v̂ for v = [1, -2, 2]ᵀ.
2. Distance Between Two Data Points (KNN & Clustering)
How does a single neuron in a neural network decide whether to fire? It takes your input features x = [study_hrs, sleep_hrs], multiplies each by its importance weight w = [3, 1], and adds them up: 3·study + 1·sleep. That multiply-and-sum scorecard IS the Dot Product — and geometrically, it measures how strongly two arrows agree in direction!
The distance between two vectors and is simply the norm of their difference vector :
- Euclidean () distance:
- Manhattan () distance:
Worked Example 2 — Customer Similarity in KNN
Suppose Customer A has normalized features and Customer B has :
- Difference vector: .
- Euclidean distance: .
- Manhattan distance: .
Why Feature Scaling Is Mandatory Before Distances: If Feature 1 is annual income in dollars (150,000) and Feature 2 is number of purchases (1–10), squared income differences will be while purchase differences are — completely drowning out Feature 2 unless you standardize first!
Why normalizing embeddings turns expensive Cosine Search into a blazing-fast single Dot Product!
Multiply matching coordinates and sum them: big & positive when a and b point together, 0 when perpendicular!
3. The Dot Product: Algebra Meets Geometry
Why do RAG engineers normalize every embedding before saving it to Pinecone or FAISS? Because a long Wikipedia page and a short user query have totally different vector lengths — without normalization, Euclidean distance accidentally thinks two short unrelated sentences are closer than a short query and its long exact answer!
The dot product (also called the inner product) of combines two vectors into a single scalar — and has two miraculous equivalent forms:
What the Sign Tells You Instantly
- : Acute angle () — pointing in roughly the same direction.
- : Exact right angle () — orthogonal (perpendicular, zero shared direction!).
- : Obtuse angle () — pointing in opposite directions.
Vector Projection (Casting a Shadow)
Drop a perpendicular from the tip of onto the line along . The shadow vector is:
Worked Example 3 — Dot Product, Angle & Orthogonal Check
Let , , and :
- : .
- Norms: , .
- (very aligned!).
- Shadow of on : .
- : !
- Even without measuring with a protractor, we immediately know and meet at an exact right angle!
The Cauchy–Schwarz Inequality
Because always, we get one of the most famous bounds in all of mathematics: Equality holds if and only if one vector is a scalar multiple of the other.
Pause & Check: Two vectors a = [3, 1] and b = [−2, 6] have dot product a · b = (3)(−2) + (1)(6) = 0. What does dot product = 0 tell you geometrically?
Are u = [2, -1, 3]ᵀ and v = [1, 5, 1]ᵀ orthogonal, pointing in a similar direction, or opposite? Compute u · v.
4. Cosine Similarity & The Unit-Vector Equivalence (Why RAG Works)
Dividing the dot product by both lengths cancels out magnitude completely and isolates pure directional similarity:
Worked Example 4 — Solving Our Opening Document Search Paradox
Suppose we count 2 keywords ["AI", "Sports"]:
- Doc A (short AI tweet):
- Doc B (long AI essay = 3× Doc A):
- Doc C (short Sports tweet):
- Raw Euclidean Distance to Doc A:
- (Euclidean mistakenly ranks Sports closer than the AI essay!)
- Cosine Similarity to Doc A:
- (Exact topic match!)
The Golden Identity for Vector Databases (FAISS / Pinecone / pgvector)
Once you -normalize every vector ():
So on unit-normalized embeddings, maximizing Dot Product = maximizing Cosine Similarity = minimizing Euclidean Distance!
If two unit-normalized embeddings û and v̂ have cosine similarity 0.5, what is their squared Euclidean distance ‖û − v̂‖₂²?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
Picture expanding a balloon (your loss contour) until it first touches a fence (your regularization budget). If the fence is a smooth L2 circle, the balloon almost always bumps into a curvy side where both and are nonzero. If the fence is a pointy L1 diamond, the balloon almost always hits one of the sharp corners sitting right on an axis — forcing the other weight to exact 0.0 (automatic feature selection)!
Transformer Attention Scaling (1 / √d_k)
If entries of query q and key k have mean 0 and variance 1, their dot product qᵀk has variance d_k (std √d_k). Dividing by √d_k restores unit variance so softmax doesn't saturate into vanishing gradients.
RAG & Semantic Vector Search
Document embeddings are L2-normalized at index time so retrieval ranks by pure semantic direction (cosine similarity) using ultra-fast inner-product hardware instructions.
L1 (Lasso) vs L2 (Ridge) Regularization
Adding λ‖w‖₁ creates sharp diamond corners on coordinate axes that zero out irrelevant features (sparsity), while λ‖w‖₂² smoothly shrinks correlated weights without eliminating them.
Curse of Dimensionality & Superposition in LLMs
In high dimensions (d = 1536), two random unit vectors are almost always nearly orthogonal (std of dot product = 1/√d ≈ 0.025), enabling LLMs to store far more features than dimensions.
import numpy as np
# 1. Computing L1, L2, and L-infinity norms in NumPy
v = np.array([3.0, -4.0])
l1 = np.linalg.norm(v, ord=1) # 7.0
l2 = np.linalg.norm(v, ord=2) # 5.0 (default)
linf = np.linalg.norm(v, ord=np.inf) # 4.0
# 2. Safe L2 normalization for a batch of embeddings (N=4, D=3)
X = np.array([[3.0, 4.0, 0.0],
[1.0, 2.0, 0.0],
[-3.0, -4.0, 0.0],
[0.0, 0.0, 0.0]]) # zero-vector edge case!
norms = np.linalg.norm(X, axis=1, keepdims=True) # shape: (4, 1)
X_unit = X / np.maximum(norms, 1e-12) # avoids NaN on row 3!
# 3. All-pairs Cosine Similarity matrix in ONE matrix multiply: O(N^2 D)
cos_sim = X_unit @ X_unit.T # shape: (4, 4)
# PyTorch equivalent:
# import torch.nn.functional as F
# X_unit = F.normalize(X_t, p=2, dim=-1, eps=1e-12)
# cos_sim = X_unit @ X_unit.T