Sub topic 10
When k-means works poorly
K-means always returns k clusters, whether or not the data contains k natural groups. A bad result raises no error, and the labels look like any other labels. This chapter covers the conditions under which k-means fails, how to spot each failure, and what to do about it.
This chapter assumes you know Lloyd's algorithm, inertia, and the scikit-learn KMeans API from the earlier chapters. You should also be comfortable with NumPy arrays and with the idea of a feature matrix whose rows are samples.
The assumptions hidden in the objective
K-means minimizes the sum of squared Euclidean distances from each point to its assigned centroid. That objective builds in several assumptions.
- Distance means similarity. Points that are close in Euclidean distance belong together.
- Clusters are compact blobs. A mean is a good summary only if the points surround it.
- Clusters have similar spread. Every cluster is measured with the same squared-distance yardstick.
- Clusters have similar size. Large clusters pull centroids toward themselves, which the next sections explain.
- Every point belongs to a cluster. There is no "noise" label.
The decision boundary between two centroids is a straight line (a hyperplane in higher dimensions). Each cluster is therefore a convex region of space, called a Voronoi cell. Any group whose natural shape is not convex cannot be recovered exactly.
Non-convex shapes
Two interleaved half-circles are an obvious grouping to a human. K-means cuts them with a straight line instead.
from sklearn.datasets import make_moons
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score
X, y_true = make_moons(n_samples=400, noise=0.05, random_state=0)
km = KMeans(n_clusters=2, n_init=10, random_state=0).fit(X)
print("inertia:", round(km.inertia_, 1))
print("adjusted Rand index:", round(adjusted_rand_score(y_true, km.labels_), 3))The adjusted Rand index (ARI) compares two labelings. It is 1.0 for a perfect match and near 0.0 for a random one. Here it comes out far below 1. The two centroids end up on opposite sides of a dividing line that slices through both moons, because that placement does give a low inertia. The objective is working as designed. It just does not match what you meant by "cluster".
A related failure is a ring around a blob. No set of centroids can separate them, because the ring's mean sits in the middle of the blob.
Different variances and correlated features
K-means uses a single distance for all directions. It implicitly assumes each cluster is a sphere, with the same variance along every axis. Two failures follow.
Elongated or tilted clusters. If a cluster is stretched along a diagonal, points at its far end can be closer to a neighbor's centroid than to their own. K-means then cuts the stretched cluster in the wrong place.
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score
X, y_true = make_blobs(n_samples=600, centers=3, random_state=170)
transform = np.array([[0.6, -0.64], [-0.4, 0.85]])
X_stretched = X @ transform
for name, data in [("round blobs", X), ("stretched blobs", X_stretched)]:
labels = KMeans(n_clusters=3, n_init=10, random_state=0).fit_predict(data)
print(name, round(adjusted_rand_score(y_true, labels), 3))The matrix multiplication shears and stretches the same three groups. The agreement with the true labels drops compared with the round version, even though the groups did not move relative to each other.
Clusters with different spreads. Suppose a tight cluster sits next to a wide one. The boundary between their centroids lies halfway between them, regardless of spread. Points from the edge of the wide cluster get assigned to the tight cluster's centroid. Gaussian mixture models fit a separate covariance per cluster and handle both cases.
Unequal cluster sizes
Inertia counts every point equally. A large cluster contributes much more inertia than a small one, so k-means can lower the total by splitting the large cluster and merging two small ones. The result looks balanced, but it is not what the data contains.
You can expect this when a rare group is close to a common one. The centroid of the common group drifts toward the rare points, or a centroid is spent subdividing the big group. If the rare group matters (fraud, a niche customer segment), k-means is a weak tool for finding it.
Outliers
A centroid is a mean, and a mean moves a long way for a single extreme value. Because the cost is squared distance, one distant point also contributes a very large term to the inertia. The cheapest way to reduce that term can be to give the outlier its own cluster.
import numpy as np
from sklearn.cluster import KMeans
rng = np.random.default_rng(0)
group_a = rng.normal(loc=[0, 0], scale=0.3, size=(50, 2))
group_b = rng.normal(loc=[5, 0], scale=0.3, size=(50, 2))
outlier = np.array([[100.0, 0.0]])
X = np.vstack([group_a, group_b, outlier])
km = KMeans(n_clusters=2, n_init=10, random_state=0).fit(X)
print("cluster sizes:", np.bincount(km.labels_))You would expect sizes of 50 and 51. Instead you get sizes of 100 and 1. Keeping the two groups apart leaves the outlier in one of them, and its squared distance of roughly 95² dominates the inertia. Merging the two groups into one cluster costs far less in total.
Common remedies:
- Detect and remove outliers before clustering, for example by trimming extreme z-scores or using an isolation-based detector.
- Use a larger k so a few clusters can absorb the extremes, then merge or ignore small ones afterward.
- Switch to k-medoids, which uses an actual data point as the center and is less sensitive to extremes, or to DBSCAN, which labels noise explicitly.
High-dimensional data
In many dimensions, Euclidean distances between random points become nearly equal. The nearest point is almost as far away as the farthest one, so "nearest centroid" carries little information. The following script shows the effect.
import numpy as np
rng = np.random.default_rng(0)
for d in (2, 10, 100, 1000):
X = rng.random((1000, d))
dist = np.linalg.norm(X[1:] - X[0], axis=1)
print(f"d={d:4d} nearest/farthest = {dist.min() / dist.max():.3f}")The printed ratio starts low in 2 dimensions and approaches 1.0 as d grows. K-means still runs in high dimensions, but the clusters it finds are more likely to reflect noise in irrelevant features. Typical remedies are to reduce dimensionality first with PCA or a similar method, to select informative features, or to use cosine distance on normalized vectors (for L2-normalized vectors, Euclidean k-means is equivalent to cosine-based clustering, which is why it is common for text embeddings).
Features that do not suit a mean
K-means needs numeric features where averaging makes sense.
- Categorical features. One-hot encoding lets k-means run, but a centroid like 0.4 for "color = red" has no meaning, and each category adds a dimension. K-modes, or k-prototypes for mixed data, are designed for this case.
- Unscaled features. A feature measured in thousands dominates one measured in fractions. Standardize first, as covered in the scaling chapter. Scaling does not fix every issue, though. It also gives each noisy feature the same weight as an informative one.
- Binary or heavily skewed features. Skewed values behave like outliers. Consider a log transform before scaling.
Sensitivity to initialization, and empty clusters
Lloyd's algorithm finds only a local minimum, so different starts give different answers. The effect is larger when clusters overlap or when k is higher than the true number of groups. Use init="k-means++" and several restarts through n_init, as covered earlier.
The NumPy implementation from this tutorial keeps the old centroid when a cluster becomes empty. Other implementations reseed the empty cluster at the point farthest from its centroid. If you see a cluster with zero or very few points in your results, that is a sign that k is too large or that outliers have captured a centroid.
Choosing k does not detect these failures
The elbow method and silhouette score assume the same spherical structure that k-means does. On the moons data, the silhouette score still favors a straight-line split, because that split produces compact-looking groups by the Euclidean measure. A good silhouette score therefore does not prove the clusters are the structure you care about.
Check results in other ways:
- Plot the clusters on two or three principal components, or on the most informative features.
- Look at cluster sizes and per-cluster feature means. Do they make sense to someone who knows the domain?
- Re-run with different seeds and with a bootstrap sample. Clusters that change substantially are unstable.
- Compare against a method with different assumptions, such as a Gaussian mixture or DBSCAN.
Matching the symptom to an alternative
The table summarizes the same information.
| Condition | Why k-means struggles | Typical symptom | Remedy |
|---|---|---|---|
| Non-convex shapes | Linear boundaries between centroids | A straight cut through a curved group | DBSCAN, spectral clustering |
| Elongated or correlated clusters | One spherical distance for all directions | Stretched clusters split across their length | Gaussian mixture, whitening |
| Unequal spread | Boundary lies midway between centroids | Wide cluster loses edge points | Gaussian mixture |
| Unequal size | Inertia favors splitting large groups | Large group divided, small groups merged | Larger k then merge, mixture model |
| Outliers | Mean and squared error are sensitive | A cluster with one or two points | Remove outliers, k-medoids, DBSCAN |
| High dimensions | Distances concentrate | Unstable clusters across seeds | PCA or feature selection first |
| Categorical features | Mean is meaningless | Odd fractional centroids | K-modes, k-prototypes |
Exercises
Exercise
You run k-means with k=2 on 100 well-separated points plus one extreme outlier, and one resulting cluster has a single point. Explain why the algorithm chose that partition, and name two ways to get the grouping you actually wanted.
Show answer
The outlier's squared distance to any centroid that also covers the main group is very large, and inertia sums squared distances. Giving the outlier its own cluster removes that term, while merging the two real groups costs less than leaving the outlier inside one of them. To fix it, remove the outlier before clustering, or use a method that is robust to outliers such as k-medoids or DBSCAN. A larger k, followed by ignoring or merging tiny clusters, also works.
Exercise
A colleague fits k-means on two interleaved crescents and reports a good silhouette score. Why does that not show the clustering is correct, and what would you try instead?
Show answer
The silhouette score measures compactness and separation using Euclidean distance, which is the same notion k-means optimizes. A straight-line split of the crescents can score well on that measure while cutting each crescent in half. The score therefore reflects the algorithm's own assumption, not the true structure. Plot the result and compare against a density-based method such as DBSCAN, or spectral clustering, which can follow connected curved shapes.