Core ML Models Guide 6 of 6 · tap to switch
K-Means Clustering
Discover natural groups inside completely unlabeled data using Lloyd's two-step loop, the Elbow Method, Silhouette Score, and K-Means++.
Suppose a grocery delivery startup hands you 32 customer homes plotted on a city map and asks: “Where should we build 4 local dispatch hubs so vans drive the shortest total distance?”
Notice there are no right-answer neighborhood labels anywhere in the table (welcome to Unsupervised Learning!). K-Means Clustering solves this puzzle by placing K center pins, our delivery hubs (called centroids), and repeating an extraordinarily simple two-step loop called Lloyd’s Algorithm:
- Assign: Every home locks onto whichever hub (centroid) is closest in straight-line distance.
- Move: Each hub slides to the exact center of gravity (average X, average Y) of its assigned homes.
How do we score whether a hub layout is getting better? Add up the squared straight-line distance from every home to its assigned delivery hub. In machine learning, that total distance score is called WCSS (Within-Cluster Sum of Squares, often nicknamed Inertia): a lower score means tighter, happier neighborhoods with shorter delivery drives.
We repeat Assign and Move until zero homes switch hubs and every hub stops moving (in ML, we say the algorithm converges). Click Next Step below to watch 4 hubs dropped near the middle of the city glide straight into the 4 real neighborhoods while WCSS plummets!
Notice something reassuring: every single Assign step and every single Move step lowers (or keeps equal) your Total Distance Score (WCSS), so K-Means is guaranteed to stop moving (converge) in just a handful of rounds!
How do you pick K? (Elbow Method + Silhouette Score)
Wait: in the real world, nobody tells you up front whether your city has 3, 4, or 7 customer neighborhoods!
You might think: “Just pick whichever K gives the lowest WCSS!” Careful: putting a dedicated delivery hub inside every single customer’s living room (K = 32) gives zero WCSS, which is completely useless! Because adding more hubs always shrinks WCSS toward 0, we pair two visual checks instead:
- Elbow Curve: Plot WCSS as
Krises from1to8and look for the sharp “elbow” bend where adding another hub suddenly stops giving a big drop in total distance. - Silhouette Score: A cleanliness grade from
-1to+1that compares how close each home is to its own hub versus the nearest rival hub. Near+1means super crisp, separate groups; around0means overlapping borders; and a negative score means a home was assigned to the wrong hub.
Lab 2 starts at K = 2 (too few hubs). Drag the K slider upward to discover where the Elbow Curve bends sharply AND the Silhouette Score hits its peak!
Escaping the bad start trap: K-Means++
Lloyd’s two-step loop always lowers WCSS on every step, yet where you drop the starting hubs still matters a lot! Because hubs only nudge locally toward their current group center, an unlucky starting drop can leave the map stuck in a weak layout forever.
If two randomly dropped hubs accidentally land inside the same top-left neighborhood, they slice one neighborhood needlessly in half while another hub stays trapped straddling two distant neighborhoods on the right.
The fix is K-Means++ (the smart starting strategy used by default in modern ML tools): it drops the first hub at random, then spreads starting hubs out by strongly preferring empty areas far away from hubs already placed. Toggle between Unlucky Random Start and K-Means++ (Smart Spread) below and trace the dashed Start rings to see the difference!
When K-Means breaks (and what to pick instead)
Because K-Means only measures plain straight-line distance to a single center point, it can only divide the map using straight halfway fences between hubs. That quietly assumes every real group is a compact, roughly round blob of similar size.
When real data forms curves, rings, or long stretched ribbons, two other clustering workhorses shine:
- DBSCAN: Follows dense connected chains of neighboring dots, making it great for curved rings, snakes, and scattered outlier dots.
- Gaussian Mixture Models (GMM): Fits flexible, stretched oval clouds instead of equal circles, following long or tilted groups cleanly.
Click through the three shapes below to see where K-Means shines, where its straight halfway fence breaks down, and how switching to DBSCAN or GMM fixes it!
Always put features on the same scale first! Just like KNN and SVMs, K-Means measures straight-line distance across every column. If one column uses huge numbers (like Annual Spend in dollars) and another uses tiny numbers (like Visits per Month), the big-number column will completely overpower the clusters unless you scale your columns first.
See the WCSS Objective, K-Means++ D² Seeding & Silhouette CoefficientThesis / Reference
1. Within-Cluster Sum of Squares (WCSS / Inertia): Given unlabeled observations , K-Means partitions indices into disjoint clusters with centroids minimizing total squared Euclidean distortion:
Finding the global optimum is NP-hard even for in general dimensions (Aloise et al., 2009). Lloyd’s algorithm (Lloyd, 1982) performs alternating coordinate descent: fixing minimizes the objective via nearest-centroid Voronoi cells, while fixing minimizes each quadratic sum uniquely at the sample mean .
2. K-Means++ Approximation Guarantee (Arthur & Vassilvitskii, 2007): Sampling the first seed uniformly and each subsequent seed with probability proportional to (where is the shortest distance to any already-chosen center) guarantees an expected objective within of the true global optimum before Lloyd’s iterations even start!
3. Silhouette Coefficient (Rousseeuw, 1987): For each observation , let be its mean distance to other points in its own cluster and be its smallest mean distance to any other cluster:
Values near indicate crisp, well-separated clusters; values near indicate overlapping borders; negative values signal misassigned points.
See StandardScaler + K-Means++ & Silhouette Selection in PythonOptional Code
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
X_scaled = StandardScaler().fit_transform(X)
# Sweep K and check both Inertia (Elbow) and Silhouette Score
for k in range(2, 8):
km = KMeans(n_clusters=k, init="k-means++", n_init="auto", random_state=42)
labels = km.fit_predict(X_scaled)
sil = silhouette_score(X_scaled, labels)
print(f"K={k} | Inertia={km.inertia_:8.1f} | Silhouette={sil:.3f}")Congratulations: you just completed Path 03!
Across Core ML Models, you mastered all six classical workhorses of applied machine learning: K-Nearest Neighbors, Decision Trees, Random Forests, Gradient Boosting (XGBoost / LightGBM / CatBoost), Support Vector Machines, and K-Means Clustering.
Ready to step from classical algorithms into Deep Learning? Continue straight into Path 04: Neural Networks & the Perceptron or browse the complete Visual Library.
Quick Intuition Check
Four quick real-world scenarios. No scores, just test your intuition.
Why can you NOT choose the best number of clusters K simply by picking whichever K produces the lowest WCSS (total squared distance)?
How does K-Means++ improve over dropping starting hubs completely at random?
Your unlabeled sensor dots form two clean concentric rings (an inner circle surrounded by an outer halo). K-Means slices straight down the middle of both rings. Which clustering algorithm fits this shape naturally?
Because K-Means measures straight-line distance from every point to each hub (centroid), skipping feature scaling on mixed-unit columns (like Annual Spend in dollars vs. Visits per Month) lets the larger-number column dominate the clusters.
Common Questions
How does K-Means clustering work step by step?
How do you choose the right number of clusters (K) in K-Means?
What is K-Means++ and why is it the default in scikit-learn?
Do you need to scale features before running K-Means?
When should you use DBSCAN or GMM instead of K-Means?
Related Visual Guides
Euclidean Distance & Cosine Similarity
How recommenders, search engines, and AI embeddings measure closeness, and why high dimensions distort everyday geometry.
Principal Component Analysis (PCA)
How to rotate and compress dozens of correlated features into a few clean axes without throwing away the real story.
K-Nearest Neighbors (KNN Algorithm)
Predict a new example simply by asking its K closest neighbors to vote, and see why choosing K and scaling features make or break the result.
Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference
Cite this guide in a paper, thesis, or course (BibTeX & APA)
@misc{irshad2026kmeansclustering,
author = {Irshad, Muhammad Aashir},
title = {K-Means Clustering: Interactive Visual Guide},
howpublished = {SeeingML},
year = {2026},
month = {dec},
url = {https://seeingml.com/learn/k-means-clustering/},
note = {Interactive visual guide}
} Irshad, M. A. (2026). K-Means Clustering: Interactive Visual Guide. SeeingML. https://seeingml.com/learn/k-means-clustering/