Sub topic 2
Distance and centroids
What this chapter assumes
You should be comfortable with NumPy arrays, shapes, and the axis argument. You should also know that a feature matrix X has one row per sample and one column per feature. This chapter covers the two geometric ideas that k-means uses: a distance between points, and a centroid that summarizes a group of points. Later chapters build the objective and the full algorithm on top of them.
Rows as points in space
Each row of X is a point in d-dimensional space, where d is the number of columns. A customer with three features (age, yearly spend, visits per month) is one point in 3D. Clustering asks which points are close to each other. That question needs a precise meaning of "close", so we define a distance.
Euclidean distance
The Euclidean distance between two points a and b with d features is the length of the straight line between them:
dist(a, b) = sqrt( (a1 - b1)^2 + (a2 - b2)^2 + ... + (ad - bd)^2 )
In NumPy this is the square root of the summed squared differences:
import numpy as np
a = np.array([1.0, 2.0])
b = np.array([4.0, 6.0])
diff = a - b
dist = np.sqrt(np.sum(diff ** 2))
print(dist) # 5.0
print(np.linalg.norm(a - b)) # 5.0, the same valuenp.linalg.norm applied to a vector computes this length directly. You will use it constantly, and its axis argument is where most mistakes happen (see the common errors section below).
Squared Euclidean distance
k-means works with the squared distance, which is the same sum without the square root:
dist^2(a, b) = sum over j of (aj - bj)^2
There are two reasons for this.
- Ranking is unchanged. The square root is increasing, so the centroid with the smallest distance also has the smallest squared distance. When you only need
argmin, you can skip the root and save computation. - The mean is optimal for squared distance. The next sections show that the centroid is the mean of its points because the quantity being minimized is a sum of squared distances. With plain distances the mean would not be the best choice.
Centroids
A centroid is the mean of a set of points, computed feature by feature. For points x_1 ... x_n:
centroid = (x1 + x2 + ... + x_n) / n
The result is a vector with the same d features as the points. It is not necessarily one of the data points. It is a location that represents the group.
points = np.array([
[1.0, 2.0],
[3.0, 4.0],
[5.0, 9.0],
])
centroid = points.mean(axis=0)
print(centroid) # [3. 5.]
print(centroid.shape) # (2,)axis=0 averages down the rows, so you get one value per column. Using axis=1 would give one value per row, which is not a centroid.
Why the mean, and not some other summary
Of all possible locations c, the mean is the one that minimizes the total squared distance to the points. You can prove this in a few lines. Let m be the mean and c any other location. Then:
sum of ||xi - c||^2 = sum of ||xi - m||^2 + n * ||m - c||^2
The cross term in the expansion contains the sum of (x_i - m), which is zero by the definition of the mean. So the total is the cost at the mean plus a non-negative penalty n * ||m - c||^2. The penalty is zero only when c = m.
You can check this numerically:
rng = np.random.default_rng(0)
points = rng.normal(loc=[3.0, -1.0], scale=1.0, size=(200, 2))
def total_sq_dist(c):
return ((points - c) ** 2).sum()
mean = points.mean(axis=0)
print(f"cost at mean: {total_sq_dist(mean):.2f}")
for _ in range(5):
other = mean + rng.normal(scale=0.3, size=2)
print(total_sq_dist(other) > total_sq_dist(mean)) # True each timeEvery nudged location gives a higher cost than the mean. This is the property that makes the update step of Lloyd's algorithm correct: moving a centroid to the mean of its points can only lower, or keep equal, the squared-distance cost.
Distances from many points to many centroids
k-means needs the distance from every point to every centroid, which is an n x k table. With X of shape (n, d) and centroids of shape (k, d), broadcasting builds it without a Python loop:
X = np.array([
[0.0, 0.0],
[1.0, 0.0],
[5.0, 5.0],
[6.0, 5.0],
[5.0, 6.0],
])
centroids = np.array([
[0.0, 0.0],
[5.0, 5.0],
])
diff = X[:, None, :] - centroids[None, :, :]
print(diff.shape) # (5, 2, 2): n points, k centroids, d features
dists = np.linalg.norm(diff, axis=2)
print(dists.shape) # (5, 2)
labels = dists.argmin(axis=1)
print(labels) # [0 0 1 1 1]The shapes work like this:
| Expression | Shape | Meaning |
|---|---|---|
| `X` | `(n, d)` | one row per point |
| `X[:, None, :]` | `(n, 1, d)` | each point gets a spare axis for centroids |
| `centroids[None, :, :]` | `(1, k, d)` | each centroid gets a spare axis for points |
| `diff` | `(n, k, d)` | difference for every point and centroid pair |
| `norm(diff, axis=2)` | `(n, k)` | one distance per pair |
| `dists.argmin(axis=1)` | `(n,)` | index of the nearest centroid per point |
This is exactly the assignment computation inside the NumPy implementation you will see in the chapter on Lloyd's algorithm.
Memory cost
The (n, k, d) array holds n * k * d numbers. For 1,000,000 points, 50 centroids, and 20 features, that is 1 billion floats, about 8 GB in float64. A teaching implementation can afford this on small data. Production libraries, including scikit-learn, compute the distances in chunks or use the expansion ||x||^2 - 2 x.c + ||c||^2 with matrix multiplication, which never builds the 3D array.
The metric and the centroid must match
A centroid is a "best summary" only relative to a particular distance. If you change the distance, the best summary changes too, and the algorithm needs a different update step.
| Distance | Best summary of a group | Algorithm name |
|---|---|---|
| Squared Euclidean | Mean | k-means |
| Manhattan (sum of absolute differences) | Per-feature median | k-medians |
| Cosine distance (angle between vectors) | Mean, then rescaled to length 1 | Spherical k-means |
| Any distance, centers restricted to data points | Medoid (the data point with lowest total distance) | k-medoids |
Mixing them silently is a bug. If you cluster with Manhattan distance for assignment but still update with the mean, nothing guarantees the cost goes down at each step, and the algorithm may fail to converge.
A one-dimensional example shows why the median fits absolute distance:
values = np.array([1.0, 2.0, 3.0, 100.0])
print(values.mean()) # 26.5
print(np.median(values)) # 2.5The mean is pulled toward the outlier at 100. The median stays with the bulk of the data. This is the intuition behind the outlier sensitivity of k-means, which comes up again in the chapter on its limitations.
Euclidean and cosine are related
For vectors scaled to unit length, the squared Euclidean distance equals 2 - 2 * cos(angle). So after you normalize each row to length 1 (for example with sklearn.preprocessing.normalize), ordinary k-means behaves much like clustering by cosine similarity. This is a common trick for text vectors.
Common errors
- Wrong
axisinnorm. On the(n, k, d)array you needaxis=2. Withaxis=1you get distances between pairs of centroids over the wrong dimension, and the shape(n, d)will not match whatargminexpects. Print.shapeafter each step. - Integer arrays. If
Xhas an integer dtype,X.mean(axis=0)is fine, but in-place updates such ascentroids[j] = ...on an integer array silently truncate the mean. Convert withX = X.astype(float)first. - Mean of an empty group.
X[labels == j].mean(axis=0)on a cluster with no points returnsnanand raises a runtime warning. Thenanthen poisons every later distance involving that centroid. Always handle empty clusters explicitly. - Features on different scales. Euclidean distance adds the squared differences of every feature. A feature measured in thousands (income) swamps one measured in single digits (number of children). The chapter on scaling covers the fix.
- Many features. In very high dimensions, the nearest and farthest points from a given point have almost the same distance, so "nearest centroid" carries little information. If you have hundreds of features, reduce the dimension first (for example with PCA) before clustering.
Summary of the key ideas
- Each row of
Xis a point, and "close" means small Euclidean distance. - k-means uses squared Euclidean distance because ranking is unchanged and because it makes the mean the optimal centroid.
- The mean minimizes the sum of squared distances to a set of points, with an extra cost of
n * ||m - c||^2for any other locationc. - Broadcasting produces an
(n, k)distance table, andargmin(axis=1)turns it into labels. - Distance and centroid are a pair. Changing one means changing the other.
Exercise
You have X with shape (1000, 8) and centroids with shape (5, 8). You compute diff = X[:, None, :] - centroids[None, :, :] and dists = np.linalg.norm(diff, axis=2). What is the shape of dists, and what does dists.argmin(axis=1) return?
Show answer
dists has shape (1000, 5), holding the distance from each of the 1000 points to each of the 5 centroids. dists.argmin(axis=1) returns an array of shape (1000,) with the index (0 to 4) of the nearest centroid for each point.
Exercise
The points (0, 0), (4, 0), and (2, 6) form one cluster. Compute the centroid, and explain why moving the centroid to (2, 0) would increase the sum of squared distances.
Show answer
The centroid is ((0 + 4 + 2) / 3, (0 + 0 + 6) / 3) = (2, 2). Moving it to (2, 0) shifts it by 2 along the second axis, so the sum of squared distances increases by n ||m - c||^2 = 3 2^2 = 12. The mean is the unique minimizer, so any other location adds this non-negative penalty.
Exercise
A colleague clusters with Manhattan distance for assignment but keeps updating centroids with the mean. What goes wrong, and what should the update be?
Show answer
The mean minimizes squared Euclidean distance, not the sum of absolute differences, so the update no longer lowers the cost that the assignment step uses. The cost can stay flat or rise, and the algorithm has no convergence guarantee. For Manhattan distance the update should be the per-feature median (the k-medians algorithm).