# Detecting exact nearest neighbors

Aaron Lun1

1Cancer Research UK Cambridge Institute, Cambridge, United Kingdom

#### Revised: 2 December 2018

#### Package

BiocNeighbors 1.22.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,] 4507 1085  500  227  478 9802 1730 5746 1100   628
    ## [2,] 2589 4533 9240  524 7720 8177 8831 6667 8700   441
    ## [3,] 5109  430 6499 4465 6993 7202 2372 3516 1789  9239
    ## [4,] 3904 2818  128 7977 4060 9920 2256 7755  624  5406
    ## [5,] 7731 3973 8541 1184  964 5974 8372 6989 1335  4491
    ## [6,] 7888 3784 9091 2303 9660 2874 7292  745 7267  3494

    head(fout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
    ## [1,] 0.9767670 0.9841882 1.0020700 1.0033059 1.0287915 1.0390664 1.0491234
    ## [2,] 0.6838043 0.8183776 0.9562435 0.9594600 0.9716077 0.9759345 0.9841573
    ## [3,] 0.8404967 0.8683284 0.8735712 0.9223438 0.9257924 0.9333166 0.9440326
    ## [4,] 0.9675290 0.9999831 1.0056546 1.0235907 1.0333157 1.0700736 1.0824257
    ## [5,] 0.8031319 0.9724362 1.0108992 1.0159501 1.0278135 1.1077578 1.1172013
    ## [6,] 0.8002232 0.8482672 0.9253086 0.9382818 0.9492094 0.9533863 0.9706040
    ##           [,8]      [,9]     [,10]
    ## [1,] 1.0506659 1.0521176 1.0873076
    ## [2,] 0.9917927 0.9940748 1.0001611
    ## [3,] 0.9573487 0.9593465 0.9674145
    ## [4,] 1.0904314 1.0919558 1.0949146
    ## [5,] 1.1246821 1.1466751 1.1578654
    ## [6,] 0.9899207 0.9917975 1.0146288

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] 5109  430 6499 4465 6993 7202 2372 3516 1789 9239

… with the following distances to those neighbors:

    fout$distance[3,]

    ##  [1] 0.8404967 0.8683284 0.8735712 0.9223438 0.9257924 0.9333166 0.9440326
    ##  [8] 0.9573487 0.9593465 0.9674145

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,] 4421 3516 4885 9301 5776
    ## [2,] 1962 5017 1251 2981 2270
    ## [3,] 4421 1730 1001 6351 5218
    ## [4,] 8877 8182 4092 2033 3259
    ## [5,] 1085 3952 8868 5961 6264
    ## [6,] 7374 7138 4528 7894   18

    head(qout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]
    ## [1,] 0.9262715 0.9584064 0.9716758 0.9747832 0.9791279
    ## [2,] 0.8242135 0.9540551 0.9812614 0.9922348 1.0075502
    ## [3,] 0.8064825 0.8364945 0.8414388 0.8616491 0.9092441
    ## [4,] 0.8058215 0.8446077 0.8871687 0.8954431 0.9501778
    ## [5,] 0.9360906 0.9521199 0.9624938 0.9758149 0.9890881
    ## [6,] 0.9591010 0.9849566 1.0226872 1.0360835 1.0381943

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] 4421 1730 1001 6351 5218

… with the following distances to those neighbors:

    qout$distance[3,]

    ## [1] 0.8064825 0.8364945 0.8414388 0.8616491 0.9092441

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,] 5109  430 6499 4465 6993
    ## [2,] 3904 2818  128 7977 4060
    ## [3,] 7731 3973 8541 1184  964
    ##
    ## $distance
    ##           [,1]      [,2]      [,3]      [,4]      [,5]
    ## [1,] 0.8404967 0.8683284 0.8735712 0.9223438 0.9257924
    ## [2,] 0.9675290 0.9999831 1.0056546 1.0235907 1.0333157
    ## [3,] 0.8031319 0.9724362 1.0108992 1.0159501 1.0278135

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.4.0 beta (2024-04-15 r86425)
    ## Platform: x86_64-pc-linux-gnu
    ## Running under: Ubuntu 22.04.4 LTS
    ##
    ## Matrix products: default
    ## BLAS:   /home/biocbuild/bbs-3.19-bioc/R/lib/libRblas.so
    ## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.10.0
    ##
    ## locale:
    ##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C
    ##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8
    ##  [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
    ##
    ## time zone: America/New_York
    ## tzcode source: system (glibc)
    ##
    ## attached base packages:
    ## [1] stats     graphics  grDevices utils     datasets  methods   base
    ##
    ## other attached packages:
    ## [1] BiocParallel_1.38.0  BiocNeighbors_1.22.0 knitr_1.46
    ## [4] BiocStyle_2.32.0
    ##
    ## loaded via a namespace (and not attached):
    ##  [1] cli_3.6.2           rlang_1.1.3         xfun_0.43
    ##  [4] jsonlite_1.8.8      S4Vectors_0.42.0    htmltools_0.5.8.1
    ##  [7] stats4_4.4.0        sass_0.4.9          rmarkdown_2.26
    ## [10] grid_4.4.0          evaluate_0.23       jquerylib_0.1.4
    ## [13] fastmap_1.1.1       yaml_2.3.8          lifecycle_1.0.4
    ## [16] bookdown_0.39       BiocManager_1.30.22 compiler_4.4.0
    ## [19] codetools_0.2-20    Rcpp_1.0.12         lattice_0.22-6
    ## [22] digest_0.6.35       R6_2.5.1            parallel_4.4.0
    ## [25] bslib_0.7.0         Matrix_1.7-0        tools_4.4.0
    ## [28] BiocGenerics_0.50.0 cachem_1.0.8

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