Skip to content

Clustering with k-Means

Group unlabelled points by repeatedly assigning them to the nearest centroid and moving each centroid to the mean

Quick recap
  • k-means partitions unlabelled points into k groups by minimizing within-cluster squared distance.
  • Lloyd’s algorithm alternates nearest-centroid assignment with centroid updates.
  • The result is a local optimum, sensitive to initialization and to the choice of k.

This lesson follows Bagging, Random Forests & Boosting and leads into Gaussian Mixtures & EM. The live companion is the k-Means Playground.

1. Labels missing

Supervised learning starts with labelled examples. Clustering starts without labels: given a cloud of points, can we discover groups that are close together? A customer segmentation, a set of sensor readings, or a pile of documents may have no target column at all.

k-means answers with a simple geometric rule. Choose k centers, assign every point to its nearest center, then move each center to the average of its points. Repeat. The groups are the clusters; the centers are the centroids.

Before reading the algorithm, look at the animated cloud. The points have no colors at the start. Predict what happens if two initial centroids both land in the same clump.

2. The objective

k-means minimizes the within-cluster sum of squares, also called inertia or WCSS:

k-means objective

μ is the centroid of the cluster assigned to point i. The objective rewards tight clusters: a point far from its centroid contributes a large squared distance.

The assignment step chooses the nearest centroid for each point:

Assignment

The update step moves each centroid to the mean of its assigned points:

Update

Each step cannot increase the objective. Assignment picks the best centroid for the current centers; update picks the best center for the current assignments. The sequence converges, but only to a local optimum.

3. Lloyd’s algorithm

The standard algorithm is alternating optimization:

  1. Choose k initial centroids.
  2. Assign every point to its nearest centroid.
  3. Move each centroid to the mean of its assigned points.
  4. Repeat until assignments stop changing or a step limit is reached.

Initialization matters. Random points can put two centroids in the same clump, producing a poor local optimum. k-means++ chooses spread-out starting points with probability proportional to squared distance; farthest-first is a deterministic teaching approximation.

An empty cluster needs a policy. A common choice is to keep the old centroid or re-seed it at the point farthest from its centroid. The playground keeps the old centroid and reports the cluster sizes.

4. Worked example

Four points: (0,0), (0,1), (10,0), (10,1). Start with centroids (0,0) and (10,0).

  1. Assignment: the first two points go to centroid 1; the last two go to centroid 2. WCSS = 0 + 1 + 0 + 1 = 2.
  2. Update: centroid 1 becomes (0, 0.5); centroid 2 becomes (10, 0.5).
  3. New WCSS: each point is 0.5 away from its centroid, so 4 × 0.25 = 1.

Worked example: one assignment and one update

pointnearest initiallydistance²after updatedistance²
(0, 0)centroid 10(0, 0.5)0.25
(0, 1)centroid 11(0, 0.5)0.25
(10, 0)centroid 20(10, 0.5)0.25
(10, 1)centroid 21(10, 0.5)0.25

Initial WCSS 2, after the update 1. The assignments are already stable, so the next iteration would stop. The final clusters are the two obvious vertical pairs.

The playground shows the same quantity for a larger cloud.

5. Choosing k

k-means cannot discover k from the objective alone. WCSS generally falls as k grows, reaching zero when every point is its own cluster. That is a perfect score for a useless partition.

The k trap

The elbow heuristic looks for a bend where extra clusters stop buying much reduction. It is a heuristic, not a theorem. Silhouette scores, gap statistics, and domain knowledge are alternatives; none replaces a task-specific evaluation.

Try it

Why can increasing k always reduce WCSS?

6. Where it fails

k-means assumes roughly convex, isotropic clusters. It struggles with elongated shapes, nested rings, and clusters of very different sizes. Euclidean distance also gives every feature an equal vote unless you scale first.

The algorithm is sensitive to outliers because squared distance amplifies them. A single far-away point can pull a centroid. It is also sensitive to initialization and can converge to a poor local optimum.

In high dimensions, distances become less discriminating. PCA or another representation step can help, but it can also discard the structure you care about. The next lesson replaces hard assignments with soft responsibilities and a probabilistic model.

Next lesson: Gaussian Mixtures & EM

7. Going deeper

k-means is the hard-assignment limit of a Gaussian mixture with equal spherical covariances. A mixture can represent elliptical clusters and overlapping memberships; k-means commits each point to one cluster.

Mini-batch k-means updates centroids from small batches, which is faster on large data. k-medoids uses actual data points as centers and can work with arbitrary distances. Hierarchical clustering builds a tree of merges instead of requiring k up front.

The final assignment is not a causal explanation. A cluster is a geometric summary; it does not tell you why the points are grouped or what intervention would move a point to another group.

8. Practice

Try it

If two centroids start at the same point, what happens on the first assignment step?

Try it

Why does k-means prefer a round cluster to a long thin one?

Try it

WCSS falls from 100 to 80 when k goes from 2 to 3. Does that prove k = 3 is better?

9. Resources

The MIT chapter covers nearest neighbors, k-means, trees, and ensembles. The scikit-learn clustering guide covers k-means assumptions, initialization, and alternatives. Both links were opened and checked for this lesson.

Continue the track

Open the playground for this topic

k-Means Playground →

Place points, choose k, and run Lloyd’s algorithm step by step while the assignments, centroids, and WCSS respond.

All Machine Learning lessons

Site soundtrack