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,] 9629 7078  420 3812 7144 4759 3046 5669 8345  6771
## [2,] 8019 1673 1725 3301 6055 5997 9922 7356 4948  8311
## [3,]  899 6723 3117 9950 6023 3613 4642  690 1340  4678
## [4,] 5172 8417 1658 2938  346   90 5589 4345  862  4860
## [5,] 4968 6657 9264 5120 2009 3134  642 3794 6646  4110
## [6,] 8714 9364 8058 9303 8589 3872 1254 7631 2870  5413
head(fout$distance)
##           [,1]      [,2]      [,3]      [,4]     [,5]     [,6]     [,7]
## [1,] 0.9027233 1.0066617 1.0136870 1.0183285 1.032744 1.034925 1.040121
## [2,] 1.0119756 1.0351176 1.0430094 1.0466482 1.050442 1.087091 1.096873
## [3,] 0.8611765 0.9752437 0.9986993 1.0130224 1.071739 1.071879 1.075845
## [4,] 0.9627508 0.9997445 1.0232153 1.0406167 1.042692 1.074789 1.079032
## [5,] 0.8300004 0.9615336 0.9992897 1.0114589 1.027239 1.028498 1.042440
## [6,] 0.8133019 0.8872547 0.9370184 0.9843907 1.068541 1.068932 1.074218
##          [,8]     [,9]    [,10]
## [1,] 1.053836 1.057407 1.064367
## [2,] 1.108921 1.109110 1.117482
## [3,] 1.089322 1.089445 1.096004
## [4,] 1.128616 1.142114 1.146305
## [5,] 1.046780 1.051033 1.051277
## [6,] 1.098834 1.101684 1.119916

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]  899 6723 3117 9950 6023 3613 4642  690 1340 4678

… with the following distances to those neighbors:

fout$distance[3,]
##  [1] 0.8611765 0.9752437 0.9986993 1.0130224 1.0717389 1.0718787 1.0758452
##  [8] 1.0893221 1.0894445 1.0960035

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,] 8410 5453 6233 1194 5137
## [2,] 2925 3832 7120 3506 9440
## [3,] 5262 2818 1284 6702 6907
## [4,] 8693 1595 2698  430 9916
## [5,] 5578 4296 1815 8532 2703
## [6,] 7281 7663 6741 7147 4111
head(qout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 0.9012505 0.9149644 0.9234280 0.9432358 0.9473960
## [2,] 0.9745036 1.0053286 1.0642224 1.0719666 1.0786551
## [3,] 0.8923212 0.9277436 0.9297912 0.9300056 0.9564014
## [4,] 0.8806939 0.9629447 0.9660313 0.9802799 0.9878287
## [5,] 0.9346088 1.0251025 1.0456104 1.0575560 1.0588644
## [6,] 1.0273251 1.0282267 1.0341404 1.0755953 1.1013998

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] 5262 2818 1284 6702 6907

… with the following distances to those neighbors:

qout$distance[3,]
## [1] 0.8923212 0.9277436 0.9297912 0.9300056 0.9564014

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,]  899 6723 3117 9950 6023
## [2,] 5172 8417 1658 2938  346
## [3,] 4968 6657 9264 5120 2009
## 
## $distance
##           [,1]      [,2]      [,3]     [,4]     [,5]
## [1,] 0.8611765 0.9752437 0.9986993 1.013022 1.071739
## [2,] 0.9627508 0.9997445 1.0232153 1.040617 1.042692
## [3,] 0.8300004 0.9615336 0.9992897 1.011459 1.027239

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.3.0 RC (2023-04-18 r84287)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 22.04.2 LTS
## 
## Matrix products: default
## BLAS:   /home/biocbuild/bbs-3.18-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.35.0  BiocNeighbors_1.19.0 knitr_1.42          
## [4] BiocStyle_2.29.0    
## 
## loaded via a namespace (and not attached):
##  [1] cli_3.6.1           rlang_1.1.0         xfun_0.39          
##  [4] jsonlite_1.8.4      S4Vectors_0.39.0    htmltools_0.5.5    
##  [7] stats4_4.3.0        sass_0.4.5          rmarkdown_2.21     
## [10] grid_4.3.0          evaluate_0.20       jquerylib_0.1.4    
## [13] fastmap_1.1.1       yaml_2.3.7          bookdown_0.33      
## [16] BiocManager_1.30.20 compiler_4.3.0      codetools_0.2-19   
## [19] Rcpp_1.0.10         lattice_0.21-8      digest_0.6.31      
## [22] R6_2.5.1            parallel_4.3.0      bslib_0.4.2        
## [25] Matrix_1.5-4        tools_4.3.0         BiocGenerics_0.47.0
## [28] cachem_1.0.7

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.