Skip to content

k-Means Playground

Place points, choose k, and run Lloyd’s algorithm one step at a time

1. The playground

The canvas starts with a seeded cloud of points. Click anywhere in the plot to add a point. Choose k = 2 through k = 5, then press Run or Step.Reset re-initializes the centroids on the current points; New sample generates a different cloud.

Colors show the current assignment. Crosses are centroids. WCSS is the sum of squared distances from every point to its assigned centroid.

Every assignment, centroid, and WCSS value is computed from the points. Nothing is pre-drawn.

2. What to notice

  • Assignment vs update. A step colors each point by its nearest centroid, then moves each centroid to the mean of its color group.
  • WCSS falls. Each full step cannot increase the objective. The status becomes Converged when assignments stop changing.
  • k changes the answer. More centroids can lower WCSS even when the extra clusters are not meaningful.
  • Initialization matters. Reset uses the same farthest-first rule; a different start can land in a different local optimum.
  • Empty clusters. If a centroid gets no points, the playground keeps its old position. In a production implementation, you need an explicit re-seeding rule.

3. The math

k-means minimizes the within-cluster sum of squares:

Objective

The assignment step chooses the nearest centroid:

Assignment

The update step takes the mean of each cluster:

Update

The two steps alternate. Assignment is optimal for fixed centroids; update is optimal for fixed assignments. The objective is non-increasing, so the process converges to a local optimum.

4. What is simplified

This is a two-dimensional, unweighted simulation with Euclidean distance. It uses farthest-first initialization, not random restarts or k-means++. It does not choose k for you, and it does not handle missing values or categorical features.

The animation is a teaching tool, not a clustering library. Real implementations use k-means++, mini-batches, multiple restarts, and task-specific evaluation. The geometry is the same; the engineering is not.

5. Related lessons

The k-means lesson derives the objective and the algorithm. The Gaussian mixture lesson replaces hard assignments with soft responsibilities.

Site soundtrack