Skip to content
AI.info

Unsupervised learning

K-Means: Objective and Lloyd’s Algorithm

Derive the intuition of K-Means, connect centroid updates to squared Euclidean loss, and diagnose when its objective matches the data.

By the end you can

The algorithm that converged perfectly to the wrong partition

A retailer clusters its stores on location, sales, and floor area. K-Means converges quickly. Yet one extreme flagship store drags a centroid and absorbs several unrelated locations. The algorithm did its job. It minimized its chosen objective from its starting point. The failure came from treating that objective as a neutral definition of groups.

That much is an illustration. The rest of this lesson is not. How long the loop can run, how hard its objective is to solve exactly, how much the starting points change the answer, why a falling inertia cannot choose K — all four are published results. They are quoted below rather than paraphrased, so every claim about the loop can be checked at its source.

Convergence proves local optimization behavior, not domain validity.

Case

The points in the plane that made Lloyd's loop run exponentially long

Convergence arrives more slowly than the textbook suggests. How much more slowly is on the record. The bound to beat belonged to Arthur and Vassilvitskii: 2^Omega(sqrt(n)) iterations, and it needed Omega(sqrt(n)) dimensions of room to build. In 2011 Andrea Vattani published the construction that beat it, and his abstract says exactly what he did: “we prove this conjecture and we improve the lower bound, by presenting a simple construction in the plane that leads to the exponential lower bound”. Two dimensions, d = 2, and 2^Omega(n) iterations. The worst case needs no exotic high-dimensional geometry, only a set of points laid out on a sheet of paper.

Practice is usually kinder, and that is a theorem too rather than an impression. The smoothed number of iterations is polynomial in n and in 1/sigma, where sigma is the standard deviation of the Gaussian perturbation applied to the input. Arthur, Manthey and Röglin settled that in 2009, and their abstract puts the consequence plainly: “This means that if an arbitrary input data set is randomly perturbed, then the k-means method will run in expected polynomial time on that input set.”

Read the two results together. The everyday speed of Lloyd's loop is not a property of the algorithm. It is a property of noisy data. Vattani's point set is what remains when the noise is removed.

Analogy

Moving meeting points until total walking effort shrinks

Several teams choose meeting points. Everyone walks to the nearest room, then each room moves to the average position of its assigned people.

Real rooms stay where they are, and walking cost may not be squared distance. Squared distance is the only cost this method knows. K-Means is exact only for the encoded geometry, not for every notion of inconvenience.

Centroids summarize the loss function, not an abstract social center.

Visual

The alternating loop at the heart of K-Means

Each step improves or preserves the squared-distance objective until the assignments stop changing.

The loop and the label it travels under have different parents, and both are dated. The name came from a paper J. MacQueen gave at the Fifth Berkeley Symposium in 1967. It opens: “The main purpose of this paper is to describe a process for partitioning an N-dimensional population into k sets on the basis of a sample.” It is in that paper that the process “is called 'k-means'”.

The alternating assign-and-update procedure drawn here is a decade older than the name it was given. A survey of the algorithm records the descent: “It was proposed in 1957 by Lloyd [58] (and independently in 1956 by Steinhaus [71])”. Stuart Lloyd's 1957 work reached print only in 1982, in IEEE Transactions on Information Theory. Hugo Steinhaus had arrived at the same procedure independently in 1956. The five steps below have a publication history. They are not folklore that has always simply been there.

FigureProcess · 5 steps
  1. 1. Choose K centers

    Initialize candidate centroids in the feature space.

  2. 2. Assign observations

    Send each point to the nearest centroid under squared Euclidean distance.

  3. 3. Recompute means

    Replace every centroid with the arithmetic mean of its assigned points.

  4. 4. Measure inertia

    Sum squared distances from points to their assigned centroids.

  5. 5. Repeat

    Continue until assignments, centroids, or objective improvement satisfy a stopping rule.

The mean is optimal for squared Euclidean loss within a fixed assignment.

Key idea

Inertia always falls when K grows

Adding more centroids cannot increase the best achievable within-cluster squared distance, and a low inertia therefore does not identify the correct number of groups by itself.

This is not a caution invented for teaching. The literature treats the monotonicity as the defining obstacle to comparing solutions at different k: “It is then necessary to specify a measure that allows to compare clusterings with different k (the SSE criterion is monotonically decreasing with k and thus not a good measure).”

The published remedy has a name. Tibshirani, Walther and Hastie proposed the gap statistic in 2001, in the Journal of the Royal Statistical Society Series B. Its move is to stop reading the within-cluster dispersion on its own. Instead it compares the change in dispersion against what that change would have been under a reference null distribution. A falling curve measured against a falling baseline, rather than against zero.

Alongside that, compare the marginal gain, stability, cluster size, interpretability, and intended use. The limiting case of one centroid per point has zero inertia and no useful compression.

Optimization quality and model selection are different questions.

Steps

Audit a fitted K-Means solution

Look beyond the final labels and objective value.

