# Detecting exact nearest neighbors

Aaron Lun1

1Cancer Research UK Cambridge Institute, Cambridge, United Kingdom

#### Revised: 2 December 2018

#### Package

BiocNeighbors 1.8.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.
- 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,]  796 7834 6121 3287 9002 1815 4170 8305 2287  6691
    ## [2,] 3822 5446 9054 6891  848 2467 3615 8133 3132  2495
    ## [3,] 7856 7483 7296 9218 4491 7785  398 3007  579  2745
    ## [4,] 5235 5749 4483 4635 7416 4507  196 6991 5883  9739
    ## [5,] 8138 4275 7610 4906 1429 8262 9143 5293 4178    82
    ## [6,] 2290  461 7617 1951 9730 2369 3121 6169 2457  5199

    head(fout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
    ## [1,] 1.0373046 1.0445765 1.0504868 1.0538269 1.0593303 1.0726551 1.0867841
    ## [2,] 0.9482220 0.9580152 1.0094369 1.0194683 1.0244142 1.0626751 1.0873970
    ## [3,] 0.8915155 0.8953327 1.0262271 1.0593928 1.0654726 1.0703312 1.0824578
    ## [4,] 0.9157547 0.9235197 0.9605796 0.9828723 0.9955004 1.0240653 1.0286297
    ## [5,] 0.8898300 0.9073856 0.9089087 0.9216727 0.9386429 0.9573680 0.9596880
    ## [6,] 0.9320882 0.9345899 0.9668153 0.9915265 0.9965271 0.9985906 0.9998187
    ##           [,8]     [,9]     [,10]
    ## [1,] 1.1108151 1.119736 1.1386523
    ## [2,] 1.1002963 1.110678 1.1162099
    ## [3,] 1.1043576 1.118109 1.1221874
    ## [4,] 1.0295654 1.031289 1.0413290
    ## [5,] 0.9667688 0.970039 0.9947082
    ## [6,] 1.0048222 1.009934 1.0215948

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] 7856 7483 7296 9218 4491 7785  398 3007  579 2745

… with the following distances to those neighbors:

    fout$distance[3,]

    ##  [1] 0.8915155 0.8953327 1.0262271 1.0593928 1.0654726 1.0703312 1.0824578
    ##  [8] 1.1043576 1.1181090 1.1221874

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,] 6685 1905 1911 9711  504
    ## [2,] 4198 8286 8818 1217 2721
    ## [3,] 5247 5353 1650 7929  484
    ## [4,] 5075  430 4906 5938 5932
    ## [5,] 2304 8975 8396 5975 2751
    ## [6,] 1752 5610  167 6020 3737

    head(qout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]
    ## [1,] 0.9438838 1.0558772 1.0823055 1.1123618 1.1129085
    ## [2,] 0.8940407 0.9220172 0.9630316 0.9968341 1.0090347
    ## [3,] 0.7798383 0.8930779 0.9779041 0.9820498 1.0335135
    ## [4,] 0.8884584 0.9286552 0.9387557 0.9441704 0.9511641
    ## [5,] 0.7651731 0.8788716 0.8827387 0.9562141 0.9579960
    ## [6,] 0.8928920 0.9737507 0.9759432 1.0030895 1.0108924

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] 5247 5353 1650 7929  484

… with the following distances to those neighbors:

    qout$distance[3,]

    ## [1] 0.7798383 0.8930779 0.9779041 0.9820498 1.0335135

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,] 7856 7483 7296 9218 4491
    ## [2,] 5235 5749 4483 4635 7416
    ## [3,] 8138 4275 7610 4906 1429
    ##
    ## $distance
    ##           [,1]      [,2]      [,3]      [,4]      [,5]
    ## [1,] 0.8915155 0.8953327 1.0262271 1.0593928 1.0654726
    ## [2,] 0.9157547 0.9235197 0.9605796 0.9828723 0.9955004
    ## [3,] 0.8898300 0.9073856 0.9089087 0.9216727 0.9386429

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.0.3 (2020-10-10)
    ## 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.24.1 BiocNeighbors_1.8.2 knitr_1.30
    ## [4] BiocStyle_2.18.1
    ##
    ## loaded via a namespace (and not attached):
    ##  [1] Rcpp_1.0.5          bookdown_0.21       lattice_0.20-41
    ##  [4] digest_0.6.27       grid_4.0.3          stats4_4.0.3
    ##  [7] magrittr_2.0.1      evaluate_0.14       rlang_0.4.9
    ## [10] stringi_1.5.3       S4Vectors_0.28.0    Matrix_1.2-18
    ## [13] rmarkdown_2.5       tools_4.0.3         stringr_1.4.0
    ## [16] parallel_4.0.3      xfun_0.19           yaml_2.2.1
    ## [19] compiler_4.0.3      BiocGenerics_0.36.0 BiocManager_1.30.10
    ## [22] htmltools_0.5.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.