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,] 9409 4947 6178 9537 5260 4894 3072  306  228  6636
## [2,] 1547 5962 9214  242 9999 2935 2289 1071 8246  3475
## [3,] 4380 5286 9594 2424 4232 7580 5375 5945 4079  3906
## [4,] 2025 3102 5535 1981 5268 5150 6909 2393 9473  2498
## [5,] 6507 7425 2858 1753 5849 7601 2396 8150 1416  7257
## [6,] 2899 1654 6726 5665  717 7604 3320 9263 4368  8343
head(fout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
## [1,] 0.9785586 0.9811400 0.9913524 0.9955739 1.0255069 1.0308471 1.0383945
## [2,] 0.9602596 0.9691522 0.9751631 0.9805606 1.0096187 1.0118636 1.0228048
## [3,] 0.9089951 0.9643081 1.0012023 1.0079162 1.0319489 1.0568212 1.0589021
## [4,] 0.7974994 1.0328205 1.0414875 1.0479995 1.0546405 1.0586517 1.0591534
## [5,] 0.8548139 0.9159989 0.9444234 0.9676975 0.9683909 0.9748149 0.9831826
## [6,] 0.9433159 1.0117848 1.0126210 1.0370186 1.0444959 1.0452362 1.0508700
##          [,8]     [,9]    [,10]
## [1,] 1.038541 1.067886 1.074520
## [2,] 1.041626 1.041785 1.046640
## [3,] 1.059560 1.065766 1.069269
## [4,] 1.072983 1.073397 1.077641
## [5,] 1.012390 1.013242 1.032472
## [6,] 1.053048 1.073025 1.086548

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] 4380 5286 9594 2424 4232 7580 5375 5945 4079 3906

… with the following distances to those neighbors:

fout$distance[3,]
##  [1] 0.9089951 0.9643081 1.0012023 1.0079162 1.0319489 1.0568212 1.0589021
##  [8] 1.0595602 1.0657655 1.0692688

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,] 3138 7318 7776 9124 7533
## [2,] 6252 1530 2753 4190 9861
## [3,] 2254 3043 8079 6589 2833
## [4,] 1178 8334 5769 6381 3610
## [5,] 9574 2021  344 5418 4231
## [6,] 1598 8368 6649 7836 5376
head(qout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 0.9110958 0.9896955 1.0039828 1.0040069 1.0055336
## [2,] 0.9441806 0.9474333 1.0602833 1.0626497 1.0770631
## [3,] 0.9538700 0.9605901 0.9634138 0.9688830 0.9759902
## [4,] 1.0595337 1.0763289 1.1018678 1.1339158 1.1457390
## [5,] 0.8947893 0.8952181 0.9134670 0.9660932 0.9958256
## [6,] 0.8996672 0.9262411 0.9570033 0.9598391 0.9925181

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] 2254 3043 8079 6589 2833

… with the following distances to those neighbors:

qout$distance[3,]
## [1] 0.9538700 0.9605901 0.9634138 0.9688830 0.9759902

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,] 4380 5286 9594 2424 4232
## [2,] 2025 3102 5535 1981 5268
## [3,] 6507 7425 2858 1753 5849
## 
## $distance
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 0.9089951 0.9643081 1.0012023 1.0079162 1.0319489
## [2,] 0.7974994 1.0328205 1.0414875 1.0479995 1.0546405
## [3,] 0.8548139 0.9159989 0.9444234 0.9676975 0.9683909

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-13 r84266)
## Platform: aarch64-apple-darwin20 (64-bit)
## Running under: macOS Monterey 12.6.1
## 
## Matrix products: default
## BLAS:   /Library/Frameworks/R.framework/Versions/4.3-arm64/Resources/lib/libRblas.0.dylib 
## LAPACK: /Library/Frameworks/R.framework/Versions/4.3-arm64/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.34.1  BiocNeighbors_1.18.0 knitr_1.42          
## [4] BiocStyle_2.28.0    
## 
## loaded via a namespace (and not attached):
##  [1] cli_3.6.1           rlang_1.1.0         xfun_0.38          
##  [4] jsonlite_1.8.4      S4Vectors_0.38.1    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.46.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–58.
Yianilos, P. N. 1993. “Data Structures and Algorithms for Nearest Neighbor Search in General Metric Spaces.” In SODA, 93:311–21. 194.