| Title: | Native UMAP and Interpolation-Based t-SNE Embeddings |
|---|---|
| Description: | A native float32 UMAP implementation and a configurable interpolation-based t-SNE implementation for embeddings from data matrices or precomputed nearest-neighbor indices and distances. One-call workflows use package-native CPU HNSW and Apple Metal exact or IVF-Flat search. Optional CUDA support links directly to FAISS GPU and the RAPIDS cuVS C API while retaining nearest-neighbor results on the device. Preprocessing, graph or affinity construction, fixed-reference transform, and layout optimization use native code with explicit CPU, Metal, and CUDA backend reporting. UMAP exposes neighborhood, metric, graph mode, backend, seed, and preprocessing controls, while optimizer controls such as epochs, minimum distance, spread, learning rate, repulsion, and negative sampling follow a recorded release policy rather than a general-purpose sweep API. Optional graph utilities support downstream Louvain, Leiden, and Walktrap community detection. |
| Authors: | Stefano Cacciatore [aut, cre] (ORCID: <https://orcid.org/0000-0001-7052-7156>) |
| Maintainer: | Stefano Cacciatore <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.99.17 |
| Built: | 2026-09-30 11:01:37 UTC |
| Source: | https://github.com/BiocStaging/fastEmbedR |
Embed from precomputed KNN
embed_knn( indices, distances = NULL, method = "umap", n_components = 2L, seed = 4L, verbose = FALSE, backend = NULL, n.cores = NULL, ... )embed_knn( indices, distances = NULL, method = "umap", n_components = 2L, seed = 4L, verbose = FALSE, backend = NULL, n.cores = NULL, ... )
indices |
A list containing KNN |
distances |
Numeric KNN distance matrix matching |
method |
Embedding method: |
n_components |
Output dimensionality. |
seed |
Random seed. |
verbose |
Print native optimizer progress. |
backend |
Execution backend: |
n.cores |
Number of CPU cores used by the CPU optimizer. Native GPU optimizers ignore this argument. |
... |
Additional t-SNE-specific parameters such as |
A numeric embedding matrix with resolved settings stored in
attr(layout, "fastEmbedR_config").
x <- scale(as.matrix(iris[1:30, 1:4])) d <- as.matrix(stats::dist(x)) diag(d) <- Inf k <- 5L indices <- t(apply(d, 1L, order))[, seq_len(k), drop = FALSE] distances <- matrix( d[cbind(rep(seq_len(nrow(d)), each = k), as.vector(t(indices)))], nrow = nrow(d), byrow = TRUE ) layout <- embed_knn(indices, distances, method = "umap", seed = 1)x <- scale(as.matrix(iris[1:30, 1:4])) d <- as.matrix(stats::dist(x)) diag(d) <- Inf k <- 5L indices <- t(apply(d, 1L, order))[, seq_len(k), drop = FALSE] distances <- matrix( d[cbind(rep(seq_len(nrow(d)), each = k), as.vector(t(indices)))], nrow = nrow(d), byrow = TRUE ) layout <- embed_knn(indices, distances, method = "umap", seed = 1)
Trustworthiness and continuity use their standard rank-penalty definitions. Local rank metrics are computed exactly on a deterministic subsample so the function does not allocate all-pairs matrices for the complete dataset. Float32 inputs are sampled before conversion to a dense double matrix.
evaluate_embedding( x_high, embedding, labels = NULL, batch = NULL, k = c(15L, 30L, 50L), primary_k = NULL, reference_nn = NULL, sample_size_for_global_metrics = min(5000L, nrow(x_high)), sample_size_for_local_metrics = min(2000L, nrow(x_high)), use_cache = FALSE, cache_dir = file.path("results", "cache"), force_recompute = FALSE, seed = NA_integer_, method = NA_character_, backend = NA_character_, n.cores = NULL, dataset = NA_character_ )evaluate_embedding( x_high, embedding, labels = NULL, batch = NULL, k = c(15L, 30L, 50L), primary_k = NULL, reference_nn = NULL, sample_size_for_global_metrics = min(5000L, nrow(x_high)), sample_size_for_local_metrics = min(2000L, nrow(x_high)), use_cache = FALSE, cache_dir = file.path("results", "cache"), force_recompute = FALSE, seed = NA_integer_, method = NA_character_, backend = NA_character_, n.cores = NULL, dataset = NA_character_ )
x_high |
High-dimensional input, usually scaled data or PCA scores. |
embedding |
Low-dimensional embedding matrix. |
labels |
Optional biological/class labels. |
batch |
Optional batch labels. |
k |
Neighbor sizes used for structure metrics. |
primary_k |
Neighbor size used for scalar trustworthiness, continuity,
label accuracy, rare-class recall, density summaries, and rank-error
metrics. The default |
reference_nn |
Optional precomputed high-dimensional nearest-neighbor list. It may include a self-neighbor column. |
sample_size_for_global_metrics |
Maximum deterministic subsample size for all-pairs global distance metrics. |
sample_size_for_local_metrics |
Maximum deterministic subsample size for local trustworthiness, continuity, and neighbor preservation metrics. |
use_cache |
Cache the high-dimensional reference neighbors used by quality metrics. |
cache_dir |
Directory for quality-metric reference-neighbor cache files. |
force_recompute |
Ignore cached quality reference neighbors. |
seed |
Random seed recorded in the output and used for subsampling. |
method |
Method name recorded in the output. |
backend |
Backend name recorded in the output. |
n.cores |
Number of CPU cores used when quality metrics need nearest-neighbor searches. Ignored by native GPU metric backends. |
dataset |
Dataset name recorded in the output. |
A one-row data frame with local, global, label-aware, batch-aware, and metadata columns. Per-class recall is also attached as an attribute.
x <- scale(as.matrix(iris[, 1:4])) metrics <- evaluate_embedding( x, x[, 1:2], labels = iris$Species, k = 5, sample_size_for_local_metrics = 100, sample_size_for_global_metrics = 100, seed = 1 )x <- scale(as.matrix(iris[, 1:4])) metrics <- evaluate_embedding( x, x[, 1:2], labels = iris$Species, k = 5, sample_size_for_local_metrics = 100, sample_size_for_global_metrics = 100, seed = 1 )
fastEmbedR_api() returns the package's machine-readable public API map.
The map distinguishes canonical workflows from advanced reusable-state
interfaces, diagnostics, secondary graph utilities, and compatibility
helpers. It also records accepted input classes, returned classes, backend
support, device-residency behavior, related S3 methods, and lifecycle
status.
fastEmbedR_api()fastEmbedR_api()
The inventory describes the public contract of the installed package. A
backend marked as supported still requires that backend to have been
compiled and to be available at runtime; use
fastEmbedR_capabilities() to
inspect the current installation.
UMAP rows describe fastEmbedR's fixed optimizer policy, not a general-purpose
parameter-sweep interface. See umap() for the
public/internal control
boundary and the resolved values recorded by each fit.
A data frame with one row per exported function.
api <- fastEmbedR_api() api[api$tier == "canonical", c("function", "purpose", "return_class")]api <- fastEmbedR_api() api[api$tier == "canonical", c("function", "purpose", "return_class")]
Configure the default fastEmbedR execution backend
fastEmbedR_backend(backend = NULL)fastEmbedR_backend(backend = NULL)
backend |
Optional backend: |
The active backend. Setting returns the previous option invisibly.
old_backend <- getOption("fastEmbedR.backend") fastEmbedR_backend("cpu") fastEmbedR_backend() options(fastEmbedR.backend = old_backend)old_backend <- getOption("fastEmbedR.backend") fastEmbedR_backend("cpu") fastEmbedR_backend() options(fastEmbedR.backend = old_backend)
Reports whether the installed fastEmbedR build can provide nearest-neighbor
search, embedding optimization, and graph clustering through each native
execution backend. This function performs capability checks only; it does
not change the backend selected by
fastEmbedR_backend().
fastEmbedR_capabilities()fastEmbedR_capabilities()
The cuvs row describes the RAPIDS cuVS nearest-neighbor component used by
the CUDA backend. It is diagnostic information and is not itself a value
accepted by public backend arguments.
A data frame with one row per backend or backend component. In addition to logical availability columns, the result records the public backend name, detected device, native KNN engine, internal precision, linked runtime families, and an explanation when a component is unavailable. Device-name queries are best effort and do not change the capability decision made by the compiled native probes.
fastEmbedR_capabilities()fastEmbedR_capabilities()
These methods summarize a fastEmbedR_embedding object or plot its first
two layout dimensions.
## S3 method for class 'fastEmbedR_embedding' print(x, ...) ## S3 method for class 'fastEmbedR_embedding' plot( x, labels = x$labels, pch = 21, bg = NULL, col = "black", xlab = "Component 1", ylab = "Component 2", main = NULL, ... )## S3 method for class 'fastEmbedR_embedding' print(x, ...) ## S3 method for class 'fastEmbedR_embedding' plot( x, labels = x$labels, pch = 21, bg = NULL, col = "black", xlab = "Component 1", ylab = "Component 2", main = NULL, ... )
x |
A |
... |
Additional arguments passed to
|
labels |
Optional labels used to color plotted observations. |
pch |
Plotting symbol passed to
|
bg |
Point background colors. When |
col |
Point border or foreground color. |
xlab, ylab
|
Axis labels. |
main |
Plot title. |
The input object, invisibly.
Print graph and graph-clustering results
## S3 method for class 'fastEmbedR_graph' print(x, ...) ## S3 method for class 'fastEmbedR_graph_cluster' print(x, ...)## S3 method for class 'fastEmbedR_graph' print(x, ...) ## S3 method for class 'fastEmbedR_graph_cluster' print(x, ...)
x |
A |
... |
Unused. |
x, invisibly.
fit_landmark_model() runs the ordinary production
umap() or
tsne() implementation on the selected reference rows. The
returned
object stores the reference data and embedding needed to project the
complementary rows or genuinely new observations.
fit_landmark_model( data, selection, method = c("umap", "tsne"), n_neighbors = NULL, perplexity = NULL, affinity_support = c("standard", "compact"), n_components = 2L, metric = c("euclidean", "cosine", "correlation", "inner_product"), seed = 4L, backend = NULL, n.cores = NULL, graph_mode = c("fuzzy", "binary"), keep_knn = FALSE, verbose = FALSE, ... )fit_landmark_model( data, selection, method = c("umap", "tsne"), n_neighbors = NULL, perplexity = NULL, affinity_support = c("standard", "compact"), n_components = 2L, metric = c("euclidean", "cosine", "correlation", "inner_product"), seed = 4L, backend = NULL, n.cores = NULL, graph_mode = c("fuzzy", "binary"), keep_knn = FALSE, verbose = FALSE, ... )
data |
Data in the analysis space used for KNN. Preprocess once before calling this staged API when centering, scaling, or PCA is required. |
selection |
A result from
|
method |
|
n_neighbors |
UMAP neighborhood size. For t-SNE this is the
precomputed KNN support width; |
perplexity |
t-SNE perplexity. |
affinity_support |
t-SNE affinity support policy. |
n_components |
Embedding dimensionality. |
metric |
KNN metric. |
seed |
Random seed. |
backend |
|
n.cores |
Number of CPU cores. |
graph_mode |
UMAP graph mode, passed unchanged to
|
keep_knn |
Retain reference KNN output. |
verbose |
Print optimizer progress. |
... |
Additional optimizer arguments passed to
|
A fastEmbedR_landmark_model.
x <- scale(as.matrix(iris[, 1:4])) selection <- select_landmarks(x, 0.5, seed = 1) model <- fit_landmark_model( x, selection, method = "umap", n_neighbors = 10, graph_mode = "fuzzy", seed = 1 )x <- scale(as.matrix(iris[, 1:4])) selection <- select_landmarks(x, 0.5, seed = 1) model <- fit_landmark_model( x, selection, method = "umap", n_neighbors = 10, graph_mode = "fuzzy", seed = 1 )
graph_cluster() clusters a compact fastEmbedR_graph with a native
multilevel Louvain implementation, a Leiden local-move/refine/aggregate
implementation, or the Pons-Latapy Walktrap algorithm. Louvain and Leiden
have CPU, CUDA, and Metal implementations. Walktrap is CPU-only. No Python,
igraph, cuGraph, or external clustering function is called at run time.
graph_cluster( graph, method = c("leiden", "louvain", "walktrap"), backend = NULL, resolution = 1, n_iterations = 10L, n_runs = 1L, steps = 4L, seed = 1L )graph_cluster( graph, method = c("leiden", "louvain", "walktrap"), backend = NULL, resolution = 1, n_iterations = 10L, n_runs = 1L, steps = 4L, seed = 1L )
graph |
A |
method |
|
backend |
Execution backend. |
resolution |
Positive modularity resolution for Louvain and Leiden. Walktrap uses its reference resolution of 1. |
n_iterations |
Maximum local-moving passes for Louvain and Leiden. |
n_runs |
Independent seeded Louvain/Leiden runs; the highest-modularity result is returned. |
steps |
Random-walk length for Walktrap. |
seed |
Reproducible random seed for Louvain and Leiden. |
A fastEmbedR_graph_cluster containing one-based membership,
modularity, method, implementation, and run metadata.
Blondel VD, Guillaume JL, Lambiotte R, Lefebvre E. Fast unfolding of communities in large networks. J Stat Mech. 2008;2008:P10008.
Traag VA, Waltman L, van Eck NJ. From Louvain to Leiden: guaranteeing well-connected communities. Sci Rep. 2019;9:5233.
Pons P, Latapy M. Computing communities in large networks using random walks. J Graph Algorithms Appl. 2006;10:191-218.
x <- scale(as.matrix(iris[, 1:4])) graph <- knn_graph(x, k = 15) clusters <- graph_cluster(graph, method = "leiden", seed = 1) table(clusters$membership)x <- scale(as.matrix(iris[, 1:4])) graph <- knn_graph(x, k = 15) clusters <- graph_cluster(graph, method = "leiden", seed = 1) table(clusters$membership)
knn_graph() converts a data matrix, a fastEmbedR_embedding, or a
precomputed KNN object into a native undirected edge graph. When neighbors
must be computed, the function uses fastEmbedR's existing native KNN route;
it does not expose a second nearest-neighbor tuning API.
knn_graph( x, k = 30L, backend = NULL, metric = c("euclidean", "cosine", "correlation"), weight = c("snn", "distance", "binary"), mutual = FALSE, prune = 0, n.cores = 1L )knn_graph( x, k = 30L, backend = NULL, metric = c("euclidean", "cosine", "correlation"), weight = c("snn", "distance", "binary"), mutual = FALSE, prune = 0, n.cores = 1L )
x |
Numeric data matrix, a |
k |
Number of non-self neighbors retained. |
backend |
KNN-search backend used only when |
metric |
Distance metric used only when KNN must be computed:
|
weight |
Edge weighting: shared-neighbor Jaccard ( |
mutual |
Keep only reciprocal KNN edges. |
prune |
Remove edges whose final weight is less than or equal to this non-negative threshold. |
n.cores |
CPU cores used by KNN search and graph construction. |
A compact fastEmbedR_graph list with from, to,
weight,
n_vertices, and construction metadata.
Blondel VD, Guillaume JL, Lambiotte R, Lefebvre E. Fast unfolding of communities in large networks. J Stat Mech. 2008;2008:P10008.
x <- scale(as.matrix(iris[, 1:4])) graph <- knn_graph(x, k = 15, weight = "snn") graphx <- scale(as.matrix(iris[, 1:4])) graph <- knn_graph(x, k = 15, weight = "snn") graph
landmark_tsne() embeds a subset of observations with
tsne(), then
places the remaining observations with transform_tsne(). Projection KNN
searches only the
fixed landmark reference: CPU uses native HNSW, Metal uses native exact or
recall-tuned IVF-Flat, and CUDA keeps native exact or IVF-Flat results
resident on the device.
landmark_tsne( data, landmarks = TRUE, reference_method = c("tsne"), n_neighbors = NULL, perplexity = NULL, affinity_support = c("standard", "compact"), n_components = 2L, standardize = TRUE, pca_dims = NULL, seed = 4L, backend = NULL, transform_k = NULL, transform_perplexity = 5, transform_iter = 250L, transform_early_exaggeration_iter = 0L, transform_n_negatives = NULL, initialization = c("median", "weighted", "random"), keep_knn = FALSE, verbose = FALSE, n.cores = NULL, ... )landmark_tsne( data, landmarks = TRUE, reference_method = c("tsne"), n_neighbors = NULL, perplexity = NULL, affinity_support = c("standard", "compact"), n_components = 2L, standardize = TRUE, pca_dims = NULL, seed = 4L, backend = NULL, transform_k = NULL, transform_perplexity = 5, transform_iter = 250L, transform_early_exaggeration_iter = 0L, transform_n_negatives = NULL, initialization = c("median", "weighted", "random"), keep_knn = FALSE, verbose = FALSE, n.cores = NULL, ... )
data |
Numeric matrix/data frame with observations in rows. |
landmarks |
|
reference_method |
Kept for compatibility. Only |
n_neighbors |
Number of non-self neighbors used to embed the landmark
reference set. If |
perplexity |
t-SNE perplexity for the landmark reference embedding. If
|
affinity_support |
Affinity candidate-neighborhood policy. The default
|
n_components |
Output dimensionality, from 1 to 3. Dimensions other
than two use CPU exact repulsion; the current Metal and CUDA
interpolation/FFT optimizers support only |
standardize |
Center and scale columns before landmark selection and
neighbor search. Unlike |
pca_dims |
Optional PCA dimension before KNN. |
seed |
Random seed. |
backend |
Execution backend: |
transform_k |
Number of landmark neighbors used to place non-landmarks. |
transform_perplexity |
Perplexity used by |
transform_iter |
Number of normal transform iterations. Use |
transform_early_exaggeration_iter |
Number of transform early exaggeration iterations. |
transform_n_negatives |
Number of sampled reference negatives used by
|
initialization |
Initial placement for transformed observations. |
keep_knn |
If |
verbose |
Print optimizer progress. |
n.cores |
Number of CPU cores used by CPU KNN and CPU transform optimization. Native GPU stages ignore this argument. |
... |
Additional low-level parameters passed to
|
A fastEmbedR_embedding object.
fit <- landmark_tsne( as.matrix(iris[, 1:4]), landmarks = 0.5, perplexity = 5, early_exaggeration_iter = 5, n_iter = 10, transform_iter = 5, seed = 1 ) plot(fit, labels = iris$Species)fit <- landmark_tsne( as.matrix(iris[, 1:4]), landmarks = 0.5, perplexity = 5, early_exaggeration_iter = 5, n_iter = 10, transform_iter = 5, seed = 1 ) plot(fit, labels = iris$Species)
landmark_umap() embeds a landmark subset with
umap() and projects the
remaining observations against the fixed landmark embedding using
query-to-reference KNN, local affine placement, and optional fixed-reference
refinement. It is an explicit landmark approximation: the UMAP objective
and parameters for the landmark subset are unchanged.
landmark_umap( data, landmarks = 0.5, n_neighbors = NULL, n_components = 2L, standardize = TRUE, pca_dims = NULL, seed = 4L, backend = NULL, transform_k = NULL, n.cores = NULL, keep_knn = FALSE, graph_mode = c("fuzzy", "binary"), verbose = FALSE )landmark_umap( data, landmarks = 0.5, n_neighbors = NULL, n_components = 2L, standardize = TRUE, pca_dims = NULL, seed = 4L, backend = NULL, transform_k = NULL, n.cores = NULL, keep_knn = FALSE, graph_mode = c("fuzzy", "binary"), verbose = FALSE )
data |
Numeric matrix/data frame, or a list containing KNN |
landmarks |
|
n_neighbors |
Number of non-self neighbors. |
n_components |
Output dimensionality. The CPU backend supports positive
dimensions, including three-dimensional embeddings. The current Metal and
CUDA optimizers support only |
standardize |
Center and scale columns before landmark selection and
neighbor search. Unlike |
pca_dims |
Optional PCA dimension before KNN. |
seed |
Random seed. |
backend |
Execution backend: |
transform_k |
Number of landmark neighbors used to project
non-landmark observations. Defaults to |
n.cores |
Requested CPU core count. For matrix input, the value is
passed to native CPU KNN and CPU UMAP; UMAP currently uses at most four
workers and records both requested and effective values. |
keep_knn |
Keep KNN matrices in the returned object. |
graph_mode |
Graph weighting mode passed unchanged to the reference
|
verbose |
Print progress. |
A fastEmbedR_embedding object containing the full layout,
landmark and query indices, timings, and resolved parameters.
x <- scale(as.matrix(iris[1:60, 1:4])) fit <- landmark_umap(x, landmarks = 0.5, n_neighbors = 10, seed = 1) plot(fit)x <- scale(as.matrix(iris[1:60, 1:4])) fit <- landmark_umap(x, landmarks = 0.5, n_neighbors = 10, seed = 1) plot(fit)
pca() computes principal component scores with a backend-native truncated
decomposition. CPU uses a package-native float32 blocked randomized SVD
(RSVD). Metal uses a package-native float32 block-subspace TSVD whose large
matrix products are executed with Metal Performance Shaders while data and
work buffers remain resident in unified GPU memory. CUDA uses native RAPIDS
RAFT TSVD with float32 input, score, and loading buffers. CUDA requests fail
explicitly when RAFT TSVD support is unavailable; they never fall back to
CPU PCA.
pca( x, ncomp = 2L, xtest = NULL, center = TRUE, scale = FALSE, backend = NULL, n.cores = 1L, seed = 4L, tsne_init = FALSE )pca( x, ncomp = 2L, xtest = NULL, center = TRUE, scale = FALSE, backend = NULL, n.cores = 1L, seed = 4L, tsne_init = FALSE )
x |
Numeric matrix/data frame or |
ncomp |
Number of principal components. |
xtest |
Optional test/query matrix with the same columns as |
center |
If |
scale |
If |
backend |
PCA backend: |
n.cores |
Positive integer CPU core limit. It controls the linked
BLAS/OpenMP numerical kernels when |
seed |
Random seed for backends that use a Gaussian subspace sketch. The native RAFT covariance-eigensolver route records this value for provenance but does not consume random numbers. |
tsne_init |
If |
CPU matrix products and factorizations use the BLAS/LAPACK linked to R.
Set n.cores to control their CPU core limit. The requested value is
applied temporarily through standard BLAS/OpenMP environment variables and,
when installed, RhpcBLASctl; the prior process settings are restored
after
the call. A single-threaded BLAS can still report one effective thread. With
float::float32 input, native Metal and CUDA preprocessing and the
returned
scores/loadings also remain float32. The API intentionally has no
decomposition method menu and does not call Python. Explicit unavailable GPU
requests fail instead of being reported as GPU work.
A fastEmbedR_pca list with scores, loadings,
singular_values, centering/scaling vectors, backend metadata, and
decomposition metadata. When tsne_init = TRUE, the list also
contains tsne_init; when xtest is supplied, it also contains
scores_test. Metal and CUDA preserve float::float32 scores,
loadings,
initialization, and compatible test projections when the input is
float32. CPU results also record n.cores_requested,
n.cores_effective, and core_control.
fit <- pca( as.matrix(iris[, 1:4]), ncomp = 2, n.cores = 2, seed = 1, tsne_init = TRUE ) plot(fit$scores, pch = 21, bg = iris$Species) plot(fit$tsne_init, pch = 21, bg = iris$Species)fit <- pca( as.matrix(iris[, 1:4]), ncomp = 2, n.cores = 2, seed = 1, tsne_init = TRUE ) plot(fit$scores, pch = 21, bg = iris$Species) plot(fit$tsne_init, pch = 21, bg = iris$Species)
precompute_knn() exposes the same package-native nearest-neighbor search
used internally by umap() and tsne().
The search algorithm is chosen
by fastEmbedR for the requested backend and is deliberately not a user
parameter.
precompute_knn( data, k = 30L, metric = c("euclidean", "cosine", "correlation", "inner_product"), backend = NULL, n.cores = NULL )precompute_knn( data, k = 30L, metric = c("euclidean", "cosine", "correlation", "inner_product"), backend = NULL, n.cores = NULL )
data |
Numeric matrix, numeric data frame, or a |
k |
Number of non-self nearest neighbors to return. |
metric |
Distance metric: |
backend |
Search backend: |
n.cores |
Number of CPU cores. Native GPU backends ignore this argument. |
CPU search uses the package-native recall-tuned HNSW implementation. Metal uses native exact search for small inputs and recall-tuned IVF-Flat for larger inputs. CUDA uses package-native direct FAISS GPU exact search below 100,000 observations and direct RAPIDS cuVS IVF-Flat above that threshold. The internal recall target is 0.99.
The CUDA result remains on the GPU and can be passed directly to
umap_knn() or tsne_knn() with
backend = "cuda". CPU and Metal
results contain one-based indices and distances matrices. Every
result
excludes the observation itself. An unavailable requested backend raises an
error; no CPU fallback is reported as GPU work.
A fastEmbedR_knn object. Host results contain indices and
distances; CUDA results additionally inherit from
fastEmbedR_gpu_knn
and own device-resident index and distance buffers.
x <- scale(as.matrix(iris[, 1:4])) knn <- precompute_knn(x, k = 15, backend = "cpu", n.cores = 2) layout <- umap_knn(knn, backend = "cpu", seed = 1)x <- scale(as.matrix(iris[, 1:4])) knn <- precompute_knn(x, k = 15, backend = "cpu", n.cores = 2) layout <- umap_knn(knn, backend = "cpu", seed = 1)
precompute_query_knn() searches a fixed reference matrix for every row of
a query matrix. It uses the same package-native backend family and routing
policy as precompute_knn(), but does not compute
unnecessary
reference-to-reference or query-to-query neighbors.
precompute_query_knn( reference, query, k = 30L, metric = c("euclidean", "cosine", "correlation", "inner_product"), backend = NULL, n.cores = NULL )precompute_query_knn( reference, query, k = 30L, metric = c("euclidean", "cosine", "correlation", "inner_product"), backend = NULL, n.cores = NULL )
reference |
Reference observations in rows. |
query |
Query observations in rows and the same feature space as
|
k |
Number of non-self nearest neighbors to return. |
metric |
Distance metric: |
backend |
Search backend: |
n.cores |
Number of CPU cores. Native GPU backends ignore this argument. |
CPU uses the native recall-tuned HNSW reference-query path. Metal routes between a native query-only exact kernel and recall-tuned IVF-Flat from the estimated reference-query distance workload. CUDA uses direct FAISS GPU exact search below 100,000 reference rows and direct RAPIDS cuVS IVF-Flat above that threshold. CUDA results remain device-resident for direct consumption by landmark UMAP and t-SNE transformations.
A fastEmbedR_knn object with one row per query observation and
one-based indices into reference.
x <- scale(as.matrix(iris[, 1:4])) ref <- x[1:100, , drop = FALSE] qry <- x[101:150, , drop = FALSE] knn <- precompute_query_knn(ref, qry, k = 10, backend = "cpu")x <- scale(as.matrix(iris[, 1:4])) ref <- x[1:100, , drop = FALSE] qry <- x[101:150, , drop = FALSE] knn <- precompute_query_knn(ref, qry, k = 10, backend = "cpu")
prepare_tsne_knn() strips self-neighbors, trims to the requested
non-self width, and stores compact KNN matrices once. Pass the returned
object to tsne_knn() for repeated seeds or backend
comparisons without
repeating KNN normalization/materialization.
prepare_tsne_knn( indices, distances = NULL, n_neighbors = NULL, perplexity = NULL, affinity_support = c("standard", "compact") )prepare_tsne_knn( indices, distances = NULL, n_neighbors = NULL, perplexity = NULL, affinity_support = c("standard", "compact") )
indices |
A list containing KNN |
distances |
Numeric KNN distance matrix matching |
n_neighbors |
Optional number of non-self neighbor columns to use from
the supplied KNN graph. This lets you compute a wide KNN once and reuse
its first columns for comparable tests. If omitted, |
perplexity |
t-SNE perplexity. If |
affinity_support |
Affinity candidate-neighborhood policy.
|
A prepared t-SNE KNN object.
x <- scale(as.matrix(iris[, 1:4])) d <- as.matrix(stats::dist(x)) diag(d) <- Inf k <- 15L idx <- t(apply(d, 1L, order))[, seq_len(k), drop = FALSE] dst <- matrix(d[cbind(rep(seq_len(nrow(d)), each = k), as.vector(t(idx)))], nrow = nrow(d), byrow = TRUE ) prep <- prepare_tsne_knn(idx, dst, perplexity = 5) y1 <- tsne_knn(prep, seed = 1, early_exaggeration_iter = 5, n_iter = 10) y2 <- tsne_knn(prep, seed = 2, early_exaggeration_iter = 5, n_iter = 10)x <- scale(as.matrix(iris[, 1:4])) d <- as.matrix(stats::dist(x)) diag(d) <- Inf k <- 15L idx <- t(apply(d, 1L, order))[, seq_len(k), drop = FALSE] dst <- matrix(d[cbind(rep(seq_len(nrow(d)), each = k), as.vector(t(idx)))], nrow = nrow(d), byrow = TRUE ) prep <- prepare_tsne_knn(idx, dst, perplexity = 5) y1 <- tsne_knn(prep, seed = 1, early_exaggeration_iter = 5, n_iter = 10) y2 <- tsne_knn(prep, seed = 2, early_exaggeration_iter = 5, n_iter = 10)
prepare_umap_knn() builds the CSR graph once from a KNN object or index
and distance matrices. The result can be passed to
umap_knn() or
embed_knn() repeatedly with different seeds without
rebuilding the graph
or recomputing epochs_per_sample.
prepare_umap_knn( indices, distances = NULL, backend = NULL, n.cores = NULL, graph_mode = c("fuzzy", "binary") )prepare_umap_knn( indices, distances = NULL, backend = NULL, n.cores = NULL, graph_mode = c("fuzzy", "binary") )
indices |
Integer matrix of nearest-neighbor indices, one row per
observation, or a KNN object containing |
distances |
Numeric matrix matching |
backend |
Execution backend: |
n.cores |
Requested CPU core count. CPU UMAP currently uses at most
four workers and records both requested and effective values. |
graph_mode |
Graph weighting mode. |
A prepared UMAP object containing the KNN, CSR graph, and resolved UMAP graph schedule.
x <- scale(as.matrix(iris[, 1:4])) d <- as.matrix(stats::dist(x)) diag(d) <- Inf k <- 15L idx <- t(apply(d, 1L, order))[, seq_len(k), drop = FALSE] dst <- matrix(d[cbind(rep(seq_len(nrow(d)), each = k), as.vector(t(idx)))], nrow = nrow(d), byrow = TRUE ) prep <- prepare_umap_knn(idx, dst) y1 <- umap_knn(prep, seed = 1) y2 <- umap_knn(prep, seed = 2)x <- scale(as.matrix(iris[, 1:4])) d <- as.matrix(stats::dist(x)) diag(d) <- Inf k <- 15L idx <- t(apply(d, 1L, order))[, seq_len(k), drop = FALSE] dst <- matrix(d[cbind(rep(seq_len(nrow(d)), each = k), as.vector(t(idx)))], nrow = nrow(d), byrow = TRUE ) prep <- prepare_umap_knn(idx, dst) y1 <- umap_knn(prep, seed = 1) y2 <- umap_knn(prep, seed = 2)
Print a precomputed nearest-neighbor object
## S3 method for class 'fastEmbedR_knn' print(x, ...)## S3 method for class 'fastEmbedR_knn' print(x, ...)
x |
A |
... |
Unused. |
x, invisibly.
Print a reusable UMAP initialization
## S3 method for class 'fastEmbedR_umap_initialization' print(x, ...)## S3 method for class 'fastEmbedR_umap_initialization' print(x, ...)
x |
A |
... |
Unused. |
x, invisibly.
project_landmark_model() computes query-to-reference KNN with the same
native backend policy used by the full embedding functions, then applies the
method-specific fixed-reference transform. Landmark coordinates remain
fixed.
project_landmark_model( model, data, query_indices = NULL, transform_k = NULL, refinement_epochs = 50L, transform_perplexity = 5, transform_iter = 250L, transform_early_exaggeration_iter = 0L, transform_n_negatives = NULL, initialization = c("median", "weighted", "random"), keep_knn = FALSE, n.cores = NULL, verbose = FALSE, ... )project_landmark_model( model, data, query_indices = NULL, transform_k = NULL, refinement_epochs = 50L, transform_perplexity = 5, transform_iter = 250L, transform_early_exaggeration_iter = 0L, transform_n_negatives = NULL, initialization = c("median", "weighted", "random"), keep_knn = FALSE, n.cores = NULL, verbose = FALSE, ... )
model |
A model returned by
|
data |
The original full data matrix for a model fitted on a strict
landmark subset, or a matrix containing only new query observations in the
same feature space. A model fitted with all training rows as references
always treats |
query_indices |
Optional rows of |
transform_k |
Number of reference neighbors. |
refinement_epochs |
Fixed-reference UMAP refinement epochs. |
transform_perplexity |
Perplexity of the t-SNE transform. |
transform_iter |
Number of t-SNE transform iterations. |
transform_early_exaggeration_iter |
Transform exaggeration iterations. |
transform_n_negatives |
Number of reference negatives for t-SNE. |
initialization |
t-SNE query initialization. |
keep_knn |
Retain query-to-reference KNN output. |
n.cores |
Number of CPU cores. |
verbose |
Print optimizer progress. |
... |
Low-level t-SNE transform controls. |
A fastEmbedR_embedding. For a strict landmark-subset model, passing
the original full matrix reassembles layout in original row order.
Otherwise layout contains only the supplied query rows. The returned
parameters record projection_scope as "original_reconstruction" or
"held_out_query".
x <- scale(as.matrix(iris[, 1:4])) selection <- select_landmarks(x, 0.5, seed = 1) model <- fit_landmark_model( x, selection, method = "umap", n_neighbors = 10, seed = 1 ) fit <- project_landmark_model(model, x, refinement_epochs = 2)x <- scale(as.matrix(iris[, 1:4])) selection <- select_landmarks(x, 0.5, seed = 1) model <- fit_landmark_model( x, selection, method = "umap", n_neighbors = 10, seed = 1 ) fit <- project_landmark_model(model, x, refinement_epochs = 2)
select_landmarks() separates row indices into a representative landmark
reference and its complementary query set. It does not embed or project the
data.
select_landmarks(data, landmarks = TRUE, seed = 4L, n.cores = NULL)select_landmarks(data, landmarks = TRUE, seed = 4L, n.cores = NULL)
data |
Numeric matrix, data frame, or |
landmarks |
|
seed |
Random seed used by projection-based landmark selection. |
n.cores |
Number of CPU cores used for float32 selection features. |
A fastEmbedR_landmark_selection object containing indices and
query_indices.
x <- scale(as.matrix(iris[, 1:4])) selection <- select_landmarks(x, landmarks = 0.5, seed = 1) selection$indicesx <- scale(as.matrix(iris[, 1:4])) selection <- select_landmarks(x, landmarks = 0.5, seed = 1) selection$indices
transform_tsne() places query observations into a fixed reference t-SNE
embedding. It follows a fixed-reference t-SNE transform design:
query-to-reference affinities are computed from KNN distances, query points
are initialized from nearby reference points, and optimization moves only the
query points.
transform_tsne( reference_layout, knn = NULL, reference_data = NULL, new_data = NULL, k = NULL, perplexity = 5, initialization = c("median", "weighted", "random"), Y_init = NULL, n_iter = 250L, early_exaggeration_iter = 0L, learning_rate = 0.1, early_exaggeration = 4, exaggeration = 1.5, initial_momentum = 0.8, final_momentum = 0.8, max_grad_norm = 0.25, max_step_norm = Inf, n_negatives = NULL, exact_repulsion_threshold = 4096L, n.cores = NULL, seed = 4L, backend = NULL, verbose = FALSE )transform_tsne( reference_layout, knn = NULL, reference_data = NULL, new_data = NULL, k = NULL, perplexity = 5, initialization = c("median", "weighted", "random"), Y_init = NULL, n_iter = 250L, early_exaggeration_iter = 0L, learning_rate = 0.1, early_exaggeration = 4, exaggeration = 1.5, initial_momentum = 0.8, final_momentum = 0.8, max_grad_norm = 0.25, max_step_norm = Inf, n_negatives = NULL, exact_repulsion_threshold = 4096L, n.cores = NULL, seed = 4L, backend = NULL, verbose = FALSE )
reference_layout |
Numeric reference embedding matrix, or a
|
knn |
Optional query-to-reference KNN list with |
reference_data |
Reference observations in the same preprocessing space
used to fit |
new_data |
Query observations in the same preprocessing space as
|
k |
Number of reference neighbors used for transform KNN. If |
perplexity |
Transform perplexity. The default is 5. |
initialization |
Initial query placement: |
Y_init |
Optional initial query embedding matrix. When supplied, it
overrides |
n_iter |
Number of normal transform optimization iterations. |
early_exaggeration_iter |
Number of early-exaggeration iterations. |
learning_rate |
Transform learning rate. |
early_exaggeration |
Early exaggeration multiplier. |
exaggeration |
Normal transform exaggeration multiplier. |
initial_momentum |
Momentum used during early exaggeration. |
final_momentum |
Momentum used during normal optimization. |
max_grad_norm |
Maximum per-query gradient norm. Use |
max_step_norm |
Maximum per-query step norm. Use |
n_negatives |
Number of sampled reference points for repulsion when
the reference set is larger than |
exact_repulsion_threshold |
Use exact query-reference repulsion at or below this reference count. |
n.cores |
Number of CPU cores for the native optimizer. |
seed |
Random seed. |
backend |
Backend used for query KNN when |
verbose |
Print native optimizer progress. |
A numeric matrix with one row per query observation.
reference <- matrix(c(0, 0, 1, 0, 0, 1, 1, 1), 4L, 2L, byrow = TRUE) query_knn <- list( indices = matrix(c(1L, 2L, 3L, 4L), 2L, 2L, byrow = TRUE), distances = matrix(c(0.1, 0.2, 0.15, 0.25), 2L, 2L, byrow = TRUE) ) query_layout <- transform_tsne( reference, knn = query_knn, perplexity = 0.5, n_iter = 2, exact_repulsion_threshold = 10, seed = 1 )reference <- matrix(c(0, 0, 1, 0, 0, 1, 1, 1), 4L, 2L, byrow = TRUE) query_knn <- list( indices = matrix(c(1L, 2L, 3L, 4L), 2L, 2L, byrow = TRUE), distances = matrix(c(0.1, 0.2, 0.15, 0.25), 2L, 2L, byrow = TRUE) ) query_layout <- transform_tsne( reference, knn = query_knn, perplexity = 0.5, n_iter = 2, exact_repulsion_threshold = 10, seed = 1 )
tsne() computes or reuses a KNN graph, then runs the package-native
two-phase t-SNE optimizer. The default optimizer is CPU-native.
Explicit backend = "metal" and backend = "cuda" requests use the
matching package-native GPU optimizer when compiled and fail clearly if the
requested backend is unavailable.
The implementation follows published sparse-affinity and interpolation-based
t-SNE methods and provides independent CPU, Metal, and CUDA kernels.
tsne( data, perplexity = NULL, affinity_support = c("standard", "compact"), n_components = 2L, init_data = NULL, Y_init = NULL, standardize = FALSE, pca_dims = NULL, metric = c("euclidean", "cosine", "correlation", "inner_product"), nn = NULL, seed = 4L, backend = NULL, keep_knn = FALSE, verbose = FALSE, n.cores = NULL, learning_rate = "auto", early_exaggeration_iter = NULL, early_exaggeration = "auto", n_iter = NULL, exaggeration = NULL, initial_momentum = 0.8, final_momentum = 0.8, max_step_norm = "auto", negative_gradient_method = "auto", record_costs = FALSE, auto_config = TRUE, ... )tsne( data, perplexity = NULL, affinity_support = c("standard", "compact"), n_components = 2L, init_data = NULL, Y_init = NULL, standardize = FALSE, pca_dims = NULL, metric = c("euclidean", "cosine", "correlation", "inner_product"), nn = NULL, seed = 4L, backend = NULL, keep_knn = FALSE, verbose = FALSE, n.cores = NULL, learning_rate = "auto", early_exaggeration_iter = NULL, early_exaggeration = "auto", n_iter = NULL, exaggeration = NULL, initial_momentum = 0.8, final_momentum = 0.8, max_step_norm = "auto", negative_gradient_method = "auto", record_costs = FALSE, auto_config = TRUE, ... )
data |
Numeric matrix/data frame with observations in rows, or a list
containing KNN |
perplexity |
t-SNE perplexity. If |
affinity_support |
Affinity candidate-neighborhood policy. The default
|
n_components |
Output dimensionality, from 1 to 3. Dimensions other
than two use CPU exact repulsion; the current Metal and CUDA
interpolation/FFT optimizers support only |
init_data |
Optional original high-dimensional data matrix used only to
compute PCA initialization with |
Y_init |
Optional explicit initial layout. Use
|
standardize |
Center and scale columns before KNN. Defaults to |
pca_dims |
Optional PCA dimension before KNN. |
metric |
KNN distance metric for one-call matrix input: |
nn |
Optional precomputed KNN output when |
seed |
Random seed. |
backend |
Execution backend: |
keep_knn |
If |
verbose |
Print optimizer progress. |
n.cores |
Number of CPU cores used by CPU KNN and CPU t-SNE
optimization. |
learning_rate |
Positive number or |
early_exaggeration_iter |
Number of early-exaggeration iterations. |
early_exaggeration |
Early-exaggeration multiplier, or |
n_iter |
Number of normal optimization iterations after early exaggeration. |
exaggeration |
Normal-phase exaggeration. |
initial_momentum |
Momentum during early exaggeration. |
final_momentum |
Momentum during normal optimization. |
max_step_norm |
Maximum per-point update norm. |
negative_gradient_method |
|
record_costs |
If |
auto_config |
If |
... |
Additional low-level parameters passed to
|
The t-SNE API exposes the principal
scientifically consequential optimizer controls: perplexity and candidate
support, initialization, iteration counts, early and normal exaggeration,
learning rate, momentum, clipping, and exact-versus-FFT repulsion. Setting
auto_config = FALSE disables automatic iteration and stopping choices;
explicit values always override automatic values. The matrix-input function
deliberately does not expose a nearest-neighbor index type or tuning
parameters: it uses the backend router with target recall 0.99. Supply an
externally generated KNN object to tsne_knn() when
search policy or
affinity support must be controlled independently. The resolved settings
are returned in fit$parameters.
A fastEmbedR_embedding object.
fit <- tsne( as.matrix(iris[, 1:4]), perplexity = 5, early_exaggeration_iter = 5, n_iter = 10, seed = 1 ) plot(fit, labels = iris$Species)fit <- tsne( as.matrix(iris[, 1:4]), perplexity = 5, early_exaggeration_iter = 5, n_iter = 10, seed = 1 ) plot(fit, labels = iris$Species)
tsne_knn() is the direct KNN-input entry point for the native
interpolation-based optimizer. It accepts either a list containing KNN
indices
and distances or separate KNN index and distance matrices. The supplied
neighbors are used directly: this function performs no neighbor search or
input scaling. PCA is computed only when init_data is supplied and
Y_init is absent.
The optimizer follows the sparse-affinity and interpolation-based t-SNE
literature while using fastEmbedR's own R API and native kernels.
tsne_knn( indices, distances = NULL, n_neighbors = NULL, perplexity = NULL, affinity_support = c("standard", "compact"), n_components = 2L, init_data = NULL, Y_init = NULL, seed = 4L, verbose = FALSE, backend = NULL, n.cores = NULL, learning_rate = "auto", early_exaggeration_iter = NULL, early_exaggeration = "auto", n_iter = NULL, exaggeration = NULL, initial_momentum = 0.8, final_momentum = 0.8, max_step_norm = "auto", negative_gradient_method = "auto", record_costs = FALSE, auto_config = TRUE, ... )tsne_knn( indices, distances = NULL, n_neighbors = NULL, perplexity = NULL, affinity_support = c("standard", "compact"), n_components = 2L, init_data = NULL, Y_init = NULL, seed = 4L, verbose = FALSE, backend = NULL, n.cores = NULL, learning_rate = "auto", early_exaggeration_iter = NULL, early_exaggeration = "auto", n_iter = NULL, exaggeration = NULL, initial_momentum = 0.8, final_momentum = 0.8, max_step_norm = "auto", negative_gradient_method = "auto", record_costs = FALSE, auto_config = TRUE, ... )
indices |
A list containing KNN |
distances |
Numeric KNN distance matrix matching |
n_neighbors |
Optional number of non-self neighbor columns to use from
the supplied KNN graph. This lets you compute a wide KNN once and reuse
its first columns for comparable tests. If omitted, |
perplexity |
t-SNE perplexity. If |
affinity_support |
Affinity candidate-neighborhood policy.
|
n_components |
Output dimensionality, from 1 to 3. Dimensions other
than two use CPU exact repulsion; the current Metal and CUDA
interpolation/FFT optimizers support only |
init_data |
Optional original high-dimensional data matrix used only to compute PCA initialization for KNN-input runs. It is not used for neighbor search or optimization. |
Y_init |
Optional explicit initial layout. Use
|
seed |
Random seed. |
verbose |
Print optimizer progress. |
backend |
Optimizer backend: |
n.cores |
Number of CPU cores used for CPU affinity construction and
t-SNE optimization. |
learning_rate |
Positive number or |
early_exaggeration_iter |
Number of early-exaggeration iterations. |
early_exaggeration |
Early-exaggeration multiplier, or |
n_iter |
Number of normal optimization iterations after early exaggeration. |
exaggeration |
Normal-phase exaggeration. |
initial_momentum |
Momentum during early exaggeration. |
final_momentum |
Momentum during normal optimization. |
max_step_norm |
Maximum per-point update norm. |
negative_gradient_method |
|
record_costs |
If |
auto_config |
If |
... |
Additional low-level optimizer controls, including |
An embedding matrix with settings stored in
attr(layout, "fastEmbedR_config"). Float32 KNN distances, including a
CUDA-resident KNN object, produce a float::float32 layout; host double
distances produce a standard R double matrix. Native optimization uses
float32 in both cases. The exact returned representation is recorded in
attr(layout, "precision") and in
fastEmbedR_config$output_precision.
x <- scale(as.matrix(iris[, 1:4])) d <- as.matrix(stats::dist(x)) diag(d) <- Inf k <- 15L idx <- t(apply(d, 1L, order))[, seq_len(k), drop = FALSE] dst <- matrix(d[cbind(rep(seq_len(nrow(d)), each = k), as.vector(t(idx)))], nrow = nrow(d), byrow = TRUE ) layout <- tsne_knn(idx, dst, init_data = x, perplexity = 5, early_exaggeration_iter = 5, n_iter = 10 )x <- scale(as.matrix(iris[, 1:4])) d <- as.matrix(stats::dist(x)) diag(d) <- Inf k <- 15L idx <- t(apply(d, 1L, order))[, seq_len(k), drop = FALSE] dst <- matrix(d[cbind(rep(seq_len(nrow(d)), each = k), as.vector(t(idx)))], nrow = nrow(d), byrow = TRUE ) layout <- tsne_knn(idx, dst, init_data = x, perplexity = 5, early_exaggeration_iter = 5, n_iter = 10 )
tsne_pca_init() creates the small-scale PCA initialization used by
tsne() and tsne_knn(). Supplying
cache_file stores the result
as an RDS file; later calls with the same path reuse the saved matrix instead
of recomputing PCA. This is useful when comparing several KNN backends with
exactly the same initialization. For backend = "cuda", fastEmbedR
requires
native RAPIDS RAFT TSVD support compiled into the CUDA backend and fails
loudly if that backend is unavailable. Metal uses fastEmbedR's native
float32 block-subspace TSVD with native Metal centering/scaling, Metal
Performance Shaders matrix products, and one resident GPU workspace. CPU
uses fastEmbedR's native float32 blocked RSVD implementation. The package
does not call Python or reticulate for PCA initialization.
tsne_pca_init( data, n_components = 2L, seed = 4L, backend = NULL, n.cores = 1L, cache_file = NULL, force_recompute = FALSE )tsne_pca_init( data, n_components = 2L, seed = 4L, backend = NULL, n.cores = 1L, cache_file = NULL, force_recompute = FALSE )
data |
Numeric matrix/data frame or |
n_components |
Output dimensionality, usually |
seed |
Random seed used by the truncated PCA subspace sketch. |
backend |
Backend used for PCA when available: |
n.cores |
Number of CPU cores used for CPU PCA initialization. Metal and CUDA ignore this argument. |
cache_file |
Optional |
force_recompute |
If |
An initialization matrix suitable for Y_init. Float32 input is
returned as float::float32 when the selected PCA backend preserves it.
init <- tsne_pca_init(as.matrix(iris[, 1:4]), seed = 1) plot(init, pch = 21, bg = iris$Species)init <- tsne_pca_init(as.matrix(iris[, 1:4]), seed = 1) plot(init, pch = 21, bg = iris$Species)
umap() is a small convenience wrapper. If data is already a list
of KNN
indices and distances, it calls
umap_knn() directly. Otherwise it
preprocesses the data, computes KNN once with fastEmbedR's native backend,
and embeds from that KNN graph.
umap( data, n_neighbors = NULL, n_components = 2L, standardize = FALSE, pca_dims = NULL, metric = c("euclidean", "cosine", "correlation", "inner_product"), nn = NULL, seed = 4L, backend = NULL, n.cores = NULL, keep_knn = FALSE, graph_mode = c("fuzzy", "binary"), verbose = FALSE )umap( data, n_neighbors = NULL, n_components = 2L, standardize = FALSE, pca_dims = NULL, metric = c("euclidean", "cosine", "correlation", "inner_product"), nn = NULL, seed = 4L, backend = NULL, n.cores = NULL, keep_knn = FALSE, graph_mode = c("fuzzy", "binary"), verbose = FALSE )
data |
Numeric matrix/data frame, or a list containing KNN |
n_neighbors |
Number of non-self neighbors. |
n_components |
Output dimensionality. The CPU backend supports positive
dimensions, including three-dimensional embeddings. The current Metal and
CUDA optimizers support only |
standardize |
Center and scale columns before KNN when |
pca_dims |
Optional PCA dimension before KNN. |
metric |
KNN distance metric for one-call matrix input: |
nn |
Optional precomputed KNN result when |
seed |
Random seed. |
backend |
Execution backend: |
n.cores |
Requested CPU core count. For matrix input, the value is
passed to native CPU KNN and CPU UMAP; UMAP currently uses at most four
workers and records both requested and effective values. |
keep_knn |
Keep KNN matrices in the returned object. |
graph_mode |
Graph weighting mode. |
verbose |
Print progress. |
umap() is an opinionated high-throughput UMAP implementation rather than
a drop-in interface for every UMAP hyperparameter. The public matrix-input
API exposes neighborhood size, distance metric, graph weighting, output
dimension, preprocessing, backend, seed, and CPU thread count. In the
current release, epochs, minimum distance, spread, learning rate, repulsion
strength, negative-sample rate, spectral iteration count, and asynchronous
update mode are selected internally. The resolved values and rule names are
stored in fit$parameters.
The default policy uses 500 epochs below 10,000 observations and 200 epochs
for larger inputs, increasing to 300 for high-variability distance profiles;
five negative samples, spread 1, and repulsion strength 1 are fixed. Minimum
distance is normally 0.01 and becomes 0.1 only under the documented
wide-shell profile; learning rate is correspondingly 1 or 1.25. Use
umap_init() to precompute and reuse package-native
initial coordinates,
or umap_knn() to supply an externally controlled KNN
graph. These controls
are scientifically consequential; fixing them is a scope
decision made to keep one tested objective and update schedule aligned across
CPU, Metal, and CUDA, not a claim that the values are universally optimal.
Arbitrary min_dist, spread, epoch, learning-rate,
negative-sampling, or
optimizer-mode sweeps should use a
general-purpose UMAP implementation; fastEmbedR does not claim API or
parameter interchangeability with those packages.
A fastEmbedR_embedding object.
x <- scale(as.matrix(iris[, 1:4])) fit <- umap(x, n_neighbors = 15, seed = 1) plot(fit)x <- scale(as.matrix(iris[, 1:4])) fit <- umap(x, n_neighbors = 15, seed = 1) plot(fit)
umap_init() separates UMAP neighbor search, graph construction, and
initialization from stochastic optimization. The returned object can be
passed directly to umap_knn() so repeated or
cross-backend runs reuse the
same KNN graph and initial coordinates.
umap_init( x, distances = NULL, n_neighbors = NULL, n_components = 2L, metric = c("euclidean", "cosine", "correlation", "inner_product"), backend = NULL, seed = 4L, n.cores = NULL, graph_mode = c("fuzzy", "binary") )umap_init( x, distances = NULL, n_neighbors = NULL, n_components = 2L, metric = c("euclidean", "cosine", "correlation", "inner_product"), backend = NULL, seed = 4L, n.cores = NULL, graph_mode = c("fuzzy", "binary") )
x |
Numeric data, a KNN object, or an object returned by
|
distances |
Optional KNN distance matrix when |
n_neighbors |
Number of non-self neighbors when |
n_components |
Output dimensionality. |
metric |
Distance metric used only when KNN must be computed. |
backend |
Initialization backend: |
seed |
Random seed. |
n.cores |
Number of CPU cores. |
graph_mode |
UMAP graph weighting. |
For the fuzzy graph, CPU initialization is computed from the prepared CSR graph, while native Metal or CUDA spectral kernels are used when requested and available. Binary initialization is computed from the same unit-weight CSR graph used by the optimizer, so its mathematical input is unchanged. Explicit GPU requests fail when the corresponding native backend is unavailable.
CUDA KNN input is materialized on the host only for this standalone diagnostic API. The ordinary one-call CUDA UMAP path remains device resident.
A fastEmbedR_umap_initialization object with layout,
prepared,
resolved parameters, and component timings. Pass the complete object to
umap_knn() or use its layout component directly
for diagnostics.
x <- scale(as.matrix(iris[, 1:4])) initialization <- umap_init( x, n_neighbors = 15, backend = "cpu", graph_mode = "fuzzy", seed = 1 ) layout <- umap_knn(initialization, backend = "cpu", seed = 1) plot(layout, pch = 21, bg = iris$Species)x <- scale(as.matrix(iris[, 1:4])) initialization <- umap_init( x, n_neighbors = 15, backend = "cpu", graph_mode = "fuzzy", seed = 1 ) layout <- umap_knn(initialization, backend = "cpu", seed = 1) plot(layout, pch = 21, bg = iris$Species)
Run UMAP from precomputed nearest neighbors
umap_knn( indices, distances = NULL, n_components = 2L, seed = 42L, verbose = FALSE, backend = NULL, n.cores = NULL, graph_mode = c("fuzzy", "binary") )umap_knn( indices, distances = NULL, n_components = 2L, seed = 42L, verbose = FALSE, backend = NULL, n.cores = NULL, graph_mode = c("fuzzy", "binary") )
indices |
Integer matrix of nearest-neighbor indices, one row per
observation, or a KNN object containing |
distances |
Numeric matrix matching |
n_components |
Output dimensionality. The CPU backend supports positive
dimensions, including three-dimensional embeddings. The current Metal and
CUDA optimizers support only |
seed |
Integer random seed. |
verbose |
Print native optimizer progress. |
backend |
Execution backend: |
n.cores |
Requested CPU core count. CPU UMAP currently uses at most
four workers and records both requested and effective values. |
graph_mode |
Graph weighting mode. |
This KNN-input function exposes the same deliberately constrained optimizer
policy as umap(). It reuses the supplied neighbors but
still selects
epochs, minimum distance, spread, learning rate, repulsion strength,
negative-sample rate, spectral iterations, and backend update mode
internally. The resolved configuration is attached as
attr(layout, "fastEmbedR_config"). Pass an object from
umap_init() to
reuse both the prepared graph and package-native initialization. This API is
intended for fixed-boundary comparisons and repeated seeds, not arbitrary
UMAP hyperparameter sweeps.
An embedding matrix with nrow(indices) rows and n_components
columns. Float32 KNN input returns a float::float32 layout; ordinary R
input returns a numeric matrix. Resolved settings are stored in
attr(layout, "fastEmbedR_config").
x <- scale(as.matrix(iris[, 1:4])) d <- as.matrix(stats::dist(x)) diag(d) <- Inf k <- 10L idx <- t(apply(d, 1L, order))[, seq_len(k), drop = FALSE] dst <- matrix( d[cbind(rep(seq_len(nrow(d)), each = k), as.vector(t(idx)))], nrow = nrow(d), byrow = TRUE ) layout <- umap_knn(idx, dst, seed = 1) plot(layout, pch = 21, bg = iris$Species)x <- scale(as.matrix(iris[, 1:4])) d <- as.matrix(stats::dist(x)) diag(d) <- Inf k <- 10L idx <- t(apply(d, 1L, order))[, seq_len(k), drop = FALSE] dst <- matrix( d[cbind(rep(seq_len(nrow(d)), each = k), as.vector(t(idx)))], nrow = nrow(d), byrow = TRUE ) layout <- umap_knn(idx, dst, seed = 1) plot(layout, pch = 21, bg = iris$Species)