Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

k-means and k-medoids

ProblemPartition points into groups, each represented by a centre, minimising the total distance from points to their centres
Devised byHugo Steinhaus (1956); Stuart Lloyd (1957, published 1982), the alternating algorithm; James MacQueen (1967), the name k-means; Leonard Kaufman and Peter Rousseeuw (1987), k-medoids (PAM); David Arthur and Sergei Vassilvitskii (2007), k-means++ seeding
AccuracyLloyd’s algorithm converges to a local minimum in finitely many steps; k-means++ seeding is within of the optimum in expectation
CostLloyd: per iteration. PAM: per swap pass in this implementation
Read firstFoundations: models, data, preprocessing and metrics
APIKMeans (new(k, seed), with_restarts, with_limits, centroids, inertia, predict), KMedoids (new(k), fit_distances, medoids, cost)

Overview

k-means is the most widely used clustering method. It describes each of clusters by its mean, the centroid, and assigns every point to the nearest centroid. Fitting alternates two easy steps, assigning points and recomputing means, each of which lowers the total squared distance. The result depends on the starting centres, and the method assumes the clusters are compact, round and of similar size. k-medoids replaces each mean by an actual data point, the medoid, and squared distances by plain distances. This makes it robust to outliers and lets it work from any matrix of dissimilarities, at a higher cost.

Where it is used

k-means is the most widely used clustering algorithm.

  • Vector quantisation and compression. Reducing the colours of an image to representatives, and the codebooks of speech and image coders.
  • Customer and market segmentation. Grouping similar customers or products.
  • Preprocessing. Initial centres for mixture models, and clustering of sensor data and trajectories.
  • k-medoids. Uses actual data points as centres, which is more robust and works with any distance.

History

Hugo Steinhaus (1956) proposed dividing a body into parts by minimising the moment of inertia about their centres. Stuart Lloyd devised the alternating algorithm at Bell Labs in 1957 for quantising signals (pulse-code modulation); it circulated as a technical report and was published only in 1982. Edward Forgy (1965) described the same method, and James MacQueen (1967) named it k-means and studied an online variant. Leonard Kaufman and Peter Rousseeuw introduced Partitioning Around Medoids (PAM) in 1987 and popularised it in their book Finding Groups in Data (1990). David Arthur and Sergei Vassilvitskii’s k-means++ seeding (2007) gave the first practical initialisation with a guarantee, and is now the default almost everywhere.

The idea

Lloyd’s algorithm

k-means minimises the inertia, the within-cluster sum of squares

For fixed centres, is smallest when each point joins its nearest centre; for fixed clusters, it is smallest when each centre is the mean of its cluster. Lloyd’s algorithm alternates the two. Neither step can increase and there are finitely many partitions, so the algorithm stops, but at a local minimum: a fixed point where no single step helps.

From an unlucky seeding with two centres in the top-right blob, the boundaries move step by step until each blob has its own centre. The nearest-centre rule makes every boundary a straight line (the cells form a Voronoi diagram), so k-means can only find convex clusters.

k-means++ seeding and restarts

k-means++ picks the first centre uniformly at random and each further centre with probability proportional to the squared distance to the nearest centre already chosen. Points far from every existing centre are likely picks, so the seeds spread across the data. The expected inertia of the seeding alone is within a factor of the optimum, and Lloyd’s iterations only improve it. Even so, a single run can stop in a poor local minimum. The remedy is to run several seedings and keep the best. On nine blobs in a 3 × 3 grid, over 200 seeds:

Table 12.3. Effect of restarts on k-means.

restarts (k-means++ seedings)runs reaching the best inertiamean inertia / bestworst inertia / best
136%1.1601.836
592%1.0061.310
20100%1.0001.000

The library uses five restarts by default.

Choosing k

always falls as grows, reaching zero when every point is its own cluster, so it cannot choose by itself. Two common heuristics are the elbow, the beyond which falls slowly, and the mean silhouette, which compares each point’s mean distance to its own cluster with its distance to the nearest other cluster (see Foundations):

