Skip to content
mlmentorship

k-means clustering

Partition n points into k clusters by minimizing within-cluster variance. Lloyd's algorithm: alternate assigning points to nearest center and recomputing centers.

Published · 7 min read ·Core ·Foundation
Reading depth

Summary

K-means seeks low squared Euclidean distortion by alternating nearest-center assignment with fixed-membership mean updates:

Each half-step minimizes the same objective while holding different variables fixed. This optimization definition does not require equal cluster sizes or establish that the resulting groups are natural classes.

The algorithm

Use finite points in meaningful Euclidean units, , and an explicit initialization. Break distance ties by a fixed center order; retain an old center if its cluster is empty in this trace. Then repeat:

  1. Assignment: for each .
  2. Update: for each .

For a nonempty cluster, . The second term proves the mean minimizes fixed-membership squared distortion. An empty cluster has no defined mean, which is why an explicit policy is needed.

In the figure, initial centers are A0 and B0 . Points choose A; choose B. For , squared distances are versus . Each group’s initial assigned SSE is , giving total . Updates produce A1 and B1 . Each group then contributes , so total SSE drops to .

Learning objective

Fix assignments before moving each centroid to its assigned mean

Assignments stay fixed during a centroid updatePoints 0 and 2 assigned to the left centroid give mean 1. Points 8 and 10 assigned right give mean 9.Fixed assignments pull each center totheir mean02Cluster 1: mean 1810Cluster 2: mean 9
Derivation
Assignment step with two fixed initial centroids Three circular observations at data coordinates 50 comma 80, 70 comma 110, and 90 comma 80 are assigned to initial centroid A at 110 comma 130. Three square observations at 230 comma 70, 250 comma 100, and 270 comma 70 are assigned to initial centroid B at 210 comma 120. For the circular observation at 90 comma 80, squared distance to A is 2900 and squared distance to B is 16000, so it joins A. Centroids do not move during this step. 1 · ASSIGN · HOLD CENTROIDS FIXED d² to A = 2,900 d² to B = 16,000 A₀ (110, 130) B₀ (210, 120) ○ joins nearest A₀ · □ joins nearest B₀ Only membership changes.
Update step moves each centroid to its assigned points' mean The same three circles and three squares retain their assignments. Initial centroid A moves from 110 comma 130 to the circular points' arithmetic mean at 70 comma 90. Initial centroid B moves from 210 comma 120 to the square points' arithmetic mean at 250 comma 80. Labelled arrows connect each old center to its new mean. Assignments do not change during this step. 2 · UPDATE · HOLD ASSIGNMENTS FIXED A₁ = (70, 90) B₁ = (250, 80) A₁ = ((50+70+90)/3, (80+110+80)/3) B₁ = ((230+250+270)/3, (70+100+70)/3)
assignment changes memberships while centers stay fixed. Updating then holds membership fixed and moves each center to its mean. The illustrated SSE decreases from 22,000 to 2,800. Original construction follows Lloyd's paper and the scikit-learn guide.
Check: What is held fixed while A moves to the mean of its three assigned samples?
Read it this way: Points 0 and 2 assigned to the left centroid give mean 1. Points 8 and 10 assigned right give mean 9.
During this centroid update, can a point silently change its assigned cluster?

Dense assignment costs per iteration; mean updates add . Standard exact updates with stable tie/empty-cluster policies reach a fixed point on finite data, not a guaranteed global optimum. Floating-point tolerances and iteration limits add numerical stopping policies.

Give Observations Unequal Weight

New task: Double the weight of in A’s fixed membership.

Picture and change: Minimize with positive weights, using . Positive per-observation weights leave fixed-center nearest assignment unchanged.

Check: A becomes .

Use when: Rows represent justified frequencies or importance in the distortion objective.

Update from an Arriving Point

New task: After the reference update, assign to A, whose count is three.

Picture and change: Increment the count to four and use .

Check: A moves from to while B remains unchanged.

Use when: A stream or mini-batch budget prevents full reassignment and mean recomputation. An incremental step does not inherit full-data Lloyd objective nonincrease.

Adding outlier to B’s fixed membership moves its mean to . Squared distance strongly rewards accommodating outliers, even when the resulting center is not typical.

k-means++ initialization

Random initialization sometimes converges to bad local minima. k-means++ (Arthur & Vassilvitskii, 2007):

  1. Pick uniformly at random.
  2. For : pick from data with probability proportional to . Points far from existing centers are more likely to be picked.

The expected approximation guarantee concerns seeded distortion under the theorem’s conditions, not global-optimum recovery or runtime.

Choosing

There is no universally right answer. Heuristics:

  • Elbow method: plot within-cluster SSE against k. Inspect diminishing returns; an elbow need not be distinct or objectively best.
  • Silhouette score: average similarity of each point to its own cluster vs. nearest other cluster; pick maximizing it.
  • Gap statistic: compare to clustering on uniform random data of the same shape.
  • Domain knowledge: often the right answer.

Choose geometry, downstream usefulness, and stability criteria before selecting among these heuristics.

Assumptions

Euclidean units and squared distortion define the task; standardizing features changes that task rather than automatically repairing it. Spherical mixture interpretations require additional probabilistic assumptions, not equal-size constraints in the objective. Replacing squared distance with absolute coordinate differences yields coordinate medians, not the same mean update.

Mini-batch k-means

Mini-batch updates trade full reassignment work for stochastic updates; evaluate quality, count policy, and workload-specific cost.

When k-means is and isn’t appropriate

Use it when squared-distance compression or grouping matches the task, including vector-quantization codebooks. Nonconvex shape discovery, categorical semantics, and alternative similarity objectives need separately justified methods.

Common pitfalls

Cluster IDs are permutation-invariant; compare partitions or aligned centers, not raw labels across runs. Alternating minimization alone does not make this algorithm an arbitrary mixture model’s EM procedure.