# Detecting exact nearest neighbors

Aaron Lun1

1Cancer Research UK Cambridge Institute, Cambridge, United Kingdom

#### Revised: 2 December 2018

#### Package

BiocNeighbors 1.20.1

# 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 deterministic11 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,]  215 4869 1671 8516 2223 4847 2849 3539 6404  1723
    ## [2,] 1370 5481 2139 6450 5206 1401 8662 9263 5423  5404
    ## [3,] 9153 9708 9967 6620 9077 1289  750 9512 3120  1773
    ## [4,] 5172  393 3072 2418 8917 6265 6345 3287 6112  4873
    ## [5,] 8296   31 9918  999 6239 3744 6286  743 8872  3950
    ## [6,] 3779 5647 9914 6944 4968 9574 1901 9654 3572  1151

    head(fout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]     [,6]     [,7]
    ## [1,] 0.9960013 1.0243851 1.0488344 1.0599886 1.0741515 1.101224 1.113522
    ## [2,] 1.0267251 1.0665891 1.0689259 1.0878683 1.1056311 1.111385 1.111674
    ## [3,] 0.9276706 0.9343985 0.9356513 0.9637536 1.0519104 1.059307 1.070900
    ## [4,] 0.8331970 0.9006124 0.9730938 0.9887161 1.0245950 1.031027 1.037998
    ## [5,] 0.8358488 0.9577742 0.9985025 1.0010155 1.0260831 1.055337 1.064033
    ## [6,] 0.8918223 0.9559115 0.9602496 0.9720945 0.9879264 1.013817 1.018813
    ##          [,8]     [,9]    [,10]
    ## [1,] 1.115204 1.123202 1.125723
    ## [2,] 1.122955 1.123371 1.129597
    ## [3,] 1.073773 1.077813 1.077898
    ## [4,] 1.050551 1.053290 1.053748
    ## [5,] 1.064381 1.066609 1.066986
    ## [6,] 1.032807 1.045535 1.051594

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] 9153 9708 9967 6620 9077 1289  750 9512 3120 1773

… with the following distances to those neighbors:

    fout$distance[3,]

    ##  [1] 0.9276706 0.9343985 0.9356513 0.9637536 1.0519104 1.0593071 1.0708998
    ##  [8] 1.0737726 1.0778131 1.0778981

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,] 3312 1272  550 1413 1860
    ## [2,] 2201 1835 9311 2351  679
    ## [3,]  181 9393 6718 9267  652
    ## [4,]  983 3779 3454 7758  755
    ## [5,] 6206 6997 6349 3026 4150
    ## [6,]  550 3909 9592 4412 2373

    head(qout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]
    ## [1,] 0.9256829 0.9329185 0.9370799 0.9428395 0.9468555
    ## [2,] 1.1213506 1.1351115 1.1472850 1.1570469 1.1809814
    ## [3,] 0.9454082 0.9683747 1.0147419 1.0253117 1.0294208
    ## [4,] 0.7713852 0.8660857 0.9441982 0.9496934 0.9758834
    ## [5,] 0.6843861 0.8097158 0.8875205 0.9129252 0.9228417
    ## [6,] 0.8673658 0.9013602 0.9284009 0.9317994 0.9616679

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]  181 9393 6718 9267  652

… with the following distances to those neighbors:

    qout$distance[3,]

    ## [1] 0.9454082 0.9683747 1.0147419 1.0253117 1.0294208

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,] 9153 9708 9967 6620 9077
    ## [2,] 5172  393 3072 2418 8917
    ## [3,] 8296   31 9918  999 6239
    ##
    ## $distance
    ##           [,1]      [,2]      [,3]      [,4]     [,5]
    ## [1,] 0.9276706 0.9343985 0.9356513 0.9637536 1.051910
    ## [2,] 0.8331970 0.9006124 0.9730938 0.9887161 1.024595
    ## [3,] 0.8358488 0.9577742 0.9985025 1.0010155 1.026083

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 clustering22 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.3.2 Patched (2023-11-13 r85521)
    ## Platform: x86_64-pc-linux-gnu (64-bit)
    ## Running under: Ubuntu 22.04.3 LTS
    ##
    ## Matrix products: default
    ## BLAS:   /home/biocbuild/bbs-3.18-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_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
    ##
    ## 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.36.0  BiocNeighbors_1.20.1 knitr_1.45
    ## [4] BiocStyle_2.30.0
    ##
    ## loaded via a namespace (and not attached):
    ##  [1] cli_3.6.2           rlang_1.1.2         xfun_0.41
    ##  [4] jsonlite_1.8.8      S4Vectors_0.40.2    htmltools_0.5.7
    ##  [7] stats4_4.3.2        sass_0.4.8          rmarkdown_2.25
    ## [10] grid_4.3.2          evaluate_0.23       jquerylib_0.1.4
    ## [13] fastmap_1.1.1       yaml_2.3.8          lifecycle_1.0.4
    ## [16] bookdown_0.37       BiocManager_1.30.22 compiler_4.3.2
    ## [19] codetools_0.2-19    Rcpp_1.0.11         lattice_0.22-5
    ## [22] digest_0.6.33       R6_2.5.1            parallel_4.3.2
    ## [25] bslib_0.6.1         Matrix_1.6-4        tools_4.3.2
    ## [28] BiocGenerics_0.48.1 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.