Both point to the four blobs that generated the data. On real data the elbow is rarely this sharp. A probabilistic model with an information criterion (Gaussian mixtures) or a density method that needs no (DBSCAN) are the alternatives.

What k-means cannot do

Figure 12.1. k-means on the moons.

Straight boundaries cannot follow curved clusters. k-means cuts the two moons across the middle. Clusters of very different sizes or elongated shapes suffer in the same way, because the squared-distance objective prefers round clusters of equal spread.

k-medoids

k-medoids restricts each centre to be one of the data points and minimises the sum of plain distances, . Two consequences follow:

  • Any dissimilarity can be used, even one with no coordinates behind it: edit distances between strings, or 1 − correlation between time series. The method needs only the matrix.
  • Outliers matter less. Squared distances make a far point’s pull grow quadratically. A medoid must be a real point, and plain distances grow only linearly.

Three outliers far above two clusters are enough to make k-means spend a centre on them and merge the two real clusters. k-medoids keeps the clusters and attaches the outliers to the nearer one.

Kaufman and Rousseeuw’s PAM algorithm has two phases. BUILD chooses the medoids greedily: first the point with the smallest total distance to the others, then repeatedly the point that most reduces the cost. SWAP then tries every exchange of a medoid with a non-medoid and makes the best improving one, until no exchange helps. Each SWAP pass examines exchanges, which makes PAM much slower than k-means:

Table 12.4. Time of k-means against k-medoids.

pointsk-means, 5 restarts (ms)k-medoids, PAM (ms)
1000.040.4
2000.061.8
4000.137.5

Algorithm

k-means++ seeding.

  1. Choose the first centre uniformly at random from the data points.
  2. For each data point, compute , its distance to the nearest centre chosen so far.
  3. Choose the next centre from the data points with probability proportional to .
  4. Repeat steps 2 and 3 until there are centres.

Lloyd’s algorithm, from a set of centres.

  1. Assign each point to its nearest centre.
  2. Update each centre to the mean of the points assigned to it. If a cluster has become empty, place its centre on the point that is currently farthest from its own centre.
  3. If no centre moved by more than the tolerance, stop; otherwise go to 1.

Each iteration costs for points in dimensions.

The complete method: run the seeding and Lloyd’s algorithm n_init times with different random numbers, and keep the run with the smallest inertia.

k-medoids (PAM), on a matrix of pairwise dissimilarities.

  1. BUILD. Choose as the first medoid the point with the smallest total distance to all the others. Then, until there are medoids, add the point whose addition reduces the total distance from every point to its nearest medoid the most.
  2. SWAP. For every pair of a medoid and a non-medoid, compute the change in the total distance if the two exchanged roles. If the best exchange lowers the total, make it and repeat; otherwise stop.

