# Detecting exact nearest neighbors

Aaron Lun1

1Cancer Research UK Cambridge Institute, Cambridge, United Kingdom

#### Revised: 2 December 2018

#### Package

BiocNeighbors 1.12.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,] 6376 5655 8789 2884 8173 6531 1038 7075 2622  3493
    ## [2,] 5543 6891 7280 1807 1691 4152 6149 6613 6005  3809
    ## [3,]  119 7505 4095 7435 2593 2688  908 2713  772  4814
    ## [4,] 6432 4821 3759 3198 1076 6553 7299 8296 1237  4407
    ## [5,] 8904 8551 1528 5565 5081  871 6988 6029 1860  6476
    ## [6,] 1848 9915 9059 9741 9010 5212 8867 7621 8984  6957

    head(fout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
    ## [1,] 0.9243889 0.9848953 1.0219790 1.0732873 1.0868778 1.1085884 1.1114282
    ## [2,] 1.1191712 1.1218404 1.1238681 1.1353661 1.1451150 1.1494344 1.1621937
    ## [3,] 0.9386683 0.9491872 0.9500659 0.9584776 1.0038957 1.0267462 1.0552156
    ## [4,] 0.9681618 1.0537551 1.0897830 1.0927326 1.0954360 1.1006627 1.1143007
    ## [5,] 0.9596218 0.9932718 1.0292100 1.0330532 1.0681664 1.0738649 1.0822719
    ## [6,] 0.8826367 0.8973894 0.9404635 0.9416462 0.9603853 0.9629363 0.9759682
    ##           [,8]     [,9]     [,10]
    ## [1,] 1.1124150 1.125666 1.1294859
    ## [2,] 1.1752572 1.177070 1.1963665
    ## [3,] 1.0756586 1.080910 1.0840294
    ## [4,] 1.1397950 1.140270 1.1439324
    ## [5,] 1.0878632 1.093252 1.0933357
    ## [6,] 0.9814336 0.985373 0.9902231

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]  119 7505 4095 7435 2593 2688  908 2713  772 4814

… with the following distances to those neighbors:

    fout$distance[3,]

    ##  [1] 0.9386683 0.9491872 0.9500659 0.9584776 1.0038957 1.0267462 1.0552156
    ##  [8] 1.0756586 1.0809097 1.0840294

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,] 1748 8994 7249 2768 4758
    ## [2,] 1964 6480 9112 1668 2033
    ## [3,] 2236 9877  928 8725 8128
    ## [4,] 9677 9041 5008 8909 7911
    ## [5,] 8831 9633 8839 5333 7563
    ## [6,] 8816 2864 3116 8964 6395

    head(qout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]
    ## [1,] 0.9480799 0.9808689 1.0113758 1.0456527 1.0484075
    ## [2,] 0.9039989 0.9197544 0.9492677 0.9564467 0.9783050
    ## [3,] 1.0470039 1.1412584 1.1421082 1.1424069 1.1521030
    ## [4,] 0.9625051 0.9717488 0.9727653 0.9851508 0.9908694
    ## [5,] 0.9452778 0.9780741 0.9858953 1.0061163 1.0066444
    ## [6,] 1.0108080 1.0295477 1.0802086 1.0965559 1.1070152

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] 2236 9877  928 8725 8128

… with the following distances to those neighbors:

    qout$distance[3,]

    ## [1] 1.047004 1.141258 1.142108 1.142407 1.152103

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,]  119 7505 4095 7435 2593
    ## [2,] 6432 4821 3759 3198 1076
    ## [3,] 8904 8551 1528 5565 5081
    ##
    ## $distance
    ##           [,1]      [,2]      [,3]      [,4]     [,5]
    ## [1,] 0.9386683 0.9491872 0.9500659 0.9584776 1.003896
    ## [2,] 0.9681618 1.0537551 1.0897830 1.0927326 1.095436
    ## [3,] 0.9596218 0.9932718 1.0292100 1.0330532 1.068166

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.1.1 (2021-08-10)
    ## Platform: x86_64-pc-linux-gnu (64-bit)
    ## Running under: Ubuntu 20.04.3 LTS
    ##
    ## Matrix products: default
    ## BLAS:   /home/biocbuild/bbs-3.14-bioc/R/lib/libRblas.so
    ## LAPACK: /home/biocbuild/bbs-3.14-bioc/R/lib/libRlapack.so
    ##
    ## locale:
    ##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C
    ##  [3] LC_TIME=en_GB              LC_COLLATE=C
    ##  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8
    ##  [7] LC_PAPER=en_US.UTF-8       LC_NAME=C
    ##  [9] LC_ADDRESS=C               LC_TELEPHONE=C
    ## [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
    ##
    ## attached base packages:
    ## [1] stats     graphics  grDevices utils     datasets  methods   base
    ##
    ## other attached packages:
    ## [1] BiocParallel_1.28.0  BiocNeighbors_1.12.0 knitr_1.36
    ## [4] BiocStyle_2.22.0
    ##
    ## loaded via a namespace (and not attached):
    ##  [1] Rcpp_1.0.7          magrittr_2.0.1      BiocGenerics_0.40.0
    ##  [4] lattice_0.20-45     R6_2.5.1            rlang_0.4.12
    ##  [7] fastmap_1.1.0       stringr_1.4.0       tools_4.1.1
    ## [10] parallel_4.1.1      grid_4.1.1          xfun_0.27
    ## [13] jquerylib_0.1.4     htmltools_0.5.2     yaml_2.2.1
    ## [16] digest_0.6.28       bookdown_0.24       Matrix_1.3-4
    ## [19] BiocManager_1.30.16 S4Vectors_0.32.0    sass_0.4.0
    ## [22] evaluate_0.14       rmarkdown_2.11      stringi_1.7.5
    ## [25] compiler_4.1.1      bslib_0.3.1         stats4_4.1.1
    ## [28] jsonlite_1.7.2

# 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.