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,] 1169 8334 9903 7108 8206 4333 1204 5552 4951  2886
## [2,] 3907 7013 7764 5540 2556 7777 9576 2513 1741   628
## [3,] 4076 2060 3085 6134 7438 9720 3205 2687 3253  5892
## [4,] 3242 5891 2856 8632 6019 1707 8951 1169 2539  3236
## [5,] 6283 8658 4334 3514 1324 4110 1215 7195  696  3375
## [6,] 4217  526 4369 9302 9973 1153 5254 6618 6139  5073
head(fout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
## [1,] 0.9271565 0.9439796 0.9537623 0.9639954 0.9640908 0.9716235 0.9727909
## [2,] 0.9600914 1.0310209 1.0490523 1.0552120 1.0669063 1.0766750 1.0785137
## [3,] 0.9540868 0.9738868 1.0133411 1.0170712 1.0658738 1.0984834 1.1043416
## [4,] 0.7575382 0.8041263 0.8089544 0.8649007 0.8724650 0.8890436 0.9082128
## [5,] 0.9396693 0.9419785 0.9440824 0.9473681 0.9508728 0.9574560 0.9800795
## [6,] 0.9021591 0.9446898 0.9484428 0.9915919 0.9972288 1.0008144 1.0120944
##           [,8]      [,9]     [,10]
## [1,] 0.9774148 0.9826766 0.9855517
## [2,] 1.0796966 1.0887189 1.0955379
## [3,] 1.1191775 1.1202664 1.1209700
## [4,] 0.9089586 0.9253481 0.9480799
## [5,] 0.9809970 0.9862728 0.9931683
## [6,] 1.0270834 1.0476586 1.0482034

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] 4076 2060 3085 6134 7438 9720 3205 2687 3253 5892

… with the following distances to those neighbors:

fout$distance[3,]
##  [1] 0.9540868 0.9738868 1.0133411 1.0170712 1.0658738 1.0984834 1.1043416
##  [8] 1.1191775 1.1202664 1.1209700

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,] 6152 6958 5401 8275 3888
## [2,] 7328 6291 1764 8565 1097
## [3,] 7429 2721 7172 1562 4268
## [4,]  743  397  782 6399 3339
## [5,] 8730 7827 5058 4271 7662
## [6,] 6255 2984 2386 1046 3480
head(qout$distance)
##           [,1]      [,2]      [,3]      [,4]     [,5]
## [1,] 0.8941259 0.9236409 0.9501536 0.9534488 0.984450
## [2,] 0.8967043 0.9070304 0.9227707 0.9981721 1.000933
## [3,] 0.9361129 1.0361750 1.1019223 1.1176439 1.130777
## [4,] 0.9715666 0.9727544 0.9760436 0.9987773 1.001732
## [5,] 0.9488184 1.0291469 1.0489787 1.1296176 1.172825
## [6,] 0.9868379 0.9910716 1.0356435 1.0628384 1.070709

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] 7429 2721 7172 1562 4268

… with the following distances to those neighbors:

qout$distance[3,]
## [1] 0.9361129 1.0361750 1.1019223 1.1176439 1.1307769

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,] 4076 2060 3085 6134 7438
## [2,] 3242 5891 2856 8632 6019
## [3,] 6283 8658 4334 3514 1324
## 
## $distance
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 0.9540868 0.9738868 1.0133411 1.0170712 1.0658738
## [2,] 0.7575382 0.8041263 0.8089544 0.8649007 0.8724650
## [3,] 0.9396693 0.9419785 0.9440824 0.9473681 0.9508728

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 Under development (unstable) (2023-11-11 r85510)
## Platform: x86_64-pc-linux-gnu
## Running under: Ubuntu 22.04.3 LTS
## 
## Matrix products: default
## BLAS:   /home/biocbuild/bbs-3.19-bioc/R/lib/libRblas.so 
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.10.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_GB              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       
## 
## time zone: America/New_York
## tzcode source: system (glibc)
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] BiocParallel_1.37.0  BiocNeighbors_1.21.2 knitr_1.45          
## [4] BiocStyle_2.31.0    
## 
## loaded via a namespace (and not attached):
##  [1] cli_3.6.2           rlang_1.1.2         xfun_0.41          
##  [4] jsonlite_1.8.8      S4Vectors_0.41.2    htmltools_0.5.7    
##  [7] stats4_4.4.0        sass_0.4.8          rmarkdown_2.25     
## [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.37       BiocManager_1.30.22 compiler_4.4.0     
## [19] codetools_0.2-19    Rcpp_1.0.11         lattice_0.22-5     
## [22] digest_0.6.33       R6_2.5.1            parallel_4.4.0     
## [25] bslib_0.6.1         Matrix_1.6-4        tools_4.4.0        
## [28] BiocGenerics_0.49.1 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–8.

Yianilos, P. N. 1993. “Data Structures and Algorithms for Nearest Neighbor Search in General Metric Spaces.” In SODA, 93:311–21. 194.