Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 1: Math FoundationsLinear Algebra

Norms and distances

P1.B430 min●○○ BeginnerReviewed Nov 30, 2026

Why this matters for machine learning

Norms turn the questions of how big a vector is and how far apart two vectors are into numbers: they are how models measure similarity, penalize large weights and tame huge gradients.

  • k-nearest neighbors predicts from the closest training examples, so the choice of distance decides who the neighbors are. (P3.B1: k-Nearest Neighbors, coming soon)
  • L1 and L2 regularization penalize the size of the weight vector, measured with the L1 norm or the (squared) L2 norm. (P3.A6: Regularization: L1 and L2, coming soon)
  • Distances only make sense if features are on comparable scales, which is why data is rescaled before it is used. (P3.A11: Features, scaling and data leakage, coming soon)
  • Gradient clipping rescales a gradient whose norm is too large, which keeps training from blowing up. (P4.16: Vanishing and exploding gradients, coming soon)
  • Normalization layers divide a vector by a length-like quantity so that activations stay on a steady scale. (P4.19: Normalization layers, coming soon)

Before this: Scalars, vectors and spaces, Vector operations, Dot product and cosine similarity

After this lesson you can

  • Compute the L1, L2 and L∞ norms of a vector, in 2-D and in more dimensions, and say what each one measures
  • Sketch the unit ball of each norm and say how the shape changes as p grows from 1 to ∞
  • State the three norm rules (only the zero vector has norm zero, scaling by c scales the norm by |c|, the triangle inequality) and use them
  • Compute the distance between two vectors as the norm of their difference, and explain why different norms can pick different nearest points
  • Explain why a feature measured in thousands dominates a distance, and why squared distance gives the same ranking
  • Compute norms and distances in NumPy, for one vector and for many at once

A recommendation system has to answer one question millions of times: how far apart are these two things? When the things are vectors, “far” needs a definition, and there is more than one sensible choice. This lesson gives you the choices, shows what each one looks like, and shows why the choice can change the answer.

How long is a vector? Pythagoras

Start with the arrow (3,4)(3, 4): 3 steps east and 4 steps north. How far is its tip from the origin? The two steps form the short sides of a right-angled triangle, and the arrow is the long side. Pythagoras says

length2=32+42=9+16=25length=5\begin{aligned} \text{length}^2 &= 3^2 + 4^2 = 9 + 16 = 25 \\ \text{length} &= 5 \end{aligned}

The same recipe gives the length of (3,1)(3, 1) that P1.B1 mentioned: 32+12=10≈3.16\sqrt{3^2+1^2}=\sqrt{10}\approx 3.16.

More dimensions work the same way: square every entry, add, take the square root. For (1,2,2)(1, 2, 2):

12+22+22=9=3\sqrt{1^2 + 2^2 + 2^2} = \sqrt{9} = 3

and for (2,3,6)(2, 3, 6) it is 4+9+36=49=7\sqrt{4 + 9 + 36} = \sqrt{49} = 7. We write the length of a\mathbf{a} as ∥a∥\|\mathbf{a}\| (you met this in P1.B3), and in general

∥a∥=a12+a22+⋯+an2\|\mathbf{a}\| = \sqrt{a_1^2 + a_2^2 + \dots + a_n^2}

This is the L2 norm, also called the Euclidean norm. (“Norm” is the mathematician’s word for a way to measure the size of a vector.) It links straight back to the dot product: ∥a∥2=a⋅a\|\mathbf{a}\|^2 = \mathbf{a}\cdot\mathbf{a}, because a⋅a=a12+⋯+an2\mathbf{a}\cdot\mathbf{a}=a_1^2+\dots+a_n^2.

Two quick facts you can already read off the formula. The length is never negative, and it is 0 only for the zero vector (every square is at least 0, so the sum is 0 only if every entry is 0). And the sign of an entry does not matter, because squaring removes it: (3,−4)(3, -4) also has length 5.

Other ways to measure “size”

Pythagoras measures the straight-line distance, “as the crow flies”. Other measures are just as valid, and each answers a different question.

Taxicab (L1, or Manhattan). A taxi in a city of square blocks cannot cut through buildings. To go 3 blocks east and 4 blocks north it drives 3+4=73 + 4 = 7 blocks. Add the absolute values of the entries:

∥a∥1=∣a1∣+∣a2∣+⋯+∣an∣\|\mathbf{a}\|_1 = |a_1| + |a_2| + \dots + |a_n|

The analogy breaks if you can move diagonally. A bird, or a drone, does not need the streets.

Max (L∞). Look only at the largest absolute entry:

∥a∥∞=max⁡(∣a1∣,∣a2∣,…,∣an∣)\|\mathbf{a}\|_\infty = \max\big(|a_1|, |a_2|, \dots, |a_n|\big)

