# 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,]  912 8294 7729 2026   81 7343 2517 5206 1706  9799
    ## [2,] 6377 9426 2435 1756 3980 4348 3668 4581 2947  7409
    ## [3,] 9645 2200 9266 5750 7445 8756 4389 5813 8963  5794
    ## [4,] 8724 6029 7329 3312 1565 8148  585 2828 5403   847
    ## [5,] 4030 8690 7974  586 6119 2616 5974 9414 5689  4157
    ## [6,]  190 8628 2943 1189 2778 3502 6424 1700 7971   994

    head(fout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
    ## [1,] 0.8655224 0.9281371 0.9455947 0.9563929 0.9578933 0.9769028 0.9814019
    ## [2,] 0.9602075 0.9673365 1.0580183 1.1010623 1.1056880 1.1072507 1.1195480
    ## [3,] 1.0516299 1.0557061 1.1193665 1.1306777 1.1415404 1.1658137 1.1732579
    ## [4,] 0.8032902 0.9038874 0.9260879 1.0057633 1.0232835 1.0360852 1.0452842
    ## [5,] 0.7521148 0.8855975 0.9091314 0.9546298 0.9636804 0.9693480 0.9795035
    ## [6,] 0.6888335 0.7734606 0.8134016 0.8927612 0.9239994 0.9243676 0.9407981
    ##           [,8]      [,9]     [,10]
    ## [1,] 0.9933581 1.0151237 1.0216950
    ## [2,] 1.1337593 1.1402434 1.1459430
    ## [3,] 1.1742585 1.1803825 1.1806593
    ## [4,] 1.0481485 1.0574745 1.0668837
    ## [5,] 0.9892922 0.9948111 0.9992599
    ## [6,] 0.9485767 0.9559917 0.9593235

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,] 1482 1335 2138 2616 5665
    ## [2,] 2559 5237 7892 1772 6923
    ## [3,]  741 1570 1798 6524  935
    ## [4,]  335 3307 7872 6937 6732
    ## [5,] 1120 8107 4960 7325 1318
    ## [6,] 7125 9169  599  659 2954

    head(qout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]
    ## [1,] 0.8288361 1.0365449 1.0719490 1.1187934 1.1299849
    ## [2,] 0.9155446 1.0002578 1.0138111 1.0192744 1.0231422
    ## [3,] 0.9103767 0.9601046 0.9663674 0.9694106 0.9854659
    ## [4,] 0.8945100 0.9371412 1.0273383 1.0341181 1.0419079
    ## [5,] 0.9933828 1.0477595 1.0719093 1.0906005 1.1151358
    ## [6,] 1.0566332 1.1369480 1.1400468 1.1501371 1.1521964

# 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] "C:\\Users\\biocbuild\\bbs-3.8-bioc\\tmpdir\\Rtmpgl5V5h\\file144c3b811550.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-24 r75008)
    ## 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] 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