# Nearest-neighbor chain algorithm

In the theory of cluster analysis, the nearest-neighbor chain algorithm is a method that can be used to perform several types of agglomerative hierarchical clustering, using an amount of memory that is linear in the number of points to be clustered and an amount of time linear in the number of distinct distances between pairs of points.[1] The main idea of the algorithm is to find pairs of clusters to merge by following paths in the nearest neighbor graph of the clusters until the paths terminate in pairs of mutual nearest neighbors. The algorithm was developed and implemented in 1982 by J. P. Benzécri[2] and J. Juan,[3] based on earlier methods that constructed hierarchical clusterings using mutual nearest neighbor pairs without taking advantage of nearest neighbor chains.[4][5]

## Background

The input to a clustering problem consists of a set of points. A cluster is any proper subset of the points, and a hierarchical clustering is a maximal family of clusters with the property that any two clusters in the family are either nested or disjoint. Alternatively, a hierarchical clustering may be represented as a binary tree with the points at its leaves; the clusters of the clustering are the sets of points in subtrees descending from each node of the tree.

In agglomerative clustering methods, the input also includes a distance function defined on the points, or a numerical measure of their dissimilarity that is symmetric (insensitive to the ordering within each pair of points) but (unlike a distance) may not satisfy the triangle inequality. Depending on the method, this dissimilarity function can be extended in several different ways to pairs of clusters; for instance, in the single-linkage clustering method, the distance between two clusters is defined to be the minimum distance between any two points from each cluster. Given this distance between clusters, a hierarchical clustering may be defined by a greedy algorithm that initially places each point in its own single-point cluster and then repeatedly merges the closest pair of clusters.[6]

However, known methods for repeatedly finding the closest pair of clusters in a dynamic set of clusters either require superlinear space to maintain a data structure that can find closest pairs quickly, or they take greater than linear time to find each closest pair.[7][8] The nearest-neighbor chain algorithm uses a smaller amount of time and space than the greedy algorithm by merging pairs of clusters in a different order. However, for many types of clustering problem, it can be guaranteed to come up with the same hierarchical clustering as the greedy algorithm despite the different merge order.

## The algorithm

Animation of the algorithm using Ward's distance. Black dots are points, grey regions are larger clusters, blue arrows point to nearest neighbors, and the red bar indicates the current chain. For visual simplicity, when a merge leaves the chain empty, it continues with the recently merged cluster.

Intuitively, the nearest neighbor chain algorithm repeatedly follows a chain of clusters ABC → ... where each cluster is the nearest neighbor of the previous one, until reaching a pair of clusters that are mutual nearest neighbors.[6]

More formally, the algorithm performs the following steps:[1][6]

• Initialize the set of active clusters to consist of n one-point clusters, one for each input point.
• Let S be a stack data structure, initially empty, the elements of which will be active clusters.
• While there is more than one cluster in the set of clusters:
• If S is empty, choose an active cluster arbitrarily and push it onto S.
• Let C be the active cluster on the top of S. Compute the distances from C to all other clusters, and let D be the nearest other cluster.
• If D is already in S, it must be the immediate predecessor of C. Pop both clusters from S, merge them, and push the merged cluster onto S.
• Otherwise, if D is not already in S, push it onto S.

If there may be multiple equal nearest neighbors to a cluster, the algorithm requires a consistent tie-breaking rule: for instance, in this case, the nearest neighbor may be chosen, among the clusters at equal minimum distance from C, by numbering the clusters arbitrarily and choosing the one with the smallest index.

## Time and space analysis

Each iteration of the loop performs a single search for the nearest neighbor of a cluster, and either adds one cluster to the stack or removes two clusters from it. Every cluster is only ever added once to the stack, because when it is removed again it is immediately made inactive and merged. There are a total of 2n − 2 clusters that ever get added to the stack: n single-point clusters in the initial set, and n − 2 internal nodes other than the root in the binary tree representing the clustering. Therefore, the algorithm performs 2n − 2 pushing iterations and n − 1 popping iterations, each time scanning as many as n − 1 inter-cluster distances to find the nearest neighbor. The total number of distance calculations it makes is therefore less than 3n2, and the total time it uses outside of the distance calculations is O(n2).

Since the only data structure is the set of active clusters and the stack containing a subset of the active clusters, the space required is linear in the number of input points.

## Correctness

The correctness of this algorithm relies on a property of its distance function called reducibility, identified by Bruynooghe (1977) in connection with an earlier clustering method that used mutual nearest neighbor pairs but not chains of nearest neighbors.[4] A distance function d on clusters is defined to be reducible if, for every three clusters A, B and C in the greedy hierarchical clustering such that A and B are mutual nearest neighbors, the following inequality holds:

d(AB, C) ≥ min(d(A,C), d(B,C)).

