# Detecting approximate nearest neighbors with Annoy

Aaron Lun1

1Cancer Research UK Cambridge Institute, Cambridge, United Kingdom

#### Revised: 27 September 2018

#### Package

BiocNeighbors 1.0.0

# 1 Introduction

The BiocNeighbors package provides an implementation of the Annoy (Approximate Nearest Neighbors Oh Yeah) method based on C++ code in the `CRANpkg("RcppAnnoy")` package. The aim is to provide an approximate method to complement the exact KMKNN algorithm described previously. Indeed, it is straightforward to switch from one algorithm to another by simply changing the `BNPARAM` argument in `findKNN` and `queryKNN`.

Briefly, the Annoy method works by building a tree where a random hyperplane partitions 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.

# 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,] 7363 3932  891 4390 4140  562 3089 1468 3277  4379
    ## [2,] 4906  888 4261 9754 2653 7737 2177 5786 1346  9239
    ## [3,] 1784 9073 7684 5871 5151 4223 5052 5845 2770  6780
    ## [4,] 9479 4067 7992 4681 5642 5506 8080 4575 7323  3209
    ## [5,] 8326  308 6726 5015 6705 3899 1575 3038 6451  7158
    ## [6,] 9915 2977 5893 6532 5362 9848 4458 9296 2334   434

    head(fout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
    ## [1,] 0.7498393 0.7713652 0.8109115 0.8134648 0.8207006 0.8786625 0.9087560
    ## [2,] 0.7737219 0.9109668 0.9224313 0.9540132 0.9559577 0.9640622 0.9663381
    ## [3,] 0.7540293 0.8930155 0.9915062 1.0377532 1.0479106 1.0497414 1.0509695
    ## [4,] 0.8836370 0.9726025 0.9819255 1.0265495 1.0617754 1.0708429 1.0728233
    ## [5,] 0.7888196 0.8682272 0.8858894 0.9124507 0.9135064 0.9424955 0.9602599
    ## [6,] 0.8436729 0.8478945 0.8951638 0.9466890 0.9560477 0.9823775 1.0233724
    ##           [,8]      [,9]     [,10]
    ## [1,] 0.9197307 0.9235410 0.9249632
    ## [2,] 0.9758505 0.9767210 0.9816678
    ## [3,] 1.0575870 1.0896720 1.1025612
    ## [4,] 1.0731101 1.0732402 1.0773706
    ## [5,] 0.9631745 0.9722813 0.9730901
    ## [6,] 1.0308864 1.0404593 1.0471570

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,] 1609  230 4740 7893 6936
    ## [2,] 9866 2374 2727 5105 8495
    ## [3,] 4754 9459 9335  317 7562
    ## [4,] 7411 2227  504 5476 2815
    ## [5,] 8226 3591 9421 5527 6702
    ## [6,] 4988 6674 4922 8039 6383

    head(qout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]
    ## [1,] 0.8729007 0.9087039 0.9206789 0.9246762 0.9318908
    ## [2,] 0.9030831 1.0121571 1.0381407 1.0488544 1.0750477
    ## [3,] 0.9796339 1.0190191 1.0425032 1.0494409 1.0760559
    ## [4,] 0.7905686 1.0034263 1.0217109 1.0532752 1.0586537
    ## [5,] 0.9743927 1.0033261 1.0132596 1.0454088 1.0479200
    ## [6,] 1.0119573 1.0856533 1.1718854 1.1786671 1.2249707

# 3 Further options

Most of the options described for the KMKNN algorithm 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 <- buildNNIndex(data, BNPARAM=AnnoyParam())
    out1 <- findKNN(BNINDEX=pre, k=5)
    out2 <- queryKNN(BNINDEX=pre, query=query, k=2)

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

# 4 Saving the index files

The forest of trees form an indexing structure that is saved to file. 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 parallelized access. and will be removed when the session finishes.

    AnnoyIndex_path(pre)

    ## [1] "/tmp/RtmpFA332q/file2b8a529f85b.idx"

If the index is to persist across sessions, the path of the index file can be directly specified in `buildNNIndex`. However, this means that it becomes the responsibility of the user to clean up any temporary indexing files after calculations are complete.

# 5 Session information

    sessionInfo()

    ## R version 3.5.1 Patched (2018-07-12 r74967)
    ## Platform: x86_64-pc-linux-gnu (64-bit)
    ## Running under: Ubuntu 16.04.5 LTS
    ##
    ## Matrix products: default
    ## BLAS: /home/biocbuild/bbs-3.8-bioc/R/lib/libRblas.so
    ## LAPACK: /home/biocbuild/bbs-3.8-bioc/R/lib/libRlapack.so
    ##
    ## locale:
    ##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C
    ##  [3] LC_TIME=en_US.UTF-8        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
    ##
    ## attached base packages:
    ## [1] stats     graphics  grDevices utils     datasets  methods   base
    ##
    ## other attached packages:
    ## [1] BiocNeighbors_1.0.0 BiocParallel_1.16.0 knitr_1.20
    ## [4] BiocStyle_2.10.0
    ##
    ## loaded via a namespace (and not attached):
    ##  [1] Rcpp_0.12.19        bookdown_0.7        digest_0.6.18
    ##  [4] rprojroot_1.3-2     backports_1.1.2     stats4_3.5.1
    ##  [7] magrittr_1.5        evaluate_0.12       stringi_1.2.4
    ## [10] S4Vectors_0.20.0    rmarkdown_1.10      tools_3.5.1
    ## [13] stringr_1.3.1       parallel_3.5.1      xfun_0.4
    ## [16] yaml_2.2.0          compiler_3.5.1      BiocGenerics_0.28.0
    ## [19] BiocManager_1.30.3  htmltools_0.3.6