EVERYTHING AIAI engineering, made visual
0/23 complete
LESSON 14 · MATHEMATICS × AI · BUILD

Close is
a choice.

d(a, b) = ‖a − b‖ A norm measures length; a distance is the norm of a difference. Pick L1, L2, cosine or Mahalanobis and you have picked what “similar” means — for your neighbours, your clusters and your search index alike.

90 MIN · 8 CHAPTERSPREREQ · LESSONS 01–02
FIG. 14 / ONE BALL, TWO PATHS
P 2.0 · L1 7 · L2 5 · L∞ 4 unit ball L1 path L2 line
LESSON 14TYPE · BUILD~90 MINPREREQ · LESSONS 01–02ORIGINAL LESSON ↗
01 / LENGTH FIRST, DISTANCE FREE

A distance is a norm of a difference.

A norm is a length that keeps three promises: never negative, scales by |c|, and never lets a detour beat the direct route. Every norm hands you a distance for free — measure the arrow between two points.

d(a, b) = ‖a − b‖
02 / ONE DIAL, MANY SHAPES

Lp slides from diamond to square.

Raise absolute coordinates to the p-th power, add, take the p-th root. p = 1 is the Manhattan diamond, p = 2 the Euclidean circle, p → ∞ the Chebyshev square. The set of length-1 vectors is the norm's fingerprint.

(Σ|xᵢ|ᵖ)^(1/p)
03 / SAME DATA, DIFFERENT NEIGHBOURS

The ranking changes with the ruler.

Cosine keeps direction and drops length; L2 keeps the straight-line gap; L1 is robust to a single large coordinate; Mahalanobis divides by the covariance so units and correlation stop deciding for you. kNN, clustering and search all inherit the choice.

cos = 1.00 vs L2 = 7.07
MENTAL MODEL IN ONE SENTENCE

A norm is a way of measuring how long a vector is, and every distance is the norm of a difference: d(a, b) = ‖a − b‖. Choosing L1, L2, cosine or Mahalanobis is choosing what “similar” means — and every nearest neighbour, cluster, loss and regularizer you build inherits that choice.

By the end you will be able to compute L1, L2 and L∞ by hand, read a unit ball on sight, explain why Lasso snaps weights to zero while Ridge only shrinks them, know when cosine beats Euclidean, whiten a distance with the covariance matrix, and see why high dimensions quietly flatten every distance ratio.

WHAT A NORM IS

Length is a promise.
A norm keeps it.

Before you can ask how far apart two points are, you need to say how long one vector is. A norm is that answer — and it comes with three non-negotiable rules.

A norm is a function that assigns every vector a non-negative number, its length, written ‖x‖. Familiar Euclidean length is one norm; it is not the only one. What makes something a norm rather than an arbitrary score is that it keeps three promises.

  1. Zero only for zero. ‖x‖ ≥ 0, and ‖x‖ = 0 exactly when x is the zero vector. Plain English: no vector has a negative length, and nothing except “no movement at all” has no length. Check: ‖(0, 0)‖ = 0, while ‖(0.001, 0)‖ = 0.001 > 0.
  2. Scaling is linear. ‖c · x‖ = |c| · ‖x‖ for any number c. Double an arrow and its length doubles; flip it and the length is unchanged. Check: ‖(6, 8)‖ = 10 and ‖(−6, −8)‖ = 10, while ‖2 · (3, 4)‖ = ‖(6, 8)‖ = 10 = 2 · 5.
  3. The detour is never shorter. ‖a + b‖ ≤ ‖a‖ + ‖b‖. Walk a and then b; you cannot arrive closer to the origin than by walking the single vector a + b. Check: a = (1, 0), b = (0, 1) gives ‖a + b‖ = √2 ≈ 1.414 ≤ 2.

That is the whole definition. Anything that keeps these three promises behaves like a length, and anything that behaves like a length gives you a distance by subtraction: d(a, b) = ‖a − b‖. The distance between two points is just the length of the arrow from one to the other.

aba + b‖a + b‖ ≈ 3.08 ≤ ‖a‖ + ‖b‖ ≈ 4.33v2v‖2v‖ = 2‖v‖ ≈ 3.67
Left: walking a then b can never beat walking straight to a + b. Right: stretching a vector stretches its length by the same factor. The third axiom is the triangle inequality; the second is scaling.
Worked check: why d(a, b) = ‖a − b‖ is automatically a distance

