# Detecting exact nearest neighbors

Aaron Lun1

1Cancer Research UK Cambridge Institute, Cambridge, United Kingdom

#### Revised: 2 December 2018

#### Package

BiocNeighbors 1.20.2

# 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,] 8648 3403 9587 9856 8347 4923 8439 2717 5680  3017
    ## [2,]  341 2946  737 6861 1266  649 7155 4948 3063  9328
    ## [3,] 5783 9765 8729 7708 3557 7429 8719 3509 1711  4166
    ## [4,] 4768 2300 7854 5113 5835 4241 7224 7916 6560  7943
    ## [5,] 4576 1901  122 8942 4211 6472 3219 7564 7581  5630
    ## [6,] 3614 6685 2227 9851 5468 5978 2996 8764 3429   652

    head(fout$distance)

    ##           [,1]      [,2]      [,3]      [,4]     [,5]     [,6]     [,7]
    ## [1,] 1.0955693 1.1006748 1.1077726 1.1306102 1.174067 1.182095 1.185080
    ## [2,] 0.8963155 0.9499747 1.0022128 1.0181016 1.045598 1.072784 1.074155
    ## [3,] 0.9772201 1.0057017 1.0115326 1.0144610 1.055065 1.071111 1.084398
    ## [4,] 0.7622648 0.8706268 1.0111896 1.0557318 1.071940 1.088337 1.089277
    ## [5,] 0.9283290 0.9531832 0.9543699 0.9677348 0.995645 1.009040 1.015632
    ## [6,] 0.9575726 0.9625094 1.0186951 1.0382929 1.038856 1.048379 1.092952
    ##          [,8]     [,9]    [,10]
    ## [1,] 1.186036 1.201084 1.202276
    ## [2,] 1.096950 1.099842 1.100999
    ## [3,] 1.087002 1.088070 1.100486
    ## [4,] 1.105960 1.109070 1.111835
    ## [5,] 1.026205 1.061772 1.062092
    ## [6,] 1.109523 1.113839 1.113948

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] 5783 9765 8729 7708 3557 7429 8719 3509 1711 4166

… with the following distances to those neighbors:

    fout$distance[3,]

    ##  [1] 0.9772201 1.0057017 1.0115326 1.0144610 1.0550655 1.0711108 1.0843979
    ##  [8] 1.0870022 1.0880698 1.1004858

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,] 9677  541 3095 8025 4879
    ## [2,]  167 3148  772 5658 4246
    ## [3,] 6752 1721 7077 1101 5870
    ## [4,] 1085  680  823 8071 6541
    ## [5,] 3193 3301 1215 8314  851
    ## [6,]  461 9986  159 3785 9099

    head(qout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]
    ## [1,] 0.9112850 1.0572266 1.0722184 1.0902098 1.1026161
    ## [2,] 0.9207526 0.9306469 0.9752983 0.9834459 0.9868368
    ## [3,] 1.0149953 1.0370714 1.0637588 1.0791699 1.0938808
    ## [4,] 0.9058743 0.9068883 0.9217502 0.9324731 0.9509409
    ## [5,] 0.9615728 0.9758282 0.9840506 1.0476025 1.0478317
    ## [6,] 0.7720508 0.8250797 0.8643901 0.9474590 0.9912357

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] 6752 1721 7077 1101 5870

… with the following distances to those neighbors:

    qout$distance[3,]

    ## [1] 1.014995 1.037071 1.063759 1.079170 1.093881

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,] 5783 9765 8729 7708 3557
    ## [2,] 4768 2300 7854 5113 5835
    ## [3,] 4576 1901  122 8942 4211
    ##
    ## $distance
    ##           [,1]      [,2]      [,3]      [,4]     [,5]
    ## [1,] 0.9772201 1.0057017 1.0115326 1.0144610 1.055065
    ## [2,] 0.7622648 0.8706268 1.0111896 1.0557318 1.071940
    ## [3,] 0.9283290 0.9531832 0.9543699 0.9677348 0.995645

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