Chapter 2 of 10 · ~20 min read & lab+50 XP
Chapter 2 · Linear Algebra

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

Why ML Engineers & Data Scientists Actually Need This

Dot Products & Cosine Similarity ARE the engine behind RAG search, Recommendations, Attention, and L1/L2 Regularization!

ML / AI Engineer

Every vector database (Pinecone, pgvector, FAISS) retrieves RAG documents by Cosine Similarity, and every Transformer Attention head starts with Q · Kᵀ dot products!

Data Scientist

Understanding L1 (diamond) vs. L2 (circle) norms instantly explains why Lasso zeroes out irrelevant features while Ridge smoothly shrinks correlated ones.

Interview & Debug Edge

Implementing Cosine Similarity Top-K retrieval and L2 normalization without NaN division-by-zero is one of the most frequent GenAI coding interview tasks.

Step 0 · Test Your Gut Before Any Math!

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?

What You Will Master in This Chapter
  • 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.
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
No mysterious math notation — translate everything into English first
How to Say It Aloud
“L2 Norm (Euclidean length of x)”
Plain-English Meaning
Ordinary straight-line ruler length from the origin: square each entry, add them, take square root!
Everyday Example
‖[3, 4]‖₂ = √(3² + 4²) = √25 = 5.
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

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∞)

Everyday Story First (Zero Math Yet!)

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!

L₁ Norm (Manhattan)|x₁| + |x₂| = 1Sharp corners → Lasso sparsityL₂ Norm (Euclidean)√(x₁² + x₂²) = 1Smooth circle → Ridge decayL∞ Norm (Max)max(|x₁|, |x₂|) = 1Square box → Adversarial ε-ball
Figure 2.1 — Unit Balls (‖x‖_p = 1): L1's sharp corners on coordinate axes explain why Lasso creates sparse zero weights, while L2's smooth circle shrinks correlated features together.

A norm ∥x∥\|\mathbf{x}\| assigns a non-negative length to any vector x∈Rd\mathbf{x} \in \mathbb{R}^d. Every valid norm obeys 3 common-sense rules:

  1. Non-negativity: ∥x∥≥0\|\mathbf{x}\| \ge 0, and ∥x∥=0  ⟺  x=0\|\mathbf{x}\| = 0 \iff \mathbf{x} = \mathbf{0}.
  2. Scaling: ∥αx∥=∣α∣∥x∥\|\alpha \mathbf{x}\| = |\alpha|\|\mathbf{x}\| (doubling a vector doubles its length).
  3. Triangle Inequality: ∥x+y∥≤∥x∥+∥y∥\|\mathbf{x} + \mathbf{y}\| \le \|\mathbf{x}\| + \|\mathbf{y}\| (a straight shortcut is never longer than a detour!).

The family of LpL_p norms is defined as ∥x∥p=(∑i=1d∣xi∣p)1/p\|\mathbf{x}\|_p = \left(\sum_{i=1}^d |x_i|^p\right)^{1/p}:

NormFormulaIntuitionML & Deep Learning Role
L1L_1 (Manhattan)$|\mathbf{x}|1 = \sum{i=1}^dx_i$
L2L_2 (Euclidean)∥x∥2=∑i=1dxi2\|\mathbf{x}\|_2 = \sqrt{\sum_{i=1}^d x_i^2}Straight-line Pythagorean lengthRidge / Weight Decay, MSE, gradient clipping, embedding normalization
L∞L_\infty (Max)$|\mathbf{x}|_\infty = \max_ix_i$

Worked Example 1 — Computing All 3 Norms by Hand

Take the simple 2D vector v=[3−4]\mathbf{v} = \begin{bmatrix} 3 \\ -4 \end{bmatrix}:

  • L1L_1 norm: ∥v∥1=∣3∣+∣−4∣=3+4=7\|\mathbf{v}\|_1 = |3| + |-4| = 3 + 4 = \mathbf{7}
  • L2L_2 norm: ∥v∥2=32+(−4)2=9+16=25=5\|\mathbf{v}\|_2 = \sqrt{3^2 + (-4)^2} = \sqrt{9 + 16} = \sqrt{25} = \mathbf{5} (classic 3-4-5 right triangle!)
  • L∞L_\infty norm: ∥v∥∞=max⁡(∣3∣,∣−4∣)=4\|\mathbf{v}\|_\infty = \max(|3|, |-4|) = \mathbf{4}

Notice a universal ordering you can always check: ∥v∥∞≤∥v∥2≤∥v∥1\|\mathbf{v}\|_\infty \le \|\mathbf{v}\|_2 \le \|\mathbf{v}\|_1 (4≤5≤74 \le 5 \le 7)!

