# Detecting approximate nearest neighbors

Aaron Lun1

1Cancer Research UK Cambridge Institute, Cambridge, United Kingdom

#### Revised: 2 December 2018

#### Package

BiocNeighbors 1.5.1

# 1 Introduction

The BiocNeighbors package provides several algorithms for approximate neighbor searches:

- The Annoy (Approximate Nearest Neighbors Oh Yeah) method uses C++ code from the RcppAnnoy package. It works by building a tree where a random hyperplane partitions a group of points into two child groups at each internal node. This is repeated to construct a forest of trees where the number of trees determines the accuracy of the search. Given a query data point, we identify all points in the same leaf node for each tree. We then take the union of leaf node sets across trees and search them exactly for the nearest neighbors.
- The HNSW (Hierarchical Navigable Small Worlds) method uses C++ code from the RcppHNSW package. It works by building a series of nagivable small world graphs containing links between points across the entire data set. The algorithm walks through the graphs where each step is chosen to move closer to a given query point. Different graphs contain links of different lengths, yielding a hierarchy where earlier steps are large and later steps are small. The accuracy of the search is determined by the connectivity of the graphs and the size of the intermediate list of potential neighbors.

These methods complement the exact algorithms described previously. Again, it is straightforward to switch from one algorithm to another by simply changing the `BNPARAM` argument in `findKNN` and `queryKNN`.

# 2 Identifying nearest neighbors

