Sub topic 2
Measuring distance between points
This chapter assumes you know Euclidean distance, basic NumPy, and scikit-learn's fit style API. Every method in this tutorial starts from one input, a distance between each pair of points. If that distance is a poor fit for your data, no later step can repair it.
What a distance measure must do
A distance (or dissimilarity) function takes two points and returns a non-negative number. Small values mean "similar". Hierarchical clustering and DBSCAN only ask which pairs are close, so the choice of measure decides what "close" means.
Common measures
| Metric | Formula idea | Typical use |
|---|---|---|
| Euclidean | Straight-line distance, square root of summed squared differences | Continuous features on comparable scales |
| Manhattan (`cityblock`) | Sum of absolute differences | Grid-like data, less sensitive to one large difference |
| Chebyshev | Largest single-coordinate difference | When the worst feature gap is what matters |
| Cosine | 1 minus the cosine of the angle between vectors | Direction matters, length does not (for example, text vectors) |
Computing distances in scipy
pdist returns all pairwise distances in a condensed form, a flat array of length n(n-1)/2. squareform turns it into a full n×n matrix.
import numpy as np
from scipy.spatial.distance import pdist, squareform
X = np.array([[1.0, 2.0], [4.0, 6.0], [8.0, 12.0]])
for metric in ["euclidean", "cityblock", "chebyshev", "cosine"]:
condensed = pdist(X, metric=metric)
D = squareform(condensed)
print(metric, condensed.shape)
print(np.round(D, 3))Points 2 and 3 lie on the same line through the origin. Their cosine distance is 0, but their Euclidean distance is about 7.211. Under cosine they are identical, and under Euclidean they are not. The metric changes which points count as neighbors.
Where the metric enters each method
scipy.cluster.hierarchy.linkageaccepts either raw data with ametricargument or a condensed distance array frompdist.AgglomerativeClusteringtakesmetric=(namedaffinity=before scikit-learn 1.2).DBSCANtakesmetric=. Itsepsis a threshold in that metric's units.
from sklearn.cluster import DBSCAN, AgglomerativeClustering
db = DBSCAN(eps=0.5, min_samples=5, metric="manhattan")
agg = AgglomerativeClustering(n_clusters=3, linkage="average", metric="cosine")Common errors
- Ward with a non-Euclidean metric. Ward linkage assumes Euclidean distance. scikit-learn rejects other metrics for it, and scipy gives results that are not meaningful.
- Cosine on zero vectors. The angle is undefined, so you get
nandistances. Remove or handle those rows first. - Reusing
epsacross metrics. Anepsof 0.5 under Euclidean is a different neighborhood from 0.5 under Manhattan or cosine. - Ignoring feature scale. A feature measured in thousands dominates one measured in decimals. The next chapter covers scaling.
Exercise
Two document vectors point in the same direction, but one is ten times longer than the other. Which metric treats them as the same, Euclidean or cosine, and why?
Show answer
Cosine. It depends only on the angle between the vectors, which is 0 here, so the distance is 0. Euclidean distance includes the length difference, so the two documents appear far apart.