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 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,] 2661 6492 2756  237  684 7701 9787 3095 1826  9552
## [2,] 4859 1210 3277 1778 7103 9789  374 5634 5084  5620
## [3,] 4694 6848 3683  510 9040 2563 7019 7366 3735  4636
## [4,] 7381 4489 7973 2885 6887 6775 7082 9072 1707  7712
## [5,] 1394 3971 3968 8155 5261 5068  388 3897 4678  9599
## [6,] 9446 1126 8880 7546 9810  907 7157 3686 7822  4303
head(fout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
## [1,] 0.8654638 0.9535729 1.0077290 1.0295951 1.0323147 1.0541938 1.0570183
## [2,] 0.9145345 0.9206711 0.9229124 0.9245392 0.9450800 0.9629023 0.9692117
## [3,] 1.0265581 1.0337355 1.0560977 1.0737594 1.1276760 1.1446531 1.1468746
## [4,] 0.8544521 0.9131057 0.9540308 0.9688714 0.9970425 0.9997975 1.0049503
## [5,] 0.8244841 0.8321083 0.9080428 0.9613234 0.9700471 1.0051207 1.0120126
## [6,] 1.0527058 1.0609092 1.0708079 1.1004113 1.1075524 1.1085332 1.1384052
##           [,8]      [,9]     [,10]
## [1,] 1.0581257 1.0803890 1.0947719
## [2,] 0.9716097 0.9883049 0.9948619
## [3,] 1.1470072 1.1523483 1.1688556
## [4,] 1.0183726 1.0310184 1.0312885
## [5,] 1.0120817 1.0236799 1.0265586
## [6,] 1.1399951 1.1407685 1.1431061

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] 4694 6848 3683  510 9040 2563 7019 7366 3735 4636

… with the following distances to those neighbors:

fout$distance[3,]
##  [1] 1.026558 1.033735 1.056098 1.073759 1.127676 1.144653 1.146875 1.147007
##  [9] 1.152348 1.168856

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,] 9844 3194 1513 5247 6033
## [2,] 8888 2991 3265 6311 8374
## [3,] 3743 8487 7233 1724 6681
## [4,] 9019 9713 3842 8655 4988
## [5,] 2680 4078 5681 4660 6069
## [6,] 3726 1544 2942 4011 3906
head(qout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 0.9453399 0.9509586 0.9904098 0.9984148 0.9997978
## [2,] 0.8806979 0.9847233 1.0043239 1.0445519 1.0692883
## [3,] 1.0144867 1.0174494 1.0224253 1.0816820 1.0859760
## [4,] 0.9688324 0.9724813 0.9758763 0.9846959 0.9854293
## [5,] 0.8362832 0.9594774 1.0064043 1.0107347 1.0161235
## [6,] 0.8784129 0.9174766 0.9415841 1.0375903 1.0432677

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] 3743 8487 7233 1724 6681

… with the following distances to those neighbors:

qout$distance[3,]
## [1] 1.014487 1.017449 1.022425 1.081682 1.085976

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,] 4694 6848 3683  510 9040
## [2,] 7381 4489 7973 2885 6887
## [3,] 1394 3971 3968 8155 5261
## 
## $distance
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 1.0265581 1.0337355 1.0560977 1.0737594 1.1276760
## [2,] 0.8544521 0.9131057 0.9540308 0.9688714 0.9970425
## [3,] 0.8244841 0.8321083 0.9080428 0.9613234 0.9700471

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 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.0.0 (2020-04-24)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 18.04.4 LTS
## 
## Matrix products: default
## BLAS:   /home/biocbuild/bbs-3.11-bioc/R/lib/libRblas.so
## LAPACK: /home/biocbuild/bbs-3.11-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] BiocParallel_1.22.0 BiocNeighbors_1.6.0 knitr_1.28         
## [4] BiocStyle_2.16.0   
## 
## loaded via a namespace (and not attached):
##  [1] Rcpp_1.0.4.6        bookdown_0.18       lattice_0.20-41    
##  [4] digest_0.6.25       grid_4.0.0          stats4_4.0.0       
##  [7] magrittr_1.5        evaluate_0.14       rlang_0.4.5        
## [10] stringi_1.4.6       S4Vectors_0.26.0    Matrix_1.2-18      
## [13] rmarkdown_2.1       tools_4.0.0         stringr_1.4.0      
## [16] parallel_4.0.0      xfun_0.13           yaml_2.2.1         
## [19] compiler_4.0.0      BiocGenerics_0.34.0 BiocManager_1.30.10
## [22] htmltools_0.4.0

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.