K-Means Clustering
Press Next → or use ← → arrow keys
The Intuition — Party Tables
That's K-Means: place K centroids, assign each point to the closest one, move each centroid to its group's centre, and repeat until nothing changes.
K-Means partitions data into K groups so that points within a group are as close as possible to their centroid — it minimizes the total within-cluster distance, no labels required.
Lloyd's Algorithm — Five Steps
The two-step dance — assign points, then move centroids — is a special case of EM. Each round can only lower (or hold) the total within-cluster distance, so K-Means is guaranteed to converge — though possibly to a local optimum, which is why initialization matters.
Watch It Converge, Step By Step
Assign points to the nearest centroid, move each centroid to its cluster's mean — and repeat. The centroids drift a little less each round until, at convergence, no point changes cluster and the centroids sit dead-centre in their groups.
The Objective — Minimize WCSS
The assignment step reduces J (points move to closer centroids) and the update step reduces J (the mean is the optimal centre). Since J can't rise and is bounded below, the algorithm must converge — its whole engine is this monotone descent.
Initialization Matters — K-Means++
K-Means++ picks the first centroid at random, then chooses each next one with probability proportional
to its squared distance from the closest existing centroid — so seeds spread across the blobs.
It's the scikit-learn default (init='k-means++') because it converges faster and avoids the
bad local optima that plain random starts fall into.
How Many Clusters? The Elbow Method
Plot WCSS against K. It always falls as K rises, but the drop is steep at first, then flattens. The elbow — where extra clusters stop buying much — is the natural choice. Pair it with the silhouette score and a sanity check against domain sense; if the elbow is unclear, silhouette often breaks the tie.
Silhouette — Are The Clusters Any Good?
Run K-Means for a range of K and pick the one with the highest average silhouette. Unlike the elbow — which can be ambiguous — silhouette gives a single number, and even lets you spot individual points that landed in the wrong cluster.
Scaling Is Mandatory, Not Optional
K-Means assigns points by Euclidean distance. If income spans 0–100,000 and age
spans 0–100, income utterly dominates the distance — age becomes invisible and clusters form on income
alone. StandardScaler (zero mean, unit variance) puts every feature on equal footing
before clustering.
StandardScaler and KMeans together so scaling is fit on training data only.
Skipping this is the single most common K-Means mistake — clusters that look meaningless are almost always
clusters formed on one runaway feature. If features are heavily skewed, consider a log transform before
scaling.
K-Means With scikit-learn
from sklearn.cluster import KMeans from sklearn.preprocessing import StandardScaler from sklearn.metrics import silhouette_score X_scaled = StandardScaler().fit_transform(X) # step 1 — always scale km = KMeans( n_clusters=3, init='k-means++', # smart seeding (default) n_init=10, # 10 restarts, keep the best max_iter=300, random_state=42) # reproducible labels = km.fit_predict(X_scaled) print(km.inertia_) # WCSS print(silhouette_score(X_scaled, labels)) # cluster quality
n_init=10 runs the whole algorithm ten times from different seeds and keeps the lowest-WCSS
result — cheap insurance against a bad start. random_state makes runs reproducible. For
millions of rows, swap in MiniBatchKMeans for a big speed-up at a tiny accuracy cost.
Where K-Means Breaks Down
K-Means assumes clusters are spherical, similar-sized, similar-density, and linearly separable — and needs K up front. Crescents, rings, elongated or unequal clusters break it. It's also sensitive to outliers, since a single far point can drag a centroid away.
When K-Means Isn't The Answer
| Problem | Why K-Means Struggles | Use Instead |
|---|---|---|
| Non-spherical shapes | Assumes round clusters | DBSCAN · Spectral |
| Unknown K | Must pre-specify | DBSCAN · Hierarchical |
| Outliers / noise | Centroids get dragged | DBSCAN · K-Medoids |
| Overlapping / soft clusters | Forces hard assignment | Gaussian Mixture (GMM) |
| Varying density | Assumes equal spread | DBSCAN · HDBSCAN |
| Millions of rows | Full passes are slow | MiniBatchKMeans |
Despite these limits, K-Means is fast, scalable, and easy to interpret — start here on roughly-round, well-separated data, and switch to a specialized method only when the diagnostics (bad silhouette, crescents on a t-SNE plot) tell you to.
The K-Means Family
All three keep K-Means' assign-and-update spirit but relax one assumption: MiniBatch trades a hair of accuracy for speed, K-Medoids trades speed for outlier-robustness, and GMM trades simplicity for soft, elliptical clusters. Pick the relaxation your data demands.
Where K-Means Is Used Every Day
Seven Rules For K-Means
You Now Own K-Means
K-Means alternates two simple moves — assign points to the nearest centroid, then recentre — driving the within-cluster distance down until the groups lock in. Scale your features, seed with K-Means++, choose K with the elbow and silhouette, and know when its round-cluster assumption calls for a different tool.
Cluster the Iris and Mall-Customers datasets, sweep K with elbow and silhouette, then compare DBSCAN and Gaussian Mixtures on the two-moons data to feel exactly where K-Means stops and they begin.
🎯 End of tutorial · Press ← to review, or click Restart