Implementation

    fn seed_centres(&self, pts: &[Vec<f64>], rng: &mut MlRng) -> Vec<Vec<f64>> {
        let mut centres = vec![pts[rng.below(pts.len())].clone()];
        let mut d2: Vec<f64> = pts.iter().map(|p| squared_distance(p, &centres[0])).collect();
        while centres.len() < self.k {
            let total: f64 = d2.iter().sum();
            let pick = if total <= 0.0 {
                rng.below(pts.len())
            } else {
                let mut target = rng.uniform() * total;
                let mut chosen = pts.len() - 1;
                for (i, &w) in d2.iter().enumerate() {
                    if target < w {
                        chosen = i;
                        break;
                    }
                    target -= w;
                }
                chosen
            };
            centres.push(pts[pick].clone());
            for (i, p) in pts.iter().enumerate() {
                d2[i] = d2[i].min(squared_distance(p, centres.last().expect("non-empty")));
            }
        }
        centres
    }
    fn lloyd(&self, pts: &[Vec<f64>], mut centres: Vec<Vec<f64>>) -> LloydRun {
        let (n, dims) = (pts.len(), pts[0].len());
        let mut labels = vec![0usize; n];
        let mut iterations = 0;
        for it in 1..=self.max_iterations {
            iterations = it;
            let mut dist = vec![0.0; n];
            for (i, p) in pts.iter().enumerate() {
                let (c, d) = nearest(p, &centres);
                labels[i] = c;
                dist[i] = d;
            }
            let mut sums = vec![vec![0.0; dims]; self.k];
            let mut counts = vec![0usize; self.k];
            for (p, &l) in pts.iter().zip(&labels) {
                counts[l] += 1;
                sums[l].iter_mut().zip(p).for_each(|(s, v)| *s += v);
            }
            let mut shift: f64 = 0.0;
            for c in 0..self.k {
                let new: Vec<f64> = if counts[c] == 0 {
                    // Re-seed an empty cluster at the worst-fitted point.
                    let far = dist.iter().enumerate().max_by(|a, b| a.1.total_cmp(b.1)).map_or(0, |(i, _)| i);
                    dist[far] = 0.0;
                    pts[far].clone()
                } else {
                    sums[c].iter().map(|s| s / counts[c] as f64).collect()
                };
                shift = shift.max(squared_distance(&new, &centres[c]));
                centres[c] = new;
            }
            if shift <= self.tolerance * self.tolerance {
                break;
            }
        }
        let mut inertia = 0.0;
        for (i, p) in pts.iter().enumerate() {
            let (c, d) = nearest(p, &centres);
            labels[i] = c;
            inertia += d;
        }
        (centres, labels, inertia, iterations)
    }
        // BUILD: first the point with the smallest total distance, then greedily the point that
        // most reduces the total cost.
        let mut medoids = vec![(0..n).min_by(|&a, &b| d.row(a).sum().total_cmp(&d.row(b).sum())).expect("n > 0")];
        let mut nearest: Vec<f64> = (0..n).map(|i| d[[i, medoids[0]]]).collect();
        while medoids.len() < self.k {
            let gain = |c: usize| (0..n).map(|i| (nearest[i] - d[[i, c]]).max(0.0)).sum::<f64>();
            let c = (0..n).filter(|c| !medoids.contains(c)).max_by(|&a, &b| gain(a).total_cmp(&gain(b))).expect("k <= n");
            medoids.push(c);
            for i in 0..n {
                nearest[i] = nearest[i].min(d[[i, c]]);
            }
        }
        let total = |m: &[usize]| (0..n).map(|i| m.iter().map(|&c| d[[i, c]]).fold(f64::INFINITY, f64::min)).sum::<f64>();
        let mut cost = total(&medoids);
        // SWAP until no exchange improves the cost.
        for _ in 0..self.max_iterations {
            let mut best = (cost, None);
            for slot in 0..self.k {
                for candidate in (0..n).filter(|c| !medoids.contains(c)) {
                    let mut trial = medoids.clone();
                    trial[slot] = candidate;
                    let c = total(&trial);
                    if c < best.0 - 1e-12 {
                        best = (c, Some((slot, candidate)));
                    }
                }
            }
            match best.1 {
                Some((slot, candidate)) => {
                    medoids[slot] = candidate;
                    cost = best.0;
                }
                None => break,
            }
        }
  • All restarts draw from one random stream seeded by seed, so a fit is reproducible.
  • predict assigns new points to the nearest fitted centroid; k-medoids has no predict, since its medoids are indices into the training data.
  • The SWAP phase recomputes the full cost for every trial exchange. Faster variants (FastPAM, CLARA) update costs incrementally or work on samples.

In practice

//! k-means and k-medoids: choosing k by the silhouette, and clustering from a distance matrix.

use lib_jsl_core::R2D;
use lib_jsl_machine_learning::common::Clusterer;
use lib_jsl_machine_learning::datasets::make_blobs;
use lib_jsl_machine_learning::metrics::silhouette_score;
use lib_jsl_machine_learning::unsupervised::clustering::{KMeans, KMedoids};

