Clustering — k-Means, k-Medoids and Hierarchical Clustering
The clustering problem and distance choices, k-means (Lloyd's algorithm, the within-cluster sum of squares, convergence, initialisation with k-means++, choosing k), k-medoids (PAM) and why it is robust, hierarchical clustering bottom-up (agglomerative with single, complete, average, centroid and Ward linkage) and top-down (divisive), dendrograms, and cluster validation with the silhouette.
The clustering problem
Clustering groups unlabelled points so that points in the same cluster are similar and points in different clusters are dissimilar. It is unsupervised: there are no labels to check against, so the result depends on the choice of distance, algorithm and number of clusters. Applications: customer segmentation, document grouping, image segmentation, anomaly detection, vector quantisation.
Distances: Euclidean (most common), Manhattan, cosine (text), Hamming (categorical). Scale features first, exactly as for k-NN.
k-means
Partition points into clusters minimising the within-cluster sum of squares:
Lloyd's algorithm:
- Initialise centroids.
- Assign each point to its nearest centroid.
- Update each centroid to the mean of its assigned points.
- Repeat 2–3 until assignments stop changing.
import numpy as np
def kmeans(X, k, iters=100, seed=0):
rng = np.random.default_rng(seed)
C = X[rng.choice(len(X), k, replace=False)] # random initial centroids
for _ in range(iters):
labels = np.argmin(((X[:, None] - C[None]) ** 2).sum(-1), axis=1)
newC = np.array([X[labels == j].mean(0) if np.any(labels == j) else C[j] for j in range(k)])
if np.allclose(newC, C):
break
C = newC
return labels, C
Properties
- Each step cannot increase , so the algorithm converges — to a local minimum that depends on initialisation. Run several random restarts and keep the lowest .
- k-means++ initialisation: choose the first centroid at random, then each next one with probability proportional to its squared distance from the nearest chosen centroid — spreads the seeds and gives a provable approximation.
- Cost per iteration .
- Assumes roughly spherical, similarly sized, convex clusters; sensitive to outliers (means are pulled) and to feature scale; needs in advance.
Choosing
- Elbow: plot against and look for the bend.
- Silhouette: for point with mean intra-cluster distance and mean distance to the nearest other cluster , ; choose the with the highest average.
- Domain knowledge or downstream usefulness.
k-medoids (PAM)
Like k-means, but each cluster centre must be an actual data point (the medoid), chosen to minimise the sum of (any) distances to the cluster's members:
PAM (Partitioning Around Medoids) repeatedly tries swapping a medoid with a non-medoid and keeps swaps that lower the total cost.
| k-means | k-medoids | |
|---|---|---|
| Centre | mean (may not be a data point) | medoid (a data point) |
| Distance | squared Euclidean | any dissimilarity (Manhattan, edit distance, …) |
| Outliers | sensitive | robust (medoid is like a median) |
| Cost per iteration | for PAM — slower | |
| Interpretability | centroid is synthetic | centre is a real example |
Hierarchical clustering
Builds a nested sequence of clusterings displayed as a dendrogram; cutting it at a height gives a flat clustering — no need to fix beforehand.
Bottom-up (agglomerative)
- Start with each point as its own cluster.
- Repeatedly merge the two closest clusters.
- Stop when one cluster remains ( merges).
The linkage defines the distance between clusters:
| Linkage | Behaviour | |
|---|---|---|
| Single (minimum) | finds elongated/non-convex clusters; prone to chaining | |
| Complete (maximum) | compact clusters of similar diameter; sensitive to outliers | |
| Average (UPGMA) | mean of all pairwise distances | compromise |
| Centroid | distance between centroids | can produce inversions in the dendrogram |
| Ward | increase in total within-cluster SSE caused by the merge | compact, k-means-like clusters |
Agglomerative clustering needs the distance matrix and – time, so it suits small and medium data sets.
Top-down (divisive)
Start with all points in one cluster and recursively split — e.g. bisecting k-means (repeatedly split the worst cluster with 2-means) or DIANA (split off the most dissimilar points). Useful when only the top few levels are needed.
Beyond these methods
DBSCAN (density-based, finds arbitrary shapes and noise points), Gaussian mixture models (soft, probabilistic k-means fitted by EM) and spectral clustering are common alternatives.
Quick revision
Practice questions
GATE-style questions: 3 one-mark and 7 two-mark. Wrong MCQs cost ⅓ of their marks in the real exam; MSQ and NAT have no negative marking. Attempt each before opening the solution.
k-means with is run on the 1-D points starting from centroids and . After the algorithm converges, the centroid of the larger cluster is ______.
The 1-D points form one cluster and another, each with its mean as centroid. The within-cluster sum of squares (WCSS) is ______.
Which statement about Lloyd's k-means algorithm is correct?
Using absolute distance, the medoid of the 1-D points (the data point minimising the sum of distances to all others) is ______.
In agglomerative hierarchical clustering, single linkage and complete linkage define the distance between clusters and as
Agglomerative clustering with complete linkage is applied to the 1-D points . The height (linkage distance) of the final merge is ______.
Which statements are correct?
One or more options are correct.
Agglomerative clustering starts with 10 singleton clusters and merges until one cluster remains. The number of merge steps is ______.
The "elbow method" for choosing in k-means plots
A point has mean distance to the other members of its own cluster and mean distance to the members of the nearest other cluster. Its silhouette coefficient is ______.