A distance (a metric) must satisfy three matching rules — symmetry, zero only for identical points, and the triangle inequality. Each one follows from the corresponding norm axiom:

Symmetric: d(a, b) = ‖a − b‖ = ‖(−1) · (b − a)‖ = |−1| · ‖b − a‖ (scaling axiom) = d(b, a) ✓ Zero only for a = b: d(a, a) = ‖0‖ = 0 (zero axiom) and ‖a − b‖ > 0 for a ≠ b Triangle: d(a, c) = ‖(a − b) + (b − c)‖ ≤ ‖a − b‖ + ‖b − c‖ (triangle axiom) = d(a, b) + d(b, c) ✓ Numeric check with a = (1, 0), b = (0, 1), c = (2, 2): d(a, b) = √2 ≈ 1.414 d(b, c) = ‖(2, 1)‖ = √5 ≈ 2.236 d(a, c) = ‖(1, 2)‖ = √5 ≈ 2.236 2.236 ≤ 1.414 + 2.236 = 3.650 ✓

Notice that the proof used only the three norm rules — nothing about squares, roots or coordinates. That is why the L1, L2 and L∞ norms you meet next all produce valid distances: each one is a length that keeps the promises.

THE LP FAMILY

One formula.
A dial between shapes.

L1, L2 and L∞ are not three unrelated rules — they are three settings of the same dial, p. Change p and the set of vectors of length 1 changes shape.

The Lp norm raises every absolute coordinate to the power p, adds the results, and takes the p-th root. In plain English: it measures the total size of the coordinates, but the dial p decides how much credit a single large coordinate gets compared with many small ones.

‖x‖ₚ = ( |x₁|ᵖ + |x₂|ᵖ + … + |xₙ|ᵖ )^(1/p) p = 1 L1, Manhattan |x₁| + |x₂| + … walk the grid, no diagonals p = 2 L2, Euclidean √(x₁² + x₂² + …) the straight line; Pythagoras p → ∞ L∞, Chebyshev max(|x₁|, |x₂|, …) only the worst coordinate counts A = (1, 1), B = (4, 5), difference (3, 4): L1 = |3| + |4| = 7 L2 = √(9 + 16) = 5 L∞ = max(3, 4) = 4 (1, 2, 3) vs (4, 0, 6), difference (3, −2, 3): L1 = 8 L2 = √22 ≈ 4.690 L∞ = 3

Read the last two lines as three different opinions about the same pair of points. L1 charges by total travel, L2 by the straight-line gap, and L∞ by the single worst disagreement — and each opinion is a legitimate definition of “far”. The unit ball makes the differences visible.

Unit balls and one pair of points under every ruler

Slide p to morph the set of vectors of length 1, then drag A and B. All four distances are recomputed live: the same two points, four answers.

A = (-1.8, 1.1) B = (2.2, -1.2) A − B = (-4.0, 2.3) L1 = |-4.0| + |2.3| = 6.30 L2 = √(-4.0² + 2.3²) = 4.61 L∞ = max(|-4.0|, |2.3|) = 4.00 Lp = 4.61 (p = 2.0) The ball shows every vector of norm exactly 1: it is a diamond at p = 1, a circle at p = 2, and a square at p = ∞.

The ball's shape is the norm's fingerprint: it tells you which directions the norm considers expensive.

Derivation: why p → ∞ gives the max, and why L∞ ≤ L2 ≤ L1 always

The limit. Let M be the largest absolute component. Factor it out of the sum:

‖x‖ₚ = M · ( Σᵢ (|xᵢ|/M)ᵖ )^(1/p) every ratio |xᵢ|/M is at most 1, and at least one equals 1, so the sum sits between 1 and n, and its p-th root sits between 1 and n^(1/p). As p grows, n^(1/p) → 1 and the whole factor → 1. x = (3, 1, 0, 0), M = 3: p = 2: ‖x‖₂ = √10 = 3.162 p = 4: ‖x‖₄ = 82^(1/4) ≈ 3.009 p = 8: ‖x‖₈ = 6562^(1/8) ≈ 3.00006 p → ∞: max(3, 1, 0, 0) = 3 ✓ the biggest coordinate progressively drowns out the rest.

