Sub topic 2
Measuring similarity with distance
This chapter assumes you know what feature vectors are and can read basic NumPy. You should also know that k-NN predicts from the training points closest to a query. Here you will learn how "closest" is defined.
Similarity as geometry
k-NN treats each example as a point in a space with one axis per feature. Two examples are similar when their points are close. A distance function turns that idea into a number: small means similar, large means different.
Your choice of distance decides which points count as neighbours, so it directly changes predictions.
Three related distances
Take two vectors a and b with n features each.
- Euclidean distance is the straight-line distance: the square root of the sum of squared differences.
- Manhattan distance is the sum of absolute differences. It is the distance you would walk on a street grid.
- Minkowski distance generalises both. It is
(sum |a_i - b_i|^p)^(1/p). Settingp = 1gives Manhattan andp = 2gives Euclidean.
Larger p puts more weight on the single largest feature difference. Squaring in Euclidean distance makes one big gap matter more than several small ones. Manhattan distance treats all gaps in proportion to their size, so it is less sensitive to a single outlying feature.
import numpy as np
def minkowski(a, b, p):
return np.sum(np.abs(a - b) ** p) ** (1 / p)
def cosine_distance(a, b):
return 1 - a @ b / (np.linalg.norm(a) * np.linalg.norm(b))
a = np.array([1.0, 2.0, 3.0])
b = np.array([4.0, 6.0, 3.0])
print(round(minkowski(a, b, 1), 3)) # 7.0 Manhattan
print(round(minkowski(a, b, 2), 3)) # 5.0 Euclidean
print(round(minkowski(a, b, 3), 3)) # 4.498
print(round(cosine_distance(a, b), 3)) # 0.145The differences here are 3, 4 and 0, so Euclidean distance is the familiar 3-4-5 triangle result of 5. Notice that the value falls as p rises. For a fixed pair of points, the Minkowski distance never increases with p.
Cosine distance: direction, not size
Cosine distance ignores vector length and compares only direction. It is 1 - cos(theta), where cos(theta) is the dot product divided by the product of the lengths.
This suits data where magnitude is incidental. In word-count vectors, a long document and a short one on the same topic have similar direction but very different length. Euclidean distance would call them far apart. Cosine distance would call them close.
Choosing a metric
Euclidean distance is a sensible default. Treat the metric as a hyperparameter and compare options with cross-validation, which later chapters cover.
Using a metric in scikit-learn
KNeighborsClassifier uses Minkowski distance with p=2 by default. You can change p or name another metric.
from sklearn.neighbors import KNeighborsClassifier
euclid = KNeighborsClassifier(n_neighbors=5) # Minkowski, p=2
manhattan = KNeighborsClassifier(n_neighbors=5, p=1) # Minkowski, p=1
cosine = KNeighborsClassifier(n_neighbors=5, metric="cosine")The cosine model uses brute-force search under the default algorithm="auto", because the tree structures do not support it.
Common errors
- Unscaled features. A feature measured in thousands swamps one measured in fractions. Any of these distances then reflects mostly the large feature. The scaling chapter covers the fix.
- Cosine on a zero vector. The norm is zero, so the division fails or yields
nan. Remove or handle all-zero rows first. - Mixing up distance and similarity. Cosine similarity is high for similar points, while cosine distance is low. k-NN needs the distance.
- Categorical codes as numbers. Encoding "red, green, blue" as 1, 2, 3 implies that red is nearer to green than to blue. Distances on such codes are meaningless.
Exercise
For a = [0, 0] and b = [3, 4], compute the Manhattan and Euclidean distances. Then say which metric would be less affected if b's second coordinate were an outlier of 40 instead of 4.
Show answer
Manhattan is |3| + |4| = 7. Euclidean is sqrt(9 + 16) = 5. With the outlier, b = [3, 40]: Manhattan becomes 43 and Euclidean becomes sqrt(9 + 1600) ≈ 40.11. The outlier raises Manhattan distance by a factor of about 6.1 and Euclidean by about 8.0, so Manhattan is less affected.