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 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
The same recipe gives the length of that P1.B1 mentioned: .
More dimensions work the same way: square every entry, add, take the square root. For :
and for it is . We write the length of as (you met this in P1.B3), and in general
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: , because .
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: 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 blocks. Add the absolute values of the entries:
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:
For that is 4. A chess king moves one square in any direction, diagonals included, so it needs exactly moves to travel 3 squares sideways and 4 forward. The max norm is “how bad is the worst entry?”.
For the same arrow the three measures give three answers, and for and too. (L1 adds the absolute values, L2 is Pythagoras, L∞ is the biggest entry.)
| Vector | L1 | L2 | L∞ |
|---|---|---|---|
| 7 | 5 | 4 | |
| 4 | 3 | ||
| 8 | 5 |
Notation. Write a small subscript for the norm: , , . With no subscript, means L2, as in P1.B3.
One family: the -norm
All three are members of one family. For any :
Put and you get L1. Put and you get L2 (the “power 1/2” is the square root). As 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 :
| 1 | 2 | 4 | 10 | 50 | ∞ | |
|---|---|---|---|---|---|---|
| 7 | 5 | 4.28 | 4.02 | 4.00 | 4 |
(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 have norm exactly 1?
- L1: is a diamond, with corners at and .
- L2: is the usual circle.
- L∞: is a square, with corners at .
Play with it and notice:
- As grows from 1, the diamond swells into the circle (at ) and then into the square (at ). The ball of a larger always contains the ball of a smaller .
- The tip of always sits on the dashed blue outline (for a long 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 : 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, . 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 and :
A function is a norm if, for all vectors and every number :
- , and only for .
- .
- (the triangle inequality).
The -norms for and the max norm satisfy all three. For every ,
and in dimensions and . So the three measures never disagree wildly, but they can differ by a factor that grows with the dimension. For example, with entries has L1 norm 9, L2 norm 3 and L∞ norm 1.
Notation. for the -norm, and 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 outnp.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
Stretch a vector by a number and its norm is multiplied by , the size of without its sign:
Take with . Then has length : twice as long, even though is negative. (Negative factors flip the direction, P1.B2; they do not shrink the length.) This holds for L1 and L∞ too: .
Rule 3: the triangle inequality
P1.B2 pointed out something odd: , and the arrows have lengths 3 and 4, but the sum has length 5, not 7. That is the triangle inequality:
Walk along , then along . The two legs, with the direct path , 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.
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, (two numbers of opposite signs partly cancel). Apply this to every entry and add: , which is . For L∞, the largest entry of is some .
L2, using the dot product. Expand the square:
The inequality is Cauchy–Schwarz from P1.B3, . Taking square roots (both sides are non-negative) gives the triangle inequality. Equality needs , 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 has the same sign or one of them is 0 (which is why has L1 length 7).
Things that are not norms
Two natural formulas break a rule, and the way they break is instructive.
Squared length, . It breaks Rule 2 (doubling a vector multiplies it by 4, not 2). It also breaks the triangle inequality: for we get , but . 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 and the formula . The points and both give 1, so both are on the “unit ball”. Their sum is , and the formula gives . The triangle inequality would need , which is false. Picture it: the midpoint of the straight line between the two ball points has value , 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 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 for the number of non-zero entries of : has . It is handy for talking about sparse vectors (mostly zeros). But it is not a norm: Rule 2 fails, because has exactly as many non-zero entries as , not twice as many. (It is the limit of as , 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.
Remember from P1.B2 that is the arrow from the tip of to the tip of , so its norm is the length of that arrow. Take and . Then , and
| Distance | Calculation | Value |
|---|---|---|
| L2, Euclidean | 5 | |
| L1, Manhattan | 7 | |
| L∞, Chebyshev | 4 |
(Chebyshev is the name usually given to the L∞ distance.) The order of the two vectors does not matter, because (Rule 2 with ): . A distance built from a norm has three properties, all inherited from the three rules:
- , and it is 0 only when .
- It is symmetric: .
- It obeys the triangle inequality: . Going from to by way of is never shorter than going directly. (Apply Rule 3 to and .)
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?
With the query in its starting position, the distances are:
| Point | L1 | L2 | L∞ |
|---|---|---|---|
| A = (3.5, 0) | 3.5 | 3.5 | 3.5 |
| B = (−2.5, −2.5) | 5 | 3.54 | 2.5 |
| C = (−3, −1) | 4 | 3.16 | 3 |
(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 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, and . The L1 distances are 6 and 4 (B is nearer), the L2 distances are 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:
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 then also . A nearest-neighbor search gets the same winner either way.
- Smooth to work with. A preview for later: the gradient of is simply , 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:
Why is its length 1? Rule 2 with gives . For : , and . 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. 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 , and . 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 is too long, rescale it to a maximum length : if , use . Example: has length 10; with the clipped gradient is , 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
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 , Bob , Carol , and the distances are
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 dimensions, and compare the farthest and the nearest distance with :
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 , 3.3 for , 0.49 for , 0.12 for and 0.04 for . For 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
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.
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
What is the (L2) length of the vector ?
Square the entries, add, then take the root: 4 + 9 + 36 = 49, and the square root of 49 is 7. The value 11 is the L1 norm (add the entries without squaring), and 6 is the L∞ norm (the biggest entry).
What are the L1 and L∞ norms of ?
L1 adds the absolute values: 2 + 5 + 1 = 8. L∞ is the largest absolute value: 5. A norm is never negative, so −2 cannot be a norm.
Two vectors have L2 lengths and . Which value is impossible for the L2 length of their sum?
The triangle inequality says the sum is at most 3 + 4 = 7, so 8 cannot happen. The other three can: 7 when the vectors point the same way, 5 when they are perpendicular, and 1 when they point opposite ways.
From the origin, and . Which norm says that is nearer than ?
L∞ distances are 3 for A and 4 for B, so A is nearer. L1 gives 6 and 4, and L2 gives about 4.24 and 4, so both of those pick B.
You rank 1000 stored points by their squared Euclidean distance to a query, instead of by the Euclidean distance. How does the ranking compare?
Squaring turns a distance into a larger number in a way that keeps the order: a smaller distance always gives a smaller square. So the nearest point is the same, and so is the whole order.
Exercises
- Find the L1, L2 and L∞ norms of .
Show answer
L1 = 6 + 8 = 14, L2 = √(36 + 64) = 10, L∞ = 8. - Find all three norms of the 4-D vector .
Show answer
L1 = 8, L2 = √16 = 4, L∞ = 2. - Find the L1, L2 and L∞ distance between and .
Show answer
The difference is (−5, −12). L1 = 17, L2 = √(25 + 144) = 13, L∞ = 12. - The L2 length of is 5. What is the length of , and which rule gives it?
Show answer
15, from Rule 2: . - Is inside, on or outside the unit ball for L1, for L2 and for L∞?
Show answer
L1 norm 1.6: outside. L2 norm √1.28 ≈ 1.13: outside. L∞ norm 0.8: inside. The L∞ ball (the square) is the biggest. - Normalize using L2, and then using L1.
Show answer
L2: 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. - For and , 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. - A gradient is and you clip it to a maximum length of 5. What do you get? What if the gradient had been (length 2.5)?
Show answer
(3, 4). The second gradient is already shorter than 5, so it is left alone. - Two points are 5 apart in L2. What is their squared distance, and does a nearest-neighbor search change if you use it?
Show answer
25. The nearest neighbor does not change, because squaring keeps the order of distances. - In the Alice, Bob and Carol example, why does the raw distance say Bob is near Alice? How do you fix it?
Show answer
Income 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. - Code: using
X = np.array([[3.0, 4.0], [1.0, 0.0], [0.0, 2.0]]), which row is nearest to in L1, and which is nearest in L∞?Show answer
np.linalg.norm(X, ord=1, axis=1)gives [7, 1, 2], andnp.linalg.norm(X, ord=np.inf, axis=1)gives [4, 1, 2]. Row 1, (1, 0), is nearest in both.