# Detecting exact nearest neighbors

Aaron Lun1

1Cancer Research UK Cambridge Institute, Cambridge, United Kingdom

#### Revised: 2 December 2018

#### Package

BiocNeighbors 1.12.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,] 1834 8520 6418 8285 1088 8396 5053 3931 2489  6432
    ## [2,] 7476 4923 2918 9109 6116 2301 3675 2161 9671  6365
    ## [3,] 4036 5029 5038 5561 9474 3861 7588 1492 9718  7818
    ## [4,]  503 3535 8856 8716 3422 9037 7334 5337 4024  8401
    ## [5,] 2706 9857 4184 1820  876 5618 4344 8028 9899  4999
    ## [6,]  815 2685 1205 3750 6818 3637 9228 1154 4633  8704

    head(fout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
    ## [1,] 0.9873224 1.0042547 1.0164828 1.0432194 1.0444058 1.0456076 1.0706495
    ## [2,] 1.0240366 1.0370456 1.1011682 1.1514759 1.1600620 1.1864552 1.1884515
    ## [3,] 0.8907877 0.9428800 0.9869554 1.0366111 1.0539570 1.0688997 1.0743881
    ## [4,] 0.8784366 0.9597062 1.0208576 1.0405754 1.0462169 1.0501523 1.0590181
    ## [5,] 0.8154634 0.8758563 0.9055711 0.9174330 0.9343276 0.9613431 0.9767778
    ## [6,] 0.9197168 0.9251531 0.9344843 0.9585882 0.9829316 0.9904147 1.0332483
    ##           [,8]      [,9]     [,10]
    ## [1,] 1.0725317 1.0778068 1.0787248
    ## [2,] 1.1934394 1.1973379 1.2020754
    ## [3,] 1.0850044 1.0934087 1.0953963
    ## [4,] 1.0616786 1.0620466 1.0708770
    ## [5,] 0.9789725 0.9807013 0.9811936
    ## [6,] 1.0409656 1.0484698 1.0489620

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] 4036 5029 5038 5561 9474 3861 7588 1492 9718 7818

… with the following distances to those neighbors:

    fout$distance[3,]

    ##  [1] 0.8907877 0.9428800 0.9869554 1.0366111 1.0539570 1.0688997 1.0743881
    ##  [8] 1.0850044 1.0934087 1.0953963

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,] 5393 8245 5970 4523 4073
    ## [2,] 4113 3468  289 1372 2273
    ## [3,] 3437 5191 3275 4174 9877
    ## [4,] 2019  541 7622 6748 7746
    ## [5,] 6770 5400 9223 2473 1704
    ## [6,] 3068 9681   46 3939 5189

    head(qout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]
    ## [1,] 0.7540807 0.9652551 0.9719752 0.9765699 1.0107931
    ## [2,] 0.8039612 0.9378730 0.9900544 0.9965463 1.0062733
    ## [3,] 0.7282259 0.9129151 0.9355368 0.9772487 0.9977412
    ## [4,] 0.8976409 0.9183535 0.9191570 0.9971014 1.0001932
    ## [5,] 0.9656236 1.0016202 1.0930467 1.1008310 1.1027531
    ## [6,] 0.9043726 0.9049974 0.9569925 0.9738977 0.9919256

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] 3437 5191 3275 4174 9877

… with the following distances to those neighbors:

    qout$distance[3,]

    ## [1] 0.7282259 0.9129151 0.9355368 0.9772487 0.9977412

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,] 4036 5029 5038 5561 9474
    ## [2,]  503 3535 8856 8716 3422
    ## [3,] 2706 9857 4184 1820  876
    ##
    ## $distance
    ##           [,1]      [,2]      [,3]     [,4]      [,5]
    ## [1,] 0.8907877 0.9428800 0.9869554 1.036611 1.0539570
    ## [2,] 0.8784366 0.9597062 1.0208576 1.040575 1.0462169
    ## [3,] 0.8154634 0.8758563 0.9055711 0.917433 0.9343276

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.1 (2021-08-10)
    ## 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.28.0  BiocNeighbors_1.12.0 knitr_1.36
    ## [4] BiocStyle_2.22.0
    ##
    ## loaded via a namespace (and not attached):
    ##  [1] Rcpp_1.0.7          magrittr_2.0.1      BiocGenerics_0.40.0
    ##  [4] lattice_0.20-45     R6_2.5.1            rlang_0.4.12
    ##  [7] fastmap_1.1.0       stringr_1.4.0       tools_4.1.1
    ## [10] parallel_4.1.1      grid_4.1.1          xfun_0.27
    ## [13] jquerylib_0.1.4     htmltools_0.5.2     yaml_2.2.1
    ## [16] digest_0.6.28       bookdown_0.24       Matrix_1.3-4
    ## [19] BiocManager_1.30.16 S4Vectors_0.32.0    sass_0.4.0
    ## [22] evaluate_0.14       rmarkdown_2.11      stringi_1.7.5
    ## [25] compiler_4.1.1      bslib_0.3.1         stats4_4.1.1
    ## [28] 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.