The ordering. L∞ ≤ L2 because M² is one of the terms of Σxᵢ², so M² ≤ Σxᵢ² and taking roots gives M ≤ √Σxᵢ². And L2 ≤ L1 because (Σ|xᵢ|)² = Σxᵢ² + 2Σᵢ<ⱼ|xᵢ||xⱼ| — the cross terms are non-negative, so Σxᵢ² ≤ (Σ|xᵢ|)². Take square roots again. Numeric check on the difference (3, −2, 3): 3 ≤ 4.690 ≤ 8 ✓. The three norms agree only when one coordinate does all the work (or nothing moves).

The same dial, a second job. In training, a norm is added to the loss as a penalty on the weights: loss + λ‖w‖. This is where L1 and L2 stop being interchangeable. L1 (“Lasso”) pushes some weights to exactly zero, selecting features. L2 (“Ridge” or weight decay) shrinks every weight smoothly, selecting nothing. The reason is geometric: the L1 ball has corners on the axes, the L2 ball does not.

w = (0.8, 0)L1: diamond · corner on the axisloss contoursw = (0.62, 0.19)L2: circle · no corners to land on
Schematic of the constraint picture: the loss wants to move toward the unregularized optimum (grey dot). The L1 region has corners on the axes, so the solution lands where a weight is exactly zero; the L2 region is smooth, so the solution keeps both weights, shrunken.
Derivation: the kink at zero is why Lasso can switch a weight off

A separable teaching model: the loss wants each weight at its best value a and curves like ½(w − a)²; add the penalty and minimize one weight at a time.

L2 penalty λw²: derivative: (w − a) + 2λw = 0 → w = a / (1 + 2λ) a = 1.6, λ = 0.8: w = 1.6 / 2.6 = 0.615 a = 0.5, λ = 0.8: w = 0.5 / 2.6 = 0.192 both weights shrink; neither is exactly 0 L1 penalty λ|w|: w > 0: (w − a) + λ = 0 → w = a − λ, valid only if a > λ w < 0: (w − a) − λ = 0 → w = a + λ, valid only if a < −λ otherwise neither branch is valid and the minimum sits at the kink: w = 0 → w = sign(a) · max(|a| − λ, 0) ("soft thresholding") a = 1.6, λ = 0.8: w = 0.8 a = 0.5, λ = 0.8: w = max(0.5 − 0.8, 0) = 0 ← exactly zero simplified teaching model: penalties away from the non-smooth point are exactly the algebra above; real losses are not perfectly separable, which is why we say "likely to be zero", not "always zero".

The absolute value has a corner at zero, and a penalty with a corner can pin a weight to the corner. The square is smooth everywhere, so it can only pull a weight toward zero, never exactly onto it.

Quick check

For x = (3, 4), which ordering of L1, L2 and L∞ is guaranteed?

TWO WAYS TO WALK

The staircase
or the shortcut.

L1 and L2 are two models of travel. One is only allowed to move along the axes; the other cuts straight across. On a city grid the difference is exactly the diagonal.

Put two points on a grid: A = (1, 1) and B = (4, 5). A taxi can move only along the streets, so it drives 3 blocks east and 4 blocks north — length 3 + 4 = 7, the L1 distance. A bird ignores the streets and flies the straight line: a 3-4-5 right triangle, so √(3² + 4²) = 5, the L2 distance. The L∞ distance keeps only the worst single leg, max(3, 4) = 4, which is how a gantry robot that can move one axis at a time experiences the trip: the slow axis sets the time.

The three numbers are not rival answers to one question. They are answers to three different questions — total travel, straight-line gap, worst coordinate — and the point of this chapter is that all three are the correct answer once you have decided what you are measuring.

difference = B − A = (3, 4) L1 = |3| + |4| = 7 one shortest route: 3 east, then 4 north L2 = √(3² + 4²) = 5 the 3-4-5 right triangle, straight across L∞ = max(3, 4) = 4 the gantry waits for the slower axis the diagonal saves 7 − 5 = 2 blocks of walking

Two points, four rulers, one grid

Drag A and B and switch rulers. Every metric agrees the points are two different places — they disagree about how far apart.

Δ = (3.0, 4.0) L1 = |3.0| + |4.0| = 7.00 → 3.0 blocks east + 4.0 blocks north → 35 different shortest routes, all length 7.00

All three norms come from the same two legs: L1 adds them, L2 squares them and takes a root, L∞ keeps the larger one. Try the “Tiny offset” preset — small Euclidean gap, large cosine angle.