For (3,4)(3, 4) that is 4. A chess king moves one square in any direction, diagonals included, so it needs exactly max⁡(3,4)=4\max(3, 4) = 4 moves to travel 3 squares sideways and 4 forward. The max norm is “how bad is the worst entry?”.

For the same arrow (3,4)(3, 4) the three measures give three answers, and for (3,1)(3, 1) and (−2,5,1)(-2, 5, 1) too. (L1 adds the absolute values, L2 is Pythagoras, L∞ is the biggest entry.)

VectorL1L2L∞
(3,4)(3, 4)754
(3,1)(3, 1)410≈3.16\sqrt{10}\approx 3.163
(−2,5,1)(-2, 5, 1)830≈5.48\sqrt{30}\approx 5.485

Notation. Write a small subscript for the norm: ∥a∥1\|\mathbf{a}\|_1, ∥a∥2\|\mathbf{a}\|_2, ∥a∥∞\|\mathbf{a}\|_\infty. With no subscript, ∥a∥\|\mathbf{a}\| means L2, as in P1.B3.

One family: the pp-norm

All three are members of one family. For any p≥1p \ge 1:

∥a∥p=(∣a1∣p+∣a2∣p+⋯+∣an∣p)1/p\|\mathbf{a}\|_p = \big(|a_1|^p + |a_2|^p + \dots + |a_n|^p\big)^{1/p}

Put p=1p = 1 and you get L1. Put p=2p = 2 and you get L2 (the “power 1/2” is the square root). As pp grows, the biggest entry matters more and more, and in the limit only the biggest entry is left: that is L∞, which is why it carries the symbol ∞. For the vector (3,4)(3, 4):

pp1241050∞
∥(3,4)∥p\|(3,4)\|_p754.284.024.004

(Values rounded to two decimals.) The number slides down from 7 towards 4 and never goes below 4.

The shape of “length 1”: unit balls

Here is the picture that makes the three norms easy to remember. The unit ball of a norm is the set of all vectors whose norm is at most 1. Its edge is the set where the norm is exactly 1, which is the thing you know as the “unit circle” when the norm is L2. In 2-D, ask: which points (x,y)(x, y) have norm exactly 1?

  • L1: ∣x∣+∣y∣=1|x| + |y| = 1 is a diamond, with corners at (±1,0)(\pm 1, 0) and (0,±1)(0, \pm 1).
  • L2: x2+y2=1x^2 + y^2 = 1 is the usual circle.
  • L∞: max⁡(∣x∣,∣y∣)=1\max(|x|, |y|) = 1 is a square, with corners at (±1,±1)(\pm 1, \pm 1).

Drag the tip of v, and slide p from 1 to ∞

−2−1.5−1−0.50.511.52−2−1.5−1−0.50.511.52v
v = (0.75, 0.5)
L1 = |0.75| + |0.5| = 1.25
L2 = √(0.5625 + 0.25) = 0.901
L∞ = max(|0.75|, |0.5|) = 0.75
p = 2: norm of v = 0.901

The L2 norm of v is 0.901, less than 1, so the tip is inside the unit ball.

The grey shape is the unit ball for the chosen p: every point whose norm is exactly 1. The dashed grey outlines are always the L1 diamond, the L2 circle and the L∞ square. The dashed blue outline is the same shape scaled up or down until it passes through the tip of v.

The unit ball (grey) of the p-norm. Drag the tip of v and slide p from 1 (diamond) through 2 (circle) towards ∞ (square). The dashed blue outline is the same shape scaled until it passes through v's tip. Keyboard: Tab to the tip, then use the arrow keys; the slider also takes arrow keys.

Play with it and notice:

  • As pp grows from 1, the diamond swells into the circle (at p=2p = 2) and then into the square (at p=∞p = \infty). The ball of a larger pp always contains the ball of a smaller pp.
  • The tip of v\mathbf{v} always sits on the dashed blue outline (for a long v\mathbf{v} part of that outline runs past the edge of the picture, and for the zero vector there is no outline), and the numbers in the readout show how the three norms of the same vector differ. A vector is inside the ball when its norm is below 1, on the edge when it is exactly 1, and outside when it is above 1.
  • Try (0.5,0.5)(0.5, 0.5): its L1 norm is 1 (on the diamond), its L2 norm is about 0.71 (inside the circle) and its L∞ norm is 0.5 (well inside the square). For every vector, ∥x∥∞≤∥x∥2≤∥x∥1\|\mathbf{x}\|_\infty \le \|\mathbf{x}\|_2 \le \|\mathbf{x}\|_1. Because L1 gives the biggest numbers, the fewest vectors fit inside the L1 ball: it is the smallest shape, and the L∞ square is the largest.
  • Tick Also allow p below 1 and slide to the left. The formula still produces a shape, but it caves in at the sides. The next sections explain why that shape is not a norm.

