Introduction: what k-means clustering actually minimises
K-means clustering takes a cloud of numeric observations and splits it into k groups, each summarised by a single representative point called a centroid. This calculator handles the two-dimensional case, where every observation is an x,y coordinate, because that is the case you can see: the plot below the form shows exactly which points ended up together and where the centroid of each group landed.
The important thing to understand before reading any k-means output is that the method is not looking for "natural" groups in any philosophical sense. It is minimising one specific number, the within-cluster sum of squares (WCSS), also called inertia. Every point contributes the squared straight-line distance from itself to the centroid it was assigned to, and k-means tries to make the total as small as possible for the k you asked for. A clustering is "good" to k-means precisely and only when that total is small.
That single objective explains almost every strength and every failure mode of the method. Because distances are squared, a point twice as far away contributes four times as much, so outliers pull centroids toward themselves. Because the representative of a group is its arithmetic mean, groups that are compact and roughly round are described well and groups that are long, curved or hollow are described badly. Because the objective always falls when you add another centroid, the total on its own can never tell you how many clusters the data really has.
The procedure that minimises this objective in practice is Lloyd's algorithm: guess some centroids, assign every point to the nearest one, move each centroid to the mean of the points it just captured, and repeat until nothing changes. Lloyd's algorithm is guaranteed to reduce the objective at every step and therefore to terminate, but it is only guaranteed to reach a local minimum. Two different starting positions on identical data can settle on two different answers, both stable, with different WCSS totals. This calculator makes the starting position explicit and deterministic so that you can see that behaviour rather than being surprised by it.
How to use this k-means clustering calculator
Type or paste your coordinates into the points box, choose how many clusters you want, and press Run k-means. The result panel then reports the objective value, the size and centroid of every cluster, the cluster label attached to each individual point, and how many assignment passes were needed before the labels stopped changing. The scatter plot underneath redraws with one colour per cluster and an X marker at each centroid, plus a faint spoke from each point to its own centroid so you can see which distances are driving the total.
Point input format and accepted separators
- One observation per line. Write each point as
x,y. Commas, semicolons, tabs and plain spaces all work as the separator, so1,2,1, 2,1;2and1 2are all read the same way. - Integers, decimals and scientific notation are accepted.
3.5, -0.2and1.2e3, 4are both valid. Negative values are fine in either coordinate. - Blank lines are skipped silently. Any line that does not resolve to exactly two finite numbers is skipped and reported back to you by line number, so a stray header row or a typo never becomes a phantom point at the origin.
- Duplicate coordinates are allowed. Repeated points simply carry more weight in the mean of whichever cluster captures them.
Choosing the number of clusters k
- k must be a whole number of at least 1 and cannot exceed the number of valid points you entered. If it does, the calculator refuses the run and says so instead of producing empty clusters by accident.
- If k exceeds the number of distinct coordinates, some clusters must be empty. The calculator warns you and reports the empty clusters with a size of zero rather than hiding them.
- Compare runs by WCSS at a fixed k, never across different k. Going from k = 3 to k = 4 always lowers WCSS, even on pure noise.
Formula for the k-means objective and the Lloyd iteration
Suppose the calculator receives n two-dimensional points, written as
Formula: p_1, p_2, …, p_n , where each point has coordinates p_i = (x_i, y_i). You choose a number of clusters k . The algorithm searches for centroids c_1, c_2, …, c_k
, where each point has coordinates .
You choose a number of clusters . The algorithm searches for centroids
and a partition of the points into clusters that minimise the total squared distance from each point to the centroid of its own cluster. In symbols, k-means minimises the objective
Formula: J = ∑ i = 1 k ∑ p ∈ S_i |p−c_i|^2
Here is the Euclidean distance from point to centroid . For this calculator's x,y plane, that distance is
Formula: | p − c_i | = sqrt((x−x_c)^2 + (y−y_c)^2)
Written out for two dimensions without the square root, the quantity the calculator reports as WCSS is
Formula: WCSS = ∑ i = 1 k ∑ p ∈ S_i [(x_p−x_i)^2 + (y_p−y_i)^2]
The update step: every centroid is a coordinate mean
For each cluster, the calculator moves the centroid to the average of the points currently assigned to it:
Formula: c_i = (∑ p ∈ S_i p) / (| S_i |)
The mean is not an arbitrary choice of representative: for a fixed membership, the point that minimises the sum of squared distances to a set of points is their arithmetic mean. That is why the two half-steps of Lloyd's algorithm — reassign, then re-average — can each only lower the objective, and why the procedure always terminates.
Explained variance: putting WCSS on a 0 to 1 scale
A raw WCSS figure depends on the units of your coordinates, so the calculator also reports the fraction of total spread the clustering removed. Let the grand mean be the centroid of all points and let TSS be the total sum of squares about it:
Formula: explained = 1 − WCSS / TSS
With k = 1 this is exactly 0 by construction, and it climbs toward 1 as k grows. It is the two-dimensional analogue of the "percentage of variance explained" curve that is plotted against k in the classic elbow heuristic.
Putting the pieces together, one full run performs these steps:
- Initialise. The first k distinct entered points become the starting centroids, which makes a run repeatable as long as the point order stays the same.
- Assignment step. Each point is assigned to the centroid with the smallest squared Euclidean distance. Omitting the square root does not change which centroid is nearest, so the calculator never takes a square root during assignment.
- Update step. Every non-empty cluster centroid moves to the mean x and mean y of the points now assigned to it. Empty clusters keep their previous centroid.
- Repeat. Assignment and update alternate until no point changes cluster, with a hard ceiling of 100 assignment passes.
Worked example: separating two 2D point clouds by hand
This example uses six coordinates arranged as two visibly separated clouds, the dataset the form is pre-filled with:
0, 0 0, 1 1, 0 5, 5 5, 6 6, 5
With k = 2 the first two distinct points, (0,0) and (0,1), become the seed centroids. The first assignment pass puts (0,0) and (1,0) with the first seed and the other four points with the second. The update step then moves the centroids to (0.5, 0) and (4, 4.25). On the second pass (0,1) is now closer to (0.5, 0) than to (4, 4.25), so it switches, and the centroids become (0.333, 0.333) and (5.333, 5.333). A third pass changes nothing, so the run stops.
Check the objective by hand. Each of the three points near the origin sits at squared distance from (0.333, 0.333): for (0,0) that is 0.333² + 0.333² = 0.2222, for (0,1) it is 0.333² + 0.667² = 0.5556, and for (1,0) it is 0.667² + 0.333² = 0.5556. Those three sum to 1.3333. The mirrored cloud around (5.333, 5.333) contributes the same 1.3333, so the total WCSS is 2.6667. The calculator prints 2.6667 for exactly this input, and the total sum of squares about the grand mean (2.833, 2.833) is 77.6667, giving an explained fraction of 1 − 2.6667 / 77.6667 = 0.9657, which the panel reports as 96.57%.
Now raise k to 3 on the same six points and something instructive happens. The seeds are the first three distinct entries, (0,0), (0,1) and (1,0), all inside the left-hand cloud. Three passes later the run converges on centroids (0.333, 0.333), (5.333, 5.333) and (3.5, 2.5) — and that third cluster is empty. WCSS is still 2.6667, exactly the k = 2 answer, and the cluster table flags the empty row. A better k = 3 solution obviously exists, since splitting either cloud would lower the total, so this run is a textbook local minimum caused by an unlucky deterministic start. Reorder the six lines so the seeds straddle both clouds and Lloyd's algorithm settles somewhere else entirely. Two lessons in one dataset: WCSS cannot pick k for you, and the starting centroids matter as much as the data.
Reading this calculator's k-means results panel
The results identify both the final location of every centre and the membership used to compute it:
- WCSS (inertia): the objective value the run reached. Use it to compare two runs on the same points at the same k, for example after reordering the input to land on a different local minimum.
- Explained fraction: WCSS rescaled against the total spread of the data, so it is unit-free and always between 0 and 1.
- Cluster table: for each cluster the size, the centroid coordinates, the cluster's own share of WCSS, and its root-mean-square radius. A cluster with a large share of the total is the loose one worth investigating.
- Point assignments: every entered coordinate receives a cluster number. The label is an identifier, not a ranking: cluster 1 is not inherently better, larger, or closer to the origin than cluster 2.
- Assignment passes: how many times the algorithm swept the points before the labels stabilised, plus whether it converged or hit the 100-pass ceiling.
When you compare several runs with different values of k, remember that smaller k forces broader groupings while larger k creates more centres and can split a single compact cloud into finer subdivisions that mean nothing in the real world.
Comparison: k-means for 2D points versus other clustering approaches
| Method | Key idea | When it works well | Limitations |
|---|---|---|---|
| K-means (this calculator) | Finds k centroids that minimise the within-cluster sum of squares. | Compact, roughly spherical clusters of similar size and spread; numeric 2D data. | Sensitive to outliers and to scaling; requires choosing k in advance; only a local minimum is guaranteed. |
| K-medoids (PAM) | Represents each cluster by an actual data point rather than a mean. | Data with outliers, or when the representative must be a real observation. | Considerably slower than k-means; still needs k in advance. |
| Hierarchical clustering | Builds a tree of merges or splits between clusters. | Exploratory analysis when you want structure at several levels at once. | Can be slow on large datasets; where to cut the tree is subjective. |
| Density-based (DBSCAN) | Grows clusters through dense regions and labels isolated points as noise. | Irregular shapes, clusters of varying size, explicit noise detection. | Requires density parameters; struggles when densities differ a lot between clusters. |
| Gaussian mixture models | Fits overlapping elliptical components and gives soft memberships. | Elongated or overlapping groups where a point can partly belong to two clusters. | More parameters to fit; can be unstable on small samples. |
This calculator implements the classic 2D k-means case: a fixed k, squared Euclidean comparisons, arithmetic-mean centroids, and deterministic initialisation from the first distinct entered coordinates.
Assumptions and limitations of this k-means tool
- 2D numeric input only: the calculator reads valid numeric
x,ypairs. Lines that do not contain exactly two finite numbers are skipped and reported by line number after a run. - Euclidean distance: the cluster decision is straight-line distance in the x,y plane. Results are not appropriate where another similarity measure is required, such as cosine similarity on text vectors.
- Compact cluster preference: k-means describes approximately round groups of similar spread. Elongated, curved or strongly unequal groups can be split or merged in unhelpful ways.
- Sensitivity to scaling: if one coordinate has much larger numeric values than the other, it dominates the squared-distance comparison. Rescale or standardise the coordinates before entering them.
- Effect of outliers: extreme coordinates move an arithmetic mean and can pull a centroid away from the denser part of its own cluster.
- Local minima: Lloyd's algorithm converges to a local minimum of the objective, not necessarily the global one. Repeating an unchanged input is reproducible, but reordering the same coordinates can produce a different, equally stable answer.
- Choosing k remains your decision: the calculator reports a partition for the k you supply; it does not decide how many clusters the data deserves.
- Ceiling of 100 passes: the run stops after 100 assignment passes even if the labels are still moving. The panel says so when that happens; in practice ordinary 2D data converges in a handful of passes.
Interpret the plotted centres and labels as an exploratory summary of the entered coordinates. For consequential decisions or complicated spatial patterns, validate the grouping with domain knowledge and, where appropriate, additional analytical methods.
Centroid Chase: the hands-on clustering game below
Underneath the calculator sits Centroid Chase, a graphical drill built on exactly the objective described above. Each level generates a fresh point cloud — tight blobs at first, then unequal densities, elongated groups and scattered noise — and gives you k centroids to place by hand. The background is shaded into Voronoi cells that recolour live as you drag, every point is tethered to its current centroid by a spoke whose weight tracks its contribution, and the running WCSS is displayed next to a par value obtained by running Lloyd's algorithm to convergence from dozens of k-means++ restarts.
Your efficiency score is the ratio of par to your own WCSS, so 100% means you matched the best converged solution the machine could find. Pressing Space runs a single Lloyd iteration and lets you watch the assignment recolouring and the centroids gliding to their cluster means — but each iteration you use costs points, so the game rewards understanding where the means ought to be before you let the algorithm do it for you.
Frequently asked k-means questions
How do I choose the number of clusters k?
For a 2D k-means run, k is a modelling choice rather than a value the calculator can infer. Run the same coordinates with several values of k and compare the reported within-cluster sum of squares. Plotting that total against k usually bends at an elbow where extra clusters stop buying much reduction, but the resulting groups still have to make sense for the purpose of your data.
What does the WCSS or inertia figure in the results mean?
WCSS is the k-means objective itself: the sum over every point of the squared Euclidean distance to the centroid of the cluster it was assigned to. Scikit-learn calls the same quantity inertia. Lower is better at a fixed k, and it can never rise as k rises, which is why WCSS compares two runs at the same k but cannot on its own tell you the right k.
Why should I scale my data before clustering?
This calculator assigns x,y points by Euclidean distance. A coordinate measured over a much larger numeric range contributes more to that distance: x values in the thousands can overwhelm y values in single digits. Rescale or standardize both coordinates first when the two dimensions should have comparable influence.
Will this k-means calculator give the same result every time?
Yes, provided the entered point order and k are unchanged. The calculator seeds the centroids from the first k distinct points you entered instead of choosing random starts, so a given input is reproducible. Reordering the same coordinates can still lead Lloyd's algorithm to a different local minimum, because the objective has many local minima.
Can k-means find any shape of cluster?
No. Euclidean k-means is most informative for compact, roughly round groups of similar spread. Curved, elongated, uneven-density or very unequally sized groups can be partitioned in misleading ways, and a single outlying coordinate can drag a centroid away from the bulk of its cluster. Density-based or hierarchical methods often suit those patterns better.
What happens if one of the clusters ends up empty?
A cluster becomes empty when no point is closer to its centroid than to some other centroid. That normally happens when k is larger than the number of distinct coordinates you entered, or when two seed centroids coincide. The calculator reports such a cluster with a size of zero and leaves its centroid where the last update step left it, rather than returning NaN.
Sources for the k-means objective and the Lloyd iteration
The squared-error objective and the alternating assign-then-average iteration implemented here are the classic k-means method. Primary sources: S. P. Lloyd, "Least squares quantization in PCM", IEEE Transactions on Information Theory 28(2), 129–137 (1982), which sets out the alternating optimality conditions; and J. MacQueen, "Some methods for classification and analysis of multivariate observations", Proceedings of the Fifth Berkeley Symposium on Mathematical Statistics and Probability, Volume 1, 281–297 (1967), which named the procedure. For the textbook treatment of the objective and the elbow heuristic see T. Hastie, R. Tibshirani and J. Friedman, The Elements of Statistical Learning, 2nd edition, section 14.3.6. The naming used in the results panel follows the scikit-learn clustering user guide, which defines inertia as the within-cluster sum-of-squares criterion and describes Lloyd's algorithm in the same three steps used above.
Centroid Chase: place the centroids yourself
Each level drops a fresh cloud of points and hands you k centroids. Move them until the live within-cluster sum of squares is as low as the converged par value shown in the HUD, then lock the level in. The shaded Voronoi cells show which centroid currently owns which part of the plane, and the spokes show which points are paying the most into the objective.
Pointer or touch: drag a centroid to move it; tap anywhere else to select the nearest centroid. Keyboard: click or tab to the board first, then Arrow keys nudge the selected centroid, C cycles between centroids, 1–6 select one directly, Space starts the round and afterwards runs one Lloyd iteration, Enter locks in the placement and advances, and R restarts the level.
Level
1 / 5
Your WCSS
—
Par WCSS
—
Efficiency
—
Lloyd steps
0
Score
0
Best
0
Press Start round, then drag the centroids or nudge them with the arrow keys.
