# Detecting exact nearest neighbors

Aaron Lun1

1Cancer Research UK Cambridge Institute, Cambridge, United Kingdom

#### Revised: 2 December 2018

#### Package

BiocNeighbors 1.6.0

# 1 Introduction

The BiocNeighbors package implements a few algorithms for exact nearest neighbor searching:

- The k-means for k-nearest neighbors (KMKNN) algorithm (Wang 2012) uses k-means clustering to create an index. Within each cluster, the distance of each of that cluster’s points to the cluster center are computed and used to sort all points. Given a query point, the distance to each cluster center is determined and the triangle inequality is applied to determine which points in each cluster warrant a full distance calculation.
- The vantage point (VP) tree algorithm (Yianilos 1993) involves constructing a tree where each node is located at a data point and is associated with a subset of neighboring points. Each node progressively partitions points into two subsets that are either closer or further to the node than a given threshold. Given a query point, the triangle inequality is applied at each node in the tree to determine if the child nodes warrant searching.
- The exhaustive search is a simple brute-force algorithm that computes distances to between all data and query points. This has the worst computational complexity but can actually be faster than the other exact algorithms in situations where indexing provides little benefit, e.g., data sets with few points and/or a very large number of dimensions.

Both KMKNN and VP-trees involve a component of randomness during index construction, though the k-nearest neighbors result is fully deterministic1 1 1 Except in the presence of ties, see `?"BiocNeighbors-ties"` for details..

# 2 Identifying k-nearest neighbors

The most obvious application is to perform a k-nearest neighbors search. We’ll mock up an example here with a hypercube of points, for which we want to identify the 10 nearest neighbors for each point.

    nobs <- 10000
    ndim <- 20
    data <- matrix(runif(nobs*ndim), ncol=ndim)

