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,] 4943   42  117 8366 5446 8169  378  489  859   166
## [2,] 2268 3229 7825 6616 6675 5817 6816 2298 5775  5430
## [3,] 4638 5820 8639 9992 7751 5673 9170 3293 1448  5433
## [4,] 6254 1192 7801 6210 6122 9063  586 4221 3733  6390
## [5,] 7885 7341 8784 5434 3448 8907 8796 3938 7421  7013
## [6,] 1863 3059 4751 9422 8061 5079 5583 2187 8111  4997
head(fout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]     [,7]
## [1,] 1.0677988 1.0854292 1.0861068 1.0871010 1.1012742 1.1015519 1.105978
## [2,] 0.9161417 0.9330447 0.9580917 0.9944697 1.0083124 1.0204020 1.022464
## [3,] 0.9025944 0.9325124 0.9663796 0.9680596 0.9779932 0.9968884 1.014175
## [4,] 0.9015750 0.9068823 0.9556981 0.9940859 1.0296577 1.0322257 1.060465
## [5,] 0.8448565 0.9837966 0.9976199 1.0068622 1.0155992 1.0216003 1.023199
## [6,] 1.0030549 1.0601362 1.0749971 1.0987396 1.1218082 1.1310049 1.143488
##          [,8]     [,9]    [,10]
## [1,] 1.118340 1.119492 1.135401
## [2,] 1.028555 1.053048 1.064902
## [3,] 1.017498 1.030310 1.030687
## [4,] 1.069836 1.076286 1.087048
## [5,] 1.028119 1.038646 1.043110
## [6,] 1.150528 1.151706 1.154854

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] 4638 5820 8639 9992 7751 5673 9170 3293 1448 5433

… with the following distances to those neighbors:

fout$distance[3,]
##  [1] 0.9025944 0.9325124 0.9663796 0.9680596 0.9779932 0.9968884 1.0141749
##  [8] 1.0174979 1.0303097 1.0306868

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,] 1569 8866 5390 7697 4480
## [2,] 3233  115  912 1105 1203
## [3,] 9508 7278 2642 4094 7411
## [4,] 9884  806 6485  686 4812
## [5,] 1524 3393 6427 2652 1263
## [6,] 6748 5971 6753 5283 1978
head(qout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 0.8986497 0.9304825 0.9310002 0.9547852 0.9608918
## [2,] 0.7529896 0.7601544 0.7984705 0.9122875 0.9182476
## [3,] 0.8519172 0.8626960 0.8690657 0.8862873 0.9222979
## [4,] 0.8718239 0.9059505 0.9256928 0.9414606 0.9680890
## [5,] 0.9917378 1.0545911 1.0637754 1.0813385 1.0845933
## [6,] 0.9252771 0.9322693 1.0482351 1.0920626 1.1228042

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] 9508 7278 2642 4094 7411

… with the following distances to those neighbors:

qout$distance[3,]
## [1] 0.8519172 0.8626960 0.8690657 0.8862873 0.9222979

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,] 4638 5820 8639 9992 7751
## [2,] 6254 1192 7801 6210 6122
## [3,] 7885 7341 8784 5434 3448
## 
## $distance
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 0.9025944 0.9325124 0.9663796 0.9680596 0.9779932
## [2,] 0.9015750 0.9068823 0.9556981 0.9940859 1.0296577
## [3,] 0.8448565 0.9837966 0.9976199 1.0068622 1.0155992

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)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 22.04.2 LTS
## 
## Matrix products: default
## BLAS:   /home/biocbuild/bbs-3.17-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.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.