Merge points bottom-up with single linkage clustering

Agglomerative clustering starts with every point alone and keeps merging the two closest clusters. Single linkage measures cluster distance by the closest pair of members, so it can follow long, curved shapes that k-means cannot.

Write single_linkage(X, k). X has shape (n, d), 1 <= k <= n. Start with n singleton clusters. While there are more than k clusters: among all pairs of points (i, j) with i < j that are in different clusters, find the pair with the smallest Euclidean distance (ties: smallest i, then smallest j) and merge their two clusters.

Return a list of n int labels. Number the final clusters in order of first appearance: point 0 gets label 0, the next point in a new cluster gets label 1, and so on.

Signaturedef single_linkage(X, k)

Example

X = [[0], [1], [5], [6], [20]], k = 2. Merges: (0, 1), (2, 3), then the closest cross pair is (1, 2) at distance 4, giving labels [0, 0, 0, 0, 1].

Understand the idea

Agglomerative clustering starts with every point alone and keeps merging the two closest clusters until k remain. Single linkage defines the distance between two clusters as their closest pair of points. That lets clusters grow along chains and curves, and splits data at its biggest gaps. Like islands joined by the shortest bridges first. Worked example: X = [[0], [2], [3], [9], [10]], k = 2. Closest pairs at distance 1 are (1, 2) and (3, 4); ties go to the smallest i, so merge (1, 2) first, then (3, 4). Clusters {0}, {1, 2}, {3, 4}. The closest cross pair now is (0, 1) at distance 2 (versus 6 between points 2 and 3), so merge to get {0, 1, 2} and {3, 4}. Labels by first appearance: [0, 0, 0, 1, 1]. Centroid distance would behave differently on long chains. Rule: while clusters > k, merge the clusters of the closest pair (i < j) in different clusters, ties by smallest i then j; relabel by first appearance. It is used for dendrograms and grouping near-duplicate items.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplesingle_linkage([[0], [1], [5], [6], [20]], 2)
  • Sample 2: two arcssingle_linkage(_X, 2)