Derivation: how many shortest grid routes are there (and why the diagonal always wins)

Why L2 ≤ L1. Square the two legs. The cross term is never negative, so the straight line can never be longer:

(|dx| + |dy|)² = dx² + dy² + 2|dx||dy| ≥ dx² + dy² take square roots: |dx| + |dy| ≥ √(dx² + dy²) equality only when dx = 0 or dy = 0 — already straight (3, 4): 7 ≥ 5 ✓ (0, 5): 5 ≥ 5 ✓

Counting routes. Every shortest grid route uses exactly 3 east steps and 4 north steps — 7 steps in all. Choosing a route is choosing which 3 of the 7 positions are the east steps, so the count is the binomial coefficient:

C(7, 3) = 7! / (3! · 4!) = 35 routes, every one of length 7 general rule: C(|dx| + |dy|, |dx|) (2, 3) → C(5, 2) = 10 (10, 10) → C(20, 10) = 184,756 all 35 routes end at the same corner; none of them is shorter than the straight line of length 5.

That is the quiet lesson of the staircase: many different paths can share one distance. A distance function does not care which route you took, only where you started and where you ended.

ANGLE VS DISTANCE

Direction is not
distance.

Cosine similarity asks how aligned two vectors are and deliberately forgets how long they are. That one decision makes it the default for text — and makes its rankings disagree with L2.

Cosine similarity is the dot product divided by both lengths: cos(a, b) = a·b / (‖a‖‖b‖). In plain English, it is the cosine of the angle between the arrows. It runs from +1 (same direction) through 0 (perpendicular) to −1 (opposite), and it does not change if you stretch either arrow. Cosine distance is simply 1 − cos, running from 0 to 2.

a = (1, 0), b = (1, 1): cos = (1·1 + 0·1) / (1 · √2) = 1/√2 = 0.7071 cosine distance = 1 − 0.7071 = 0.2929 two rankings, same query q = (1, 1): u = (6, 6): cos(q, u) = 1.0000 L2(q, u) = √(25 + 25) = 7.071 v = (1.5, 0): cos(q, v) = 0.7071 L2(q, v) = √(0.25 + 1) = 1.118 cosine ranks u first L2 ranks v first u points exactly where q points, but is six times longer; v is much closer, but sits 45° off the line.

Cosine ranking vs Euclidean ranking

One query, six items. Switch the ruler and watch the order change: cosine sorts by direction, L2 sorts by straight-line gap.

123456q1 · 2 point the same way, different lengthsarrows are normalized: cosine cannot see the difference between 1 and 2
RankItemvectorL2 distancecosine
11. same topic, short(2, 0.3)1.0050.9988
22. same topic, long(6, 0.9)5.0490.9988
35. close but angled(0.9, 0.9)0.7070.8321
44. off-topic, tiny(0.05, 0.05)0.9620.8321
53. keyword overlap(0.5, 1.2)1.1180.5582
66. odd angle, close(0.2, 1)1.1310.3846
query = (1, 0.2) cosine winner: same topic, short cos = 0.9988 L2 winner: close but angled L2 = 0.707 The top pick changes with the ruler. Items 1 and 2 (same direction, ×3 length) are tied at cos = 0.9988 but sit at L2 = 1.005 vs 5.049 — cosine cannot tell them apart, L2 can.

When magnitude is noise and direction is meaning — text, embeddings — rank by cosine. When magnitude is the message, keep it: use L2 or a raw dot product.

A second worked example, with all four rulers. Take a = (1, 0, 3) and b = (4, 2, 0). The difference is (3, 2, −3), so L1 = 8, L2 = √22 ≈ 4.690 and L∞ = 3 — the points look reasonably close. But the dot product is 1·4 + 0·2 + 3·0 = 4, with lengths ‖a‖ = √10 ≈ 3.162 and ‖b‖ = √20 ≈ 4.472, so cos = 4 / 14.142 ≈ 0.283: nearly perpendicular. Close in position, far in direction. Which one is “more similar” depends entirely on what the vectors represent.

Derivation: the dot product is cosine with the lengths left in

For unit vectors, the dot product is the cosine. For general vectors it is the cosine multiplied by both lengths:

a · b = a₁b₁ + a₂b₂ + … + aₙbₙ = ‖a‖ · ‖b‖ · cos θ (θ is the angle between them) so cos θ = a · b / (‖a‖ · ‖b‖) and a · b = cos θ when ‖a‖ = ‖b‖ = 1. numeric check: a = (3, 0), b = (1, 0), c = (0, 1) dot(a, b) = 3 cos(a, b) = 1.000 dot(a, c) = 0 cos(a, c) = 0.000 cosine cannot tell b from 3b — both lie on the same ray. the dot product can: 3 versus 1. That leftover factor is magnitude, and in retrieval it can carry popularity or confidence on purpose.

This is also the reason a vector database can offer “cosine or dot product” as a choice: if the stored embeddings are already L2-normalized, each has length 1 and the two formulas compute exactly the same number.

Quick check

For q = (1, 1), u = (6, 6) and v = (1.5, 0), which ruler ranks u as the nearest neighbour?

DISTANCE IN CONTEXT

Same gap,
different surprise.

Euclidean distance treats every feature as equally important and independent. Real features have units, spread and correlations — Mahalanobis distance measures a gap in units of how unusual it is.

Someone who is 188 cm tall and weighs 82 kg is ordinary. Someone who is 152 cm tall and weighs 82 kg is unusual — but both people are the same Euclidean distance from the average, because Euclidean distance cannot see that weight is a much noisier feature than height, or that the two move together. Mahalanobis distance fixes this by measuring the difference in standard deviations instead of centimetres and kilograms.

d_M(x, y) = √( (x − y)ᵀ · S⁻¹ · (x − y) ) S is the covariance matrix of the data: entry Sᵢⱼ says how features i and j vary, and how they vary together. plain English: Mahalanobis first whitens the difference — decorrelates it and rescales every coordinate to unit spread — then takes the ordinary L2 length. It is "how many standard deviations away, in every direction at once". if S = I (uncorrelated, unit-variance features): d_M(x, y) = √((x − y)ᵀ(x − y)) = ‖x − y‖₂ — plain Euclidean.

Distance in units of “how unusual”

A correlated cloud of points. Drag the scored point: L2 measures the straight-line gap to the mean, Mahalanobis measures it in standard deviations along the cloud’s own axes.

point = (3.0, 2.2) raw difference from the mean (0, 0) Δx = 3.0 Δy = 2.2 L2 distance = 3.720 per-feature z-scores Δx / σx = 1.50 Δy / σy = 1.27 Mahalanobis dM = 1.580 Where does the ellipse come from? S = [[4, 2], [2, 3]]: σx = 2, σy = √3, and the features move together (ρ ≈ 0.58). Mahalanobis divides by S⁻¹, so a step along the crowded diagonal is cheap and a step across it is expensive. Rule of thumb: dM > 3 is an outlier.

A point with a big L2 distance can have a small Mahalanobis distance if it follows the cloud’s correlation — and a small L2 distance can be very unusual if it crosses it. The presets show both.

Derivation: whitening, two cases, with numbers

Case 1 — independent features. If features do not correlate, S is diagonal: S = diag(σ₁², …, σₙ²) and S⁻¹ = diag(1/σ₁², …, 1/σₙ²), so the formula collapses to a sum of z-scores:

d_M² = (d₁/σ₁)² + (d₂/σ₂)² + … heights spread by σ = 7 cm, weights by σ = 10 kg: P: +14 cm from the mean → z = 14/7 = 2.0 Q: +30 kg from the mean → z = 30/10 = 3.0 P and Q together? the units disappear: d_M = √(2² + 3²) = √13 ≈ 3.606 the same difference in raw units: ‖(14, 30)‖ = √(196 + 900) = √1096 ≈ 33.1 which is not a number anyone can interpret.

Case 2 — correlated features. Any covariance matrix factors as S = L·Lᵀ (Cholesky). Then d_M = ‖L⁻¹(x − y)‖₂: multiply the difference by L⁻¹ and take an ordinary Euclidean length. Numeric check with S = [[4, 2], [2, 3]] and d = (2, 1):

det S = 4·3 − 2·2 = 8 S⁻¹ = (1/8) · [[3, −2], [−2, 4]] d_M² = (3·4 − 2·2·2·1 + 4·1) / 8 = (12 − 8 + 4) / 8 = 8/8 = 1 d_M = 1.000 while plain L2 = √5 ≈ 2.236 whitening check: L = [[2, 0], [1, √2]] has S = L·Lᵀ. L⁻¹ · (2, 1) = (2/2, (1 − 1)/√2) = (1, 0) ‖(1, 0)‖ = 1 ✓ the same d_M, computed after a coordinate change.