We perform the k-nearest neighbors search with the Annoy algorithm by specifying `BNPARAM=AnnoyParam()`.

    nobs <- 10000
    ndim <- 20
    data <- matrix(runif(nobs*ndim), ncol=ndim)

    fout <- findKNN(data, k=10, BNPARAM=AnnoyParam())
    head(fout$index)

    ##      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
    ## [1,] 1342 9537 4028  465 5521 1146 4975 7851 9211  9954
    ## [2,] 5397 4321  733 1078 4933 9459 3435 7908 1086  6561
    ## [3,]  928  673   15 6502 8324 8840 8037 4824 4300  8618
    ## [4,] 3551 9968 1063 9684 9154 3760 5180 9411 3850  3785
    ## [5,] 7347 3679  881 2935 8516  543 2366 1479 9628  5729
    ## [6,] 5349  581 5453 1207 5781 6175 2344 2286 1196  1382

    head(fout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
    ## [1,] 0.8649724 0.9421955 0.9607775 0.9958355 1.0072033 1.0137219 1.0185637
    ## [2,] 0.9822696 1.0075930 1.0211786 1.0298489 1.0339681 1.0386904 1.0534862
    ## [3,] 0.9149191 1.0382372 1.0390248 1.0447446 1.0563128 1.0564233 1.0602862
    ## [4,] 0.8458163 0.8890622 0.9321060 0.9491568 1.0571254 1.0854096 1.1165049
    ## [5,] 0.8575791 0.9944410 1.0035101 1.0580266 1.0635271 1.0718808 1.0965167
    ## [6,] 0.8717038 0.8870363 0.8940122 0.9176141 0.9401619 0.9407771 0.9430245
    ##           [,8]      [,9]     [,10]
    ## [1,] 1.0298446 1.0398561 1.0445073
    ## [2,] 1.0618356 1.0788580 1.0861516
    ## [3,] 1.0639808 1.0743583 1.0774040
    ## [4,] 1.1233051 1.1257586 1.1378013
    ## [5,] 1.1093510 1.1201334 1.1453010
    ## [6,] 0.9587717 0.9620373 0.9710137

We can also identify the k-nearest neighbors in one dataset based on query points in another dataset.

    nquery <- 1000
    ndim <- 20
    query <- matrix(runif(nquery*ndim), ncol=ndim)

    qout <- queryKNN(data, query, k=5, BNPARAM=AnnoyParam())
    head(qout$index)

    ##      [,1] [,2] [,3] [,4] [,5]
    ## [1,] 2574  757   64 1667 2207
    ## [2,] 8589 2652 1426 9795 4711
    ## [3,] 4690 7723 2649 2269  314
    ## [4,] 7833 1488 1243 5536 3746
    ## [5,] 9914 1371 8387 4777 6000
    ## [6,] 4684 1241 6243  671 5973

    head(qout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]
    ## [1,] 0.9677466 1.0506908 1.0512137 1.1060612 1.1483465
    ## [2,] 0.9663165 0.9820809 1.0109591 1.0551009 1.0692099
    ## [3,] 1.0240239 1.0469348 1.0485976 1.0753884 1.0846994
    ## [4,] 0.9187490 0.9705116 0.9722099 1.0341027 1.0864275
    ## [5,] 0.8062440 0.9372289 0.9532933 0.9561649 1.0026485
    ## [6,] 0.9194435 0.9400893 0.9421133 0.9579048 0.9905839

It is similarly easy to use the HNSW algorithm by setting `BNPARAM=HnswParam()`.

# 3 Further options

Most of the options described for the exact methods are also applicable here. For example:

- `subset` to identify neighbors for a subset of points.
- `get.distance` to avoid retrieving distances when unnecessary.
- `BPPARAM` to parallelize the calculations across multiple workers.
- `BNINDEX` to build the forest once for a given data set and re-use it across calls.

The use of a pre-built `BNINDEX` is illustrated below:

    pre <- buildIndex(data, BNPARAM=AnnoyParam())
    out1 <- findKNN(BNINDEX=pre, k=5)
    out2 <- queryKNN(BNINDEX=pre, query=query, k=2)

Both Annoy and HNSW perform searches based on the Euclidean distance by default. Searching by Manhattan distance is done by simply setting `distance="Manhattan"` in `AnnoyParam()` or `HnswParam()`.

Users are referred to the documentation of each function for specific details on the available arguments.

# 4 Saving the index files

Both Annoy and HNSW generate indexing structures - a forest of trees and series of graphs, respectively - that are saved to file when calling `buildIndex()`. By default, this file is located in `tempdir()`11 On HPC file systems, you can change `TEMPDIR` to a location that is more amenable to concurrent access. and will be removed when the session finishes.

    AnnoyIndex_path(pre)

    ## [1] "/tmp/Rtmpr7mv08/file602142ff1be9.idx"

If the index is to persist across sessions, the path of the index file can be directly specified in `buildIndex`. This can be used to construct an index object directly using the relevant constructors, e.g., `AnnoyIndex()`, `HnswIndex()`. However, it becomes the responsibility of the user to clean up any temporary indexing files after calculations are complete.

# 5 Session information

    sessionInfo()

    ## R Under development (unstable) (2019-11-03 r77362)
    ## Platform: x86_64-apple-darwin15.6.0 (64-bit)
    ## Running under: OS X El Capitan 10.11.6
    ##
    ## Matrix products: default
    ## BLAS:   /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRblas.0.dylib
    ## LAPACK: /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRlapack.dylib
    ##
    ## locale:
    ## [1] C/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
    ##
    ## attached base packages:
    ## [1] stats     graphics  grDevices utils     datasets  methods   base
    ##
    ## other attached packages:
    ## [1] BiocNeighbors_1.5.1 knitr_1.25          BiocStyle_2.15.0
    ##
    ## loaded via a namespace (and not attached):
    ##  [1] Rcpp_1.0.2          bookdown_0.14       lattice_0.20-38
    ##  [4] digest_0.6.22       grid_4.0.0          stats4_4.0.0
    ##  [7] magrittr_1.5        evaluate_0.14       rlang_0.4.1
    ## [10] stringi_1.4.3       S4Vectors_0.25.0    Matrix_1.2-17
    ## [13] rmarkdown_1.16      BiocParallel_1.21.0 tools_4.0.0
    ## [16] stringr_1.4.0       parallel_4.0.0      xfun_0.10
    ## [19] yaml_2.2.0          compiler_4.0.0      BiocGenerics_0.33.0
    ## [22] BiocManager_1.30.9  htmltools_0.4.0