If a distance function has the reducibility property, then merging two clusters C and D can only cause the nearest neighbor of E to change if that nearest neighbor was one of C and D. This has two important consequences for the nearest neighbor chain algorithm: first, it can be shown using this property that, at each step of the algorithm, the clusters on the stack S form a valid chain of nearest neighbors, because whenever a nearest neighbor becomes invalidated it is immediately removed from the stack.

Second, and even more importantly, it follows from this property that, if two clusters C and D both belong to the greedy hierarchical clustering, and are mutual nearest neighbors at any point in time, then they will be merged by the greedy clustering, for they must remain mutual nearest neighbors until they are merged. It follows that each mutual nearest neighbor pair found by the nearest neighbor chain algorithm is also a pair of clusters found by the greedy algorithm, and therefore that the nearest neighbor chain algorithm computes exactly the same clustering (although in a different order) as the greedy algorithm.

## Application to specific clustering distances

### Ward's method

Ward's method is an agglomerative clustering method in which the dissimilarity between two clusters A and B is measured by the amount by which merging the two clusters into a single larger cluster would increase the average squared distance of a point to its cluster centroid.[9] That is,

$d(A,B)=\sum_{x\in A, y\in B} \frac{d^2(x,y)}{|A|+|B|} - \sum_{x,y\in A} \frac{d^2(x,y)}{|A|} - \sum_{x,y\in B} \frac{d^2(x,y)}{|B|}.$

Expressed in terms of the centroid $c_A$ and cardinality $n_A$ of the two clusters, it has the simpler formula

$d(A,B)=\frac{d^2(c_a,c_b)}{1/n_A + 1/n_B},$

allowing it to be computed in constant time per distance calculation. Although highly sensitive to outliers, Ward's method is the most popular variation of agglomerative clustering both because of the round shape of the clusters it typically forms and because of its principled definition as the clustering that at each step has the smallest variance within its clusters.[10] Alternatively, this distance can be seen as the difference in k-means cost between the new cluster and the two old clusters.

Ward's distance is also reducible, as can be seen more easily from a different formula of Lance–Williams type for calculating the distance of a merged cluster from the distances of the clusters it was merged from:[9][11]

$d(A\cup B,C) = \frac{n_A+n_C}{n_A+n_B+n_C} d(A,C) + \frac{n_B+n_C}{n_A+n_B+n_C} d(B,C) - \frac{n_C}{n_A+n_B+n_C} d(A,B).$

If $d(A,B)$ is the smallest of the three distances on the right hand side (as would necessarily be true if $A$ and $B$ are mutual nearest-neighbors) then the negative contribution from its term is cancelled by the $n_C$ coefficient of one of the two other terms, leaving a positive value added to the weighted average of the other two distances. Therefore, the combined distance is always at least as large as the minimum of $d(A,C)$ and $d(B,C)$, meeting the definition of reducibility.

Therefore, the nearest-neighbor chain algorithm using Ward's distance calculates exactly the same clustering as the standard greedy algorithm. For n points in a Euclidean space of constant dimension, it takes time O(n2) and space O(n).[1]

### Complete linkage and average distance

Complete-linkage or furthest-neighbor clustering is a form of agglomerative clustering that uses the maximum distance between any two points from the two clusters as the dissimilarity, and similarly average-distance clustering uses the average pairwise distance. Like Ward's distance, these forms of clustering obey a formula of Lance-Williams type: in complete linkage, the distance $d(A\cup B,C)$ is the average of the distances $d(A,C)$ and $d(B,C)$ plus a positive correction term, while for average distance it is just a weighted average of the distances $d(A,C)$ and $d(B,C)$.[9][11] Thus, in both of these cases, the distance is reducible.

Unlike Ward's method, these two forms of clustering do not have a constant-time method for computing distances between pairs of clusters. Instead it is possible to maintain an array of distances between all pairs of clusters, using the Lance–Williams formula to update the array as pairs of clusters are merged, in time and space O(n2). The nearest-neighbor chain algorithm may be used in conjunction with this array of distances to find the same clustering as the greedy algorithm for these cases in total time and space O(n2). The same O(n2) time and space bounds can also be achieved by a different and more general technique that overlays a quadtree-based priority queue data structure on top of the distance matrix and uses it to perform the standard greedy clustering algorithm, avoiding the need for reducibility,[7] but the nearest-neighbor chain algorithm matches its time and space bounds while using simpler data structures.[12]

In single-linkage or nearest-neighbor clustering, the oldest form of agglomerative hierarchical clustering,[11] the dissimilarity between clusters is measured as the minimum distance between any two points from the two clusters. With this dissimilarity,

$d(A\cup B,C) = \min(d(A,C),d(B,C)),$

meeting as an equality rather than an inequality the requirement of reducibility. (Single-linkage also obeys a Lance–Williams formula,[9][11] but with a negative coefficient from which it is more difficult to prove reducibility.)