So the units cancel, the correlation is undone, and what is left is a gap measured in standard deviations — comparable across features and across datasets.

Quick check

Heights spread by 7 cm and weights by 10 kg, and the two are uncorrelated. Person P is 14 cm above average; person Q is 30 kg above average. Under Mahalanobis distance with S = diag(49, 100), who is more unusual?

WHEN DISTANCES BLUR

In high dimensions,
everyone is far.

Add enough independent features and the nearest and farthest points start reporting almost the same distance. The ruler is still accurate — the contrast it measures has drained away.

In two dimensions, a near neighbour and a far point are obviously different. In 500 dimensions, every pair of random points sits at almost the same distance from every other pair. This is distance concentration, the sharpest edge of the curse of dimensionality: as dimension grows, the ratio of farthest to nearest distance for unrelated data approaches 1.

The simulation below is small enough to check by hand: 200 points drawn uniformly in [0, 1]ᵈ, every one of the 19,900 pairwise distances computed, then bucketed. At d = 2 the histogram is wide — some pairs are nearly touching, others are a third of the square apart. By d = 500 the whole distribution has collapsed into a narrow spike.

d = 2 · distances 0.00 – 1.2701.30pairsd = 500 · distances 8.14 – 10.078.010.20pairs200 uniform points, 19,900 pairs, fixed seed · bar height = share of pairs
The same dataset construction, twice. At d = 2 the nearest and farthest gaps differ by a factor of 375; at d = 500 the whole distribution is only about 24% wide.
dimension dmean distanceminmaxmax / min
20.5070.0031.272375×
101.2690.3812.2285.8×
1004.0633.2214.9491.54×
5009.1118.14110.0681.24×
200018.25417.38419.1801.10×
Derivation: why distances grow like √d while their spread grows like √d too

Take two random points in [0, 1]ᵈ, coordinate by coordinate. For a single coordinate, the squared gap (u − v)² has mean 1/6 and variance 7/180 — both facts you can verify by integrating over the unit square. Square distances add across coordinates, so:

E[d²] = d / 6 sd[d²] = √(d · 7/180) distance itself: √(d/6) — grows like √d relative spread of d²: sd / mean = √(d · 7/180) / (d/6) = √(1.4 / d) for d = 500: mean d² = 83.33 sd d² = 4.41 mean d = 9.111 relative spread of d ≈ half of 5.3% ≈ 2.6% simulation check: sd ≈ 0.24 around 9.11 ✓ min 8.14, max 10.07 — the whole range is ±10%. the √d in the numerator comes from summing d independent variances; the extra √d in the denominator comes from converting d² back to d. That leftover 1/√d is the whole story.

The average distance still grows — like √d, not d — but the spread grows more slowly than the mean, so the ratio narrows. Distances are not wrong in 500 dimensions; they are all crowded together.

Quick check

You keep adding independent random features to a dataset, and nothing else changes. What happens to the ratio of the farthest pair's distance to the nearest pair's distance?

THE METRIC DECIDES

The ruler is
part of the model.

kNN, clustering, search indexes, losses and regularizers all inherit one decision made before training starts: what counts as close. Two labs below make the inheritance visible.

A nearest-neighbour classifier is nothing but a distance function plus a vote. A clustering algorithm is a distance function plus a rule for grouping. A vector database is a distance function plus an index. Change the distance and you have changed the model — before a single weight is trained. The heatmap shows six points under four rulers; the kNN lab shows the decision boundary moving.

The distance matrix: four rulers, one dataset

Six points, all pairwise distances. Darker cells are closer. The ring marks each row’s nearest neighbour — switch rulers and watch the rings move.

ABCDEFnearest
0.010.130.130.000.29E
0.010.080.180.010.22A
0.130.080.470.130.04F
0.130.180.470.130.73A
0.000.010.130.130.29A
0.290.220.040.730.29C

Cosine picks a different nearest neighbour than L1 in 6 of 6 rows: A and E point in exactly the same direction (cosine distance 0), so they are each other's nearest.

point A = (1, 1) — bottom-left under cosine distance: closest 3 → E 0.00 · B 0.01 · C 0.13 nearest neighbour overall: E A = (1, 1) B = (4, 5) C = (2, 7) D = (7, 2) E = (5, 5) F = (0, 4) Same six points, four different "closest" answers. The data never changed.

