# Detecting exact nearest neighbors

Aaron Lun1

1Cancer Research UK Cambridge Institute, Cambridge, United Kingdom

#### Revised: 2 December 2018

#### Package

BiocNeighbors 1.22.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,] 1989 4622 8618 2158 7879 2133 9013 9508 4499  5229
    ## [2,] 4794 2009 6091 4188 7004 7215 9857 2796 3660  9161
    ## [3,] 7830 3666 2945 4592 7275 3335 1716 1889 5439  9718
    ## [4,] 8439 5358 7958 4857 6985 6399 6370 2443  195   830
    ## [5,] 3889 1124 5754 6799 7697 5520 9800 9926 2738  9240
    ## [6,] 5991 6412 5266  775 3885 6310 3578 4606 9008  3014

    head(fout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
    ## [1,] 1.0097842 1.0227242 1.0275769 1.0369262 1.0564901 1.0822241 1.0903339
    ## [2,] 0.8701481 0.9319641 0.9348332 0.9844711 1.0252510 1.0303986 1.0325786
    ## [3,] 0.7910433 0.8477791 0.8976068 0.9115301 0.9490122 0.9499254 0.9516261
    ## [4,] 0.9264327 0.9326880 0.9717430 0.9931083 1.0444846 1.0664840 1.0695115
    ## [5,] 0.8315563 0.8344440 0.8452555 0.8651816 0.8747433 0.9340461 0.9385280
    ## [6,] 0.7639928 0.8173307 0.8219567 0.8996072 0.9188609 0.9191398 0.9250174
    ##           [,8]      [,9]     [,10]
    ## [1,] 1.0947257 1.1138215 1.1281925
    ## [2,] 1.0334664 1.0475224 1.0774493
    ## [3,] 0.9990428 1.0041717 1.0050663
    ## [4,] 1.0747146 1.0776285 1.0778396
    ## [5,] 0.9424983 0.9426294 0.9727308
    ## [6,] 0.9263940 0.9375396 0.9443515

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] 7830 3666 2945 4592 7275 3335 1716 1889 5439 9718

… with the following distances to those neighbors:

    fout$distance[3,]

    ##  [1] 0.7910433 0.8477791 0.8976068 0.9115301 0.9490122 0.9499254 0.9516261
    ##  [8] 0.9990428 1.0041717 1.0050663

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,] 9010 9330 1883 9571 8936
    ## [2,] 1242 1502 4466 3303 6279
    ## [3,] 5867 6335 2119 3411 7181
    ## [4,] 4554 1357 3309 6206 1565
    ## [5,] 6028 1151 2490  821 6469
    ## [6,] 5165 7568 8421 1632 6761

    head(qout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]
    ## [1,] 0.8425451 0.8884211 0.9081493 0.9326827 0.9341941
    ## [2,] 0.9518900 0.9574701 0.9744274 0.9783393 0.9979423
    ## [3,] 0.8600595 0.9278923 0.9574250 0.9704132 0.9881491
    ## [4,] 0.9573079 0.9713062 0.9997422 1.0025234 1.0665254
    ## [5,] 0.8129505 0.8139442 0.8182734 0.8732380 0.8733563
    ## [6,] 0.9073574 0.9250673 0.9812302 0.9813518 1.0058444

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] 5867 6335 2119 3411 7181

… with the following distances to those neighbors:

    qout$distance[3,]

    ## [1] 0.8600595 0.9278923 0.9574250 0.9704132 0.9881491

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,] 7830 3666 2945 4592 7275
    ## [2,] 8439 5358 7958 4857 6985
    ## [3,] 3889 1124 5754 6799 7697
    ##
    ## $distance
    ##           [,1]      [,2]      [,3]      [,4]      [,5]
    ## [1,] 0.7910433 0.8477791 0.8976068 0.9115301 0.9490122
    ## [2,] 0.9264327 0.9326880 0.9717430 0.9931083 1.0444846
    ## [3,] 0.8315563 0.8344440 0.8452555 0.8651816 0.8747433

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.4.0 beta (2024-04-15 r86425 ucrt)
    ## Platform: x86_64-w64-mingw32/x64
    ## Running under: Windows Server 2022 x64 (build 20348)
    ##
    ## Matrix products: default
    ##
    ##
    ## locale:
    ## [1] LC_COLLATE=C
    ## [2] LC_CTYPE=English_United States.utf8
    ## [3] LC_MONETARY=English_United States.utf8
    ## [4] LC_NUMERIC=C
    ## [5] LC_TIME=English_United States.utf8
    ##
    ## time zone: America/New_York
    ## tzcode source: internal
    ##
    ## attached base packages:
    ## [1] stats     graphics  grDevices utils     datasets  methods   base
    ##
    ## other attached packages:
    ## [1] BiocParallel_1.38.0  BiocNeighbors_1.22.0 knitr_1.46
    ## [4] BiocStyle_2.32.0
    ##
    ## loaded via a namespace (and not attached):
    ##  [1] cli_3.6.2           rlang_1.1.3         xfun_0.43
    ##  [4] jsonlite_1.8.8      S4Vectors_0.42.0    htmltools_0.5.8.1
    ##  [7] stats4_4.4.0        sass_0.4.9          rmarkdown_2.26
    ## [10] grid_4.4.0          evaluate_0.23       jquerylib_0.1.4
    ## [13] fastmap_1.1.1       yaml_2.3.8          lifecycle_1.0.4
    ## [16] bookdown_0.39       BiocManager_1.30.22 compiler_4.4.0
    ## [19] codetools_0.2-20    Rcpp_1.0.12         lattice_0.22-6
    ## [22] digest_0.6.35       R6_2.5.1            parallel_4.4.0
    ## [25] bslib_0.7.0         Matrix_1.7-0        tools_4.4.0
    ## [28] BiocGenerics_0.50.0 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.