In 3-D the same three shapes are an octahedron (L1), a sphere (L2) and a cube (L∞). In higher dimensions we cannot draw them, but the formulas still work. A first look at why ML cares about these shapes: in P3.A6, a penalty on the size of the weights uses the L1 or the L2 ball, and the corners of the L1 diamond turn out to matter. That story belongs there.

Measuring size, in three depths

Intuition

Ask “how far did I travel?” in three ways. L2 is the straight line to where you ended up. L1 is the total distance you walked if you could only move along the grid (east-west or north-south). L∞ is the biggest gap along any single axis, ignoring the others.

The unit ball is the “what counts as 1 unit away?” shape. Under L2 everything exactly 1 unit away forms a circle: no direction is special. Under L1 and L∞ the directions along the axes are special, and the balls have corners.

Math

For x∈Rn\mathbf{x}\in\mathbb{R}^n and 1≤p<∞1\le p<\infty:

∥x∥p=(∑i=1n∣xi∣p)1/p∥x∥∞=max⁡i∣xi∣=lim⁡p→∞∥x∥p\begin{aligned} \|\mathbf{x}\|_p &=\Big(\sum_{i=1}^{n}|x_i|^p\Big)^{1/p} \\ \|\mathbf{x}\|_\infty &=\max_i |x_i|=\lim_{p\to\infty}\|\mathbf{x}\|_p \end{aligned}

A function ∥⋅∥\|\cdot\| is a norm if, for all vectors a,b\mathbf{a},\mathbf{b} and every number cc:

  1. ∥a∥≥0\|\mathbf{a}\|\ge 0, and ∥a∥=0\|\mathbf{a}\|=0 only for a=0\mathbf{a}=\mathbf{0}.
  2. ∥c a∥=∣c∣ ∥a∥\|c\,\mathbf{a}\|=|c|\,\|\mathbf{a}\|.
  3. ∥a+b∥≤∥a∥+∥b∥\|\mathbf{a}+\mathbf{b}\|\le\|\mathbf{a}\|+\|\mathbf{b}\| (the triangle inequality).

The pp-norms for p≥1p\ge 1 and the max norm satisfy all three. For every x\mathbf{x},

∥x∥∞≤∥x∥2≤∥x∥1\|\mathbf{x}\|_\infty\le\|\mathbf{x}\|_2\le\|\mathbf{x}\|_1

and in nn dimensions ∥x∥1≤n ∥x∥2\|\mathbf{x}\|_1\le\sqrt{n}\,\|\mathbf{x}\|_2 and ∥x∥2≤n ∥x∥∞\|\mathbf{x}\|_2\le\sqrt{n}\,\|\mathbf{x}\|_\infty. So the three measures never disagree wildly, but they can differ by a factor that grows with the dimension. For example, (1,1,…,1)(1,1,\dots,1) with n=9n=9 entries has L1 norm 9, L2 norm 3 and L∞ norm 1.

Notation. ∥x∥p\|\mathbf{x}\|_p for the pp-norm, and ∥x∥\|\mathbf{x}\| without a subscript for L2.

Code

import numpy as np

v = np.array([3.0, -4.0, 0.0])

np.linalg.norm(v)                  # 5.0  L2, the default
np.linalg.norm(v, ord=1)           # 7.0  L1
np.linalg.norm(v, ord=np.inf)      # 4.0  L∞
np.linalg.norm(v, ord=4)           # general p

np.sqrt((v ** 2).sum())            # 5.0  L2 written out
np.abs(v).sum()                    # 7.0  L1 written out
np.abs(v).max()                    # 4.0  L∞ written out

np.linalg.norm(v) is the one you will use most. In PyTorch the same idea is torch.linalg.vector_norm(v, ord=1).

The three rules of a norm

Not every formula that gives “a size” deserves the name. A norm must follow three rules, and each one has a picture.

Rule 1: only the zero vector has size zero

The norm is never negative, and it is 0 only for the zero vector. A non-zero arrow has some length in every one of the three measures. (L1, L2 and L∞ all satisfy this: if some entry is not 0, its absolute value or its square is positive.)

Rule 2: scaling scales the size by ∣c∣|c|

Stretch a vector by a number cc and its norm is multiplied by ∣c∣|c|, the size of cc without its sign:

∥c a∥=∣c∣ ∥a∥\|c\,\mathbf{a}\| = |c|\,\|\mathbf{a}\|

Take a=(3,1)\mathbf{a} = (3, 1) with ∥a∥=10≈3.16\|\mathbf{a}\|=\sqrt{10}\approx 3.16. Then −2a=(−6,−2)-2\mathbf{a} = (-6, -2) has length 36+4=40=210≈6.32\sqrt{36 + 4}=\sqrt{40}=2\sqrt{10}\approx 6.32: twice as long, even though c=−2c=-2 is negative. (Negative factors flip the direction, P1.B2; they do not shrink the length.) This holds for L1 and L∞ too: ∥(−6,−2)∥1=8=2×4\|(-6,-2)\|_1 = 8 = 2\times 4.