Click a row label to focus that point. In high dimensions these differences matter even more, because the distances themselves lose contrast — the next chapter.

The kNN classifier under a metric switch

Drag the query and change k or the ruler. The shaded regions are where each class would win the vote; the boundary itself moves when the metric does.

query = (1.50, 1.20) metric = L1 k = 3 nearest 3: 1. class A d = 0.40 2. class B d = 1.00 3. class B d = 1.00 votes: A 1 · B 2 prediction: class B Try the presets: (1.0, 1.0) flips the nearest neighbour between L1 and L2; (1.5, 1.2) flips the k = 3 vote.

kNN inherits whatever “close” means. The same points, a different ruler, and a different decision boundary — before any model is trained.

Losses are distances too: they score the gap between a prediction and a target. Regularizers are norms on the weights. The whole training objective is therefore a statement about which errors you care about and which weights you are willing to pay for.

LossDistance it usesBehavior
Mean squared error (MSE)L2 squaredLarge errors punished hard; sensitive to outliers
Mean absolute error (MAE)L1Every error counts linearly; robust to outliers
Huber lossL2 near zero, L1 far awaySmooth gradient at zero, robust tails
Cross-entropyKL divergenceDistribution mismatch; the classification default
TaskDistanceWhy
Text and embeddingsCosine (or dot product)Length is noise, direction is meaning; embeddings are trained that way
Pixel-level image comparisonL2Comparable scales, spatial meaning
Sparse high-dimensional featuresL1Robust; one huge difference does not dominate
Tags, categories, masksJaccardThe data are sets, not vectors
Strings and DNAEdit distanceThe operations match how text changes
Outlier detectionMahalanobisAccounts for feature scale and correlation
Comparing distributionsKL, or Wasserstein if they may not overlapInformation lost, or earth actually moved
Manufacturing tolerance, chess king movesL∞Only the worst coordinate matters
CHECK YOURSELF

Five questions.
Then the terms worth keeping.

Answer before you look. The Lasso question and the Mahalanobis question are the two that decide whether the ideas have actually landed.

0 / 5 answered · 0 correct

01What does cosine similarity measure between two vectors?

02Why is L1 distance called “Manhattan distance”?

03Why does L1 regularization (Lasso) produce sparse weights while L2 regularization (Ridge) does not?

04What advantage does Wasserstein distance have over KL divergence when comparing probability distributions?

05When would you use Mahalanobis distance instead of Euclidean distance?

Key terms, demystified

Click a card to swap the lazy description for what it actually means.

Exercises from the lesson

