k-means

k-means

How k-means clustering groups unlabeled data into k clusters by repeatedly assigning points to the nearest center and updating the centers, and how to choose k and check the result.

What it is

k-means is an unsupervised learning algorithm that partitions a data set into k groups (clusters) so that points in the same cluster are close to each other and far from points in other clusters. Each cluster is represented by its centroid, the mean of its members. The standard procedure, Lloyd’s algorithm (1957, published 1982), is simple and fast, and the name “k-means” was introduced by James MacQueen in 1967. It is used for customer segmentation, image color quantization and compression, grouping gene expression profiles or spectra, document clustering, sensor data summarization, and as a preprocessing step that creates a compact “codebook” for other methods (vector quantization).

It answers questions such as: Are there natural groups in these data, and what do their typical members look like? How can a large set of colors or signals be summarized by a few representatives? Which samples belong together when no labels exist? How many groups are sensible? The answers are exploratory, since clusters depend on the features, scaling and the choice of k.

Fundamentals

The objective and Lloyd’s algorithm

k-means minimizes the within-cluster sum of squares (WCSS, also called inertia): J = Σk=1K Σx∈Ck ‖x − μk‖2, where μk is the centroid of cluster Ck. The algorithm alternates two steps. Assignment: each point goes to the nearest centroid (Euclidean distance). Update: each centroid is recomputed as the mean of its assigned points, μk = (1/|Ck|) Σ x. Each step cannot increase J, so the process converges, usually in a few dozen iterations, when assignments stop changing. It reaches only a local minimum, which depends on the starting centroids, and finding the global minimum is NP-hard. The cost per iteration is O(n k d) for n points, k clusters and d dimensions, so k-means scales to millions of points. Equivalently, k-means is the hard-assignment limit of a Gaussian mixture model with equal spherical covariances fitted by the EM algorithm.

Initialization and variants

Random starting centers can give poor results, so the standard remedy is k-means++ (Arthur and Vassilvitskii, 2007): the first center is random, and each next one is chosen with probability proportional to its squared distance from the nearest chosen center, spreading starts out and giving a provable O(log k) approximation. In practice, the algorithm is also run several times (10 or more random restarts) and the solution with the lowest J is kept. Mini-batch k-means updates centroids from small random batches, trading a little accuracy for large speed gains on big data. Related methods: k-medoids (PAM), which uses actual data points as centers and is more robust to outliers; k-modes for categorical data; fuzzy c-means (soft membership); spherical k-means for text (cosine distance); and bisecting k-means.

Choosing the number of clusters

k must be specified in advance, and several tools help. The elbow method plots J against k and looks for the bend where gains slow, which is often ambiguous. The silhouette coefficient of a point, s = (b − a)/max(a, b), compares the mean distance a to its own cluster with the mean distance b to the nearest other cluster; it lies between −1 and 1, and the average silhouette is maximized over k (values above about 0.5 suggest reasonable structure, below 0.25 weak). Other indices: Calinski–Harabasz, Davies–Bouldin, and the gap statistic, which compares J with that expected under a reference with no structure. Stability analysis (do clusters persist under resampling?) and domain knowledge also matter, as the “best” k statistically may not be useful. Note that J always decreases as k grows, so it cannot be used alone.

Assumptions, preprocessing and pitfalls

k-means implicitly assumes clusters are roughly spherical, similar in size and variance, and convex, and it fails on elongated, ring-shaped or very unequal clusters, where DBSCAN, hierarchical clustering or Gaussian mixture models work better. It is sensitive to scale (standardize variables before clustering), to outliers (which pull centroids), and to irrelevant features; in high dimensions distances lose contrast, so dimension reduction first (PCA, see principal component analysis) often helps. Categorical variables need other methods. Empty clusters can occur and are re-seeded. Clusters found are patterns in data, not proof of real categories, so validate them against external information, such as known labels (adjusted Rand index) or subject knowledge, and examine cluster profiles (mean of each variable per cluster).

Software, typical applications and limits

Tools: scikit-learn (KMeans, MiniBatchKMeans), R (kmeans, cluster, factoextra), MATLAB kmeans, and Spark MLlib for large data. Applications: market segmentation, image compression (replace each pixel color by its centroid), anomaly detection (points far from all centroids), grouping of materials or spectra, and initializing other models. Limits: the need to choose k, sensitivity to initialization, scale and outliers, restrictive cluster shape, and hard assignments with no uncertainty.

Basic operation

  1. Prepare the data. Clean, handle missing values and select relevant features.
  2. Scale the features. Standardize so that all variables contribute fairly.
  3. Choose candidate values of k. Use the elbow, silhouette and domain knowledge.
  4. Initialize. Use k-means++ with several restarts.
  5. Run the algorithm. Alternate assignment and update until assignments stop changing.
  6. Evaluate clusters. Check silhouette values, sizes and stability.
  7. Profile and interpret. Describe each cluster with its mean feature values.
  8. Collect the output. You obtain cluster labels and centroids; choosing k and validating clusters are covered in the video.

Good practice

  • Standardize variables. Otherwise large-scale features dominate.
  • Use k-means++ and restarts. This avoids poor local minima.
  • Do not rely on one criterion for k. Combine indices with judgment.
  • Check cluster stability. Re-run on subsamples.
  • Consider alternatives. Test other methods if clusters are not spherical.
  • Use segments responsibly. Segmenting people (for credit, pricing or services) can create unfair or discriminatory treatment, so review impacts and follow privacy rules.

Key terms

  • Centroid — the mean position of all points in a cluster.
  • Inertia (WCSS) — the sum of squared distances from points to their cluster centroid.
  • k-means++ — an initialization method that spreads out starting centers.
  • Elbow method — choosing k where the decrease in inertia levels off.
  • Silhouette coefficient — a measure of how well a point fits its own cluster versus others.
  • Local minimum — a solution that cannot be improved by small changes but may not be the best.
  • Vector quantization — representing data by a small set of prototype vectors.

Video coming soon

About five minutes on k-means: how it works in detail, how the data is acquired, and how it is analyzed.

Shopping cart

0
image/svg+xml

No products in the cart.

Continue Shopping