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,] 3990 1256 2678 8189 1786 5729 5726 1542 5000  1416
## [2,] 5723 7206  162  508 7157 2557 6072  645 3507  3219
## [3,] 3150 2092 8001 2389 3315 3017  416 7905 1343  2104
## [4,] 6592 8313 2598 4078 9490 3143 1649 5658 6134  7544
## [5,]  747 5797 5847 6325 6183 8674 1091 1408  712   616
## [6,] 2706 5154 5955 1131 9008 8692 8837  146 9084   149
head(fout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
## [1,] 1.0192533 1.0247568 1.0281821 1.0488706 1.0500594 1.0512640 1.0619946
## [2,] 0.8311384 0.8937575 0.9153321 0.9483128 0.9789319 1.0855162 1.0865905
## [3,] 1.0448792 1.1124269 1.1202775 1.1307786 1.1824509 1.1908090 1.2053786
## [4,] 0.7515965 0.8451115 0.8463285 0.8773696 0.8788666 0.8837025 0.8980226
## [5,] 0.8458863 0.9264530 0.9888018 1.0014175 1.0027488 1.0098700 1.0128590
## [6,] 0.9340589 1.0078800 1.0261086 1.0402877 1.0534461 1.0604241 1.1142859
##           [,8]      [,9]     [,10]
## [1,] 1.0730520 1.0745016 1.0760593
## [2,] 1.0958460 1.1005297 1.1071504
## [3,] 1.2099943 1.2122591 1.2151444
## [4,] 0.9053535 0.9185046 0.9222714
## [5,] 1.0157803 1.0190847 1.0253924
## [6,] 1.1289262 1.1301519 1.1528408

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] 3150 2092 8001 2389 3315 3017  416 7905 1343 2104

… with the following distances to those neighbors:

fout$distance[3,]
##  [1] 1.044879 1.112427 1.120277 1.130779 1.182451 1.190809 1.205379 1.209994
##  [9] 1.212259 1.215144

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,] 6401 1014 5776 9858 6161
## [2,] 2902 7581 1169 1316 4376
## [3,] 3652  170 7005 9353 7201
## [4,] 2215 9568 5005 5033 2814
## [5,] 5743 5242 2632 4851 4115
## [6,] 1809 9397 8548 5473 5132
head(qout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 0.8050374 0.8462342 0.8506457 0.9750981 0.9802985
## [2,] 0.8913882 0.9587463 0.9702392 0.9975312 1.0062795
## [3,] 0.9320308 0.9775122 0.9929154 1.0210373 1.0808122
## [4,] 0.9226920 0.9374076 0.9919162 1.0283241 1.0378355
## [5,] 0.8773009 0.8788105 0.8913275 0.9005823 0.9056954
## [6,] 0.8453398 0.8590331 0.8916978 0.9019537 0.9646821

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] 3652  170 7005 9353 7201

… with the following distances to those neighbors:

qout$distance[3,]
## [1] 0.9320308 0.9775122 0.9929154 1.0210373 1.0808122

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,] 3150 2092 8001 2389 3315
## [2,] 6592 8313 2598 4078 9490
## [3,]  747 5797 5847 6325 6183
## 
## $distance
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 1.0448792 1.1124269 1.1202775 1.1307786 1.1824509
## [2,] 0.7515965 0.8451115 0.8463285 0.8773696 0.8788666
## [3,] 0.8458863 0.9264530 0.9888018 1.0014175 1.0027488

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.2 Patched (2023-11-01 r85457)
## Platform: x86_64-apple-darwin20 (64-bit)
## Running under: macOS Monterey 12.7.1
## 
## Matrix products: default
## BLAS:   /Library/Frameworks/R.framework/Versions/4.3-x86_64/Resources/lib/libRblas.0.dylib 
## LAPACK: /Library/Frameworks/R.framework/Versions/4.3-x86_64/Resources/lib/libRlapack.dylib;  LAPACK version 3.11.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.36.0  BiocNeighbors_1.20.2 knitr_1.45          
## [4] BiocStyle_2.30.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.40.2    htmltools_0.5.7    
##  [7] stats4_4.3.2        sass_0.4.8          rmarkdown_2.25     
## [10] grid_4.3.2          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.3.2     
## [19] codetools_0.2-19    Rcpp_1.0.11         lattice_0.22-5     
## [22] digest_0.6.33       R6_2.5.1            parallel_4.3.2     
## [25] bslib_0.6.1         Matrix_1.6-4        tools_4.3.2        
## [28] BiocGenerics_0.48.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.