# Detecting exact nearest neighbors

Aaron Lun1

1Cancer Research UK Cambridge Institute, Cambridge, United Kingdom

#### Revised: 2 December 2018

#### Package

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

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,] 3471 9597 6464 1523  739 3467 6083 5928 8217  4251
    ## [2,] 1295   91 7913 2910 9595 1744 7896 1427 8003  9929
    ## [3,] 9441 1934 2339 1915 3488 6020 2848 4402 3963  9024
    ## [4,] 1182 5211  811 1262 6731 5202 6977 7171  311  8911
    ## [5,] 1758 3774 4030 8039 6074 4825 3655  900 3276  4645
    ## [6,] 8731 6885  771 5097 9203 9990 9744 5781 9116  8644

    head(fout$distance)

    ##           [,1]      [,2]      [,3]     [,4]      [,5]      [,6]      [,7]
    ## [1,] 0.9268582 1.0194071 1.0388245 1.066455 1.0665949 1.0735655 1.0824382
    ## [2,] 0.9048371 0.9359871 1.0120881 1.043779 1.0444235 1.0455441 1.0539717
    ## [3,] 0.8742062 1.0089846 1.0463352 1.092934 1.0957071 1.1094109 1.1122402
    ## [4,] 1.0222398 1.0787940 1.1068635 1.151365 1.1552857 1.1567531 1.1812896
    ## [5,] 0.8097950 0.8529465 0.8786228 0.898006 0.9218992 0.9421305 0.9433766
    ## [6,] 0.8107696 0.9445785 0.9817260 0.996435 1.0598795 1.0600409 1.0772381
    ##           [,8]      [,9]     [,10]
    ## [1,] 1.0861026 1.0911286 1.0939449
    ## [2,] 1.0543530 1.0643257 1.0665777
    ## [3,] 1.1136279 1.1211136 1.1215756
    ## [4,] 1.1840725 1.1974826 1.2041063
    ## [5,] 0.9455532 0.9602737 0.9887302
    ## [6,] 1.0894124 1.0899001 1.1018226

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] 9441 1934 2339 1915 3488 6020 2848 4402 3963 9024

… with the following distances to those neighbors:

    fout$distance[3,]

    ##  [1] 0.8742062 1.0089846 1.0463352 1.0929340 1.0957071 1.1094109 1.1122402
    ##  [8] 1.1136279 1.1211136 1.1215756

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,] 9606    4  811 6674 6268
    ## [2,]  579   85 1794 5640 1477
    ## [3,] 6376 1290 9318 9619 9845
    ## [4,] 8142 1163 8498 9618 4912
    ## [5,] 1086  718 8134 2105 5030
    ## [6,] 2871 7543 2875 9281 9353

    head(qout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]
    ## [1,] 1.0499570 1.0873210 1.1693635 1.1906433 1.1906587
    ## [2,] 0.7563082 0.8060312 0.9013444 0.9136694 0.9237472
    ## [3,] 0.9370101 0.9899433 0.9916329 1.0248902 1.0273259
    ## [4,] 0.9029047 0.9092907 1.0669237 1.0870684 1.0878579
    ## [5,] 0.8753091 0.9623679 0.9792136 0.9888376 0.9939094
    ## [6,] 0.9021625 0.9179247 0.9275851 0.9527184 0.9609630

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] 6376 1290 9318 9619 9845

… with the following distances to those neighbors:

    qout$distance[3,]

    ## [1] 0.9370101 0.9899433 0.9916329 1.0248902 1.0273259

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,] 9441 1934 2339 1915 3488
    ## [2,] 1182 5211  811 1262 6731
    ## [3,] 1758 3774 4030 8039 6074
    ##
    ## $distance
    ##           [,1]      [,2]      [,3]     [,4]      [,5]
    ## [1,] 0.8742062 1.0089846 1.0463352 1.092934 1.0957071
    ## [2,] 1.0222398 1.0787940 1.1068635 1.151365 1.1552857
    ## [3,] 0.8097950 0.8529465 0.8786228 0.898006 0.9218992

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.1 (2019-07-05)
    ## Platform: x86_64-pc-linux-gnu (64-bit)
    ## Running under: Ubuntu 18.04.3 LTS
    ##
    ## Matrix products: default
    ## BLAS:   /home/biocbuild/bbs-3.10-bioc/R/lib/libRblas.so
    ## LAPACK: /home/biocbuild/bbs-3.10-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.20.0 BiocNeighbors_1.4.0 knitr_1.25
    ## [4] BiocStyle_2.14.0
    ##
    ## loaded via a namespace (and not attached):
    ##  [1] Rcpp_1.0.2          bookdown_0.14       lattice_0.20-38
    ##  [4] digest_0.6.22       grid_3.6.1          stats4_3.6.1
    ##  [7] magrittr_1.5        evaluate_0.14       rlang_0.4.1
    ## [10] stringi_1.4.3       S4Vectors_0.24.0    Matrix_1.2-17
    ## [13] rmarkdown_1.16      tools_3.6.1         stringr_1.4.0
    ## [16] parallel_3.6.1      xfun_0.10           yaml_2.2.0
    ## [19] compiler_3.6.1      BiocGenerics_0.32.0 BiocManager_1.30.9
    ## [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.