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,] 3593 4313  907 1002 7282 8683 3595 8399  848  6678
## [2,] 7802 9655 7344 4817 8689 5888 2030 4944 3693  6272
## [3,] 1219 5122 6269 1648 2869  678 6353 2478 7158  8680
## [4,] 7319 9218 7258 8506 6977 6956 4402 1217 8731  7582
## [5,] 8899 9789 9488 3160 3675 6385 3564 8917 2255  2774
## [6,] 3629 9958 4358 5831    9 3585 6049 7790 6317  5331
head(fout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
## [1,] 1.0278047 1.0306726 1.0504756 1.0959360 1.1137915 1.1190509 1.1333746
## [2,] 0.9077045 0.9805629 1.0074328 1.0353564 1.0626669 1.0678195 1.0991695
## [3,] 0.9751269 1.0438264 1.0454963 1.0472891 1.0680452 1.0693661 1.0892393
## [4,] 0.9033597 0.9723765 1.0115388 1.0618291 1.0626665 1.0682732 1.0687832
## [5,] 0.6474258 0.8182325 0.8775846 0.8806179 0.9276964 0.9334993 0.9476659
## [6,] 0.9429028 1.0239210 1.0457233 1.1014457 1.1314009 1.1385395 1.1463713
##          [,8]      [,9]     [,10]
## [1,] 1.138833 1.1494311 1.1495873
## [2,] 1.106937 1.1088017 1.1162130
## [3,] 1.109377 1.1215955 1.1285174
## [4,] 1.082938 1.0829724 1.0930714
## [5,] 0.953771 0.9594747 0.9653706
## [6,] 1.157123 1.1734521 1.1816066

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] 1219 5122 6269 1648 2869  678 6353 2478 7158 8680

… with the following distances to those neighbors:

fout$distance[3,]
##  [1] 0.9751269 1.0438264 1.0454963 1.0472891 1.0680452 1.0693661 1.0892393
##  [8] 1.1093768 1.1215955 1.1285174

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,] 2615  933 8453 8891 4696
## [2,] 3628 6227 3619 8621 8746
## [3,] 1788 7082 9884 6208   31
## [4,]  602  658 1434 8155 5610
## [5,] 7639 6570 7619 3877 4817
## [6,] 7447 4731 3711 3697 5095
head(qout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 1.0138632 1.0480533 1.0631914 1.0776290 1.0813289
## [2,] 0.9431117 0.9595148 0.9787943 0.9889256 1.0026289
## [3,] 0.8276454 0.8506553 0.9483997 0.9526141 1.1051499
## [4,] 0.9278760 0.9476145 1.0020613 1.0325332 1.0370940
## [5,] 0.8527885 0.8915468 0.8942529 0.8984609 0.9114426
## [6,] 1.0185486 1.0238605 1.0364221 1.0548117 1.0588723

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] 1788 7082 9884 6208   31

… with the following distances to those neighbors:

qout$distance[3,]
## [1] 0.8276454 0.8506553 0.9483997 0.9526141 1.1051499

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,] 1219 5122 6269 1648 2869
## [2,] 7319 9218 7258 8506 6977
## [3,] 8899 9789 9488 3160 3675
## 
## $distance
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 0.9751269 1.0438264 1.0454963 1.0472891 1.0680452
## [2,] 0.9033597 0.9723765 1.0115388 1.0618291 1.0626665
## [3,] 0.6474258 0.8182325 0.8775846 0.8806179 0.9276964

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.2.0 RC (2022-04-19 r82224)
## 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.2/Resources/lib/libRblas.0.dylib
## LAPACK: /Library/Frameworks/R.framework/Versions/4.2/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.30.0  BiocNeighbors_1.14.0 knitr_1.38          
## [4] BiocStyle_2.24.0    
## 
## loaded via a namespace (and not attached):
##  [1] Rcpp_1.0.8.3        magrittr_2.0.3      BiocGenerics_0.42.0
##  [4] lattice_0.20-45     R6_2.5.1            rlang_1.0.2        
##  [7] fastmap_1.1.0       stringr_1.4.0       tools_4.2.0        
## [10] parallel_4.2.0      grid_4.2.0          xfun_0.30          
## [13] cli_3.3.0           jquerylib_0.1.4     htmltools_0.5.2    
## [16] yaml_2.3.5          digest_0.6.29       bookdown_0.26      
## [19] Matrix_1.4-1        BiocManager_1.30.17 S4Vectors_0.34.0   
## [22] sass_0.4.1          evaluate_0.15       rmarkdown_2.14     
## [25] stringi_1.7.6       compiler_4.2.0      bslib_0.3.1        
## [28] stats4_4.2.0        jsonlite_1.8.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.