Sub topic 2
Distance and centroids
This chapter assumes you know basic NumPy indexing and broadcasting, the idea of a feature matrix X with one row per sample and one column per feature, and the difference between supervised and unsupervised learning. It covers the two quantities k-means is built on: a distance between a point and a centroid, and the centroid itself.
Points as vectors
k-means treats each row of X as a point in d-dimensional space, where d is the number of features. A sample with features [height, weight] is a point in 2D. Everything k-means does is geometry on these points.
Euclidean distance
The Euclidean distance between two points a and b is the length of the straight line between them:
dist(a, b) = sqrt( (a1 - b1)^2 + (a2 - b2)^2 + ... + (ad - bd)^2 )Each feature contributes its squared difference to the total. A feature with large numeric differences therefore contributes more than one with small differences. The chapter on feature scaling returns to this.
k-means works with the squared distance, ||a - b||^2, which is the same sum without the square root. Squared distance is cheaper to compute. It is also the quantity the algorithm minimizes. Taking the square root does not change which centroid is nearest, so the assignment step can use either form.
Centroids
A centroid is the mean of a group of points, computed separately for each feature. For points (1, 2), (1.5, 1.8), the centroid is ((1 + 1.5) / 2, (2 + 1.8) / 2) = (1.25, 1.9).
A centroid is a location, not a data point. It usually coincides with no row of X, and it can sit in empty space between points.
The mean is used because it minimizes the sum of squared distances to a group of points. For one feature, the sum is S(c) = Σ (x_i - c)^2. Its derivative is -2 Σ (x_i - c). Setting that to zero gives c = (1/n) Σ x_i, which is the mean. The same argument applies to each feature independently. The mean is what pairs with squared Euclidean distance. A different distance would call for a different center. The median, for example, minimizes the sum of absolute distances.
Computing distances with NumPy
The next example computes the distance from every point to every centroid without a Python loop.
import numpy as np
X = np.array([[1.0, 2.0], [1.5, 1.8], [8.0, 8.0], [9.0, 9.5]])
centroids = np.array([[1.0, 2.0], [9.0, 9.5]])
diff = X[:, None, :] - centroids[None, :, :] # shape (4, 2, 2)
dists = np.linalg.norm(diff, axis=2) # shape (4, 2)
labels = dists.argmin(axis=1)
print(dists.round(2))
print(labels)
# Centroid of each group is the per-feature mean
for j in range(2):
print(j, X[labels == j].mean(axis=0))The shapes explain how this works:
X[:, None, :]has shape(n, 1, d).centroids[None, :, :]has shape(1, k, d).- Subtracting broadcasts both to
(n, k, d). Entry[i, j]is the difference vector between pointiand centroidj. np.linalg.norm(..., axis=2)collapses the feature axis, leaving an(n, k)table of distances.argmin(axis=1)picks, for each row, the column of the nearest centroid.
The result is labels = [0 0 1 1]. The centroids of the two groups are (1.25, 1.9) and (8.5, 8.75).
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| `norm(diff, axis=1)` instead of `axis=2` | Shape error, or distances to the wrong thing | Check that the result has shape `(n, k)` |
| `argmin(axis=0)` | One label per centroid instead of one per point | Use `axis=1` on an `(n, k)` table |
| `mean()` without `axis=0` | One scalar instead of one value per feature | Use `mean(axis=0)` |
| Integer `X` | Mixed integer and float arithmetic can surprise you | Convert with `X.astype(float)` |
| Empty group | `mean` of zero rows returns `nan` and a warning | Keep the old centroid, as the Lloyd implementation does |
The broadcast approach builds an (n, k, d) array in memory. For large n, this array is the main cost, and libraries such as scikit-learn compute distances in chunks.
What comes next
Distance decides which centroid a point belongs to. The centroid is the best representative of the points assigned to it. The next chapter combines the two into a single number, inertia, which measures how well a set of centroids fits the data.
Exercise
Three points are assigned to one cluster: (0, 0), (2, 0) and (4, 6). What is the centroid, and what is the squared Euclidean distance from the point (4, 6) to it?
Show answer
The centroid is the per-feature mean: x = (0 + 2 + 4) / 3 = 2, y = (0 + 0 + 6) / 3 = 2, so the centroid is (2, 2). It is not one of the three data points. The squared distance from (4, 6) is (4 - 2)^2 + (6 - 2)^2 = 4 + 16 = 20.