Sub topic 2
Measuring similarity with distance
k-nearest neighbours (k-NN) predicts from the training points that look most like a new point. "Looks like" has to be turned into a number, and that number is a distance. This chapter covers the common distance functions, what each one measures, and how to choose between them. It assumes you know what feature vectors are, can read basic NumPy, and have met Euclidean distance. Later chapters use these distances for voting, scaling and tuning.
Why the distance function is a modelling choice
k-NN has no fitted parameters. The only thing that decides which stored points count as "near" is the distance function. Change it and you change the neighbours, so you change the predictions. Two models with the same data and the same k can disagree on a point because they define similarity differently.
A distance function takes two feature vectors and returns one non-negative number. A smaller number means more similar. A function d is a metric if it satisfies four rules:
- Non-negativity:
d(a, b) >= 0. - Identity:
d(a, b) = 0only whenaandbare the same point. - Symmetry:
d(a, b) = d(b, a). - Triangle inequality:
d(a, c) <= d(a, b) + d(b, c).
The triangle inequality matters more than it looks. The tree-based search structures covered later use it to rule out whole groups of points without measuring them. A measure that breaks it can still rank neighbours, but those structures cannot use it.
The main distances
Let x and y be vectors with n features each. The distances below are all built from the per-feature differences x_i - y_i.
Euclidean distance
Euclidean distance is the straight-line distance:
d(x, y) = sqrt( sum_i (x_i - y_i)^2 )
It squares each difference, adds them, and takes the root. Squaring means a single large difference dominates the sum. It is the default in most k-NN libraries and fits data where all features are measured on comparable scales, such as coordinates in space.
Manhattan distance
Manhattan distance (also called L1 or city-block distance) adds the absolute differences:
d(x, y) = sum_i |x_i - y_i|
It is named after walking along a street grid, where you cannot cut diagonally. Because it does not square, one extreme feature value has less influence than it does under Euclidean distance. It is a common choice when features are counts or when some features contain outliers.
Chebyshev distance
Chebyshev distance takes only the largest single-feature difference:
d(x, y) = max_i |x_i - y_i|
Two points are close only if every feature is close. It is used less often, but it is the limiting case of the family below.
Minkowski distance
Minkowski distance generalises the previous three with a parameter p:
d(x, y) = ( sum_i |x_i - y_i|^p )^(1/p)
| p | Resulting distance |
|---|---|
| 1 | Manhattan |
| 2 | Euclidean |
| large | approaches Chebyshev |
Larger p gives more weight to the biggest differences. Smaller p spreads weight more evenly across features. Values of p below 1 break the triangle inequality, so they are not metrics. scikit-learn's default k-NN metric is Minkowski with p=2, which is Euclidean.
Cosine distance
Cosine distance ignores vector length and compares only direction:
cosine similarity = (x · y) / (‖x‖ ‖y‖)
cosine distance = 1 - cosine similarity
Two vectors pointing the same way have distance 0, even if one is ten times longer. This suits text represented as word counts. A long document and a short one on the same subject have similar word proportions but very different lengths, and cosine distance treats them as close. Cosine distance is not a true metric, because it can violate the triangle inequality. It is also undefined for the zero vector, which has no direction.
Computing the distances in NumPy
The code below computes every distance for one pair of vectors. The difference vector is [-3, -4, 0], so the arithmetic is easy to check by hand.
import numpy as np
x = np.array([1.0, 2.0, 3.0])
y = np.array([4.0, 6.0, 3.0])
diff = x - y # [-3, -4, 0]
euclidean = np.sqrt(np.sum(diff ** 2))
manhattan = np.sum(np.abs(diff))
chebyshev = np.max(np.abs(diff))
def minkowski(a, b, p):
return np.sum(np.abs(a - b) ** p) ** (1.0 / p)
def cosine_distance(a, b):
sim = a @ b / (np.linalg.norm(a) * np.linalg.norm(b))
return max(0.0, 1.0 - sim) # clip tiny negative rounding error
print(euclidean) # 5.0
print(manhattan) # 7.0
print(chebyshev) # 4.0
print(minkowski(x, y, 1)) # 7.0, same as Manhattan
print(minkowski(x, y, 2)) # 5.0, same as Euclidean
print(round(cosine_distance(x, y), 4)) # 0.1445Notice the ordering: Manhattan (7) is at least Euclidean (5), which is at least Chebyshev (4). This always holds for the same pair of points. The distances differ in size, but what matters for k-NN is whether they agree on the ranking of neighbours. They often do not.
The same data, different neighbours
Consider a query point at the origin and two stored points. Point A is at (3, 3), and point B is at (4, 0).
| Point | Euclidean | Manhattan |
|---|---|---|
| A = (3, 3) | about 4.24 | 6 |
| B = (4, 0) | 4.00 | 4 |
Under both measures B is closer here, so the ranking agrees. Move B to (5.5, 0) and Euclidean distance becomes 5.5 while Manhattan becomes 5.5, but A stays at 4.24 and 6. Now Euclidean ranks A closer and Manhattan ranks B closer. Diagonal movement costs more under Manhattan than under Euclidean, which is why the two can disagree. With k=1, the prediction would flip.
Magnitude and direction can also disagree, as the next example shows.
import numpy as np
a = np.array([1.0, 2.0])
b = np.array([10.0, 20.0]) # same direction as a, ten times longer
euclid = np.linalg.norm(a - b)
cos_dist = max(0.0, 1.0 - a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))
print(round(euclid, 2)) # 20.12
print(round(cos_dist, 4)) # 0.0Euclidean distance calls these points far apart. Cosine distance calls them identical. Neither is wrong; they answer different questions.
Choosing a metric
Treat the chart as a starting point. The reliable way to choose is to try the plausible candidates and compare them on held-out data, which a later chapter covers.
Using a metric in scikit-learn
scikit-learn exposes the metric through the metric and p arguments of its neighbour classes.
from sklearn.neighbors import KNeighborsClassifier
euclid_knn = KNeighborsClassifier(n_neighbors=5) # Minkowski, p=2
manhattan_knn = KNeighborsClassifier(n_neighbors=5, p=1) # Minkowski, p=1
cosine_knn = KNeighborsClassifier(n_neighbors=5, metric="cosine", algorithm="brute")
print(euclid_knn.get_params()["metric"]) # minkowski
print(manhattan_knn.get_params()["p"]) # 1
print(cosine_knn.get_params()["metric"]) # cosineThe p argument only applies when metric="minkowski". Cosine is not supported by the KD-tree and ball tree structures, so algorithm="brute" makes the intent explicit. With the default algorithm="auto", scikit-learn would pick brute force for you in that case.
Common errors
- Using cosine distance on a zero vector. The norm is zero and the division produces
nan. Remove or handle empty rows first. - Assuming Minkowski
pis a free tuning knob without checking its range. Values below 1 are not metrics, and tree structures can return wrong neighbours with them. - Mixing units without noticing. Height in centimetres and income in dollars cannot be compared directly.
- Reading a distance value as a probability or score. Distances from different metrics are on different scales and are not comparable with each other.
- Applying Euclidean distance to categorical codes. If "red", "green" and "blue" are stored as 0, 1, 2, the metric treats green as between red and blue, which is meaningless.
Exercise
For x = (0, 0) and y = (3, 4), compute the Manhattan, Euclidean and Chebyshev distances. Then say which of the three would rank y as closest to x if the other candidate point were z = (4, 0) under each measure.
Show answer
For y: Manhattan = 3 + 4 = 7, Euclidean = sqrt(9 + 16) = 5, Chebyshev = max(3, 4) = 4. For z = (4, 0): Manhattan = 4, Euclidean = 4, Chebyshev = 4. Under Manhattan z is closer (4 < 7). Under Euclidean z is closer (4 < 5). Under Chebyshev the two are tied at 4, so a tie-breaking rule decides. y is never strictly the closest.
Exercise
A search engine represents each document as a vector of word counts. A 2000-word article and a 200-word summary of it have nearly the same word proportions. Which metric would you expect to rate them as similar, and why?
Show answer
Cosine distance. It compares direction, which reflects word proportions, and ignores vector length. Euclidean and Manhattan distance would rate the two as far apart because the long article has much larger counts.