Sub topic 10
When k-means works poorly
This chapter assumes you know Lloyd's algorithm, the inertia objective, and how to run KMeans in scikit-learn. It covers the data conditions where k-means gives misleading answers, and what to do about each one.
Why the objective sets the limits
K-means minimizes the sum of squared Euclidean distances from each point to its assigned centroid. Every limitation comes from that definition. The algorithm doesn't look for "natural groups". It looks for the partition of the data into k compact, roughly round blobs that gives the lowest inertia. If your data's real structure isn't compact and round, a lower inertia can still mean a worse clustering.
The main implicit assumptions are:
- Clusters are roughly spherical, because distance to a single point is the only criterion.
- Clusters have similar spread and similar size.
- Every point belongs to some cluster, so there is no notion of noise.
- You can supply a sensible k in advance.
- All features are on comparable scales.
Common failure modes
| Data condition | What k-means does | Typical remedy |
|---|---|---|
| Non-convex shapes (rings, crescents) | Cuts the shape with a straight boundary between centroids | DBSCAN, spectral clustering |
| Elongated or correlated clusters | Splits a long cluster and merges parts of neighbors | Gaussian mixture with full covariance |
| Very different densities or sizes | Moves a centroid into a large, loose cluster and takes points from it | Gaussian mixture, density-based methods |
| Outliers | Pulls a centroid toward the outlier, or spends a whole cluster on it | Remove or clip outliers, or use k-medoids |
| Unscaled features | The feature with the largest range decides the clusters | Standardize first |
| High dimensions | Distances between points become similar, so nearest-centroid labels carry little information | Reduce dimensions (PCA), then cluster |
The boundary between two clusters is always a straight line (a hyperplane in more dimensions) halfway between their centroids. Any structure that needs a curved boundary is out of reach.
Seeing a non-convex failure
The crescent-shaped "two moons" dataset has two clear groups. Compare k-means with DBSCAN, which groups points by density instead of by distance to a centroid. The adjusted Rand index (ARI) scores agreement with the true labels, where 1.0 is a perfect match.
from sklearn.datasets import make_moons
from sklearn.cluster import KMeans, DBSCAN
from sklearn.metrics import adjusted_rand_score
X, y = make_moons(n_samples=400, noise=0.05, random_state=0)
km = KMeans(n_clusters=2, n_init=10, random_state=0).fit(X)
db = DBSCAN(eps=0.2, min_samples=5).fit(X)
print("k-means ARI:", round(adjusted_rand_score(y, km.labels_), 2))
print("DBSCAN ARI:", round(adjusted_rand_score(y, db.labels_), 2))K-means scores far below 1.0 because it slices each crescent with a straight line. DBSCAN follows the density and scores close to 1.0.
Seeing an outlier failure
Because inertia squares distances, one far-away point has a large effect. Here two tight clusters share the data with a single extreme point.
import numpy as np
from sklearn.cluster import KMeans
rng = np.random.default_rng(0)
a = rng.normal([0, 0], 0.5, size=(100, 2))
b = rng.normal([5, 0], 0.5, size=(100, 2))
outlier = np.array([[40.0, 40.0]])
X = np.vstack([a, b, outlier])
km = KMeans(n_clusters=2, n_init=10, random_state=0).fit(X)
print(np.bincount(km.labels_))The output shows cluster sizes of 200 and 1, in some order. One cluster is spent on the outlier, and the two real groups are merged. Lowering inertia required it: the merged cluster costs far less than letting the outlier drag a real centroid away.
Diagnosing before you trust the result
Practical checks, in order:
- Project to two dimensions with PCA and plot the points colored by cluster label.
- Look at cluster sizes with
np.bincount(labels). A cluster with one or two points often signals an outlier. - Compare silhouette scores across several k values. Low scores for every k suggest the data isn't well described by compact blobs.
- Rerun with different seeds. Large changes in the labels point to weak structure or a poor local minimum.
Exercises
Exercise
You run k-means with k=3 on a dataset with one large, spread-out cluster and two small, tight ones. The result splits the large cluster in two and merges the two small ones. Why does this happen, and name one method that handles it better?
Show answer
Inertia treats all squared distances equally, so splitting the large cluster removes more total squared distance than keeping the two small clusters apart. K-means has no concept of per-cluster size or spread. A Gaussian mixture model fits a separate variance to each cluster and handles this case better. A density-based method such as DBSCAN also works.
Exercise
A dataset has two features: income in dollars (range 20,000 to 200,000) and age in years (range 18 to 80). K-means on the raw values produces clusters that depend almost entirely on income. What should you do first?
Show answer
Standardize the features, for example with StandardScaler in a pipeline before KMeans. Euclidean distance is dominated by income because its numeric range is thousands of times larger than age.