# 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,] 6295 4952 1090 1828 1118 3005 7483 8335 5016  4974
    ## [2,]  593 4223 9895 1005 8169 8085 3289 7681 9791  3429
    ## [3,] 8599 6332 2204 3155 4281 5885  131 4218 5120  3655
    ## [4,] 6114 3358 2674 9434 5635  861 3999 2065  532    25
    ## [5,] 5045 7114 7362 1603 6834 5890 8249 4851 8645  7582
    ## [6,] 7679 1538 4627 9115 4510 3678 3596 2076 2472  2674

    head(fout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
    ## [1,] 0.8681479 0.8897752 0.9127894 0.9348734 0.9461919 0.9735984 0.9839596
    ## [2,] 0.9571206 0.9589984 0.9771774 1.0156536 1.0161441 1.0239847 1.0274582
    ## [3,] 0.8818880 0.9236179 0.9334733 1.0055367 1.0401387 1.0464910 1.0729269
    ## [4,] 0.8700128 1.0540885 1.0715972 1.0922847 1.0970133 1.1099301 1.1137744
    ## [5,] 0.8718934 0.8776878 0.9640895 0.9744083 0.9932702 0.9986655 1.0063359
    ## [6,] 0.7529839 0.9099724 1.0097919 1.0444033 1.0565020 1.0635699 1.0994820
    ##           [,8]     [,9]    [,10]
    ## [1,] 0.9850137 0.992611 1.005767
    ## [2,] 1.0376677 1.049334 1.063692
    ## [3,] 1.0793518 1.103488 1.117661
    ## [4,] 1.1190147 1.127653 1.130532
    ## [5,] 1.0487871 1.054724 1.056918
    ## [6,] 1.1012567 1.124284 1.125254

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] 8599 6332 2204 3155 4281 5885  131 4218 5120 3655

… with the following distances to those neighbors:

    fout$distance[3,]

    ##  [1] 0.8818880 0.9236179 0.9334733 1.0055367 1.0401387 1.0464910 1.0729269
    ##  [8] 1.0793518 1.1034884 1.1176614

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,] 2041 5949 8717 6163 6573
    ## [2,] 1280 6397 3815 4852 1571
    ## [3,] 8008 4922 5053 3575 8831
    ## [4,] 7311 3384 7207 2337 8812
    ## [5,] 2219 6322 8332 6718 4064
    ## [6,]  570 2483 6753 2806 2125

    head(qout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]
    ## [1,] 1.0366429 1.0565809 1.0691140 1.0708496 1.0752425
    ## [2,] 0.9454142 1.0606813 1.0691869 1.1141864 1.1199522
    ## [3,] 0.8896047 0.9690943 0.9718616 0.9880406 0.9886149
    ## [4,] 0.7650812 0.8937650 0.9142046 0.9336479 0.9483447
    ## [5,] 0.8883523 0.9312492 0.9392397 0.9452236 0.9647510
    ## [6,] 0.8526225 0.8776879 0.8951662 0.9584557 0.9758564

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] 8008 4922 5053 3575 8831

… with the following distances to those neighbors:

    qout$distance[3,]

    ## [1] 0.8896047 0.9690943 0.9718616 0.9880406 0.9886149

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,] 8599 6332 2204 3155 4281
    ## [2,] 6114 3358 2674 9434 5635
    ## [3,] 5045 7114 7362 1603 6834
    ##
    ## $distance
    ##           [,1]      [,2]      [,3]      [,4]      [,5]
    ## [1,] 0.8818880 0.9236179 0.9334733 1.0055367 1.0401387
    ## [2,] 0.8700128 1.0540885 1.0715972 1.0922847 1.0970133
    ## [3,] 0.8718934 0.8776878 0.9640895 0.9744083 0.9932702

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-w64-mingw32/x64 (64-bit)
    ## Running under: Windows Server x64 (build 17763)
    ##
    ## 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.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.