Rule 3: the triangle inequality

P1.B2 pointed out something odd: (3,0)+(0,4)=(3,4)(3, 0) + (0, 4) = (3, 4), and the arrows have lengths 3 and 4, but the sum has length 5, not 7. That is the triangle inequality:

∥a+b∥≤∥a∥+∥b∥\|\mathbf{a}+\mathbf{b}\| \le \|\mathbf{a}\| + \|\mathbf{b}\|

Walk along a\mathbf{a}, then along b\mathbf{b}. The two legs, with the direct path a+b\mathbf{a}+\mathbf{b}, make a triangle. A side of a triangle is never longer than the other two sides added together: a detour is never shorter than the direct path.

Detour or direct? Drag the tips of a and b

−8−6−4−22468−8−6−4−22468aba + b
Measure with:
a = (3, 0), b = (0, 4), a + b = (3, 4)
‖a‖ = 3
‖b‖ = 4
Detour ‖a‖ + ‖b‖ = 7
Direct ‖a + b‖ = 5

The direct path is shorter by 2. It can never be longer: ‖a + b‖ ≤ ‖a‖ + ‖b‖ always holds.

Walk along a, then along b (the pink arrow starts at the tip of a; its tip is the second handle). The black arrow is the direct path, a + b. The triangle inequality says the direct path is never longer than the detour.

Walk along a (blue), then b (pink, starting at the tip of a). The black arrow is the direct path a + b. Drag the tip of a, or the pink tip (which sets b), and switch the norm. The detour is never shorter than the direct path. Keyboard: Tab to a handle, then use the arrow keys.

Try the preset buttons:

  • Same direction: the direct path is exactly as long as the detour. Equality. The lengths add only when both vectors point the same way (or one of them is zero), as P1.B2 said.
  • Opposite directions: the arrows partly cancel, so the direct path is much shorter than the detour.
  • Perpendicular (the starting picture): the detour is 7, the direct path is 5. Now click L1: the direct path is 7 too. L1 counts blocks, and 3 blocks east plus 4 blocks north is 7 blocks whichever way you order them, so nothing is saved. The triangle inequality still holds (7 is not more than 7); it just holds with equality.

The inequality holds for L1, L2 and L∞. The three rules are what make a function a norm, and many of the facts in this course (for example, that “closest” behaves sensibly) follow from them.

Go deeper Why does the triangle inequality hold? (a short proof)

L1 and L∞, entry by entry. For ordinary numbers, ∣x+y∣≤∣x∣+∣y∣|x + y| \le |x| + |y| (two numbers of opposite signs partly cancel). Apply this to every entry and add: ∑i∣ai+bi∣≤∑i∣ai∣+∑i∣bi∣\sum_i |a_i + b_i| \le \sum_i |a_i| + \sum_i |b_i|, which is ∥a+b∥1≤∥a∥1+∥b∥1\|\mathbf{a}+\mathbf{b}\|_1\le\|\mathbf{a}\|_1+\|\mathbf{b}\|_1. For L∞, the largest entry of a+b\mathbf{a}+\mathbf{b} is some ∣aj+bj∣≤∣aj∣+∣bj∣≤∥a∥∞+∥b∥∞|a_j+b_j|\le|a_j|+|b_j|\le\|\mathbf{a}\|_\infty+\|\mathbf{b}\|_\infty.

L2, using the dot product. Expand the square:

∥a+b∥2=∥a∥2+2 a⋅b+∥b∥2≤∥a∥2+2 ∥a∥∥b∥+∥b∥2=(∥a∥+∥b∥)2\begin{gathered} \|\mathbf{a}+\mathbf{b}\|^2 = \|\mathbf{a}\|^2 + 2\,\mathbf{a}\cdot\mathbf{b} + \|\mathbf{b}\|^2 \\ \le \|\mathbf{a}\|^2 + 2\,\|\mathbf{a}\|\|\mathbf{b}\| + \|\mathbf{b}\|^2 \\ = \big(\|\mathbf{a}\|+\|\mathbf{b}\|\big)^2 \end{gathered}

The inequality is Cauchy–Schwarz from P1.B3, a⋅b≤∥a∥∥b∥\mathbf{a}\cdot\mathbf{b}\le\|\mathbf{a}\|\|\mathbf{b}\|. Taking square roots (both sides are non-negative) gives the triangle inequality. Equality needs a⋅b=∥a∥∥b∥\mathbf{a}\cdot\mathbf{b}=\|\mathbf{a}\|\|\mathbf{b}\|, which means the vectors point the same way (or one is zero). So for L2, equality happens only in that case. For L1 equality happens whenever no entry pair cancels, meaning each pair ai,bia_i, b_i has the same sign or one of them is 0 (which is why (3,0)+(0,4)(3,0)+(0,4) has L1 length 7).

Things that are not norms

Two natural formulas break a rule, and the way they break is instructive.

