SeeingML
Core ML Models Guide 6 of 6 · tap to switch
✦ Interactive Visual Guide 8 min · 4 hands-on labs · Beginner friendly

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:

  1. Assign: Every home locks onto whichever hub (centroid) is closest in straight-line distance.
  2. 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!

Interactive Lab 1: Step Through Lloyd's Loop (Assign → Move → Repeat)
Total Distance Score (WCSS):Unassigned(lower = tighter)
00252550507575100100East-West BlockNorth-South Block1234Step 0: Drop Starting Hubs · Numbered circles = 4 Delivery Hubs (Centroids)
StartStep 1 of 6
Zero neighborhood labels exist! We drop 4 starting hubs (centroids) near the middle of the city. Every home pin starts gray and unassigned. Click Next Step to assign each home to its closest hub.

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 K rises from 1 to 8 and 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 -1 to +1 that compares how close each home is to its own hub versus the nearest rival hub. Near +1 means super crisp, separate groups; around 0 means 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!

Interactive Lab 2: Choosing K With the Elbow Curve & Silhouette Score
Selected: K = 2
City Map With K = 2 Hubs020k40k60kWCSS12345678Elbow Curve: Total Distance (WCSS) vs. K
Total Distance (WCSS)26,793
Always drops toward 0 as K grows; watch for the bend
Silhouette Score0.48
Cleanliness: -1 to +1, higher = cleaner groups
K = 2
K = 2 (Too Few Hubs): look at the long spokes on the map. At least one hub is stretched across two separate neighborhoods, keeping WCSS high (26,793). Keep sliding K upward to find where the curve bends sharply!

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!

Interactive Lab 3: Unlucky Random Start vs. K-Means++ Smart Spread
Start 1Start 2Start 3Start 41234← 2 hubs crowded hereHub 4 stuck in the middle →Dashed ring = Starting hub spot · Arrow = Path hub slid · Solid circle = Final hub (centroid)Final Distance Score (WCSS): 14,217 · Silhouette Score: 0.46
Stuck in a weak layout (WCSS = 14,217): Follow the dashed Start rings! Hubs 1 and 2 happened to drop inside the same top-left neighborhood, so they sliced one group in half while Hub 4 slid into no-man's-land between the two right-side neighborhoods. Click K-Means++ (Smart Spread) above to see the fix.

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!

Interactive Lab 4: When K-Means Breaks (and What to Pick Instead)
Straight halfway fence12Dashed line = K-Means straight halfway fence (Color = Assigned cluster)
Why K-Means Shines Here
Compact, round blobs of similar size sit neatly on opposite sides of the straight halfway fence between the two hubs.
Best Pick: K-Means
Fast, simple, and scales effortlessly to millions of rows whenever your natural groups are compact round clouds.
✓ Tip

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 x1,…,xn∈Rd\mathbf{x}_1, \dots, \mathbf{x}_n \in \mathbb{R}^d, K-Means partitions indices into KK disjoint clusters C1,…,CKC_1, \dots, C_K with centroids μk\boldsymbol{\mu}_k minimizing total squared Euclidean distortion:

min⁡{Ck},{μk}∑k=1K∑xi∈Ck∥xi−μk∥22\min_{\{C_k\}, \{\boldsymbol{\mu}_k\}} \sum_{k=1}^{K} \sum_{\mathbf{x}_i \in C_k} \|\mathbf{x}_i - \boldsymbol{\mu}_k\|_2^2

Finding the global optimum is NP-hard even for K=2K = 2 in general dimensions (Aloise et al., 2009). Lloyd’s algorithm (Lloyd, 1982) performs alternating coordinate descent: fixing μk\boldsymbol{\mu}_k minimizes the objective via nearest-centroid Voronoi cells, while fixing CkC_k minimizes each quadratic sum uniquely at the sample mean μk=1∣Ck∣∑xi∈Ckxi\boldsymbol{\mu}_k = \frac{1}{|C_k|}\sum_{\mathbf{x}_i \in C_k}\mathbf{x}_i.

2. K-Means++ Approximation Guarantee (Arthur & Vassilvitskii, 2007): Sampling the first seed uniformly and each subsequent seed x\mathbf{x} with probability proportional to D(x)2/∑zD(z)2D(\mathbf{x})^2 / \sum_{\mathbf{z}} D(\mathbf{z})^2 (where D(x)D(\mathbf{x}) is the shortest distance to any already-chosen center) guarantees an expected objective within O(log⁡K)\mathcal{O}(\log K) of the true global optimum before Lloyd’s iterations even start!

3. Silhouette Coefficient (Rousseeuw, 1987): For each observation ii, let a(i)a(i) be its mean distance to other points in its own cluster and b(i)b(i) be its smallest mean distance to any other cluster:

s(i)=b(i)−a(i)max⁡ ⁣(a(i), b(i))∈[−1,+1]s(i) = \frac{b(i) - a(i)}{\max\!\big(a(i),\, b(i)\big)} \in [-1, +1]

Values near +1+1 indicate crisp, well-separated clusters; values near 00 indicate overlapping borders; negative values signal misassigned points.

See StandardScaler + K-Means++ & Silhouette Selection in PythonOptional Code
python
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.

✓ Self-Check

Quick Intuition Check

Four quick real-world scenarios. No scores, just test your intuition.

1

Why can you NOT choose the best number of clusters K simply by picking whichever K produces the lowest WCSS (total squared distance)?

Pick an option first, or peek anytime
2

How does K-Means++ improve over dropping starting hubs completely at random?

Pick an option first, or peek anytime
3

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?

Pick an option first, or peek anytime
4

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.

Pick an option first, or peek anytime
Quick Reference

Common Questions

How does K-Means clustering work step by step?
First, place K starting cluster centers (centroids) using K-Means++. Then repeat two steps until nothing changes: (1) assign every unlabeled data point to its closest centroid, and (2) move each centroid to the average coordinates (mean) of the points currently assigned to it.
How do you choose the right number of clusters (K) in K-Means?
Run K-Means across several candidate values of K and inspect two diagnostics together: the Elbow Curve (look for the bend where WCSS Inertia stops dropping sharply) and the Silhouette Score (choose the K that maximizes cohesion within clusters relative to separation from neighboring clusters).
What is K-Means++ and why is it the default in scikit-learn?
Standard random starts can drop two initial centroids into the same cluster and trap Lloyd's algorithm in a bad local minimum forever. K-Means++ spreads initial centroids far apart by choosing each new seed with probability proportional to squared distance D(x)^2 from existing centroids.
Do you need to scale features before running K-Means?
Yes! Because K-Means assigns points using Euclidean distance, a column measured in thousands (such as annual spend in pounds) will completely dominate a small-scale column (such as website visits) unless you run StandardScaler first.
When should you use DBSCAN or GMM instead of K-Means?
Use K-Means for fast segmentation of compact, roughly spherical clusters when you know roughly how many groups you want. Switch to DBSCAN for curved shapes, concentric rings, or heavy outlier noise, and switch to Gaussian Mixture Models (GMM) for stretched elliptical clusters of unequal sizes.

Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference

https://seeingml.com/learn/k-means-clustering/ Open GitHub issue Suggest an edit
Cite this guide in a paper, thesis, or course (BibTeX & APA)
BibTeX
@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}
}
APA

Irshad, M. A. (2026). K-Means Clustering: Interactive Visual Guide. SeeingML. https://seeingml.com/learn/k-means-clustering/