Detecting approximate nearest neighbors

opts_chunk$set(error=FALSE, message=FALSE, warning=FALSE)


The r Biocpkg("BiocNeighbors") package provides several algorithms for approximate neighbor searches:

These methods complement the exact algorithms r Biocpkg("BiocNeighbors", vignette="exact.html", label="described previously"). Again, it is straightforward to switch from one algorithm to another by simply changing the BNPARAM argument in findKNN and queryKNN.

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())

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())

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

Further options

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

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.

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()^[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.


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.

Session information


Try the BiocNeighbors package in your browser

Any scripts or data that you put into this service are public.

BiocNeighbors documentation built on Dec. 9, 2020, 2:01 a.m.