# Detecting exact nearest neighbors

Aaron Lun1

1Cancer Research UK Cambridge Institute, Cambridge, United Kingdom

#### Revised: 2 December 2018

#### Package

BiocNeighbors 1.20.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,] 2065 3382 9533 6800 7401 6027 8114 2676 3376  2115
    ## [2,] 5440 2966 9413 8952 8321 8963 6158 2420 3812   134
    ## [3,] 8774 9799  367 2519 6234 9930 4373 6345 8692  8965
    ## [4,] 2148 9200 5277 7036 7967 6239 7887 1658 4406  4455
    ## [5,] 3999 9006  353 9666 7327 5542 5491 4161 7471  1536
    ## [6,] 8447 7364 1229 3462 2859 5880 8753 7978 3477  5057

    head(fout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
    ## [1,] 0.8601041 0.9405645 0.9441125 0.9635423 0.9694718 0.9796962 0.9873729
    ## [2,] 0.8796636 0.8815487 1.0410194 1.0890603 1.0928391 1.1079828 1.1171982
    ## [3,] 0.8381739 0.9027989 1.0481477 1.0529239 1.0538338 1.0565367 1.0602912
    ## [4,] 0.8008537 0.9552288 0.9555032 0.9755692 0.9805155 0.9818309 1.0077884
    ## [5,] 1.0846477 1.0980233 1.1084281 1.1473471 1.1496366 1.1501803 1.1510255
    ## [6,] 0.8706205 0.9055222 0.9159952 0.9233606 0.9338148 0.9814867 0.9859933
    ##           [,8]     [,9]    [,10]
    ## [1,] 1.0025652 1.005314 1.038677
    ## [2,] 1.1173337 1.132791 1.134128
    ## [3,] 1.0632358 1.075982 1.085719
    ## [4,] 1.0262845 1.051799 1.062860
    ## [5,] 1.1538075 1.156275 1.159527
    ## [6,] 0.9966103 1.004058 1.005432

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] 8774 9799  367 2519 6234 9930 4373 6345 8692 8965

… with the following distances to those neighbors:

    fout$distance[3,]

    ##  [1] 0.8381739 0.9027989 1.0481477 1.0529239 1.0538338 1.0565367 1.0602912
    ##  [8] 1.0632358 1.0759820 1.0857192

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,] 2386 4418 6449 5340 2518
    ## [2,] 6158 4949  729 7451 8321
    ## [3,] 2234 4236 3897 2139 1332
    ## [4,] 9255 6489 4716 9554 5314
    ## [5,] 8740 9926 2242   34 1405
    ## [6,] 2507 3074 6277 6389 7293

    head(qout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]
    ## [1,] 0.7603441 0.8482767 0.8776201 0.8933037 0.9188237
    ## [2,] 0.8588626 0.8873143 0.9607321 0.9699190 1.0059270
    ## [3,] 0.8563127 0.9349425 0.9768696 0.9887398 1.0160313
    ## [4,] 0.8235188 0.9186935 0.9253849 0.9547868 0.9610018
    ## [5,] 0.8146578 0.8711415 0.9147830 0.9238796 0.9280706
    ## [6,] 0.9415215 1.0382651 1.0693572 1.1052094 1.1185167

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] 2234 4236 3897 2139 1332

… with the following distances to those neighbors:

    qout$distance[3,]

    ## [1] 0.8563127 0.9349425 0.9768696 0.9887398 1.0160313

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,] 8774 9799  367 2519 6234
    ## [2,] 2148 9200 5277 7036 7967
    ## [3,] 3999 9006  353 9666 7327
    ##
    ## $distance
    ##           [,1]      [,2]      [,3]      [,4]      [,5]
    ## [1,] 0.8381739 0.9027989 1.0481477 1.0529239 1.0538338
    ## [2,] 0.8008537 0.9552288 0.9555032 0.9755692 0.9805155
    ## [3,] 1.0846477 1.0980233 1.1084281 1.1473471 1.1496366

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.3.1 (2023-06-16)
    ## Platform: x86_64-pc-linux-gnu (64-bit)
    ## Running under: Ubuntu 22.04.3 LTS
    ##
    ## Matrix products: default
    ## BLAS:   /home/biocbuild/bbs-3.18-bioc/R/lib/libRblas.so
    ## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.10.0
    ##
    ## locale:
    ##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C
    ##  [3] LC_TIME=en_GB              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
    ##
    ## time zone: America/New_York
    ## tzcode source: system (glibc)
    ##
    ## attached base packages:
    ## [1] stats     graphics  grDevices utils     datasets  methods   base
    ##
    ## other attached packages:
    ## [1] BiocParallel_1.36.0  BiocNeighbors_1.20.0 knitr_1.44
    ## [4] BiocStyle_2.30.0
    ##
    ## loaded via a namespace (and not attached):
    ##  [1] cli_3.6.1           rlang_1.1.1         xfun_0.40
    ##  [4] jsonlite_1.8.7      S4Vectors_0.40.0    htmltools_0.5.6.1
    ##  [7] stats4_4.3.1        sass_0.4.7          rmarkdown_2.25
    ## [10] grid_4.3.1          evaluate_0.22       jquerylib_0.1.4
    ## [13] fastmap_1.1.1       yaml_2.3.7          bookdown_0.36
    ## [16] BiocManager_1.30.22 compiler_4.3.1      codetools_0.2-19
    ## [19] Rcpp_1.0.11         lattice_0.22-5      digest_0.6.33
    ## [22] R6_2.5.1            parallel_4.3.1      bslib_0.5.1
    ## [25] Matrix_1.6-1.1      tools_4.3.1         BiocGenerics_0.48.0
    ## [28] cachem_1.0.8

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