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.

Both methods involve a component of randomness during index construction, though the k-nearest neighbors result is fully deterministic1 Except in the presence of ties, see ?findKNN 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,] 8689 9674 1715 5268 4825 2953 2014 8495 6700   515
## [2,] 8143 3454 3678 2145 5704 7971 6335 3176 9265  8057
## [3,] 4085  100 7520 1328   99 3880 4237 6908 9623  2985
## [4,] 6690 2876 5359 7754 3015 9976 8018 9550 8479  1056
## [5,] 1427 8448 3824 3956 7901 7724 4494 6241 7797  3792
## [6,] 6898  702 6276 1713 1105 5904 8814 3967 7011  7320
head(fout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
## [1,] 0.8959479 0.9201659 0.9779226 0.9790988 0.9855343 1.0032347 1.0035816
## [2,] 0.8560283 0.8889203 0.9085646 0.9368956 0.9434487 0.9462028 0.9579706
## [3,] 1.0082185 1.0320893 1.0358297 1.0723616 1.0759531 1.0763841 1.0776739
## [4,] 0.8793344 0.9825183 0.9874073 0.9999368 1.0109222 1.0184248 1.0370691
## [5,] 0.9546003 0.9844909 1.0127349 1.0525597 1.0642416 1.0690185 1.0731933
## [6,] 0.9988366 1.0190078 1.0199900 1.0313229 1.0501413 1.0602339 1.0619406
##           [,8]      [,9]     [,10]
## [1,] 1.0097023 1.0158156 1.0189978
## [2,] 0.9587032 0.9589145 0.9620609
## [3,] 1.0873479 1.0910444 1.0922318
## [4,] 1.0619503 1.0677022 1.0833311
## [5,] 1.0744999 1.0772461 1.0793413
## [6,] 1.0876117 1.1194489 1.1296613

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] 4085  100 7520 1328   99 3880 4237 6908 9623 2985

… with the following distances to those neighbors:

fout$distance[3,]
##  [1] 1.008219 1.032089 1.035830 1.072362 1.075953 1.076384 1.077674 1.087348
##  [9] 1.091044 1.092232

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,] 7557 5152 5390 1500 9906
## [2,] 6337 8172 1490  406 3071
## [3,] 3788 9556 3963 6570 5689
## [4,] 9050  338 5483 8974 3349
## [5,] 4123 2894 9297 9248 2616
## [6,] 8033 4703 9546 9229 4156
head(qout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 0.7788202 0.8314470 0.8689862 0.8705281 0.8711024
## [2,] 0.8718284 0.9362180 0.9401400 1.0109214 1.0289175
## [3,] 0.8978702 0.9228632 0.9406342 0.9612989 0.9649704
## [4,] 0.9315198 0.9778405 1.0046366 1.0085137 1.0338306
## [5,] 0.7850513 0.9218201 0.9928727 1.0072714 1.0170828
## [6,] 0.7952307 0.9643012 0.9764935 0.9955798 1.0104670

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] 3788 9556 3963 6570 5689

… with the following distances to those neighbors:

qout$distance[3,]
## [1] 0.8978702 0.9228632 0.9406342 0.9612989 0.9649704

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,] 4085  100 7520 1328   99
## [2,] 6690 2876 5359 7754 3015
## [3,] 1427 8448 3824 3956 7901
## 
## $distance
##           [,1]      [,2]      [,3]      [,4]     [,5]
## [1,] 1.0082185 1.0320893 1.0358297 1.0723616 1.075953
## [2,] 0.8793344 0.9825183 0.9874073 0.9999368 1.010922
## [3,] 0.9546003 0.9844909 1.0127349 1.0525597 1.064242

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 3.6.0 (2019-04-26)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 18.04.2 LTS
## 
## Matrix products: default
## BLAS:   /home/biocbuild/bbs-3.10-bioc/R/lib/libRblas.so
## LAPACK: /home/biocbuild/bbs-3.10-bioc/R/lib/libRlapack.so
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        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       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] BiocParallel_1.19.0 BiocNeighbors_1.3.2 knitr_1.23         
## [4] BiocStyle_2.13.1   
## 
## loaded via a namespace (and not attached):
##  [1] Rcpp_1.0.1          bookdown_0.11       lattice_0.20-38    
##  [4] digest_0.6.19       grid_3.6.0          stats4_3.6.0       
##  [7] magrittr_1.5        evaluate_0.14       stringi_1.4.3      
## [10] S4Vectors_0.23.10   Matrix_1.2-17       rmarkdown_1.13     
## [13] tools_3.6.0         stringr_1.4.0       parallel_3.6.0     
## [16] xfun_0.7            yaml_2.2.0          compiler_3.6.0     
## [19] BiocGenerics_0.31.3 BiocManager_1.30.4  htmltools_0.3.6

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.