fn main() {
    let centres = vec![vec![0.0, 0.0], vec![5.0, 0.5], vec![1.0, 5.0], vec![6.0, 5.5]];
    let (x, _) = make_blobs(60, &centres, 1.0, 3);
    for k in 2..=6 {
        let mut km = KMeans::new(k, 1).with_restarts(10);
        let labels = km.fit_predict(x.view()).unwrap();
        println!("k = {k}: inertia {:7.1}, silhouette {:.3}", km.inertia(), silhouette_score(x.view(), &labels).unwrap());
    }
    let mut km = KMeans::new(4, 1);
    km.fit_predict(x.view()).unwrap();
    println!("centroids:\n{:.2}", km.centroids());

    // k-medoids needs only dissimilarities: here, the number of differing letters between words.
    let words = ["cat", "car", "cab", "bat", "dog", "dot", "dig", "fig"];
    let d = R2D::from_shape_fn((8, 8), |(i, j)| words[i].chars().zip(words[j].chars()).filter(|(a, b)| a != b).count() as f64);
    let mut pam = KMedoids::new(2);
    let labels = pam.fit_distances(d.view()).unwrap();
    let medoids: Vec<&str> = pam.medoids().iter().map(|&m| words[m]).collect();
    println!("medoids {medoids:?}, labels {labels:?}, total distance {}", pam.cost());
}
k = 2: inertia  1847.7, silhouette 0.431
k = 3: inertia  1120.9, silhouette 0.483
k = 4: inertia   462.5, silhouette 0.604
k = 5: inertia   406.3, silhouette 0.534
k = 6: inertia   355.9, silhouette 0.473
centroids:
[[5.85, 5.52],
 [1.11, 4.71],
 [0.14, -0.10],
 [5.03, 0.38]]
medoids ["cat", "dig"], labels [0, 0, 0, 0, 1, 0, 1, 1], total distance 7

The word example clusters by the Hamming distance between three-letter words. “dot” differs from both medoids in two letters. The tie goes to the first medoid, a reminder that ties are common with integer-valued dissimilarities.

Strengths

  • k-means is simple and fast, scales to millions of points, and gives centroids that summarise each cluster.
  • k-medoids works with any dissimilarity, resists outliers, and its centres are real, interpretable examples.

Weaknesses

  • Both need in advance and find only convex, roughly equal clusters.
  • k-means is sensitive to feature scales, outliers and initialisation; PAM costs memory and is slow beyond a few thousand points.

Exercises

  1. Show that, for a fixed cluster, the mean minimises , and that the median minimises in one dimension.
  2. Prove that Lloyd’s algorithm terminates in finitely many iterations.
  3. Construct four points in the plane and a seeding from which Lloyd’s algorithm converges to a clustering with twice the optimal inertia.
  4. Show that , so k-means also minimises within-cluster pairwise distances.
  5. Implement MacQueen’s online update, which moves the nearest centre a step towards each new point, and compare it with Lloyd’s algorithm.
Hints and answers
  1. has gradient , zero at the mean. In one dimension has subgradient , which changes sign at the median.
  2. There are finitely many partitions. Each step does not increase the inertia (assigning to the nearest centre, then recentring on the mean) and strictly decreases it unless the partition is unchanged, so no partition repeats and the algorithm stops.
  3. Take the corners of a rectangle of width and length . Pairing the corners along the short sides (centres at the midpoints of the short sides) gives total inertia ; pairing them along the long sides gives . Both clusterings are fixed points of Lloyd’s algorithm (each corner is nearer its own centre), so a seeding at the midpoints of the long sides ends at twice the optimal inertia.
  4. Expanding gives the identity.
  5. MacQueen’s update is a stochastic-gradient step: each centre becomes a running mean of its assigned points; it converges more slowly and depends on the point order.

Further reading

  • S. P. Lloyd, “Least squares quantization in PCM”, IEEE Transactions on Information Theory 28 (1982) 129–137.
  • D. Arthur and S. Vassilvitskii, “k-means++: the advantages of careful seeding”, Proceedings of the 18th ACM-SIAM Symposium on Discrete Algorithms (2007) 1027–1035.
  • L. Kaufman and P. J. Rousseeuw, Finding Groups in Data: An Introduction to Cluster Analysis, Wiley, 1990, chapter 2.
  • A. K. Jain, “Data clustering: 50 years beyond K-means”, Pattern Recognition Letters 31 (2010) 651–666.