# Detecting exact nearest neighbors

Aaron Lun1

1Cancer Research UK Cambridge Institute, Cambridge, United Kingdom

#### Revised: 2 December 2018

#### Package

BiocNeighbors 1.16.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,]  717 5496 3565 8997 7322  866 4694 2917 3343  6072
    ## [2,] 1853 3527 5796  790 9964 8919 4410 7172 7672  8837
    ## [3,] 4700 8828 3653 4087 4599 7992 3385 7156 4363  4785
    ## [4,] 6406 8363 1675 9586 1425 4676 5775 9240 9710  5488
    ## [5,] 5739 6973 1454 6377 5065 5883 3622 2642 1627  6345
    ## [6,] 9150  432 7032 4270 5856  291 6420 2732 2673  1429

    head(fout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
    ## [1,] 1.0786411 1.0935873 1.1091675 1.1110469 1.1135933 1.1282774 1.1372475
    ## [2,] 0.9813525 1.0827709 1.0910177 1.1131309 1.1348132 1.1391874 1.1529560
    ## [3,] 0.8852510 0.9270202 0.9349374 0.9863894 0.9865515 0.9885502 1.0247215
    ## [4,] 0.8541885 0.9425756 0.9639482 0.9666795 0.9863081 1.0008632 1.0195524
    ## [5,] 0.7791659 0.8932182 0.9575628 0.9940821 1.0036101 1.0358600 1.0452221
    ## [6,] 0.8065253 0.8381450 0.8574622 0.8711766 0.8881060 0.9022264 0.9250125
    ##           [,8]      [,9]     [,10]
    ## [1,] 1.1439494 1.1440076 1.1514502
    ## [2,] 1.1562024 1.1569880 1.1654826
    ## [3,] 1.0308652 1.0315084 1.0323486
    ## [4,] 1.0379479 1.0419155 1.0497176
    ## [5,] 1.0516996 1.0558903 1.0571575
    ## [6,] 0.9367332 0.9618553 0.9633797

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] 4700 8828 3653 4087 4599 7992 3385 7156 4363 4785

… with the following distances to those neighbors:

    fout$distance[3,]

    ##  [1] 0.8852510 0.9270202 0.9349374 0.9863894 0.9865515 0.9885502 1.0247215
    ##  [8] 1.0308652 1.0315084 1.0323486

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,] 7459 4411 8165 5320 2984
    ## [2,]   39 1469  772 5990 5448
    ## [3,] 7979 4022 7683 1120 6510
    ## [4,] 2554 9370 8031 9103 1448
    ## [5,] 9713 6659 3394 7012  499
    ## [6,] 8299 7001  241 9121 2402

    head(qout$distance)

    ##           [,1]      [,2]      [,3]      [,4]     [,5]
    ## [1,] 0.9477588 0.9632012 1.0194776 1.0381358 1.062561
    ## [2,] 0.9175062 0.9570939 0.9703075 0.9707472 1.014997
    ## [3,] 0.9670374 0.9827063 0.9945135 1.0007530 1.019716
    ## [4,] 0.9760775 0.9784902 1.0200073 1.0330013 1.046844
    ## [5,] 0.8773103 0.9597151 1.0116841 1.0118393 1.036191
    ## [6,] 0.9351569 0.9700087 1.0046291 1.0344532 1.049225

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] 7979 4022 7683 1120 6510

… with the following distances to those neighbors:

    qout$distance[3,]

    ## [1] 0.9670374 0.9827063 0.9945135 1.0007530 1.0197165

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,] 4700 8828 3653 4087 4599
    ## [2,] 6406 8363 1675 9586 1425
    ## [3,] 5739 6973 1454 6377 5065
    ##
    ## $distance
    ##           [,1]      [,2]      [,3]      [,4]      [,5]
    ## [1,] 0.8852510 0.9270202 0.9349374 0.9863894 0.9865515
    ## [2,] 0.8541885 0.9425756 0.9639482 0.9666795 0.9863081
    ## [3,] 0.7791659 0.8932182 0.9575628 0.9940821 1.0036101

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.2.1 (2022-06-23)
    ## Platform: x86_64-pc-linux-gnu (64-bit)
    ## Running under: Ubuntu 20.04.5 LTS
    ##
    ## Matrix products: default
    ## BLAS:   /home/biocbuild/bbs-3.16-bioc/R/lib/libRblas.so
    ## LAPACK: /home/biocbuild/bbs-3.16-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.32.0  BiocNeighbors_1.16.0 knitr_1.40
    ## [4] BiocStyle_2.26.0
    ##
    ## loaded via a namespace (and not attached):
    ##  [1] Rcpp_1.0.9          magrittr_2.0.3      BiocGenerics_0.44.0
    ##  [4] lattice_0.20-45     R6_2.5.1            rlang_1.0.6
    ##  [7] fastmap_1.1.0       stringr_1.4.1       tools_4.2.1
    ## [10] parallel_4.2.1      grid_4.2.1          xfun_0.34
    ## [13] cli_3.4.1           jquerylib_0.1.4     htmltools_0.5.3
    ## [16] yaml_2.3.6          digest_0.6.30       bookdown_0.29
    ## [19] Matrix_1.5-1        BiocManager_1.30.19 S4Vectors_0.36.0
    ## [22] sass_0.4.2          codetools_0.2-18    cachem_1.0.6
    ## [25] evaluate_0.17       rmarkdown_2.17      stringi_1.7.8
    ## [28] compiler_4.2.1      bslib_0.4.0         stats4_4.2.1
    ## [31] jsonlite_1.8.3

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