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,] 9807 2027 9072 9141 4545 4720 1047 8271 4179  8402
## [2,] 8238 4499 6202 1063 7131 8545 1398 9335 6537  6354
## [3,] 9466 4054 1798 8175 2910 8408 2921 4443 1917  2310
## [4,]  672 4714 1313 2134 6864 4512 8774 3180 1812  1310
## [5,] 9394 5775  589 4430 7131  727 6450 9766 3722  2957
## [6,] 7054 5099 6085 1258 4773  181 6594 3137 7131   621
head(fout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
## [1,] 0.8029993 0.8619781 1.0233647 1.0253978 1.0331460 1.0584929 1.0644485
## [2,] 0.9272425 0.9303490 0.9405530 0.9530761 0.9746595 1.0011566 1.0353124
## [3,] 0.8601126 0.9268570 0.9418621 0.9475276 0.9741962 0.9821631 0.9925872
## [4,] 0.8928506 0.9518442 0.9661308 0.9984138 1.0165544 1.0412973 1.0636039
## [5,] 1.0349288 1.0381253 1.0678044 1.0723444 1.0940562 1.0948337 1.0969092
## [6,] 0.9100995 0.9662203 0.9818912 1.0082017 1.0164379 1.0383214 1.0435660
##           [,8]     [,9]    [,10]
## [1,] 1.0664330 1.069151 1.072377
## [2,] 1.0381568 1.044041 1.046707
## [3,] 0.9973036 1.018176 1.035821
## [4,] 1.0764116 1.076812 1.079538
## [5,] 1.1044750 1.112224 1.122354
## [6,] 1.0535371 1.061944 1.087267

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] 9466 4054 1798 8175 2910 8408 2921 4443 1917 2310

… with the following distances to those neighbors:

fout$distance[3,]
##  [1] 0.8601126 0.9268570 0.9418621 0.9475276 0.9741962 0.9821631 0.9925872
##  [8] 0.9973036 1.0181758 1.0358213

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,] 7777 1779 9547 2768  403
## [2,] 7194 4397  966 9155 4929
## [3,] 8238 8112  271 4482 4499
## [4,] 1900 1085 8161 3601 4391
## [5,] 1289 1536 2160 4594 4788
## [6,] 2557 3518 1932 6367 3886
head(qout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 0.8416128 0.9034852 0.9075590 0.9221376 0.9424425
## [2,] 0.8227091 0.8874959 0.9100663 0.9753504 1.0011267
## [3,] 0.8913444 0.9360598 0.9378437 0.9951432 0.9969981
## [4,] 0.7219239 0.8953267 0.8967805 0.9117143 0.9130250
## [5,] 0.9208902 0.9376989 0.9389022 0.9608645 0.9730416
## [6,] 0.8336378 0.8525780 0.8913728 0.9039267 0.9283180

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] 8238 8112  271 4482 4499

… with the following distances to those neighbors:

qout$distance[3,]
## [1] 0.8913444 0.9360598 0.9378437 0.9951432 0.9969981

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,] 9466 4054 1798 8175 2910
## [2,]  672 4714 1313 2134 6864
## [3,] 9394 5775  589 4430 7131
## 
## $distance
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 0.8601126 0.9268570 0.9418621 0.9475276 0.9741962
## [2,] 0.8928506 0.9518442 0.9661308 0.9984138 1.0165544
## [3,] 1.0349288 1.0381253 1.0678044 1.0723444 1.0940562

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.4.0 Patched (2024-04-24 r86482)
## Platform: aarch64-apple-darwin20
## Running under: macOS Ventura 13.6.6
## 
## Matrix products: default
## BLAS:   /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/lib/libRblas.0.dylib 
## LAPACK: /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/lib/libRlapack.dylib;  LAPACK version 3.12.0
## 
## locale:
## [1] C/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
## 
## time zone: America/New_York
## tzcode source: internal
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] BiocParallel_1.39.0  BiocNeighbors_1.23.0 knitr_1.46          
## [4] BiocStyle_2.33.0    
## 
## loaded via a namespace (and not attached):
##  [1] cli_3.6.2           rlang_1.1.3         xfun_0.43          
##  [4] jsonlite_1.8.8      S4Vectors_0.43.0    htmltools_0.5.8.1  
##  [7] stats4_4.4.0        sass_0.4.9          rmarkdown_2.26     
## [10] grid_4.4.0          evaluate_0.23       jquerylib_0.1.4    
## [13] fastmap_1.1.1       yaml_2.3.8          lifecycle_1.0.4    
## [16] bookdown_0.39       BiocManager_1.30.22 compiler_4.4.0     
## [19] codetools_0.2-20    Rcpp_1.0.12         lattice_0.22-6     
## [22] digest_0.6.35       R6_2.5.1            parallel_4.4.0     
## [25] bslib_0.7.0         Matrix_1.7-0        tools_4.4.0        
## [28] BiocGenerics_0.51.0 cachem_1.0.8

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–58.
Yianilos, P. N. 1993. “Data Structures and Algorithms for Nearest Neighbor Search in General Metric Spaces.” In SODA, 93:311–21. 194.