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,] 8087 9400 1103 4827  789 9043 7093 2546 5489  9048
## [2,] 7038 6879 6487 9297 5524 2617 4995 1168 7587  7743
## [3,] 1231 6550 6701   10 9733 8813 3246  611  583   991
## [4,]  483 5924  361  476 6253 8707 4219 1617 6874   352
## [5,] 5644 7989 8849 7191 9553 5721 9874 7789 8376  9174
## [6,] 8263 3926 6004 7436 8491 5874 7509 4529 2916  9661
head(fout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
## [1,] 0.8731521 0.9653392 0.9683257 1.0338930 1.0469617 1.0588056 1.0589208
## [2,] 0.8773101 0.9183035 0.9312565 0.9603871 0.9887890 0.9897631 0.9898572
## [3,] 0.9518038 0.9971894 1.0096301 1.0268473 1.0493543 1.0515094 1.0960192
## [4,] 0.9359130 0.9661439 0.9718334 0.9792598 0.9834347 0.9908157 0.9926092
## [5,] 0.8554691 0.9441565 1.0489588 1.0668435 1.0738195 1.0743257 1.0972799
## [6,] 0.9303372 0.9845239 1.0764743 1.0816151 1.0861782 1.1095560 1.1246339
##           [,8]     [,9]    [,10]
## [1,] 1.0624306 1.063123 1.072711
## [2,] 0.9909363 1.002287 1.004458
## [3,] 1.1053905 1.108868 1.109241
## [4,] 1.0250100 1.030065 1.030114
## [5,] 1.1034892 1.112987 1.135207
## [6,] 1.1424204 1.159952 1.162334

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] 1231 6550 6701   10 9733 8813 3246  611  583  991

… with the following distances to those neighbors:

fout$distance[3,]
##  [1] 0.9518038 0.9971894 1.0096301 1.0268473 1.0493543 1.0515094 1.0960192
##  [8] 1.1053905 1.1088682 1.1092409

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,] 4873 4487 8454 5838 2319
## [2,] 2021 5494 1764 9941 7871
## [3,] 7868 3630 2361 2179 2459
## [4,] 4331  588 2727 1405 1222
## [5,] 8965 3862 6363 5891 4995
## [6,] 2136 7567   47 5842 7333
head(qout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 0.9222334 0.9531127 0.9896927 0.9934973 1.0093904
## [2,] 0.9983183 1.0161948 1.0401222 1.0419147 1.1294887
## [3,] 1.0775833 1.0783785 1.1454099 1.1586000 1.1840437
## [4,] 0.8741795 0.9455144 0.9718740 1.0135042 1.0259661
## [5,] 0.8920619 0.9137741 0.9658429 0.9875645 0.9892986
## [6,] 0.8688632 0.9187435 0.9663638 0.9792254 1.0009669

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] 7868 3630 2361 2179 2459

… with the following distances to those neighbors:

qout$distance[3,]
## [1] 1.077583 1.078378 1.145410 1.158600 1.184044

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,] 1231 6550 6701   10 9733
## [2,]  483 5924  361  476 6253
## [3,] 5644 7989 8849 7191 9553
## 
## $distance
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 0.9518038 0.9971894 1.0096301 1.0268473 1.0493543
## [2,] 0.9359130 0.9661439 0.9718334 0.9792598 0.9834347
## [3,] 0.8554691 0.9441565 1.0489588 1.0668435 1.0738195

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.0.0 (2020-04-24)
## Platform: x86_64-apple-darwin17.0 (64-bit)
## Running under: macOS Mojave 10.14.6
## 
## Matrix products: default
## BLAS:   /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRblas.dylib
## LAPACK: /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRlapack.dylib
## 
## locale:
## [1] C/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] BiocParallel_1.22.0 BiocNeighbors_1.6.0 knitr_1.28         
## [4] BiocStyle_2.16.0   
## 
## loaded via a namespace (and not attached):
##  [1] Rcpp_1.0.4.6        bookdown_0.18       lattice_0.20-41    
##  [4] digest_0.6.25       grid_4.0.0          stats4_4.0.0       
##  [7] magrittr_1.5        evaluate_0.14       rlang_0.4.5        
## [10] stringi_1.4.6       S4Vectors_0.26.0    Matrix_1.2-18      
## [13] rmarkdown_2.1       tools_4.0.0         stringr_1.4.0      
## [16] parallel_4.0.0      xfun_0.13           yaml_2.2.1         
## [19] compiler_4.0.0      BiocGenerics_0.34.0 BiocManager_1.30.10
## [22] htmltools_0.4.0

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.