Squared length, ∥a∥22\|\mathbf{a}\|_2^2. It breaks Rule 2 (doubling a vector multiplies it by 4, not 2). It also breaks the triangle inequality: for a=b=(1,0)\mathbf{a}=\mathbf{b}=(1,0) we get ∥a+b∥2=4\|\mathbf{a}+\mathbf{b}\|^2=4, but ∥a∥2+∥b∥2=2\|\mathbf{a}\|^2+\|\mathbf{b}\|^2=2. We still use squared lengths a lot, for reasons given below.

Go deeper Why the formula with p below 1 is not a norm

Take p=0.5p = 0.5 and the formula (∣x∣0.5+∣y∣0.5)2(|x|^{0.5} + |y|^{0.5})^{2}. The points (1,0)(1, 0) and (0,1)(0, 1) both give 1, so both are on the “unit ball”. Their sum is (1,1)(1, 1), and the formula gives (1+1)2=4(1 + 1)^2 = 4. The triangle inequality would need 4≤1+1=24 \le 1 + 1 = 2, which is false. Picture it: the midpoint (0.5,0.5)(0.5, 0.5) of the straight line between the two ball points has value (2×0.5)2=2(2\times\sqrt{0.5})^2 = 2, so it lies outside the ball. A true norm’s ball is convex: the straight segment between any two points of the ball stays inside the ball. The p<1p<1 ball is pinched in (see the widget), so it is not convex, and that is exactly the failure of the triangle inequality.

The formula can still be computed, but it is not a norm, so results that rely on the three norm rules do not apply to it.

Go deeper The “L0 norm” (counting non-zero entries) is not a norm either

People write ∥x∥0\|\mathbf{x}\|_0 for the number of non-zero entries of x\mathbf{x}: (3,0,−2,0)(3, 0, -2, 0) has ∥⋅∥0=2\|\cdot\|_0=2. It is handy for talking about sparse vectors (mostly zeros). But it is not a norm: Rule 2 fails, because 2x2\mathbf{x} has exactly as many non-zero entries as x\mathbf{x}, not twice as many. (It is the limit of ∑i∣xi∣p\sum_i |x_i|^p as p→0p\to 0, with no root taken, which is where the name comes from.) NumPy will compute it with np.linalg.norm(x, ord=0).

Distance: the norm of a difference

Length measures how far a vector is from the origin. Distance measures how far two vectors are from each other, and it is the same idea: subtract, then measure.

d(a,b)=∥a−b∥d(\mathbf{a},\mathbf{b}) = \|\mathbf{a}-\mathbf{b}\|

Remember from P1.B2 that a−b\mathbf{a}-\mathbf{b} is the arrow from the tip of b\mathbf{b} to the tip of a\mathbf{a}, so its norm is the length of that arrow. Take a=(1,2)\mathbf{a}=(1,2) and b=(4,6)\mathbf{b}=(4,6). Then a−b=(−3,−4)\mathbf{a}-\mathbf{b}=(-3,-4), and

DistanceCalculationValue
L2, Euclidean32+42\sqrt{3^2+4^2}5
L1, Manhattan3+43+47
L∞, Chebyshevmax⁡(3,4)\max(3,4)4

(Chebyshev is the name usually given to the L∞ distance.) The order of the two vectors does not matter, because ∥−x∥=∥x∥\|-\mathbf{x}\|=\|\mathbf{x}\| (Rule 2 with c=−1c=-1): d(a,b)=d(b,a)d(\mathbf{a},\mathbf{b})=d(\mathbf{b},\mathbf{a}). A distance built from a norm has three properties, all inherited from the three rules:

  • d(a,b)≥0d(\mathbf{a},\mathbf{b})\ge 0, and it is 0 only when a=b\mathbf{a}=\mathbf{b}.
  • It is symmetric: d(a,b)=d(b,a)d(\mathbf{a},\mathbf{b})=d(\mathbf{b},\mathbf{a}).
  • It obeys the triangle inequality: d(a,c)≤d(a,b)+d(b,c)d(\mathbf{a},\mathbf{c})\le d(\mathbf{a},\mathbf{b})+d(\mathbf{b},\mathbf{c}). Going from a\mathbf{a} to c\mathbf{c} by way of b\mathbf{b} is never shorter than going directly. (Apply Rule 3 to a−b\mathbf{a}-\mathbf{b} and b−c\mathbf{b}-\mathbf{c}.)

Who is nearest? It depends on the norm

Here is the practical punchline. Take a query point and a few stored points, and ask which stored point is nearest. That is exactly what k-nearest neighbors does (P3.B1). Does the answer depend on how you measure?

Which point is nearest to q? Drag q and see.

−4−224−4−224ABCDEq
Draw the ball around q for:
Distance from q to…ABCDENearest
L1 3.55467A
L2 3.53.543.164.244.95C
L∞ 3.52.5333.5B