The `findKNN()` method expects a numeric matrix as input with data points as the rows and variables/dimensions as the columns. We indicate that we want to use the KMKNN algorithm by setting `BNPARAM=KmknnParam()` (which is also the default, so this is not strictly necessary here). We could use a VP tree instead by setting `BNPARAM=VptreeParam()`.

    fout <- findKNN(data, k=10, BNPARAM=KmknnParam())
    head(fout$index)

    ##      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
    ## [1,] 7704 3812 2732 7485 9026 7950 4844 5782 2418  4552
    ## [2,] 2418 9044 3101   93 5548 9062 3988 6713 3220  2496
    ## [3,] 7513  513 3319 9183 3835 3812 2764 8987 4980   518
    ## [4,] 5381 7279 5268 1546 7344 8763 7962 4115 4572  9932
    ## [5,] 4317 5753 2682 4857 2385 7040 3849 7183 6195  8891
    ## [6,] 4686 4182 1894 1731 1182 6481 8799 4026 5237  3372

    head(fout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
    ## [1,] 0.9220449 0.9323551 0.9526357 0.9935758 1.0423888 1.0827256 1.0837365
    ## [2,] 0.9777124 0.9995806 1.0613944 1.0636746 1.0875799 1.0893438 1.1183661
    ## [3,] 0.8513908 0.9472697 0.9604440 0.9906484 1.0220802 1.0450553 1.0458348
    ## [4,] 0.9359031 1.0011259 1.0467141 1.0954113 1.1127008 1.1221098 1.1290555
    ## [5,] 0.9343316 1.0413058 1.0534356 1.0608078 1.0875907 1.0893875 1.0909580
    ## [6,] 0.8509972 0.8588191 0.8900524 0.9137953 0.9148286 0.9524322 0.9597217
    ##           [,8]      [,9]     [,10]
    ## [1,] 1.0925151 1.1072296 1.1072813
    ## [2,] 1.1250463 1.1308155 1.1424698
    ## [3,] 1.0664560 1.0772833 1.0913108
    ## [4,] 1.1365076 1.1368529 1.1413779
    ## [5,] 1.1038071 1.1138966 1.1193266
    ## [6,] 0.9667839 0.9755881 0.9838134

Each row of the `index` matrix corresponds to a point in `data` and contains the row indices in `data` that are its nearest neighbors. For example, the 3rd point in `data` has the following nearest neighbors:

    fout$index[3,]

    ##  [1] 7513  513 3319 9183 3835 3812 2764 8987 4980  518

… with the following distances to those neighbors:

    fout$distance[3,]

    ##  [1] 0.8513908 0.9472697 0.9604440 0.9906484 1.0220802 1.0450553 1.0458348
    ##  [8] 1.0664560 1.0772833 1.0913108

Note that the reported neighbors are sorted by distance.

# 3 Querying k-nearest neighbors

Another application is to identify the k-nearest neighbors in one dataset based on query points in another dataset. Again, we mock up a small data set:

    nquery <- 1000
    ndim <- 20
    query <- matrix(runif(nquery*ndim), ncol=ndim)

We then use the `queryKNN()` function to identify the 5 nearest neighbors in `data` for each point in `query`.

    qout <- queryKNN(data, query, k=5, BNPARAM=KmknnParam())
    head(qout$index)

    ##      [,1] [,2] [,3] [,4] [,5]
    ## [1,] 7898 8113 9663 8018 7594
    ## [2,] 6973 4519  400 2447 7474
    ## [3,]  520 7616 2133 2525 2753
    ## [4,] 5422 1834 5114 1444 8955
    ## [5,]  780  235 1702 7149 2736
    ## [6,] 6699 4654 7701  935 1394

    head(qout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]
    ## [1,] 0.7462425 0.8220431 0.8632926 0.9006545 0.9051815
    ## [2,] 0.8322732 0.9209732 0.9851134 1.0015805 1.0094636
    ## [3,] 1.0278264 1.1017083 1.1100442 1.1243124 1.1349793
    ## [4,] 0.8456185 0.9392159 0.9449050 0.9651462 0.9731684
    ## [5,] 0.9456846 0.9696223 1.0008496 1.0189542 1.0310230
    ## [6,] 0.7670822 0.8415293 0.9008054 0.9515454 0.9575494

Each row of the `index` matrix contains the row indices in `data` that are the nearest neighbors of a point in `query`. For example, the 3rd point in `query` has the following nearest neighbors in `data`:

    qout$index[3,]

    ## [1]  520 7616 2133 2525 2753

… with the following distances to those neighbors:

    qout$distance[3,]

    ## [1] 1.027826 1.101708 1.110044 1.124312 1.134979

Again, the reported neighbors are sorted by distance.

# 4 Further options

Users can perform the search for a subset of query points using the `subset=` argument. This yields the same result as but is more efficient than performing the search for all points and subsetting the output.

    findKNN(data, k=5, subset=3:5)

    ## $index
    ##      [,1] [,2] [,3] [,4] [,5]
    ## [1,] 7513  513 3319 9183 3835
    ## [2,] 5381 7279 5268 1546 7344
    ## [3,] 4317 5753 2682 4857 2385
    ##
    ## $distance
    ##           [,1]      [,2]     [,3]      [,4]     [,5]
    ## [1,] 0.8513908 0.9472697 0.960444 0.9906484 1.022080
    ## [2,] 0.9359031 1.0011259 1.046714 1.0954113 1.112701
    ## [3,] 0.9343316 1.0413058 1.053436 1.0608078 1.087591

If only the indices are of interest, users can set `get.distance=FALSE` to avoid returning the matrix of distances. This will save some time and memory.

    names(findKNN(data, k=2, get.distance=FALSE))

    ## [1] "index"

It is also simple to speed up functions by parallelizing the calculations with the BiocParallel framework.

    library(BiocParallel)
    out <- findKNN(data, k=10, BPPARAM=MulticoreParam(3))

For multiple queries to a constant `data`, the pre-clustering can be performed in a separate step with `buildIndex()`. The result can then be passed to multiple calls, avoiding the overhead of repeated clustering2 2 2 The algorithm type is automatically determined when `BNINDEX` is specified, so there is no need to also specify `BNPARAM` in the later functions..

    pre <- buildIndex(data, BNPARAM=KmknnParam())
    out1 <- findKNN(BNINDEX=pre, k=5)
    out2 <- queryKNN(BNINDEX=pre, query=query, k=2)

The default setting is to search on the Euclidean distance. Alternatively, we can use the Manhattan distance by setting `distance="Manhattan"` in the `BiocNeighborParam` object.

    out.m <- findKNN(data, k=5, BNPARAM=KmknnParam(distance="Manhattan"))

Advanced users may also be interested in the `raw.index=` argument, which returns indices directly to the precomputed object rather than to `data`. This may be useful inside package functions where it may be more convenient to work on a common precomputed object.

# 5 Session information

    sessionInfo()

    ## R version 4.0.0 (2020-04-24)
    ## Platform: x86_64-w64-mingw32/x64 (64-bit)
    ## Running under: Windows Server 2012 R2 x64 (build 9600)
    ##
    ## Matrix products: default
    ##
    ## locale:
    ## [1] LC_COLLATE=C
    ## [2] LC_CTYPE=English_United States.1252
    ## [3] LC_MONETARY=English_United States.1252
    ## [4] LC_NUMERIC=C
    ## [5] LC_TIME=English_United States.1252
    ##
    ## attached base packages:
    ## [1] stats     graphics  grDevices utils     datasets  methods   base
    ##
    ## other attached packages:
    ## [1] BiocParallel_1.22.0 BiocNeighbors_1.6.0 knitr_1.28
    ## [4] BiocStyle_2.16.0
    ##
    ## loaded via a namespace (and not attached):
    ##  [1] Rcpp_1.0.4.6        bookdown_0.18       lattice_0.20-41
    ##  [4] digest_0.6.25       grid_4.0.0          stats4_4.0.0
    ##  [7] magrittr_1.5        evaluate_0.14       rlang_0.4.5
    ## [10] stringi_1.4.6       S4Vectors_0.26.0    Matrix_1.2-18
    ## [13] rmarkdown_2.1       tools_4.0.0         stringr_1.4.0
    ## [16] parallel_4.0.0      xfun_0.13           yaml_2.2.1
    ## [19] compiler_4.0.0      BiocGenerics_0.34.0 BiocManager_1.30.10
    ## [22] htmltools_0.4.0

# References

Wang, X. 2012. “A Fast Exact k-Nearest Neighbors Algorithm for High Dimensional Search Using k-Means Clustering and Triangle Inequality.” Proc Int Jt Conf Neural Netw 43 (6): 2351–8.

Yianilos, P. N. 1993. “Data Structures and Algorithms for Nearest Neighbor Search in General Metric Spaces.” In SODA, 93:311–21. 194.