Step 4 is the one with a measured price attached. Nothing inside the Lloyd loop changed — same objective, same assignment rule, same mean update. Only the seeding changed. David Arthur and Sergei Vassilvitskii ran that experiment in 2007 and called the result k-means++. Their abstract states the guarantee: “By augmenting k-means with a very simple, randomized seeding technique, we obtain an algorithm that is Θ(log k)-competitive with the optimal clustering.” Their Theorem 3.1 bounds the seeding on its own, before a single Lloyd iteration has run: E[phi] <= 8(ln k + 2) phi_OPT. That factor of 8(ln k + 2) is the only quality guarantee the method carries.

The experiment says what the guarantee is worth in practice. On the KDD Intrusion dataset — n = 494,019 points, d = 35, with 20 trials per case and k in {10, 25, 50} — D^2 seeding cut the average final potential of plain k-means by 93.37% at k = 10 and by 99.84% at k = 50. It cut average running time by 44.49% and 66.70% as well. Faster and better, from the choice of starting points alone. When restarts of the same fit disagree, that spread is the quantity step 4 measures. It is large enough to dominate any conclusion drawn from a single run.

FigureProcess · 5 steps
  1. 1. Verify preprocessing

    Confirm numerical units, scaling, missingness, and duplicate handling.

  2. 2. Inspect centroid profiles

    Translate centers back into original units and check whether means describe plausible observations.

  3. 3. Review boundary points

    Examine observations with similar distances to multiple centroids.

  4. 4. Compare restarts

    Measure inertia and partition agreement across several initializations.

  5. 5. Stress outliers

    Refit after robust scaling or removing extreme points to expose centroid sensitivity.

Example

Reading the loop on a tiny dataset

A small numeric example makes the optimization mechanics visible.

  • Initial centers: With points at 1, 2, 8, and 9 and K=2, centers near 1 and 9 produce the intuitive split immediately.
  • Assignment: Points 1 and 2 choose the first center; points 8 and 9 choose the second because their squared distances are smaller.
  • Update: The new means become 1.5 and 8.5, which minimize squared error for those fixed assignments.
  • Objective: Inertia becomes 0.5 + 0.5 = 1.0 across both groups under one-dimensional squared distance.
  • Sensitivity: A point at 100 would shift the second mean sharply, showing why outliers matter to centroid geometry.

Comparison

What the K-Means objective favors and rejects

K-Means works best when its geometry resembles how the data is actually organized. The favorable case is compact groups well represented by their arithmetic means. The unfavorable case is groups whose identity depends on shape, density, sequence, or category. Between them sits the ambiguous case, where several compact partitions reach similar inertia and the multiple local optima are real rather than an artifact of a bad run. That third column is where the seeding evidence from the workflow bites. When partitions of nearly equal objective value exist, the starting points decide which one is returned. The objective value alone will not tell you that a different answer was available.

FigureComparison · 3 columns

Favorable structure

Compact groups represented well by their arithmetic means.

  • Numerical scaled features
  • Roughly convex clusters
  • Similar within-cluster spread
  • Few extreme outliers

Unfavorable structure

Groups whose identity depends on shape, density, sequence, or category.

  • Nested rings or curved manifolds
  • Strongly unequal cluster sizes
  • Heavy-tailed or contaminated coordinates
  • Categorical modes without numeric meaning

Ambiguous structure

Data where several compact partitions achieve similar inertia.

  • Weak separation between regimes
  • Continuous gradients rather than groups
  • Multiple local optima
  • K chosen for convenience rather than evidence

K-Means is simple because its contract is narrow

What K-Means offers is a fast, interpretable compression into K means under squared Euclidean geometry. That narrow contract explains both its usefulness and its failures. When the contract fits, K-Means is a strong baseline. When it does not, more restarts only optimize the wrong notion of structure more carefully.

The narrow contract is also hard to satisfy exactly, and the hardness is bounded from two directions at once. Take the low-dimensional side first. Mahajan, Nimbhorkar and Varadarajan closed it: “We show that this well-known problem is NP-hard even for instances in the plane, answering an open question posed by Dasgupta [7].” Andrea Vattani reached the same place independently, by reduction from Exact Cover by 3-Sets, in a theorem that reads “The k-means clustering problem is NP-complete even for d = 2.”

The other side is the number of clusters. In 2008 four authors reduced from densest cut and made Euclidean sum-of-squares clustering NP-hard already at k = 2. Their abstract also records something worth noticing about how such results are established: “A recent proof of NP-hardness of Euclidean sum-of-squares clustering, due to Drineas et al., Machine Learning 56, 9--33, 2004, is not valid. An alternate short proof is provided.” A published proof failed. A short correct one replaced it.

Two dimensions is enough, and two clusters is enough. Lloyd's loop is a heuristic for a problem with no known efficient exact solution. Its output is a partition worth auditing, not an answer worth trusting.

Use K-Means as a geometric model, not a universal cluster detector.

Key takeaways