Unit Vectors (Pure Direction, Length = 1)

To strip away a vector's length and keep only its direction, divide by its L2L_2 norm: v^=v∥v∥2\hat{\mathbf{v}} = \frac{\mathbf{v}}{\|\mathbf{v}\|_2} For v=[3,−4]T\mathbf{v} = [3, -4]^T, its unit vector is v^=[3/5,−4/5]T=[0.6,−0.8]T\hat{\mathbf{v}} = [3/5, -4/5]^T = [0.6, -0.8]^T. Check its length: 0.62+(−0.8)2=0.36+0.64=1.0\sqrt{0.6^2 + (-0.8)^2} = \sqrt{0.36 + 0.64} = \mathbf{1.0}!

Hands-On Mini-Lab · Taxi Blocks (L1) vs. Helicopter (L2) Distance!

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²)).

Target Vector: v = [4, 3]
L1 (Taxi / Lasso): |4| + |3| = 7.0
L2 (Helicopter / Ridge): √(4²+3²) = 5.00
L∞ (Max Step): max(4, 3) = 4
Try It Yourself

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)

Everyday Story First (Zero Math Yet!)

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 p\mathbf{p} and q\mathbf{q} is simply the norm of their difference vector p−q\mathbf{p} - \mathbf{q}:

  • Euclidean (L2L_2) distance: d2(p,q)=∥p−q∥2=∑i=1d(pi−qi)2d_2(\mathbf{p}, \mathbf{q}) = \|\mathbf{p} - \mathbf{q}\|_2 = \sqrt{\sum_{i=1}^d (p_i - q_i)^2}
  • Manhattan (L1L_1) distance: d1(p,q)=∥p−q∥1=∑i=1d∣pi−qi∣d_1(\mathbf{p}, \mathbf{q}) = \|\mathbf{p} - \mathbf{q}\|_1 = \sum_{i=1}^d |p_i - q_i|

Worked Example 2 — Customer Similarity in KNN

Suppose Customer A has normalized features p=[1,2]T\mathbf{p} = [1, 2]^T and Customer B has q=[4,6]T\mathbf{q} = [4, 6]^T:

  1. Difference vector: p−q=[1−4,2−6]T=[−3,−4]T\mathbf{p} - \mathbf{q} = [1 - 4, 2 - 6]^T = [-3, -4]^T.
  2. Euclidean distance: (−3)2+(−4)2=9+16=5.0\sqrt{(-3)^2 + (-4)^2} = \sqrt{9 + 16} = \mathbf{5.0}.
  3. Manhattan distance: ∣−3∣+∣−4∣=7.0|-3| + |-4| = \mathbf{7.0}.

Why Feature Scaling Is Mandatory Before Distances: If Feature 1 is annual income in dollars (30,000–30,000–150,000) and Feature 2 is number of purchases (1–10), squared income differences will be 101010^{10} while purchase differences are <100< 100 — completely drowning out Feature 2 unless you standardize first!

Formula Anatomy · Click Any Colored Piece to Decode It
Cosine Similarity: cos(θ) = (a · b) / (‖a‖₂ · ‖b‖₂)

Why normalizing embeddings turns expensive Cosine Search into a blazing-fast single Dot Product!

Dot Product (Raw Alignment)

Multiply matching coordinates and sum them: big & positive when a and b point together, 0 when perpendicular!

In our example: [2, 2] · [20, 20] = 40 + 40 = 80
Put it together with real numbers: Production RAG trick: L2-normalize every vector once when indexing (so ‖a‖ = ‖b‖ = 1) — then Cosine Similarity is literally JUST `a @ b`!

3. The Dot Product: Algebra Meets Geometry

Everyday Story First (Zero Math Yet!)

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!

aShadow length = ‖b‖ cos(θ)bResidual r ⊥ a (90°)θa · b = ‖a‖ · (‖b‖ cos θ)Length of a × Shadow of b
Figure 2.2 — Geometric Meaning of the Dot Product: a·b equals ‖a‖ times the signed orthogonal shadow of b cast onto a.

The dot product (also called the inner product) of a,b∈Rd\mathbf{a}, \mathbf{b} \in \mathbb{R}^d combines two vectors into a single scalar — and has two miraculous equivalent forms:

