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,] 6824  785  310 5417 6452 1299 8029 6280 1327  5011
## [2,] 6336 1355 8299 3386 7678 6633 3882 8351 7917  8375
## [3,]  976 2926  525  916 3486 8238 3259 2300 8044  6738
## [4,] 4318 9353 7170 4508 5422 9890 7656 2897  738  5625
## [5,] 7260 7473  225 9144 4646  969 4769 2857 6447  6142
## [6,] 8296 2670 3217 4491  585 3904 7244 8106 6281  2688
head(fout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
## [1,] 0.9316278 0.9544263 0.9659454 0.9951629 1.0046510 1.0096569 1.0630784
## [2,] 0.8712304 0.8949821 0.9091715 0.9106557 0.9226406 0.9372379 0.9593607
## [3,] 0.9552110 0.9793939 1.0738635 1.1039845 1.1140267 1.1243279 1.1258000
## [4,] 1.1038792 1.1303407 1.1389502 1.1482181 1.1605684 1.1700002 1.1705975
## [5,] 0.8386672 0.8653343 0.8764472 0.8801504 0.9953194 1.0272324 1.0273986
## [6,] 0.8538452 0.9031763 0.9551028 0.9694123 0.9696303 0.9706063 1.0033187
##           [,8]      [,9]     [,10]
## [1,] 1.0705245 1.0764675 1.0765348
## [2,] 0.9619467 0.9665224 0.9813825
## [3,] 1.1488759 1.1774701 1.1835828
## [4,] 1.1717133 1.1803322 1.1806312
## [5,] 1.0314364 1.0380102 1.0628315
## [6,] 1.0189871 1.0257382 1.0332624

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]  976 2926  525  916 3486 8238 3259 2300 8044 6738

… with the following distances to those neighbors:

fout$distance[3,]
##  [1] 0.9552110 0.9793939 1.0738635 1.1039845 1.1140267 1.1243279 1.1258000
##  [8] 1.1488759 1.1774701 1.1835828

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,] 9806 3674  692 1647 9390
## [2,] 7799 2670 6302 1370 3062
## [3,] 7076 4098 3130 2343 6550
## [4,] 3463 4173 3170 4518 4232
## [5,] 8056 9714 8225 5218 5504
## [6,] 2278 3417 4590 6595  389
head(qout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 0.9318871 0.9622434 0.9720072 1.0064636 1.0287397
## [2,] 0.9722240 0.9929964 1.0331243 1.0450943 1.0853969
## [3,] 0.9231742 0.9409917 0.9531869 0.9558733 0.9635372
## [4,] 1.0453552 1.0651827 1.1110755 1.1545569 1.1551394
## [5,] 0.8763046 0.9339019 0.9738064 0.9838785 0.9854353
## [6,] 0.9005429 0.9581917 0.9611703 0.9799628 1.0038721

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] 7076 4098 3130 2343 6550

… with the following distances to those neighbors:

qout$distance[3,]
## [1] 0.9231742 0.9409917 0.9531869 0.9558733 0.9635372

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,]  976 2926  525  916 3486
## [2,] 4318 9353 7170 4508 5422
## [3,] 7260 7473  225 9144 4646
## 
## $distance
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 0.9552110 0.9793939 1.0738635 1.1039845 1.1140267
## [2,] 1.1038792 1.1303407 1.1389502 1.1482181 1.1605684
## [3,] 0.8386672 0.8653343 0.8764472 0.8801504 0.9953194

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-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.4 LTS
## 
## Matrix products: default
## BLAS:   /home/biocbuild/bbs-3.15-bioc/R/lib/libRblas.so
## LAPACK: /home/biocbuild/bbs-3.15-bioc/R/lib/libRlapack.so
## 
## 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       
## 
## 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.