∑GATE DA Atlas

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.

Section 610 practice questions

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 nn points into kk clusters minimising the within-cluster sum of squares:

J=∑j=1k∑xi∈Cj∥xi−μj∥2.J = \sum_{j=1}^k\sum_{\mathbf x_i\in C_j}\lVert\mathbf x_i - \boldsymbol\mu_j\rVert^2.

Lloyd's algorithm:

  1. Initialise kk centroids.
  2. Assign each point to its nearest centroid.
  3. Update each centroid to the mean of its assigned points.
  4. Repeat 2–3 until assignments stop changing.
Python
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
assign to nearest centroid move centroids to cluster means squares = centroids; repeat until nothing changes
Alternate between assignment and update; the objective never increases.

Properties

  • Each step cannot increase JJ, so the algorithm converges — to a local minimum that depends on initialisation. Run several random restarts and keep the lowest JJ.
  • 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 O(log⁡k)O(\log k) approximation.
  • Cost per iteration O(nkd)O(nkd).
  • Assumes roughly spherical, similarly sized, convex clusters; sensitive to outliers (means are pulled) and to feature scale; needs kk in advance.

Choosing kk

  • Elbow: plot JJ against kk and look for the bend.
  • Silhouette: for point ii with mean intra-cluster distance a(i)a(i) and mean distance to the nearest other cluster b(i)b(i), s(i)=b(i)−a(i)max⁡(a(i),b(i))∈[−1,1]s(i) = \frac{b(i) - a(i)}{\max(a(i), b(i))} \in [-1, 1]; choose the kk 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:

medoid(C)=arg⁡min⁡m∈C∑x∈Cd(x,m).\text{medoid}(C) = \arg\min_{\mathbf m\in C}\sum_{\mathbf x\in C}d(\mathbf x, \mathbf m).

PAM (Partitioning Around Medoids) repeatedly tries swapping a medoid with a non-medoid and keeps swaps that lower the total cost.

k-meansk-medoids
Centremean (may not be a data point)medoid (a data point)
Distancesquared Euclideanany dissimilarity (Manhattan, edit distance, …)
Outlierssensitiverobust (medoid is like a median)
Cost per iterationO(nkd)O(nkd)O(k(n−k)2)O(k(n - k)^2) for PAM — slower
Interpretabilitycentroid is syntheticcentre 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 kk beforehand.

Bottom-up (agglomerative)

  1. Start with each point as its own cluster.
  2. Repeatedly merge the two closest clusters.
  3. Stop when one cluster remains (n−1n - 1 merges).

The linkage defines the distance between clusters:

Linkaged(A,B)d(A, B)Behaviour
Single (minimum)min⁡a∈A,b∈Bd(a,b)\min_{a\in A, b\in B}d(a, b)finds elongated/non-convex clusters; prone to chaining
Complete (maximum)max⁡a,bd(a,b)\max_{a, b}d(a, b)compact clusters of similar diameter; sensitive to outliers
Average (UPGMA)mean of all pairwise distancescompromise
Centroiddistance between centroidscan produce inversions in the dendrogram
Wardincrease in total within-cluster SSE caused by the mergecompact, k-means-like clusters
single linkage ABCD 124 complete linkage ABCD 137
Same points, different linkage, different merge heights (vertical axis = linkage distance).

Agglomerative clustering needs the O(n2)O(n^2) distance matrix and O(n2log⁡n)O(n^2\log n)–O(n3)O(n^3) 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.

Q1NAT2 marks

k-means with k=2k = 2 is run on the 1-D points 1,2,3,8,9,10,251, 2, 3, 8, 9, 10, 25 starting from centroids 11 and 2525. After the algorithm converges, the centroid of the larger cluster is ______.

Q2NAT2 marks

The 1-D points 1,2,31, 2, 3 form one cluster and 8,9,108, 9, 10 another, each with its mean as centroid. The within-cluster sum of squares (WCSS) is ______.

Q3MCQ1 mark

Which statement about Lloyd's k-means algorithm is correct?

Q4NAT2 marks

Using absolute distance, the medoid of the 1-D points 1,2,4,7,201, 2, 4, 7, 20 (the data point minimising the sum of distances to all others) is ______.

Q5MCQ2 marks

In agglomerative hierarchical clustering, single linkage and complete linkage define the distance between clusters AA and BB as

Q6NAT2 marks

Agglomerative clustering with complete linkage is applied to the 1-D points 1,2,4,81, 2, 4, 8. The height (linkage distance) of the final merge is ______.

Q7MSQ2 marks

Which statements are correct?

One or more options are correct.

Q8NAT1 mark

Agglomerative clustering starts with 10 singleton clusters and merges until one cluster remains. The number of merge steps is ______.

Q9MCQ1 mark

The "elbow method" for choosing kk in k-means plots

Q10NAT2 marks

A point has mean distance a=2a = 2 to the other members of its own cluster and mean distance b=5b = 5 to the members of the nearest other cluster. Its silhouette coefficient s=b−amax⁡(a,b)s = \dfrac{b - a}{\max(a, b)} is ______.