Method · Statistics Library

k-Means clustering

k-means partitions observations into a chosen number of groups (k) so that each point belongs to the cluster with the nearest center, minimizing the total within-cluster squared distance, with a silhouette score to judge how well-separated the resulting groups actually are.

Topic indexA reference reading outside the guided chapter sequence

Understand the idea

k-means asks a simple question: if I had to sort all these observations into k baskets so that everything in a basket is as close together as possible, how would I do it? It starts with k guessed 'centers', assigns every point to whichever center it is nearest to, recomputes each center as the average of the points now assigned to it, and repeats that assign-then-recompute cycle until nothing changes anymore.

Because the starting centers are somewhat random, different runs can land on different final groupings, so KernelStats runs the whole process several times from different random starts and keeps whichever attempt produced the tightest, most compact clusters overall.

Here is the single most important thing to know about k-means: IT ALWAYS RETURNS EXACTLY k GROUPS, even when there is no real group structure in the data at all. Feed it a featureless cloud of random noise and ask for 3 clusters, and it will hand you back 3 tidy-looking groups with centers and sizes: the algorithm partitions whatever you give it; it never checks whether a partition was actually warranted in the first place. The silhouette score is your main defense against being fooled by this: a low score is the warning sign that you may be looking at arbitrary cuts through one continuous blob rather than real, separate groups.

K-means clustering, usually fitted with Lloyd's algorithm, alternates between assigning each row to its nearest center and moving each center to the average of its rows. The elbow method plots the within-cluster spread against the number of clusters and picks the k where adding more clusters stops helping much.

Practitioner explanation

KernelStats standardizes by default (mean 0, SD 1 per variable, since distances drive every assignment and an unscaled high-variance variable would dominate), runs Lloyd's algorithm with k-means++ initialization across n_init restarts (default 10) and keeps the lowest-inertia solution, with a fixed random_state (default 42) for reproducibility. Centroids are reported back-transformed to the ORIGINAL variable scale, not the standardized scale, so they are directly interpretable against the source data.

When k exceeds the number of distinct data points available, Lloyd's algorithm can leave clusters with zero members; KernelStats explicitly detects this and reports only the clusters that actually contain observations (with a warning), rather than R's stats::kmeans convention of refusing the input outright: a deliberate, documented product choice, not a bug. Silhouette score is only computed when there are at least 2 distinct non-empty clusters and fewer clusters than observations; otherwise it is reported as not computable rather than a fabricated number.

The verbal labels attached to the silhouette score (strong >= 0.70, reasonable >= 0.50, weak >= 0.25, poor below) deliberately use DIFFERENT wording from the negligible/small/medium/large family used for Cohen-style effect sizes elsewhere in KernelStats, and follow Rousseeuw's (1987) own conventional bands rather than Cohen's benchmarks: a silhouette score is a cluster-separation index on its own scale, not an effect size, and the separate vocabulary signals the two are not interchangeable. KernelStats does not implement the gap statistic (Tibshirani, Walther & Hastie 2001) for formally testing whether k>1 is even warranted; the silhouette score and comparing several k values by eye is the tool this card provides for that judgment.

When to use it

Consider it when

You have continuous numeric variables and want to discover a specific, pre-chosen number of natural groupings (customer segments, specimen types), particularly when clusters are expected to be roughly spherical and similarly sized.

Use caution when

Clusters are expected to be elongated, irregularly shaped, or very different in size (k-means' spherical-cluster assumption will distort the result), you do not want to commit to a specific k in advance (hierarchical clustering lets you inspect the tree before cutting), or the data may have NO real cluster structure at all: k-means will still confidently produce k groups regardless, and only a low silhouette score (or a formal check like the gap statistic, which this function does not compute) would reveal that.

Formulas and symbols

Inertia (within-cluster sum of squares)

inertia=∑i=1n∥xi−μc(i)∥2\text{inertia} = \sum_{i=1}^{n} \lVert x_i - \mu_{c(i)} \rVert^2

mu_c(i) the centroid of the cluster point x_i is assigned to; the quantity k-means minimizes.

Silhouette score

s=b−amax⁡(a,b)s = \dfrac{b - a}{\max(a, b)}

a the mean distance to points in the same cluster; b the mean distance to the nearest other cluster. Ranges -1 to +1; higher is better-separated.

Assumptions and checks

  • k-means assumes clusters are roughly spherical, similarly sized, and separated in Euclidean distance; elongated, unequal-density, or non-convex clusters get carved up incorrectly regardless of how many clusters k are requested.

    In KernelStats: Not checked by KernelStats: no cluster-shape diagnostic is run; the silhouette score reported measures overall separation and cohesion, not whether the spherical-cluster assumption itself holds.

  • Variables on very different scales let the highest-variance variable dominate the Euclidean distance k-means minimizes, so the clustering reflects scale rather than genuine similarity.

    In KernelStats: Handled by default rather than checked: the standardize option (on by default) rescales every variable to mean 0, SD 1 before clustering; if the analyst turns it off, the card does not flag variables on very different scales.

  • Independence of observations. k-means treats every row as an independent point in space; clustering rows that are actually repeated measurements of the same unit, or otherwise dependent, can create spurious 'clusters' that just reflect the grouping structure rather than genuine subpopulations.

    In KernelStats: Not checked by KernelStats.

Alternatives

  • Hierarchical Clustering. You want to inspect the nested tree structure before committing to a specific number of clusters, or clusters may not be roughly spherical.
  • Principal Component Analysis. The goal is dimensionality reduction or visualization of variable structure rather than partitioning observations into discrete groups.

Worked example

Scenario

k-means (k=3, standardized, 10 restarts, seed 42) on four penguin body measurements across 342 birds.

Result

Inertia = 379.4, silhouette = 0.45 ('weak' on Rousseeuw's bands), with cluster sizes of 87, 123 and 132; the 123 matches the Gentoo count, while the other two clusters cut across the 151 Adelie and 68 Chinstrap.

Interpretation

A silhouette of 0.45 says the three groups overlap substantially: one cluster (Gentoo) is well separated, but the split of the remaining birds is not a clean natural break in these four measurements. Checking the clusters against species labels is external corroboration the silhouette cannot provide, and here it shows k-means does not recover all three species.

Dataset: penguins.csv

Common misconceptions

Misconception

If k-means returns k clusters with sensible-looking centroids and sizes, the data must genuinely contain k real groups.

Correction

k-means ALWAYS returns exactly k clusters, even when run on featureless random noise with no real group structure whatsoever: the algorithm partitions whatever it is given; it never tests whether a partition is actually warranted. A low silhouette score (roughly below 0.25, weak between 0.25 and 0.50) is the main clue that the 'clusters' found are arbitrary cuts through one continuous blob rather than real, separate groups; compare several k values and treat clean-looking output with appropriate skepticism unless the silhouette score genuinely supports it.

Misconception

A single k-means run gives the one correct clustering for a given k.

Correction

k-means' result depends on where its initial centroids happen to land, and different random starts can converge to different final solutions. KernelStats runs multiple restarts (n_init) and keeps the lowest-inertia solution specifically because a single run is not guaranteed to find the best partition for the chosen k.

References

  1. NIST/SEMATECH e-Handbook of Statistical Methods, §8.4 Cluster analysis, NIST/SEMATECH (2012), §8.4.
  2. Estimating the number of clusters in a data set via the gap statistic, Tibshirani, R., Walther, G. and Hastie, T. (2001), Journal of the Royal Statistical Society, Series B, 63(2), 411-423.