# Detecting exact nearest neighbors

Aaron Lun1

1Cancer Research UK Cambridge Institute, Cambridge, United Kingdom

#### Revised: 2 December 2018

#### Package

BiocNeighbors 1.8.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 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,] 6103 8528 1292 4561 2182 4378 7264 3345 7483  5964
    ## [2,] 8948 9335 2489 5325 9012 5484 9399 8309 1802  6803
    ## [3,] 4828 1437 2609 6206 4510 6989 9060  522 9075  2880
    ## [4,] 9733 8882 4534 3851  197 9159 8178 6415 8256  3700
    ## [5,] 9465 5011 7034 4398 7857 6325  578 1150  106  1050
    ## [6,] 2774 6292 2180 8667 7961 1130 3085 8737 2654  4246

    head(fout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
    ## [1,] 0.9103647 0.9361689 0.9717628 1.0335159 1.0337317 1.0425594 1.0441994
    ## [2,] 0.9042676 0.9223158 0.9576286 0.9702274 0.9753036 0.9953621 0.9986536
    ## [3,] 1.0031695 1.0207397 1.0856244 1.0941237 1.1359445 1.1422915 1.1590551
    ## [4,] 0.8973770 1.0187309 1.0491946 1.0502620 1.0554495 1.0647645 1.0762483
    ## [5,] 0.8625907 1.0215347 1.0470398 1.0554959 1.0633966 1.0772213 1.0844264
    ## [6,] 0.9662761 1.0399201 1.0611860 1.0676490 1.0718437 1.0753005 1.0813390
    ##          [,8]     [,9]    [,10]
    ## [1,] 1.068581 1.073286 1.075732
    ## [2,] 1.048339 1.067277 1.070248
    ## [3,] 1.167019 1.167830 1.171124
    ## [4,] 1.090760 1.106904 1.120498
    ## [5,] 1.086713 1.090671 1.091018
    ## [6,] 1.103183 1.120599 1.139403

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] 4828 1437 2609 6206 4510 6989 9060  522 9075 2880

… with the following distances to those neighbors:

    fout$distance[3,]

    ##  [1] 1.003169 1.020740 1.085624 1.094124 1.135945 1.142292 1.159055 1.167019
    ##  [9] 1.167830 1.171124

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,] 6176 2579 7200 7223  123
    ## [2,] 7703 8315 9326 5659 9505
    ## [3,] 5223 4139 2730 9920 6128
    ## [4,] 8050  854 9675 3098 8118
    ## [5,] 3889 4415 8681 9538 7336
    ## [6,]  131 8508 1293 7311 2702

    head(qout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]
    ## [1,] 0.9035172 0.9806076 0.9854816 0.9856075 0.9860263
    ## [2,] 0.8729239 0.9232282 0.9727012 0.9807652 1.0050498
    ## [3,] 0.8312204 0.8583152 0.8664711 0.8821679 0.9074463
    ## [4,] 0.8642877 0.9144968 0.9202820 0.9598606 1.0009541
    ## [5,] 0.9147538 0.9496725 0.9685844 0.9952473 0.9985577
    ## [6,] 0.9354603 0.9666705 0.9865788 1.0121686 1.0179415

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] 5223 4139 2730 9920 6128

… with the following distances to those neighbors:

    qout$distance[3,]

    ## [1] 0.8312204 0.8583152 0.8664711 0.8821679 0.9074463

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,] 4828 1437 2609 6206 4510
    ## [2,] 9733 8882 4534 3851  197
    ## [3,] 9465 5011 7034 4398 7857
    ##
    ## $distance
    ##           [,1]     [,2]     [,3]     [,4]     [,5]
    ## [1,] 1.0031695 1.020740 1.085624 1.094124 1.135945
    ## [2,] 0.8973770 1.018731 1.049195 1.050262 1.055450
    ## [3,] 0.8625907 1.021535 1.047040 1.055496 1.063397

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.0.3 (2020-10-10)
    ## Platform: x86_64-pc-linux-gnu (64-bit)
    ## Running under: Ubuntu 18.04.5 LTS
    ##
    ## Matrix products: default
    ## BLAS:   /home/biocbuild/bbs-3.12-bioc/R/lib/libRblas.so
    ## LAPACK: /home/biocbuild/bbs-3.12-bioc/R/lib/libRlapack.so
    ##
    ## locale:
    ##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C
    ##  [3] LC_TIME=en_US.UTF-8        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.24.0 BiocNeighbors_1.8.0 knitr_1.30
    ## [4] BiocStyle_2.18.0
    ##
    ## loaded via a namespace (and not attached):
    ##  [1] Rcpp_1.0.5          bookdown_0.21       lattice_0.20-41
    ##  [4] digest_0.6.27       grid_4.0.3          stats4_4.0.3
    ##  [7] magrittr_1.5        evaluate_0.14       rlang_0.4.8
    ## [10] stringi_1.5.3       S4Vectors_0.28.0    Matrix_1.2-18
    ## [13] rmarkdown_2.5       tools_4.0.3         stringr_1.4.0
    ## [16] parallel_4.0.3      xfun_0.18           yaml_2.2.1
    ## [19] compiler_4.0.3      BiocGenerics_0.36.0 BiocManager_1.30.10
    ## [22] htmltools_0.5.0

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