a⋅b=aTb=∑i=1daibi⏟Fast Algebraic Formula=∥a∥2∥b∥2cos⁡θ⏟Geometric Meaning\underbrace{\mathbf{a} \cdot \mathbf{b} = \mathbf{a}^T \mathbf{b} = \sum_{i=1}^d a_i b_i}_{\text{Fast Algebraic Formula}} = \underbrace{\|\mathbf{a}\|_2 \|\mathbf{b}\|_2 \cos\theta}_{\text{Geometric Meaning}}

What the Sign Tells You Instantly

  • a⋅b>0\mathbf{a} \cdot \mathbf{b} > 0: Acute angle (θ<90∘\theta < 90^\circ) — pointing in roughly the same direction.
  • a⋅b=0\mathbf{a} \cdot \mathbf{b} = 0: Exact right angle (θ=90∘\theta = 90^\circ) — orthogonal (perpendicular, zero shared direction!).
  • a⋅b<0\mathbf{a} \cdot \mathbf{b} < 0: Obtuse angle (θ>90∘\theta > 90^\circ) — pointing in opposite directions.

Vector Projection (Casting a Shadow)

Drop a 90∘90^\circ perpendicular from the tip of b\mathbf{b} onto the line along a\mathbf{a}. The shadow vector is: proja(b)=aTbaTaa\text{proj}_{\mathbf{a}}(\mathbf{b}) = \frac{\mathbf{a}^T \mathbf{b}}{\mathbf{a}^T \mathbf{a}} \mathbf{a}

Worked Example 3 — Dot Product, Angle & Orthogonal Check

Let a=[3,4]T\mathbf{a} = [3, 4]^T, b=[1,2]T\mathbf{b} = [1, 2]^T, and c=[−4,3]T\mathbf{c} = [-4, 3]^T:

  1. a⋅b\mathbf{a} \cdot \mathbf{b}: (3)(1)+(4)(2)=3+8=11(3)(1) + (4)(2) = 3 + 8 = \mathbf{11}.
    • Norms: ∥a∥2=5\|\mathbf{a}\|_2 = 5, ∥b∥2=5≈2.236\|\mathbf{b}\|_2 = \sqrt{5} \approx 2.236.
    • cos⁡θ=1155≈0.9839  ⟹  θ≈10.3∘\cos\theta = \frac{11}{5\sqrt{5}} \approx 0.9839 \implies \theta \approx 10.3^\circ (very aligned!).
    • Shadow of b\mathbf{b} on a\mathbf{a}: 1125[3,4]T=[1.32,1.76]T\frac{11}{25}[3, 4]^T = [1.32, 1.76]^T.
  2. a⋅c\mathbf{a} \cdot \mathbf{c}: (3)(−4)+(4)(3)=−12+12=0(3)(-4) + (4)(3) = -12 + 12 = \mathbf{0}!
    • Even without measuring with a protractor, we immediately know a\mathbf{a} and c\mathbf{c} meet at an exact 90∘90^\circ right angle!

The Cauchy–Schwarz Inequality

Because ∣cos⁡θ∣≤1|\cos\theta| \le 1 always, we get one of the most famous bounds in all of mathematics: ∣aTb∣≤∥a∥2∥b∥2|\mathbf{a}^T \mathbf{b}| \le \|\mathbf{a}\|_2 \|\mathbf{b}\|_2 Equality holds if and only if one vector is a scalar multiple of the other.

Pause & Check · Quick Intuition Pulse

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?

Try It Yourself

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)

Doc A (short)Doc B = 3×Doc ADoc C (unrelated)Comparing Doc A to B & C:✗ Raw Euclidean (L₂) Distance:dist(A, C) < dist(A, B) → picks wrong doc!✓ Cosine Similarity (Angle):cos(A, B) = 1.000 (exact same topic!)cos(A, C) = 0.690 (different topic)
Figure 2.3 — Why RAG & Semantic Search Normalize Vectors: Doc B has the exact same topic direction as Doc A (cos = 1.0), even though Euclidean distance thinks Doc C is closer!

Dividing the dot product by both lengths cancels out magnitude completely and isolates pure directional similarity:

cos⁡(a,b)=aTb∥a∥2∥b∥2=a^Tb^∈[−1,1]\cos(\mathbf{a}, \mathbf{b}) = \frac{\mathbf{a}^T \mathbf{b}}{\|\mathbf{a}\|_2 \|\mathbf{b}\|_2} = \hat{\mathbf{a}}^T \hat{\mathbf{b}} \in [-1, 1]

Worked Example 4 — Solving Our Opening Document Search Paradox

