K-Means clustering works by alternating two steps until the grouping stops changing: assign each data point to its nearest centroid, then move each centroid to the mean of the points assigned to it. The algorithm minimizes within-cluster squared distance. It needs the number of clusters, k, chosen in advance, and it converges to a local optimum rather than a guaranteed global one.
That single paragraph is the whole skeleton. Everything below explains why each step exists, where the arithmetic decides the outcome, and where practitioners get surprised. The mechanics are stable mathematics, so nothing here depends on current prices or product versions.
The two-step engine: assignment and centroid update
Start with n data points, each described by d numeric features. Pick k, the number of groups you want. Place k centroids in the feature space, either at random data points or by a smarter seeding rule such as k-means++. Then repeat two operations.
The assignment step compares every point to every centroid and hands the point to its closest one. Distance is almost always squared Euclidean distance: sum the squared differences across all d features. Squaring is not cosmetic. It grows large gaps faster than small ones, so a point sitting twice as far away contributes four times the penalty.
The update step recomputes each centroid as the coordinate-wise mean of its assigned points. If a cluster contains three points at heights 10, 20, and 30, its centroid height becomes 20.
Why does this pair of steps make progress? Fix the centroids, and assigning each point to the nearest one is provably the best you can do for the current centers. Fix the assignments, and the mean is provably the point that minimizes total squared distance to its members. Each half-step can only lower or hold the objective, never raise it.
That objective, called inertia or within-cluster sum of squares, adds up the squared distance from every point to its own centroid. The loop stops when no point changes cluster, when centroids move less than a small tolerance, or when a maximum iteration count is reached. Convergence usually arrives within tens of iterations on typical tabular data, though there is no universal guarantee on the count.
One plain-language version: the algorithm keeps asking "which center is closest?" and "where is the middle of each group now?" until the answers stop moving.
Quantified context: distance, k, and how much searching happens
The assignment step performs k × n distance comparisons per iteration, each costing roughly d arithmetic operations. With 10,000 rows, 20 features, and k = 5, that is 50,000 comparisons per round, about a million operations per iteration, which is trivial for modern hardware. Scaling to 10 million rows and k = 100 pushes each round to a billion comparisons, which is where approximate methods and mini-batch variants enter.
Elbow analysis often shows inertia dropping steeply through k = 2 to 4 and flattening after k = 5 or 6 on well-separated data, which is why the bend is read as a candidate k. The silhouette score, which ranges from −1 to 1, uses 1.0 as the ideal; values above roughly 0.5 suggest reasonable structure and values near 0 suggest overlapping clusters. These thresholds are conventions from practice, not laws, and they disagree often enough that you should compare them rather than trust either alone.
Feature scale matters numerically. A feature measured in thousands dominates a feature measured in single digits, because its squared differences are millions of times larger. Standardizing every feature to zero mean and unit variance puts them on comparable footing. The choice of distance also matters: squared Euclidean favors compact, roughly spherical clusters, and it will happily split an elongated cluster rather than accept its shape.
The initial placement is the single largest source of run-to-run variation. Random initialization can land two centroids inside one dense region while a separate cluster goes unrepresented. K-means++ addresses this by choosing each new centroid with probability proportional to its squared distance from the nearest already-chosen centroid, which spreads seeds out. Practitioners typically run 10 or more restarts with different seeds and keep the solution with the lowest inertia.
Edge cases that break the clean story
Empty clusters happen. If every point assigned to a centroid moves elsewhere during a later round, the centroid has no members and its mean is undefined. Implementations handle this by reseeding the empty centroid, often at the point farthest from its current centroid.
Duplicate points create a subtler problem. If k exceeds the number of distinct locations in the data, two centroids can sit on the same point and inertia reaches zero while the grouping is meaningless. This is a red flag that k is too large for the data's granularity.
Non-convex shapes defeat the model. Two interlocking crescents, a ring around a blob, or any cluster defined by density rather than proximity will be cut incorrectly, because K-Means draws straight boundaries between centroids. Density-based methods such as DBSCAN handle those shapes; K-Means does not.
Outliers drag centroids. Because the mean is sensitive to extreme values, one far-flung point can pull a centroid away from the cluster it should represent and steal members from a neighboring cluster. Trimming outliers before fitting, or using K-Medoids, which centers on actual data points, reduces the damage.
Categorical features have no meaningful mean. Encoding them as numbers imposes an arbitrary order and distance, so K-Means on one-hot or label-encoded categoricals produces clusters that reflect the encoding, not the data. K-Prototypes or K-Modes exist for that case.
Misconceptions worth correcting
The biggest one: K-Means does not find the "true" clusters. It finds a local optimum of a specific objective, and a different seed can yield a different answer with similar inertia. Reporting a single run without restarts hides that instability.
A second misconception treats the objective as a measure of quality. Low inertia partly reflects more clusters, since splitting any cluster into two always lowers total squared distance. That is why inertia cannot be compared across different values of k and why the elbow method reads shape, not absolute height.
A third: convergence means correctness. The loop ending proves the assignments and centroids are mutually consistent, not that the grouping is useful. A converged solution can still be a poor local minimum.
A related trap is assuming scaling is optional. Unscaled features quietly define the distance, so the clusters you get are clusters of whichever feature has the largest units.
The professional caveat: K-Means assumes clusters are roughly spherical, similar in size, and separated by distance. Real data often violates all three at once. The algorithm will still return k groups, which is exactly the danger: it always answers, whether or not an answer exists.
Comparison: K-Means against its neighbors
| Method | Needs k upfront | Cluster shape | Handles outliers | Typical use |
|---|---|---|---|---|
| K-Means | Yes | Spherical, similar size | Poorly | Fast partitioning of numeric data |
| K-Medoids | Yes | Spherical, robust center | Better | Noisy data, mixed distances |
| DBSCAN | No | Arbitrary, density-based | Flags as noise | Irregular shapes, spatial data |
| Gaussian mixture | Yes (components) | Elliptical, soft | Poorly | Overlapping clusters, probabilities |
| Hierarchical | No (cut later) | Varies by linkage | Moderate | Small data, dendrogram exploration |
| Mini-batch K-Means | Yes | Spherical | Poorly | Very large datasets |
The choice usually comes down to whether you can defend k and whether your clusters are compact. If either answer is no, the table's lower rows are worth the extra complexity.
Timeline: one typical K-Means run
| Stage | What happens | Scale |
|---|---|---|
| 0. Prepare | Select features, impute gaps, standardize | Minutes to hours |
| 1. Choose k | Elbow, silhouette, domain input | Minutes |
| 2. Seed | Random or k-means++ placement | Seconds |
| 3. Assign | Each point to nearest centroid | Seconds to minutes |
| 4. Update | Recompute means | Seconds |
| 5. Iterate | Repeat steps 3–4 | Tens of rounds typical |
| 6. Restart | Repeat seeding and loop | 10+ seeds common |
| 7. Select | Keep lowest-inertia run | Minutes |
| 8. Interpret | Profile clusters, validate | Hours to days |
Step 0 and step 8 consume most of the calendar time. The loop itself is fast; deciding what to feed it and what the groups mean is slow.
Practical actions with concrete thresholds
Standardize numeric features to zero mean and unit variance before fitting, unless every feature already shares units and scale. Run at least 10 random restarts and keep the lowest-inertia solution; if the best and worst inertia differ by more than about 10 percent, the clustering is unstable and k or the features need rethinking. Sweep k from 2 to about 10, record inertia and silhouette at each value, and look for a bend plus a silhouette peak before settling on k. Use k-means++ seeding rather than plain random placement; it costs little and reduces bad local minima. Cap iterations at a few hundred and set a tolerance on centroid movement, so runs terminate predictably. Profile every cluster after fitting: size, centroid values, and a sample of members. A cluster with 2 percent of the data or a centroid sitting between two others is a warning sign.
The thresholds reconcile simply: silhouette above 0.5 supports a k, the elbow bend suggests the same k, and stable restarts confirm it. When those three disagree, treat the clustering as exploratory rather than final. Match k to what the elbow and silhouette both tolerate, run enough seeds to expose instability, and standardize features so distance means what you intend.
Limitations and what the output cannot tell you
K-Means cannot determine k from the data alone. Every internal metric is a heuristic, and different heuristics disagree on real datasets, which is why domain knowledge has to break the tie.
It cannot express uncertainty. Every point lands in exactly one cluster with full membership, even points sitting almost equidistant between two centroids. A Gaussian mixture model returns probabilities instead, which is more honest when boundaries blur.
It cannot handle missing values natively. Imputation is required first, and the imputation method shapes the clusters.
It cannot reveal causality or meaning. A cluster is a geometric grouping of features, not a category with a definition. Two clusters that differ mainly in a proxy feature may reflect a data artifact rather than anything real.
Finally, the answer is not unique. Different seeds, different scalings, and different feature subsets produce different groupings of the same rows. Reproducibility requires fixing the seed, documenting preprocessing, and reporting the number of restarts. The value of K-Means is speed and simplicity on compact numeric data, not certainty about the structure of the world.