# Detecting exact nearest neighbors

Aaron Lun1

1Cancer Research UK Cambridge Institute, Cambridge, United Kingdom

#### Revised: 2 December 2018

#### Package

BiocNeighbors 1.10.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,] 7099 6200 6485 6893 9566 1376 7958  549 1537  1004
    ## [2,] 6936 4179 6137 6017 7734 9695  230 3106 6858  8956
    ## [3,]  248 2387 3544 2209 5215 4001 6934 6721 7898  3241
    ## [4,] 6424  641 3170 5808 2430 2729 8751 3399 3651  2834
    ## [5,] 5668 9722  337 4637 1921 8452 8644 5026 5484  9431
    ## [6,] 6059  678 2246 1047  791 2869 8134 2848 2706  6974

    head(fout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
    ## [1,] 0.8879002 0.9122381 0.9154213 0.9255397 0.9335748 0.9506347 0.9537064
    ## [2,] 0.9010761 0.9980604 1.0274427 1.0387540 1.0417325 1.0446863 1.0620324
    ## [3,] 0.8776323 0.9098536 0.9763203 0.9881648 1.0064094 1.0116512 1.0148250
    ## [4,] 0.7958431 0.9037620 0.9277526 0.9330558 0.9330847 0.9353315 0.9427484
    ## [5,] 0.9621558 0.9621896 0.9777817 0.9847706 1.0280363 1.0352073 1.0369808
    ## [6,] 0.9077439 0.9254729 0.9847225 0.9933598 1.0003513 1.0053419 1.0331628
    ##           [,8]      [,9]     [,10]
    ## [1,] 0.9611631 0.9704880 0.9842655
    ## [2,] 1.0623869 1.0641231 1.0647031
    ## [3,] 1.0288918 1.0377311 1.0486898
    ## [4,] 0.9465238 0.9575306 0.9593012
    ## [5,] 1.0377079 1.0451699 1.0767352
    ## [6,] 1.0441608 1.0489526 1.0640462

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]  248 2387 3544 2209 5215 4001 6934 6721 7898 3241

… with the following distances to those neighbors:

    fout$distance[3,]

    ##  [1] 0.8776323 0.9098536 0.9763203 0.9881648 1.0064094 1.0116512 1.0148250
    ##  [8] 1.0288918 1.0377311 1.0486898

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,] 3931 5577 5677 9840 1850
    ## [2,] 5515 2337 4938 8714 7807
    ## [3,]  174 7374  715 5501 7084
    ## [4,] 5597 3619 3950 4720 9437
    ## [5,] 1578 6238 6819 2180 7274
    ## [6,] 6742 2874 9497 5657 6536

    head(qout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]
    ## [1,] 1.0199987 1.0376850 1.0826383 1.1128773 1.1222347
    ## [2,] 0.8533508 0.8911792 0.9712616 0.9755471 1.0036667
    ## [3,] 0.9105697 0.9430303 0.9549132 0.9844046 0.9863771
    ## [4,] 0.9818129 0.9857438 1.0347501 1.0629480 1.0629703
    ## [5,] 0.8306203 0.9305679 0.9624847 0.9669547 1.0193001
    ## [6,] 0.8811809 0.9762420 0.9881336 0.9966026 0.9966967

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]  174 7374  715 5501 7084

… with the following distances to those neighbors:

    qout$distance[3,]

    ## [1] 0.9105697 0.9430303 0.9549132 0.9844046 0.9863771

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,]  248 2387 3544 2209 5215
    ## [2,] 6424  641 3170 5808 2430
    ## [3,] 5668 9722  337 4637 1921
    ##
    ## $distance
    ##           [,1]      [,2]      [,3]      [,4]      [,5]
    ## [1,] 0.8776323 0.9098536 0.9763203 0.9881648 1.0064094
    ## [2,] 0.7958431 0.9037620 0.9277526 0.9330558 0.9330847
    ## [3,] 0.9621558 0.9621896 0.9777817 0.9847706 1.0280363

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.0 RC (2021-05-10 r80283)
    ## Platform: x86_64-apple-darwin17.0 (64-bit)
    ## Running under: macOS Mojave 10.14.6
    ##
    ## Matrix products: default
    ## BLAS:   /Library/Frameworks/R.framework/Versions/4.1/Resources/lib/libRblas.dylib
    ## LAPACK: /Library/Frameworks/R.framework/Versions/4.1/Resources/lib/libRlapack.dylib
    ##
    ## locale:
    ## [1] C/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
    ##
    ## attached base packages:
    ## [1] stats     graphics  grDevices utils     datasets  methods   base
    ##
    ## other attached packages:
    ## [1] BiocParallel_1.26.0  BiocNeighbors_1.10.0 knitr_1.33
    ## [4] BiocStyle_2.20.0
    ##
    ## loaded via a namespace (and not attached):
    ##  [1] Rcpp_1.0.6          magrittr_2.0.1      BiocGenerics_0.38.0
    ##  [4] lattice_0.20-44     R6_2.5.0            rlang_0.4.11
    ##  [7] stringr_1.4.0       tools_4.1.0         parallel_4.1.0
    ## [10] grid_4.1.0          xfun_0.23           jquerylib_0.1.4
    ## [13] htmltools_0.5.1.1   yaml_2.2.1          digest_0.6.27
    ## [16] bookdown_0.22       Matrix_1.3-3        BiocManager_1.30.15
    ## [19] S4Vectors_0.30.0    sass_0.4.0          evaluate_0.14
    ## [22] rmarkdown_2.8       stringi_1.6.2       compiler_4.1.0
    ## [25] bslib_0.2.5.1       stats4_4.1.0        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.