require(knitr) opts_chunk$set(error=FALSE, message=FALSE, warning=FALSE) library(kmknn)
The r Biocpkg("kmknn")
package provides an implementation of the k-means for k-nearest neighbors algorithm, as described by @wang2012fast.
For a dataset with $N$ points, the pre-training is done as follows:
For each query point, identification of the nearest neighbors is done as follows:
The pre-clustering arranges the points in a manner that effectively reduces the search space, even in high-dimensional data.
Note that, while kmeans
itself is random, the k-nearest neighbors result is fully deterministic^[Except in the presence of ties, see ?findKNN
for details.].
The algorithm is implemented in a combination of R and C++, derived from code in r Biocpkg("cydar")
[@lun2017testing].
We observe 2-5-fold speed-ups in 20- to 50-dimensional data, compared to KD-trees in r CRANpkg("FNN")
and r CRANpkg("RANN")
(see https://github.com/LTLA/OkNN2018 for timings).
This is consistent with results from @wang2012fast.
The most obvious application is to perform a k-nearest neighbors search.
The findKNN()
function expects a numeric matrix as input with data points as the rows and variables/dimensions as the columns.
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) fout <- findKNN(data, k=10) head(fout$index) head(fout$distance)
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,]
... with the following distances to those neighbors:
fout$distance[3,]
Note that the reported neighbors are sorted by distance.
Another application is to identify the k-nearest neighbors in one dataset based on query points in another dataset.
This is achieved using the queryKNN()
function:
nquery <- 1000 ndim <- 20 query <- matrix(runif(nquery*ndim), ncol=ndim) qout <- queryKNN(data, query, k=5) head(qout$index) head(qout$distance)
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,]
... with the following distances to those neighbors:
qout$distance[3,]
Again, the reported neighbors are sorted by distance.
Another application is to identify all neighboring points within a certain (Euclidean) distance of the current point.
This is done using the findNeighbors()
function:
fout <- findNeighbors(data, threshold=1) head(fout$index) head(fout$distance)
Each entry of the index
list corresponds to a point in data
and contains the row indices in data
that are within threshold
.
For example, the 3rd point in data
has the following neighbors:
fout$index[[3]]
... with the following distances to those neighbors:
fout$distance[[3]]
Note that, for this function, the reported neighbors are not sorted by distance. The order of the output is completely arbitrary and will vary depending on the random seed. However, the identity of the neighbors is fully deterministic.
The queryNeighbors()
function is also provided for identifying all points within a certain distance of a query point.
This is analogous to queryKNN()
for identifying the nearest neighbors of a query.
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)
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))
For multiple queries to a constant data
, the pre-clustering can be performed in a separate step with precluster()
.
The result can then be passed to multiple calls, avoiding the overhead of repeated clustering.
pre <- precluster(data) out1 <- findKNN(precomputed=pre, k=5) out2 <- queryKNN(precomputed=pre, query=query, k=2) out3 <- findNeighbors(precomputed=pre, threshold=2)
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 during package development where it is more convenient to work on the common precomputed object.
To demonstrate a practical use of this package, let's have a look at a small single-cell RNA seq dataset from the r Biocexptpkg("scRNAseq")
package.
The allen
dataset contains a subset of cells from a study of the mouse visual cortex [@tasic2016adult].
library(scRNAseq) data(allen)
We use the r Biocpkg("scater")
package [@mccarthy2017scater] to obtain the first 20 principal components of the log-normalized expression matrix.
library(scater) sce <- as(allen, "SingleCellExperiment") sce <- normalize(sce, exprs_values="tophat_counts") sce <- runPCA(sce, ncomponents=50) dim(reducedDim(sce, "PCA"))
We can then identify cels that are nearest neighbors of each other using findKNN()
.
This is the basis of a number of procedures such as shared nearest-neighbors clustering [@xu2015identification] and mutual nearest neighbors batch correction [@haghverdi2018batch].
nns <- findKNN(reducedDim(sce, "PCA"), k=10) head(nns$index) head(nns$distance)
sessionInfo()
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.