# Detecting exact nearest neighbors

Aaron Lun1

1Cancer Research UK Cambridge Institute, Cambridge, United Kingdom

#### Revised: 2 December 2018

#### Package

BiocNeighbors 1.4.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.

Both methods involve a component of randomness during index construction, though the k-nearest neighbors result is fully deterministic11 Except in the presence of ties, see `?findKNN` 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,] 3731 8193 8715 5101  711 9204 1135 2972 6793  1775
    ## [2,] 4811 8193 8891 7985 4050 6157 5341 3824 7244  5625
    ## [3,] 6846 8962 3097 6675 7936 8069 8800 8157 8786  3964
    ## [4,] 9821 2201 5118 6937 9310 5379 3665 9321 7683   792
    ## [5,] 7039 6058 1976   74 6614 9370 4828 2472 9208  4929
    ## [6,] 4403 7676 6566 1123 1060 1340 9133 2079  859  1330

    head(fout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
    ## [1,] 0.8877962 0.9304677 0.9474476 0.9536876 1.0181418 1.0427188 1.0646312
    ## [2,] 0.7734972 0.8820828 0.9029303 0.9325645 0.9325774 0.9345082 0.9684734
    ## [3,] 0.8620950 0.8731361 0.8939240 0.9472417 0.9658871 0.9909066 0.9930843
    ## [4,] 0.9427948 0.9476987 0.9939279 1.0230269 1.0268361 1.0443186 1.0574298
    ## [5,] 0.9981762 1.0152140 1.0420699 1.0472745 1.0641663 1.0873278 1.1004294
    ## [6,] 0.9230868 0.9355691 0.9402517 0.9776362 1.0129484 1.0157912 1.0170590
    ##          [,8]      [,9]     [,10]
    ## [1,] 1.067713 1.0749696 1.0790763
    ## [2,] 0.978591 0.9788287 0.9788691
    ## [3,] 1.000988 1.0153002 1.0204145
    ## [4,] 1.076196 1.1035483 1.1167119
    ## [5,] 1.103175 1.1060766 1.1095735
    ## [6,] 1.018815 1.0316504 1.0521335

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] 6846 8962 3097 6675 7936 8069 8800 8157 8786 3964

… with the following distances to those neighbors:

    fout$distance[3,]

    ##  [1] 0.8620950 0.8731361 0.8939240 0.9472417 0.9658871 0.9909066 0.9930843
    ##  [8] 1.0009880 1.0153002 1.0204145

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,] 7112 4909 8180 4689 9334
    ## [2,] 2375 6015 4717 1141 6207
    ## [3,] 1991 4335  397 6297 3539
    ## [4,] 2896 2085 8052  779  119
    ## [5,] 5758 5470 6605 3937 8776
    ## [6,] 6793 7596 6274 8882 6115

    head(qout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]
    ## [1,] 0.9912301 1.0527817 1.0680408 1.0955668 1.1148675
    ## [2,] 0.8987992 0.9267031 0.9283958 0.9473312 0.9627777
    ## [3,] 0.9735692 0.9914094 1.0068135 1.0471135 1.0555359
    ## [4,] 0.8664562 0.9515824 1.0290090 1.0332125 1.0390702
    ## [5,] 0.9695840 1.0482527 1.0823021 1.0933350 1.1015033
    ## [6,] 0.8759028 0.9320623 0.9325132 0.9352203 0.9575112

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] 1991 4335  397 6297 3539

… with the following distances to those neighbors:

    qout$distance[3,]

    ## [1] 0.9735692 0.9914094 1.0068135 1.0471135 1.0555359

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,] 6846 8962 3097 6675 7936
    ## [2,] 9821 2201 5118 6937 9310
    ## [3,] 7039 6058 1976   74 6614
    ##
    ## $distance
    ##           [,1]      [,2]      [,3]      [,4]      [,5]
    ## [1,] 0.8620950 0.8731361 0.8939240 0.9472417 0.9658871
    ## [2,] 0.9427948 0.9476987 0.9939279 1.0230269 1.0268361
    ## [3,] 0.9981762 1.0152140 1.0420699 1.0472745 1.0641663

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 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 3.6.2 (2019-12-12)
    ## Platform: x86_64-w64-mingw32/x64 (64-bit)
    ## Running under: Windows Server 2012 R2 x64 (build 9600)
    ##
    ## Matrix products: default
    ##
    ## locale:
    ## [1] LC_COLLATE=C
    ## [2] LC_CTYPE=English_United States.1252
    ## [3] LC_MONETARY=English_United States.1252
    ## [4] LC_NUMERIC=C
    ## [5] LC_TIME=English_United States.1252
    ##
    ## attached base packages:
    ## [1] stats     graphics  grDevices utils     datasets  methods   base
    ##
    ## other attached packages:
    ## [1] BiocParallel_1.20.1 BiocNeighbors_1.4.2 knitr_1.28
    ## [4] BiocStyle_2.14.4
    ##
    ## loaded via a namespace (and not attached):
    ##  [1] Rcpp_1.0.3          bookdown_0.17       lattice_0.20-40
    ##  [4] digest_0.6.25       grid_3.6.2          stats4_3.6.2
    ##  [7] magrittr_1.5        evaluate_0.14       rlang_0.4.4
    ## [10] stringi_1.4.6       S4Vectors_0.24.3    Matrix_1.2-18
    ## [13] rmarkdown_2.1       tools_3.6.2         stringr_1.4.0
    ## [16] parallel_3.6.2      xfun_0.12           yaml_2.2.1
    ## [19] compiler_3.6.2      BiocGenerics_0.32.0 BiocManager_1.30.10
    ## [22] htmltools_0.4.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.