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,] 1475 3924 6398 1397 3803 6226 1092 1775 2695  3033
## [2,] 1431 8407 9210 9827 2004 4755 3055 2425 9199  5591
## [3,] 6260 7596  967 1345 8065 4257 3837 5540 7794  7771
## [4,] 6506 5140 6063 9410 3777 5683 1085 8505 7022  6758
## [5,] 8441 5030 5374 7217 6286  913 8360 7175  940  2197
## [6,] 9020 4120 3344 6359 1046 5928 5920 6907 2418  4224
head(fout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
## [1,] 0.8608422 0.8641390 0.8916383 0.9634926 0.9858023 0.9863873 0.9895430
## [2,] 1.0696593 1.0755356 1.1319923 1.1392915 1.1428294 1.1497810 1.1649679
## [3,] 0.7505679 0.7655474 0.8155142 0.8735982 0.8831654 0.8992442 0.9017388
## [4,] 0.8032986 0.9396509 0.9482572 0.9535497 0.9631937 0.9645796 0.9766409
## [5,] 0.8779930 0.9590474 0.9826428 0.9922442 0.9938853 1.0051482 1.0140008
## [6,] 0.8733323 0.8964203 0.9325068 0.9486481 0.9787784 0.9808929 0.9817277
##           [,8]      [,9]     [,10]
## [1,] 0.9896291 0.9977157 1.0028539
## [2,] 1.1699543 1.1931662 1.2049512
## [3,] 0.9085771 0.9095112 0.9160579
## [4,] 1.0147802 1.0227495 1.0240145
## [5,] 1.0261465 1.0336971 1.0481576
## [6,] 0.9904496 0.9927003 1.0028325

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] 6260 7596  967 1345 8065 4257 3837 5540 7794 7771

… with the following distances to those neighbors:

fout$distance[3,]
##  [1] 0.7505679 0.7655474 0.8155142 0.8735982 0.8831654 0.8992442 0.9017388
##  [8] 0.9085771 0.9095112 0.9160579

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,] 4742 3996 9038 6194 4911
## [2,] 4925 2585 1224 1741 8216
## [3,] 8294 9668 8002   75 5677
## [4,] 5214 1799 3507   19 3465
## [5,] 2308 1638 1433 7871 3097
## [6,] 1934 7571 4126 7883 8290
head(qout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 1.0606358 1.0856064 1.0872369 1.1049552 1.1120492
## [2,] 0.8582900 0.9097412 0.9594431 0.9804437 0.9907725
## [3,] 0.9986486 1.0459272 1.1040033 1.1123857 1.1137113
## [4,] 0.8744265 0.9634130 1.0127840 1.0206271 1.0275663
## [5,] 0.8834043 0.9047219 0.9589461 0.9621767 1.0220830
## [6,] 0.8552389 0.8994096 0.9060309 0.9180037 0.9400187

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] 8294 9668 8002   75 5677

… with the following distances to those neighbors:

qout$distance[3,]
## [1] 0.9986486 1.0459272 1.1040033 1.1123857 1.1137113

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,] 6260 7596  967 1345 8065
## [2,] 6506 5140 6063 9410 3777
## [3,] 8441 5030 5374 7217 6286
## 
## $distance
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 0.7505679 0.7655474 0.8155142 0.8735982 0.8831654
## [2,] 0.8032986 0.9396509 0.9482572 0.9535497 0.9631937
## [3,] 0.8779930 0.9590474 0.9826428 0.9922442 0.9938853

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 r84269 ucrt)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows Server 2022 x64 (build 20348)
## 
## Matrix products: default
## 
## 
## locale:
## [1] LC_COLLATE=C                          
## [2] LC_CTYPE=English_United States.utf8   
## [3] LC_MONETARY=English_United States.utf8
## [4] LC_NUMERIC=C                          
## [5] LC_TIME=English_United States.utf8    
## 
## 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.0  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.39          
##  [4] jsonlite_1.8.4      S4Vectors_0.38.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.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–8.

Yianilos, P. N. 1993. “Data Structures and Algorithms for Nearest Neighbor Search in General Metric Spaces.” In SODA, 93:311–21. 194.