K-Means Clustering Explained: Centroids, K-Means++, Elbow & Silhouette Score
Step-by-step Lloyd's algorithm for beginners, why feature scaling is mandatory, choosing K with Elbow & Silhouette, and when K-Means fails
K-Means is an unsupervised clustering algorithm that partitions unlabeled data into K compact groups by alternating two simple steps: assign every point to its nearest centroid, then move each centroid to the average of its assigned points.
When you have raw customer logs, documents, or sensor readings with zero labels, K-Means fast-tracks segmentation into clear personas in linear O(N·K·D) time.
K-Means is the #1 workhorse of unsupervised segmentation, vector quantization (IVF indexes in vector databases), and exploratory persona discovery.
Billion-scale vector databases (FAISS IVF) literally run K-Means to partition embeddings into fast searchable buckets!
Customer RFM segmentation (Recency, Frequency, Monetary) powered by standardized K-Means drives marketing personalization everywhere.
Classic question: 'Why does K-Means require feature scaling, how does K-Means++ improve initialization, and why can't K-Means separate two concentric circles?'
A point has a Silhouette Score of +0.82. What does that tell you about its cluster assignment?
- Trace Lloyd's 2-step Assign → Update loop by hand until convergence.
- Explain why K-Means++ smart initialization prevents terrible local minima.
- Choose K systematically using both the Elbow Method (Inertia/WCSS) and the Silhouette Score (−1 to +1).
- Recognize the 3 shapes where K-Means fails (crescents, rings, unequal cluster sizes) — motivating DBSCAN & GMM next!
K-Means is a 2-step dance: (1) Assign every dot to its closest flag (centroid), (2) Move each flag to the center of mass of its dots, and repeat until the flags stop moving. Always StandardScale first and initialize with K-Means++!
1. Choosing K: Elbow Method vs. Silhouette Score
- Elbow Method: Plot Inertia vs. . Look for the sharp "bend" where adding another cluster stops giving big drops.
- Silhouette Score: Measures both cohesion () and separation (). Unlike Inertia, Silhouette peaks at the true and drops if you over-split!
Compare K-Means vs. DBSCAN on Blobs & Concentric Rings
K-Means assumes convex spherical Voronoi cells — it brutally slices BOTH rings in half! Click Algo to switch to DBSCAN.
2. When K-Means Fails (Preview of Next Chapter)
Because K-Means draws straight Voronoi boundaries around spherical balls, it fails on:
- Non-convex shapes (two interlocking moons or concentric rings) → Use DBSCAN!
- Stretched ellipses of different sizes → Use Gaussian Mixture Models (GMM)!
- Extreme outliers (pull centroids off-center) → Clip outliers or use K-Medoids / DBSCAN.
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
Random initialization can accidentally drop two starting centroids into the same cluster, trapping K-Means in a poor local minimum. K-Means++ picks each new starting centroid with probability proportional to (farther points are much more likely), spreading initial centers cleanly across the data!
Watch Centroids Glide to Cluster Means & Inertia Drop Monotonically
Alternating E-Step (Assign nearest centroid) → M-Step (Move centroid to mean)
import numpy as np
# Minimal K-Means (Lloyd's Algorithm) From Scratch
rng = np.random.default_rng(42)
X = np.vstack([rng.normal([0, 0], 0.5, (15, 2)), rng.normal([5, 5], 0.5, (15, 2))])
K = 2
centroids = X[rng.choice(len(X), K, replace=False)]
for step in range(1, 6):
# 1. Assign each point to nearest centroid
dists = np.linalg.norm(X[:, None, :] - centroids[None, :, :], axis=-1)
labels = np.argmin(dists, axis=1)
# 2. Update each centroid to mean of its assigned points
centroids = np.array([X[labels == k].mean(axis=0) for k in range(K)])
inertia = float(sum(np.sum((X[labels == k] - centroids[k]) ** 2) for k in range(K)))
print(f"Iter {step} | Inertia={inertia:.2f} | Centroids={np.round(centroids, 2).tolist()}")
age + annual_income).StandardScaler before clustering.