The norms disagree about which point is nearest. Same points, same query: only the way of measuring distance changed.

The nearest point is marked with a diamond (L1), a circle (L2) or a square (L∞). The grey outline is the ball around q that just touches the nearest point under the chosen norm: nothing is inside it. q is at (0, 0).

Five fixed points (pink, A to E) and a query q (blue). The table gives the distance from q to each point under L1, L2 and L∞; the nearest is marked in the plot (diamond for L1, circle for L2, square for L∞) and highlighted in the table. Drag q or use the arrow keys, and choose which ball to draw around q.

With the query q=(0,0)\mathbf{q}=(0,0) in its starting position, the distances are:

PointL1L2L∞
A = (3.5, 0)3.53.53.5
B = (−2.5, −2.5)53.542.5
C = (−3, −1)43.163

(D and E are farther away in all three.) The nearest point by L1 is A, by L2 it is C, and by L∞ it is B. One query, one set of points, three different answers. The reason is in the shapes: the ball around q\mathbf{q} that just touches the nearest point is a diamond, a circle or a square, and these three shapes reach different points first. The widget draws that ball, so you can watch what “nearest” means.

A small case you can do by hand: from the origin, A=(3,3)A=(3,3) and B=(4,0)B=(4,0). The L1 distances are 6 and 4 (B is nearer), the L2 distances are 18≈4.24\sqrt{18}\approx 4.24 and 4 (B is nearer), and the L∞ distances are 3 and 4 (A is nearer).

So the choice of distance is part of the model. Some guidelines, and where they come from:

  • L2 is the default. It treats all directions alike (the ball is a circle) and it squares each difference, so one large difference counts for a lot.
  • L1 adds the differences without squaring, so one large difference counts only in proportion to its size. It is a natural fit when differences along each feature add up independently, like blocks on a grid.
  • L∞ is determined by the single largest difference: all the others are ignored. It fits “every feature must be close” questions.

No norm is “correct” in general: it depends on what “close” should mean for your data.

Squared distance

Often you will see the squared Euclidean distance:

∥a−b∥22=(a1−b1)2+(a2−b2)2+⋯+(an−bn)2\begin{aligned} \|\mathbf{a}-\mathbf{b}\|_2^2 &= (a_1-b_1)^2 + (a_2-b_2)^2 \\ &\quad + \dots + (a_n-b_n)^2 \end{aligned}

For the example above (distance 5), the squared distance is 25. Why use it?

  • No square root to compute. It is a plain sum of squares, which is cheaper.
  • Same ranking. Squaring never changes the order of non-negative numbers, so if ∥a−q∥<∥b−q∥\|\mathbf{a}-\mathbf{q}\|<\|\mathbf{b}-\mathbf{q}\| then also ∥a−q∥2<∥b−q∥2\|\mathbf{a}-\mathbf{q}\|^2<\|\mathbf{b}-\mathbf{q}\|^2. A nearest-neighbor search gets the same winner either way.
  • Smooth to work with. A preview for later: the gradient of ∑iwi2\sum_i w_i^2 is simply 2w2\mathbf{w}, with no square root to differentiate. This is one reason the mean squared error (P4.6) and L2 regularization (P3.A6) are written with squares.

Remember from the section on things that are not norms that the squared distance is not a distance in the strict sense (it fails the triangle inequality), though it is fine for ranking and for loss functions.

Unit vectors and normalizing

A unit vector has length 1. Divide any non-zero vector by its own length and you get a unit vector pointing the same way, as P1.B3 explained:

a^=a∥a∥\hat{\mathbf{a}} = \frac{\mathbf{a}}{\|\mathbf{a}\|}

Why is its length 1? Rule 2 with c=1/∥a∥c = 1/\|\mathbf{a}\| gives ∥a^∥=1∥a∥ ∥a∥=1\|\hat{\mathbf{a}}\| = \frac{1}{\|\mathbf{a}\|}\,\|\mathbf{a}\| = 1. For a=(3,4)\mathbf{a}=(3,4): a^=(0.6,0.8)\hat{\mathbf{a}}=(0.6,0.8), and 0.36+0.64=10.36+0.64=1. It is also called normalizing, and it keeps the direction and throws the length away. The zero vector cannot be normalized, because dividing by 0 is not allowed.

The same trick works for any norm: divide by that norm. (3,4)/7=(3/7,4/7)(3,4)/7=(3/7,4/7) has L1 norm 1, so it lies on the diamond. When ML people say “normalize” with no other detail they usually mean L2.

Cosine versus Euclidean. P1.B3 showed that for unit vectors, ranking by cosine similarity and ranking by Euclidean distance agree. For vectors of different lengths they can disagree. Take the query q=(1,0)\mathbf{q}=(1,0), A=(10,0)\mathbf{A}=(10,0) and B=(1,1)\mathbf{B}=(1,1). Cosine similarity says A is the better match (cosine 1, against 0.71 for B: A points exactly the same way). Euclidean distance says B is much nearer (distance 1, against 9 for A). Neither is wrong: they answer different questions, “same direction?” and “same place?”.

