Skip to content

k-Means Clustering

Splits data into k groups by alternating two steps: assign each point to its nearest center, then move each center to the middle of its points.

Also k-means · Lloyd's algorithm

Fig. / How it works
ASSIGN TO NEAREST · MOVE TO MEAN
Role · kind
Models and algorithmsModel
Level
Beginner

MacQueen, 1967 (Lloyd's algorithm, 1957)

Drop k flags on a playground. Every kid runs to the closest flag. Then move each flag to the middle of its crowd. Kids switch flags if another is now closer. Repeat until nobody moves.

Where it fits

+All relationships as a list

See it on the full map

Try it

k-means, one step at a time
Loading interactive widget…
Takeawayk-means only ever alternates two simple moves, and it always settles, but where it settles depends on where the centroids start.

How it works

k-means needs one number from you: k, how many groups you want. Then:

  1. Initialize: place k centers, for example on k random data points.
  2. Assign: each point joins the cluster of its nearest center.
  3. Update: move each center to the average position of its points.
  4. Repeat steps 2 and 3 until assignments stop changing.

Each round can only lower the total squared distance from points to their centers, so the algorithm always stops. But it may stop in a poor arrangement if the starting centers were unlucky. The usual fixes: run it several times and keep the best, or use k-means++, which spreads the initial centers out.

To choose k, people often plot the total distance for k = 1, 2, 3… and look for the “elbow” where adding clusters stops helping much.

The math

k-means minimizes the within-cluster sum of squares over assignments C1,…,CkC_1, \dots, C_k with centroids μj\mu_j:

∑j=1k∑x∈Cj∥x−μj∥2\sum_{j=1}^{k} \sum_{x \in C_j} \lVert x - \mu_j \rVert^2

Everyday use cases

  • Case 01

    Supermarket customer types

    Group shoppers by basket size, visit frequency and spend into a handful of segments.

  • Case 02

    Color quantization

    Reduce an image to 16 colors by clustering its pixel colors.

Strengths, weaknesses and when to use it

Strengths

  • Simple, fast and scales to large datasets.
  • Easy to explain and visualize.

Weaknesses

  • You must choose k in advance.
  • Assumes roughly round, similarly sized clusters.
  • Different starting centers can give different results.

When to use itFor a quick segmentation of numeric data into a known or guessable number of groups.

Check yourself

  1. Q01

    What are the two alternating steps of k-means?

    Show answer

    B: Assign points to the nearest center, then move centers to the mean of their points

  2. Q02

    Which shape of cluster does k-means handle worst?

    Show answer

    B: Two interlocking crescent moons

Go deeper