As with complete linkage and average distance, the difficulty of calculating cluster distances causes the nearest-neighbor chain algorithm to take time and space O(n2) to compute the single-linkage clustering. However, the single-linkage clustering can be found more efficiently by an alternative algorithm that computes the minimum spanning tree of the input distances using Prim's algorithm (with an unsorted list of vertices and their priorities in place of the usual priority queue), and then sorts the minimum spanning tree edges and uses this sorted list to guide the merger of pairs of clusters. This alternative method would take time O(n2) and space O(n), matching the best bounds that could be achieved with the nearest-neighbor chain algorithm for distances with constant-time calculations.[13]

### Centroid distance

Another distance measure commonly used in agglomerative clustering is the distance between the centroids of pairs of clusters, also known as the weighted group method.[9][11] It can be calculated easily in constant time per distance calculation. However, it is not reducible: for instance, if the input forms the set of three points of an equilateral triangle, merging two of these points into a larger cluster causes the inter-cluster distance to decrease, a violation of reducibility. Therefore, the nearest-neighbor chain algorithm will not necessarily find the same clustering as the greedy algorithm. A different algorithm by Day and Edelsbrunner can be used to find the clustering in O(n2) time for this distance measure.[8]

### Distances sensitive to merge order

The above presentation explicitly disallowed distances sensitive to merge order; indeed, allowing such distances can cause problems. In particular, there exist order-sensitive cluster distances which satisfy reducibility, but the above algorithm will return a hierarchy with suboptimal costs.[14] Following the earlier discussion of the value of defining cluster distances recursively (so that memoization can be used to greatly speed up distance computations), care must be taken with recursively defined distances so that they are not using the hierarchy in a way which is sensitive to merge order.

## References

1. ^ a b c Murtagh, Fionn (2002), "Clustering in massive data sets", in Abello, James M.; Pardalos, Panos M.; Resende, Mauricio G. C., Handbook of massive data sets, Massive Computing 4, Springer, pp. 513–516, ISBN 978-1-4020-0489-6.
2. ^ Benzécri, J.-P. (1982), "Construction d'une classification ascendante hiérarchique par la recherche en chaîne des voisins réciproques", Les Cahiers de l'Analyse des Données 7 (2): 209–218.
3. ^ Juan, J. (1982), "Programme de classification hiérarchique par l'algorithme de la recherche en chaîne des voisins réciproques", Les Cahiers de l'Analyse des Données 7 (2): 219–225.
4. ^ a b Bruynooghe, Michel (1977), "Méthodes nouvelles en classification automatique de données taxinomiqes nombreuses", Statistique et Analyse des Données 3: 24–42.
5. ^ de Rham, C. (1980), "La classification hiérarchique ascendante selon la méthode des voisins réciproques", Les Cahiers de l'Analyse des Données 5 (2): 135–144.
6. ^ a b c Murtagh, Fionn (1983), "A survey of recent advances in hierarchical clustering algorithms", The Computer Journal 26 (4): 354–359, doi:10.1093/comjnl/26.4.354.
7. ^ a b Eppstein, David (2000), "Fast hierarchical clustering and other applications of dynamic closest pairs", J. Experimental Algorithmics (ACM) 5 (1): 1–23, arXiv:cs.DS/9912014.
8. ^ a b Day, William H. E.; Edelsbrunner, Herbert (1984), "Efficient algorithms for agglomerative hierarchical clustering methods", Journal of Classification 1 (1): 7–24, doi:10.1007/BF01890115.
9. Mirkin, Boris (1996), Mathematical classification and clustering, Nonconvex Optimization and its Applications 11, Dordrecht: Kluwer Academic Publishers, pp. 140–144, ISBN 0-7923-4159-7, MR 1480413.
10. ^ Tuffery, Stéphane (2011), "9.10 Agglomerative hierarchical clustering", Data Mining and Statistics for Decision Making, Wiley Series in Computational Statistics, pp. 253–261, ISBN 978-0-470-68829-8.
11. Lance, G. N.; Williams, W. T. (1967), "A general theory of classificatory sorting strategies. I. Hierarchical systems", The Computer Journal 9 (4): 373–380, doi:10.1093/comjnl/9.4.373.
12. ^ Gronau, Ilan; Moran, Shlomo (2007), "Optimal implementations of UPGMA and other common clustering algorithms", Information Processing Letters 104 (6): 205–210, doi:10.1016/j.ipl.2007.07.002, MR 2353367.
13. ^ Gower, J. C.; Ross, G. J. S. (1969), "Minimum spanning trees and single linkage cluster analysis", Journal of the Royal Statistical Society, Series C 18 (1): 54–64, JSTOR 2346439, MR 0242315.
14. ^ Müllner, Daniel (2011), Modern hierarchical, agglomerative clustering algorithms, arXiv:1109.2378v1.