Two previews from ML.

  • Gradient clipping (P4.16, P10.B7). If a gradient g\mathbf{g} is too long, rescale it to a maximum length cc: if ∥g∥>c\|\mathbf{g}\|>c, use g c/∥g∥\mathbf{g}\,c/\|\mathbf{g}\|. Example: g=(6,8)\mathbf{g}=(6,8) has length 10; with c=5c=5 the clipped gradient is (3,4)(3,4), which has length 5 and points the same way. That is Rule 2 at work.
  • Normalization layers (P4.19) divide the numbers in a layer by a quantity that measures their typical size, so the next layer sees values on a steady scale. They are cousins of “divide a vector by its length”, with details that P4.19 explains.

Feature scale: when one number drowns the rest

Distances add up the differences in every feature, so a feature measured in big units dominates. Suppose each person is a vector (age in years, income in dollars):

Person(age, income)
Alice(25, 50 000)
Bob(60, 50 500)
Carol(26, 60 000)

Alice and Bob are 35 years apart in age but only 500 dollars apart in income. Alice and Carol are a year apart in age but 10 000 dollars apart in income. The Euclidean distances are

d(Alice,Bob)=352+5002≈501.2d(Alice,Carol)=12+100002≈10000.0\begin{aligned} d(\text{Alice},\text{Bob}) &= \sqrt{35^2+500^2} \\ &\approx 501.2 \\ d(\text{Alice},\text{Carol}) &= \sqrt{1^2+10000^2} \\ &\approx 10000.0 \end{aligned}

By this measure Bob is about 20 times “closer” to Alice than Carol is. The age difference is almost invisible next to the income difference, only because dollars are bigger numbers than years. Now rescale each feature to a similar range, here by subtracting the smallest value assumed for the feature (20 years, 20 000 dollars) and dividing by its range (50 years, 100 000 dollars). Alice becomes (0.1,0.3)(0.1, 0.3), Bob (0.8,0.305)(0.8, 0.305), Carol (0.12,0.4)(0.12, 0.4), and the distances are

d(Alice,Bob)≈0.700d(Alice,Carol)≈0.102\begin{aligned} d(\text{Alice},\text{Bob}) &\approx 0.700 \\ d(\text{Alice},\text{Carol}) &\approx 0.102 \end{aligned}

Now Carol is the near neighbor, which fits the idea that a one-year age gap is a small difference. (The ranges are an assumption made for this example. Rescaling methods, and the traps around them, are the topic of P3.A11.) The lesson for any distance-based method such as k-nearest neighbors: rescale features to comparable sizes first, or the biggest-numbered feature decides everything.

Go deeper High dimensions: distances bunch together (a warning, not a law)

In many dimensions, the distances from a query to a crowd of random points tend to become nearly equal: the nearest point is hardly nearer than the farthest. Here is a simulation. Draw 1000 points and one query with independent entries uniform between 0 and 1, in dd dimensions, and compare the farthest and the nearest distance with (farthest−nearest)/nearest(\text{farthest}-\text{nearest})/\text{nearest}:

import numpy as np
for d in [2, 10, 100, 1000, 10000]:
    rng = np.random.default_rng(1)
    X = rng.random((1000, d)); q = rng.random(d)
    dist = np.linalg.norm(X - q, axis=1)
    print(d, (dist.max() - dist.min()) / dist.min())

In one run of this code the ratio is about 113 for d=2d=2, 3.3 for d=10d=10, 0.49 for d=100d=100, 0.12 for d=1000d=1000 and 0.04 for d=10000d=10000. For d=10000d=10000 the farthest point is only about 4% farther than the nearest. So “nearest” becomes a weaker idea as the dimension grows (this is part of what is called the curse of dimensionality, which P3.B1 returns to). This is a statement about random data. Real data is often not spread out like that, so distance-based methods can still work well in high dimensions, but the effect is a good reason to be careful, and to check that your distance really separates near from far.

Norms in NumPy

Try it: norms, p-norms, scaling and the triangle inequality

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Distances are norms of differences, and the axis= argument gives one norm per row, which is how you measure many vectors at once. In the next cell, each row of X is one vector.

Try it: distances, nearest neighbor and many vectors at once

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Read the last three lines carefully. For a 2-D array, np.linalg.norm treats it as a matrix and computes a matrix norm: with no ord it combines all entries as if they were one long vector (this is correct for L2), but ord=1 means “the largest column sum”, which is 6 here and not the sum of all the absolute values. If you want the L1 norm of every entry, use M.ravel() first, or np.abs(M).sum(). To get one norm per row, write axis=1.

