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,] 9543 2532  447 7238 3838 7778 1011 5895 4503   909
## [2,] 7363 9375 4680 2555 9869 2846  462 8510 1255  2326
## [3,]  704 5736 4835 4430 1596 5236  705 9338 1663  2369
## [4,] 8357 5841 6359 7588 7940 6258 2167 4216 7456  3100
## [5,] 5242 5013 7599 8679 9133 3533 2703 3227 7410   242
## [6,]  592  715 2503 4703 2757 6562 2251 3279 2937  8122
head(fout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
## [1,] 0.8214548 0.9006679 0.9339448 0.9492371 0.9564776 0.9596623 0.9613887
## [2,] 0.8684205 1.0179142 1.1342891 1.1476056 1.1477573 1.1488392 1.1533568
## [3,] 0.8876058 0.9626092 0.9893169 1.0071721 1.0331187 1.0350839 1.0452993
## [4,] 0.8885362 0.9358744 0.9570417 0.9580818 0.9910722 1.0090404 1.0118213
## [5,] 0.8669883 0.9322840 0.9601927 0.9624524 0.9751056 0.9831700 0.9891420
## [6,] 0.8866881 1.0049338 1.0169996 1.0270842 1.0366717 1.0682006 1.0823789
##           [,8]      [,9]     [,10]
## [1,] 0.9629122 0.9678202 0.9860902
## [2,] 1.1577736 1.1580163 1.1670640
## [3,] 1.0491723 1.0518366 1.0589681
## [4,] 1.0351123 1.0364901 1.0365683
## [5,] 1.0024123 1.0029771 1.0120922
## [6,] 1.0847746 1.0908035 1.1039797

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]  704 5736 4835 4430 1596 5236  705 9338 1663 2369

… with the following distances to those neighbors:

fout$distance[3,]
##  [1] 0.8876058 0.9626092 0.9893169 1.0071721 1.0331187 1.0350839 1.0452993
##  [8] 1.0491723 1.0518366 1.0589681

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,] 8146 6954  339 8892 3380
## [2,] 2704 4752 1308 9212 3355
## [3,] 1051 7135 4773 6949 7314
## [4,] 2923 6535   76 5640  676
## [5,] 4593 8967 7127 3067 5266
## [6,] 7800 5258 9078 7356 6722
head(qout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 0.9484274 0.9737244 1.0268648 1.0408492 1.0687381
## [2,] 0.8890053 0.9167334 0.9241990 0.9477432 0.9585424
## [3,] 0.9279746 0.9423550 0.9555778 0.9572509 0.9594539
## [4,] 0.7384279 0.8273071 0.9802986 1.0018564 1.0125103
## [5,] 0.9925494 1.0057181 1.0173867 1.0202225 1.0207956
## [6,] 1.0402561 1.0858138 1.1208415 1.1421837 1.1826633

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] 1051 7135 4773 6949 7314

… with the following distances to those neighbors:

qout$distance[3,]
## [1] 0.9279746 0.9423550 0.9555778 0.9572509 0.9594539

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,]  704 5736 4835 4430 1596
## [2,] 8357 5841 6359 7588 7940
## [3,] 5242 5013 7599 8679 9133
## 
## $distance
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 0.8876058 0.9626092 0.9893169 1.0071721 1.0331187
## [2,] 0.8885362 0.9358744 0.9570417 0.9580818 0.9910722
## [3,] 0.8669883 0.9322840 0.9601927 0.9624524 0.9751056

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.4.0 beta (2024-04-14 r86421)
## Platform: x86_64-apple-darwin20
## Running under: macOS Monterey 12.7.1
## 
## Matrix products: default
## BLAS:   /Library/Frameworks/R.framework/Versions/4.4-x86_64/Resources/lib/libRblas.0.dylib 
## LAPACK: /Library/Frameworks/R.framework/Versions/4.4-x86_64/Resources/lib/libRlapack.dylib;  LAPACK version 3.12.0
## 
## locale:
## [1] en_US.UTF-8/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.38.0  BiocNeighbors_1.22.0 knitr_1.46          
## [4] BiocStyle_2.32.0    
## 
## loaded via a namespace (and not attached):
##  [1] cli_3.6.2           rlang_1.1.3         xfun_0.43          
##  [4] jsonlite_1.8.8      S4Vectors_0.42.0    htmltools_0.5.8.1  
##  [7] stats4_4.4.0        sass_0.4.9          rmarkdown_2.26     
## [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.39       BiocManager_1.30.22 compiler_4.4.0     
## [19] codetools_0.2-20    Rcpp_1.0.12         lattice_0.22-6     
## [22] digest_0.6.35       R6_2.5.1            parallel_4.4.0     
## [25] bslib_0.7.0         Matrix_1.7-0        tools_4.4.0        
## [28] BiocGenerics_0.50.0 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.