Suppose we count 2 keywords ["AI", "Sports"]:

  • Doc A (short AI tweet): dA=[2,1]T\mathbf{d}_A = [2, 1]^T
  • Doc B (long AI essay = 3× Doc A): dB=[6,3]T\mathbf{d}_B = [6, 3]^T
  • Doc C (short Sports tweet): dC=[1,3]T\mathbf{d}_C = [1, 3]^T
  1. Raw Euclidean Distance to Doc A:
    • d2(A,B)=(6−2)2+(3−1)2=20≈4.47d_2(A, B) = \sqrt{(6-2)^2 + (3-1)^2} = \sqrt{20} \approx \mathbf{4.47}
    • d2(A,C)=(1−2)2+(3−1)2=5≈2.24d_2(A, C) = \sqrt{(1-2)^2 + (3-1)^2} = \sqrt{5} \approx \mathbf{2.24} (Euclidean mistakenly ranks Sports closer than the AI essay!)
  2. Cosine Similarity to Doc A:
    • cos⁡(A,B)=2(6)+1(3)545=1515=1.000\cos(A, B) = \frac{2(6)+1(3)}{\sqrt{5}\sqrt{45}} = \frac{15}{15} = \mathbf{1.000} (Exact topic match!)
    • cos⁡(A,C)=2(1)+1(3)510=550≈0.707\cos(A, C) = \frac{2(1)+1(3)}{\sqrt{5}\sqrt{10}} = \frac{5}{\sqrt{50}} \approx \mathbf{0.707}

The Golden Identity for Vector Databases (FAISS / Pinecone / pgvector)

Once you L2L_2-normalize every vector (∥a^∥2=∥b^∥2=1\|\hat{\mathbf{a}}\|_2 = \|\hat{\mathbf{b}}\|_2 = 1):

∥a^−b^∥22=∥a^∥22+∥b^∥22−2a^Tb^=2(1−cos⁡θ)\|\hat{\mathbf{a}} - \hat{\mathbf{b}}\|_2^2 = \|\hat{\mathbf{a}}\|_2^2 + \|\hat{\mathbf{b}}\|_2^2 - 2\hat{\mathbf{a}}^T\hat{\mathbf{b}} = 2(1 - \cos\theta)

So on unit-normalized embeddings, maximizing Dot Product = maximizing Cosine Similarity = minimizing Euclidean Distance!

Try It Yourself

If two unit-normalized embeddings û and v̂ have cosine similarity 0.5, what is their squared Euclidean distance ‖û − v̂‖₂²?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

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 w1w_1 and w2w_2 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)!

Interactive Visual Lab
Lab Challenge: Drag the angle slider until vectors a and b are nearly orthogonal (|cos θ| < 0.08).
a (3.0, 1.0)b (1.5, 2.1)
Angle θ between a & b35°
Length ‖b‖2.6
Dot Product a·b
6.74
Cosine Similarity
0.819
-1 (Opposite)0 (Orthogonal)+1 (Identical)
Geometric Takeaway: Norms measure length (L1 diamond, L2 circle, L∞ square); Dot product = ‖a‖‖b‖cos(θ); on unit-normalized vectors, Dot Product, Cosine Similarity, and L2 Distance rank neighbors identically.
Where This Powers Real ML, Deep Learning & GenAI

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.

Production NumPy & PyTorch Code Patterns
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
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Dividing by ‖x‖ without guarding zero vectors
Best Practice: Always guard with np.where(norm > 0, x / norm, 0.0) or np.maximum(norm, 1e-12) so an empty/zero embedding never injects NaNs into cosine similarity.
Trap #2: Using Cosine Similarity when magnitude actually carries signal
Best Practice: In recommendation systems (ALS user/item factors) or classification logits, vector norm often encodes confidence or popularity — use raw Dot Product instead of cosine.
Trap #3: Forgetting to scale features before computing Euclidean / Manhattan distance
Best Practice: KNN, K-Means, and RBF-kernel SVMs are NOT scale-invariant — always apply StandardScaler or MinMaxScaler (fit on train only!) before computing distances.
Chapter Mastery Check (+50 XP)
Score: 0 / 5
1For the vector v = [3, -4]ᵀ, what are (‖v‖₁, ‖v‖₂, ‖v‖∞)?
2If two non-zero vectors have a dot product of 0, what is the angle between them?
3Why does L1 regularization (Lasso) tend to drive irrelevant weights to exact zero while L2 (Ridge) does not?
4Suppose u and v are both unit vectors (‖u‖₂ = ‖v‖₂ = 1) with cosine similarity 0.5. What is ‖u − v‖₂²?
5Why does Scaled Dot-Product Attention divide QKᵀ by √d_k before softmax?

Apply What You Learned — Solve Matching Coding Problems