Check your understanding

  1. What is the (L2) length of the vector (2,3,6)(2, 3, 6)?

  2. What are the L1 and L∞ norms of (−2,5,1)(-2, 5, 1)?

  3. Two vectors have L2 lengths 33 and 44. Which value is impossible for the L2 length of their sum?

  4. From the origin, A=(3,3)A=(3,3) and B=(4,0)B=(4,0). Which norm says that AA is nearer than BB?

  5. You rank 1000 stored points by their squared Euclidean distance to a query, instead of by the Euclidean distance. How does the ranking compare?

Exercises

  1. Find the L1, L2 and L∞ norms of (−6,8)(-6, 8).
    Show answerL1 = 6 + 8 = 14, L2 = √(36 + 64) = 10, L∞ = 8.
  2. Find all three norms of the 4-D vector (2,−2,2,−2)(2, -2, 2, -2).
    Show answerL1 = 8, L2 = √16 = 4, L∞ = 2.
  3. Find the L1, L2 and L∞ distance between a=(1,1)\mathbf{a}=(1,1) and b=(6,13)\mathbf{b}=(6,13).
    Show answerThe difference is (−5, −12). L1 = 17, L2 = √(25 + 144) = 13, L∞ = 12.
  4. The L2 length of (3,4)(3, 4) is 5. What is the length of −3×(3,4)-3\times(3,4), and which rule gives it?
    Show answer15, from Rule 2: ∥ca∥=∣c∣∥a∥=3×5\|c\mathbf{a}\|=|c|\|\mathbf{a}\|=3\times 5.
  5. Is (0.8,0.8)(0.8, 0.8) inside, on or outside the unit ball for L1, for L2 and for L∞?
    Show answerL1 norm 1.6: outside. L2 norm √1.28 ≈ 1.13: outside. L∞ norm 0.8: inside. The L∞ ball (the square) is the biggest.
  6. Normalize (5,12)(5, 12) using L2, and then using L1.
    Show answerL2: divide by 13 to get (5/13, 12/13) ≈ (0.385, 0.923). L1: divide by 17 to get (5/17, 12/17) ≈ (0.294, 0.706), whose entries add to 1.
  7. For a=(1,2)\mathbf{a}=(1,2) and b=(3,−1)\mathbf{b}=(3,-1), check the triangle inequality in L2.
    Show answer‖a‖ = √5 ≈ 2.236 and ‖b‖ = √10 ≈ 3.162, so the sum of lengths is about 5.398. And a + b = (4, 1) has length √17 ≈ 4.123, which is smaller, as it must be.
  8. A gradient is (6,8)(6, 8) and you clip it to a maximum length of 5. What do you get? What if the gradient had been (1.5,2)(1.5, 2) (length 2.5)?
    Show answer(3, 4). The second gradient is already shorter than 5, so it is left alone.
  9. Two points are 5 apart in L2. What is their squared distance, and does a nearest-neighbor search change if you use it?
    Show answer25. The nearest neighbor does not change, because squaring keeps the order of distances.
  10. In the Alice, Bob and Carol example, why does the raw distance say Bob is near Alice? How do you fix it?
    Show answerIncome is measured in much bigger numbers than age, so the 500-dollar gap outweighs the 35-year gap. Rescale each feature to a similar range first (P3.A11); then Carol is the near neighbor.
  11. Code: using X = np.array([[3.0, 4.0], [1.0, 0.0], [0.0, 2.0]]), which row is nearest to (0,0)(0, 0) in L1, and which is nearest in L∞?
    Show answernp.linalg.norm(X, ord=1, axis=1) gives [7, 1, 2], and np.linalg.norm(X, ord=np.inf, axis=1) gives [4, 1, 2]. Row 1, (1, 0), is nearest in both.

Key takeaways

  • The length (L2 or Euclidean norm) of a is ‖a‖₂ = √(a₁² + … + aₙ²): Pythagoras in any dimension. For (3, 4) it is 5.
  • The L1 (Manhattan) norm adds the absolute values of the entries: 7 for (3, 4). The L∞ (max) norm is the largest absolute entry: 4 for (3, 4). The Lp norm slides between them as p grows.
  • The unit ball of a norm is the set of vectors with norm at most 1. For L1 it is a diamond, for L2 a circle, for L∞ a square. For p below 1 the formula is not a norm: the ball is pinched in and the triangle inequality fails.
  • Every norm obeys three rules: the norm is zero only for the zero vector; ‖c·a‖ = |c|·‖a‖; and the triangle inequality ‖a + b‖ ≤ ‖a‖ + ‖b‖ (a detour is never shorter than the direct path).
  • The distance between a and b is ‖a − b‖. Different norms can disagree about which point is nearest.
  • Squared L2 distance skips the square root and ranks points in exactly the same order. A feature measured in thousands drowns the others in a distance unless you rescale the features first.
  • In NumPy: np.linalg.norm(v), ord=1, ord=np.inf, and axis=1 to get one norm per row.
Found a mistake? Tell us