K-Means Clustering
Lloyd's algorithm, k-means++ init, silhouette, failure modes
You have 100,000 user embeddings and want 5 segments. K-means: randomly initialize 5 centroids. Step 1 (assignment) — assign each user to the nearest centroid by Euclidean distance. Step 2 (update) — move each centroid to the mean of all users assigned to it. Repeat until assignments stop changing. This is Lloyd's algorithm. It is guaranteed to converge. It is not guaranteed to find the global optimum.
K-means minimizes the within-cluster sum of squared distances (inertia): Σₖ Σᵢ ∈ cluster k ‖xᵢ - μₖ‖². This is NP-hard in general — K-means finds a local minimum. The result depends on initialization. K-means++ fixes this: choose the first centroid uniformly at random, then each subsequent centroid with probability proportional to the squared distance from the nearest existing centroid. This produces better local optima with fewer restarts. sklearn uses k-means++ by default; note that sklearn's default n_init changed in v1.4 to 'auto', which resolves to a single run when init='k-means++' (versions before 1.4 defaulted to n_init=10).
Elbow method: plot inertia vs K. Inertia always decreases as K increases — more clusters always fit tighter. Look for the elbow where marginal gain of adding a cluster drops off. This is approximate and often there is no clear elbow in real data.
Silhouette score is a per-point diagnostic: it compares each point's average distance to points in its own cluster (cohesion) against its average distance to points in the nearest other cluster (separation), and ranges from -1 to 1 — near 1 means well-clustered, near 0 means the point sits on a cluster boundary, and negative means it was probably assigned to the wrong cluster. Averaged across all points, scores below roughly 0.25 signal weak or absent structure (e.g., curse-of-dimensionality noise) — so a uniformly low average like 0.08-0.12 across every K tested is a structural warning that no choice of K will fix, not a sign you have not found the right K yet.
Three structural limitations to know. First: K-means assumes spherical clusters (Euclidean distance to centroid). If your data has non-spherical or unequal-density clusters, K-means draws the wrong boundaries regardless of K. Second: sensitive to outliers — one outlier pulls a centroid far from the cluster. (K-medoids addresses this directly by using an actual data point, the medoid, as the cluster center instead of the mean — more robust to outliers and more interpretable, at higher compute cost; choose k-medoids over k-means when outliers or interpretability matter more than speed.) Third: requires specifying K in advance, and an incorrect K produces confident but wrong assignments.
K-means also has a probabilistic reading, covered in full in the GMM module: a Gaussian Mixture Model fits several Gaussian "components" (bell-curve clusters, each with its own center and spread) to the data using Expectation-Maximization (EM), a soft version of K-means that assigns each point a probability of belonging to each component instead of one hard label. K-means is exactly the hard-assignment limit of that EM process when every component is forced to share the same isotropic covariance σ²I (the same, direction-independent spread) and σ→0: as σ shrinks toward 0, each point's soft, probabilistic membership collapses into an all-or-nothing 1-or-0 vote for whichever component is nearest — precisely K-means' nearest-centroid assignment step. That equivalence is also where K-means' spherical, equal-radius cluster assumption comes from; see the GMM module for the full derivation.
NOT-this: "K-means finds the natural clusters." K-means partitions space into Voronoi cells — every point gets assigned to the nearest centroid. Try DBSCAN or GMM when clusters are not spherical or equal in size.
Key points
- Always run K-means with K-means++ initialization and n_init=10 — a single random initialization frequently gets trapped in a poor local minimum. Running 10 times and taking the best result (lowest inertia) adds 10× compute but significantly improves cluster quality. As of sklearn 1.4, this is no longer the default (n_init now defaults to 'auto', which runs only once with k-means++ init) — so set n_init=10 explicitly rather than relying on the default.
- Trap: using K-means on high-dimensional data without dimensionality reduction. In high dimensions, Euclidean distance concentrates — all points become approximately equidistant, making centroid-based assignment meaningless. Apply PCA to 20–50 dimensions first. This is not optional at 100+ features; it is the difference between signal and noise.
- Diagnostic: after clustering, compute the per-cluster variance of key business metrics (revenue, engagement). If all clusters have similar metric distributions, the clustering is not capturing meaningful signal. Try different features or a different algorithm. Clusters that look geometrically clean but collapse to the same business profile have not solved the segmentation problem.
K-means converges every time — the dangerous part is that it converges just as confidently when clusters are non-spherical, unequal in size, or initialization was poor as when everything is perfect.
Recap
- Lloyd's algorithm: assign to nearest centroid → move centroid to mean → repeat.
- Converges always, global optimum never — minimizes inertia $\Sigma\|x_i-\mu_k\|^2$, NP-hard, local min.
- K-means++ + n_init=10: distance-weighted init beats random restarts (sklearn default).
- Elbow method: inertia always drops with K — look for the knee.
- Three limits: assumes spherical clusters, outlier-sensitive, K fixed in advance.
- High-D first reduce: distances concentrate → PCA to 20–50 dims before clustering.
- Hard-assignment limit of EM on GMM with shared isotropic $\sigma^2 I$, $\sigma\to0$.
Check your understanding
Q1. K-means gives very different results on different runs on the same dataset. What is wrong and how do you fix it?
- A) The dataset has non-spherical clusters — switching to DBSCAN, which is fully deterministic given fixed parameters, would fix this
- B) Use a fixed random seed across runs — this guarantees k-means finds the global optimum of the WCSS objective every time
- C) Different runs converge to different local optima from random init — fix with k-means++ init plus multiple restarts (n_init>1)
- D) The k value is wrong — instability across runs always means k has been set too high relative to the true cluster count
Q2. You apply k-means to 50,000 customer vectors with 200 features. Silhouette scores are uniformly low (0.08–0.12) for all k from 2 to 20. What does this tell you and what do you do?
- A) Uniformly low silhouette across all k signals the curse of dimensionality or absent structure — apply PCA to ~20-30 dims and re-inspect
- B) The silhouette threshold for high-dimensional data is lower — scores of 0.08 to 0.12 are actually acceptable once you exceed 200 features
- C) Increase k beyond 20 — silhouette scores will keep improving once k is large enough to capture fine-grained subgroups reliably
- D) Switch to hierarchical clustering instead — silhouette is mathematically incompatible with k-means on large, high-dimensional datasets
Q3. A k-means run with k=5 produces one cluster with 90% of the data and four clusters each with 2-3%. What likely went wrong?
- A) The dataset is too large for k-means to handle well at all — switch to MiniBatchKMeans whenever one cluster ends up dominating
- B) k=5 may be too high, or outliers each captured a tiny cluster, or init placed centroids in low-density regions — try k=2,3
- C) The silhouette metric should be fully replaced with WCSS whenever diagnosing unequal cluster sizes produced by a k-means run
- D) This is expected, normal behaviour for k-means on any imbalanced dataset — use per-cluster class weights to rebalance the sizes
Q4. What is the difference between k-means and k-medoids, and when would you choose each?
- A) K-means is faster but only works on strictly binary data; k-medoids is required whenever features are continuous-valued
- B) They are mathematically identical — the only difference is that k-medoids always uses Manhattan distance instead of Euclidean
- C) K-means uses the mean as centroid; k-medoids uses an actual data point — choose it for outliers or interpretability needs
- D) K-medoids always produces strictly better clusters than k-means — k-means should only be used when runtime is the top concern
Q5. Which two of the following are true about why k-means is equivalent to EM on a specific probabilistic model?
- A) K-means is the hard-assignment limit of EM on a GMM as σ→0, where all components share the same isotropic covariance
- B) This equivalence reveals that k-means implicitly assumes spherical, equal-radius clusters with hard, all-or-nothing membership
- C) K-means is equivalent to EM on a Poisson mixture model, which is why it assumes count-distributed integer features throughout
- D) K-means replaces the EM M-step with gradient descent, so the relationship is only a similar update rule, not a true equivalence
Try it interactively
ML Systems Lab is a free interview-prep platform for ML engineers — work through the full interactive module, quizzes, and drills.
Open ML Systems Lab →