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.

Both methods involve a component of randomness during index construction, though the k-nearest neighbors result is fully deterministic1 Except in the presence of ties, see ?findKNN 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,] 2611 1455 8265 7906 5597 6420 7990 2741 4625  1416
## [2,] 3144 8899 1044 3964 9630 1144 1154 8818  577  3221
## [3,]  845  860 7204 2018 1710 1456 8345 9758 5480  5790
## [4,] 7499 5948 6292 4181    6 5799 7449 9071 6547  7520
## [5,] 6616 2433 8250  736  597 2403 5976 9750 4653  5006
## [6,] 8410 8627 6070 6843 8794 8836 3872 5802 8919  6469
head(fout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
## [1,] 0.7443332 0.8265739 0.9034054 0.9045826 0.9376346 0.9382075 0.9410192
## [2,] 0.9721935 1.0178130 1.0257161 1.0264498 1.0636917 1.0649762 1.0655651
## [3,] 0.8812944 0.9372977 0.9517617 0.9644498 1.0185278 1.0294998 1.0405074
## [4,] 1.0233953 1.0266353 1.0579811 1.0716241 1.0862288 1.1167280 1.1186260
## [5,] 0.9276079 0.9957344 1.0092712 1.0230559 1.0753146 1.0920685 1.1134526
## [6,] 0.8110613 0.9393808 0.9585001 0.9649054 0.9920358 0.9971239 1.0027644
##           [,8]      [,9]     [,10]
## [1,] 0.9638958 0.9679633 0.9746096
## [2,] 1.0730469 1.0747894 1.0853011
## [3,] 1.0410095 1.0451696 1.0565634
## [4,] 1.1299000 1.1569201 1.1667648
## [5,] 1.1273183 1.1290897 1.1484358
## [6,] 1.0157788 1.0178664 1.0363335

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]  845  860 7204 2018 1710 1456 8345 9758 5480 5790

… with the following distances to those neighbors:

fout$distance[3,]
##  [1] 0.8812944 0.9372977 0.9517617 0.9644498 1.0185278 1.0294998 1.0405074
##  [8] 1.0410095 1.0451696 1.0565634

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,] 4066 6109 9726 2924 9032
## [2,] 7904 3020 9820 5055 9226
## [3,]  892 7782  714 5325 7527
## [4,]  123 5178 7749 6432 1863
## [5,] 1763 7922 1074 4172 8314
## [6,] 3780 7442 9112 8818  133
head(qout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 0.7743226 0.9133076 0.9422172 0.9426692 0.9538491
## [2,] 0.8307646 0.9025309 0.9482951 0.9658060 0.9808643
## [3,] 0.8777280 0.8813021 0.9283698 0.9286381 0.9332893
## [4,] 0.8691112 0.9090381 1.0019596 1.0351455 1.0491174
## [5,] 0.9250452 0.9387339 0.9704878 0.9759447 1.0221966
## [6,] 0.9380530 0.9564137 0.9661672 0.9765563 0.9850136

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]  892 7782  714 5325 7527

… with the following distances to those neighbors:

qout$distance[3,]
## [1] 0.8777280 0.8813021 0.9283698 0.9286381 0.9332893

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,]  845  860 7204 2018 1710
## [2,] 7499 5948 6292 4181    6
## [3,] 6616 2433 8250  736  597
## 
## $distance
##           [,1]      [,2]      [,3]      [,4]     [,5]
## [1,] 0.8812944 0.9372977 0.9517617 0.9644498 1.018528
## [2,] 1.0233953 1.0266353 1.0579811 1.0716241 1.086229
## [3,] 0.9276079 0.9957344 1.0092712 1.0230559 1.075315

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 alpha (2020-04-05 r78150)
## Platform: x86_64-apple-darwin17.0 (64-bit)
## Running under: macOS Mojave 10.14.6
## 
## Matrix products: default
## BLAS:   /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRblas.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] BiocParallel_1.21.3 BiocNeighbors_1.5.6 knitr_1.28         
## [4] BiocStyle_2.15.8   
## 
## 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.25.15   Matrix_1.2-18      
## [13] rmarkdown_2.1.2     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.33.3 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.