K-means Clustering

Machine Learning
Introduced by
MacQueen, J. B.; Lloyd, S. P.
Year
1967 (formalized 1982)
Type
Partitional clustering
Family
Machine learning

What does it do?

K-means is a partitional clustering algorithm that divides a numeric dataset into K non-overlapping groups.

It alternates between assigning each observation to its nearest centroid and recomputing each centroid as the mean of its assigned points. It is one of the most widely used exploratory clustering methods.

The intuition behind the method

Imagine dropping K magnets on a map of data points. Each point is drawn to its nearest magnet, and then each magnet moves to the center of gravity of the points it attracted. Repeat this pull-and-move cycle until nothing moves: the magnets have found K natural groupings. K-means formalizes exactly this idea, minimizing the total squared distance from every point to its cluster center, called the within-cluster sum of squares (WCSS or inertia).

History

The term k-means and the clustering procedure are attributed to MacQueen (1967). Lloyd's 1982 paper in IEEE Transactions on Information Theory derives necessary conditions for optimal finite quantization schemes in pulse-code modulation, with the aim of minimizing average quantization noise power. It is a closely related quantization result and serves as background to the iterative assign-and-update logic, not as the origin of the clustering method. Later refinements, such as the k-means++ initialization, are now standard in practice.

When to use it

Choose K-means for exploratory clustering of large, purely numeric datasets when you need fast partitioning and can specify K in advance or search for it with the elbow or silhouette method. It is a reasonable choice for customer segmentation, color quantization, grouping of document vectors, or grouping of gene expression profiles. Do not use it when features are categorical or ordinal (use k-modes or k-prototypes instead), when clusters are clearly non-spherical or differ greatly in size and density, when the data contain many outliers (DBSCAN or a robust variant is more suitable), or when no plausible range for K can be explored.

Limitations and considerations

  • K must be fixed before fitting. A poor choice of K produces a partition that looks valid but does not reflect the structure of the data.
  • The objective is a sum of squared Euclidean distances to the means, so elongated, irregular, or strongly differently sized clusters are often split or merged incorrectly.
  • Centroids are means, so a single extreme observation can pull a centroid away from the bulk of its cluster.
  • Euclidean distance and mean centroids are undefined for categorical variables, so such features require a different algorithm such as k-modes.
  • The algorithm converges to a local minimum of WCSS, so different starting configurations can produce different partitions unless k-means++ or multiple restarts are used.

Source conditions do not replace independent scientific review or validation by an analysis engine.

Strengths

  • Scales to large numeric datasets: each iteration costs O(nKdi), where n is the number of observations, K the number of clusters, d the number of features and i the number of iterations, so it remains practical for moderate K and d.
  • Simple to implement and to explain: each iteration consists of assigning points to the nearest mean and then recomputing the means.
  • Well suited to compact, roughly spherical clusters of similar size, where the WCSS objective matches the structure of the data.
  • k-means++ initialization reduces, but does not remove, dependence on the starting centroids compared with purely random initialization.
  • For a fixed random seed, initialization method, data order and software implementation, a run can be reproduced exactly. Results can differ across implementations or library versions, so multiple restarts with the lowest-WCSS solution are the standard safeguard against local minima.

Applications

  • Customer segmentation for marketing and personalization based on behavioral or demographic features.
  • Image compression by quantizing pixel colors to K representative values (color quantization).
  • Document and text clustering as a step in topic modeling pipelines after vectorization.
  • Pre-processing for anomaly detection: observations that lie far from every centroid are candidate outliers.
  • Initialization of Gaussian mixture model fitting, where k-means gives the starting component means.
  • Gene expression analysis to group genes or samples with similar expression profiles.

How it works

How it works

1

K starting centroids are placed in the feature space, either by randomly selecting K data points or by the k-means++ strategy, which spreads the initial centroids out rather than choosing them purely at random. The starting configuration matters because the final solution depends on it. k-means++ is intended to reduce the chance of ending in a poor local minimum, but it does not guarantee the global optimum.

2

Every observation is assigned to the cluster whose centroid is nearest in Euclidean distance. This hard assignment creates K non-overlapping partitions of the data. Formally, each point x_i is assigned to cluster c_i = argmin_k ||x_i - mu_k||^2.

Formula
c_i = \arg\min_k \|x_i - \mu_k\|^2
3

Each centroid is recalculated as the arithmetic mean of all points currently assigned to that cluster: mu_k = (1/|C_k|) times the sum of all x_i in C_k. For a fixed assignment, this mean is the centroid that minimizes the squared distances within that cluster, which is why the update step cannot increase WCSS.

Formula
\mu_k = \frac{1}{|C_k|} \sum_{x_i \in C_k} x_i
4

The assign and update steps alternate until the centroid positions stop changing (or change by less than a tolerance) or a maximum number of iterations is reached. The procedure reaches a local minimum of WCSS, which is not necessarily the global minimum.

5

Solution quality is assessed with the total WCSS (inertia) J = sum over clusters of sum over assigned points of ||x_i - mu_k||^2. The algorithm itself requires K to be specified in advance, so choosing K is a separate step, usually supported by the elbow method, silhouette scores, or gap statistics.

Formula
J = \sum_{k=1}^{K} \sum_{x_i \in C_k} \|x_i - \mu_k\|^2

Common pitfalls

  • Clustering without standardizing features first. Variables with large numeric ranges dominate the Euclidean distances and therefore the assignments.
  • Choosing K from the WCSS curve alone. WCSS always decreases as K increases, so choose K where the decrease levels off, and check silhouette scores because the elbow is often ambiguous.
  • Running a single initialization and accepting its result, without multiple restarts to guard against a poor local minimum.
  • Including categorical or ordinal variables in the feature matrix without suitable encoding, or without switching to k-modes or k-prototypes.
  • Interpreting cluster labels as real group identities without external validation, especially when the clusters are not well separated.

Frequently asked questions

How do I choose the right number of clusters K?

Run k-means for a range of K values, plot the within-cluster sum of squares against K, and look for an 'elbow' where the rate of decrease slows sharply. Supplement this with silhouette scores, which measure how similar each point is to its own cluster versus neighboring clusters; higher average silhouette indicates better-defined clusters.

Why do I get different results each run?

K-means is sensitive to initialization and converges to a local rather than global minimum of WCSS. Use k-means++ initialization and set a fixed random seed for reproducibility. Running the algorithm multiple times with different seeds and keeping the solution with the lowest inertia is good practice.

Does k-means work with categorical data?

No. K-means relies on Euclidean distance and centroid means, which are undefined for categorical variables. For purely categorical data use k-modes; for mixed numeric and categorical data use k-prototypes.

When should I prefer DBSCAN or GMM over k-means?

Use DBSCAN when clusters have irregular shapes or you need automatic outlier detection without specifying K. Use Gaussian Mixture Models (GMM) when you want soft (probabilistic) cluster assignments or clusters of different sizes and orientations, at the cost of higher computational complexity.

Do I need to scale my features?

Yes, almost always. K-means uses Euclidean distance, so features with large numeric ranges will dominate the clustering. Apply z-score standardization or min-max scaling before fitting k-means, unless all features are already on the same scale.

Related methods

Sources

  1. Lloyd, S. P. (1982). Least squares quantization in PCM. IEEE Transactions on Information Theory, 28(2), 129–137.

    Open DOI reference
  2. MacQueen, J. B. (1967). Some methods for classification and analysis of multivariate observations. Proceedings of the 5th Berkeley Symposium on Mathematical Statistics and Probability, 1, 281–297.

    Open publication reference