Four problems, all worked. Try first; the answer is one click away.

  1. Compute L1, L2 and L∞ distances between (1, 2, 3) and (4, 0, 6). Verify L∞ ≤ L2 ≤ L1, then explain why the ordering is guaranteed for any pair of points.
    Show one worked answer

    Difference = (4−1, 0−2, 6−3) = (3, −2, 3). L1 = 3 + 2 + 3 = 8. L2 = √(9 + 4 + 9) = √22 ≈ 4.690. L∞ = max(3, 2, 3) = 3. So 3 ≤ 4.690 ≤ 8 ✓. Why it must hold: let M = max|xᵢ|. Then M² is one term of Σxᵢ², so M² ≤ Σxᵢ² and M ≤ √Σxᵢ² — that is L∞ ≤ L2. For L2 ≤ L1, expand (Σ|xᵢ|)² = Σxᵢ² + 2Σᵢ<ⱼ|xᵢ||xⱼ|. The cross terms are non-negative, so Σxᵢ² ≤ (Σ|xᵢ|)²; take square roots. Equality holds only when all non-zero components sit in one coordinate (or the vector is zero).

  2. Find two vectors with cosine similarity above 0.9 but L2 distance above 10, then two vectors with cosine similarity below 0.3 but L2 distance below 0.5. Explain each geometrically.
    Show one worked answer

    Same direction, different length: a = (1, 1) and b = (100, 100). cos = 1 > 0.9, but L2 = √(99² + 99²) = 99√2 ≈ 140.0 > 10. The arrows point the same way; only their lengths differ, and cosine deliberately ignores length. Different directions, both tiny: a = (0.1, 0) and b = (0, 0.1). cos = 0 < 0.3, while L2 = √(0.01 + 0.01) ≈ 0.141 < 0.5. They are perpendicular — maximum directional disagreement — but they both sit near the origin, so the straight-line gap is small. One more check on the same idea: (1, 0) and (2, 0) have cosine 1 but L2 = 1.

  3. Find one small dataset and query where L1, L2, cosine and Mahalanobis each pick a different nearest neighbour.
    Show one worked answer

    Query q = (0, 0). Candidates A = (2, 0.1), B = (0.42, 0.42), C = (0.05, 0.63), D = (0.75, 0.05). Suppose the two features have spreads σx = 4 and σy = 1 with no correlation, so S = diag(16, 1) and dM = √(x²/16 + y²). Scores: A — L1 2.100, L2 2.003, cos 0.9988, dM 0.510. B — L1 0.840, L2 0.594, cos 0.7071, dM 0.433. C — L1 0.680, L2 0.632, cos 0.0791, dM 0.630. D — L1 0.800, L2 0.752, cos 0.9978, dM 0.194. Each ruler picks a different winner: L1 → C (0.680), L2 → B (0.594), cosine → A (0.9988), Mahalanobis → D (0.194). Nothing about the data changed; only the definition of “close” did.

  4. Compute the 1D Wasserstein distance between P = [0.5, 0.5, 0, 0] and Q = [0, 0, 0.5, 0.5], then between the uniform P = [0.25, 0.25, 0.25, 0.25] and the same Q. Which is larger, and why?
    Show one worked answer

    In one dimension W₁ = Σ |CDF_P(i) − CDF_Q(i)| over the bin edges. For P: CDF = (0.5, 1, 1, 1); for Q: CDF = (0, 0, 0.5, 1). Gaps: |0.5−0| = 0.5, |1−0| = 1, |1−0.5| = 0.5, |1−1| = 0 → W₁ = 2. For the uniform P: CDF = (0.25, 0.5, 0.75, 1); same Q. Gaps: 0.25, 0.5, 0.25, 0 → W₁ = 1. The first is larger: half of P's mass must travel from bins 1–2 to bins 3–4, crossing 2 bin widths. The uniform distribution already has half its mass on the right, so less earth moves. KL divergence would instead report ∞ in both directions, because Q puts zero probability where P is non-zero — a true metric keeps giving a useful number.

Terms this lesson borrows from later lessons (or outside)

You do not need to master these here. Each one gets a proper treatment in its own lesson; the one-line meaning is enough to keep reading. Orange dotted underlines in the prose point back to this list.

  • covarianceA matrix S recording how much each feature varies and how features move together. Mahalanobis distance is built from it. (Lesson 10)
  • whiteningTransforming data so its features are uncorrelated and each has unit variance — which is exactly what multiplying by S^(−1/2) does. (Lesson 10)
  • featureOne input column: a single measured property of each example, such as age, pixel value or word count. (Lesson 00)
  • CholeskyWriting a positive-definite matrix as S = LLᵀ with L lower-triangular; a matrix square root, and the reason whitening is a real coordinate change. (Lesson 17)
  • outlierA data point far from the rest — unusually large or small. Large Mahalanobis distance from the mean is the standard multivariate test. (Lesson 15)
  • clusteringGrouping data points so that points in a group are closer to each other than to points in other groups. The grouping changes when the metric changes. (outside these lessons)
  • nearest neighbourThe stored point (or points) closest to a query under some distance. The k-nearest-neighbours classifier votes among them. (this lesson)
  • GANGenerative Adversarial Network: a generator tries to fool a discriminator. The Wasserstein version scores with earth-mover distance instead of KL. (outside these lessons)
  • segmentationLabelling every pixel of an image with a class. It is evaluated with Intersection over Union — which is Jaccard similarity for sets of pixels. (outside these lessons)
  • CDFCumulative Distribution Function: P(X ≤ x), the running total of probability up to x. The 1D Wasserstein distance is the area between two CDFs. (Lesson 06)
KEEP GOING

A picture is a start.
Practice is the rest.

This lesson is a port of an open course. Everything here traces back to it — and the next step is running the code yourself.

Lesson text adapted from AI Engineering from Scratch (Phase 01, Lesson 14) and the Math Foundations Notebook reference build. The unit-ball explorer, distance playground, cosine/L2 ranking board, Mahalanobis cloud, distance-matrix heatmap, kNN metric lab, regularization figure and simulation histograms are original to this page. Every numeric check and worked answer was recomputed. All labs run in your browser.