Skip to contents

Embeds the rows of a data frame or matrix in a low-dimensional space with Uniform Manifold Approximation and Projection (UMAP). This is the engine behind stat_umap(), made available for use outside of plots.

Usage

umap_embed(
  data,
  features = where(is.numeric),
  ...,
  n_neighbors = 15L,
  n_components = 2L,
  min_dist = 0.1,
  spread = 1,
  metric = "euclidean",
  n_epochs = NULL,
  init = "auto",
  flavour = c("0.5", "0.6"),
  scale = FALSE,
  seed = NULL,
  n_threads = umap_threads(),
  control = umap_control()
)

Arguments

data

A data frame or a numeric matrix with observations in rows.

features

<tidy-select> Columns of data to use as input. Defaults to all numeric columns. Ignored when data is a matrix.

...

These dots are for future extensions and must be empty.

n_neighbors

Size of the local neighbourhood (number of nearest neighbours). Larger values preserve more global structure.

n_components

Dimension of the embedding.

min_dist

Minimum distance between embedded points. Smaller values give tighter clusters.

spread

Scale of the embedded points; together with min_dist it determines how clumped the embedding is.

metric

Distance metric in the input space, for example "euclidean" (default), "cosine", "manhattan" or "correlation".

n_epochs

Number of optimisation epochs. NULL uses the default (500 for small, 200 for large data sets).

init

Initialisation of the embedding: "auto" (spectral for flavour = "0.5", recursive for "0.6"), "spectral", "tswspectral", "pca", "random" or "recursive".

flavour

Which umap-learn pipeline to reproduce. "0.5" (default) is the established algorithm: spectral initialisation and stochastic gradient descent. "0.6" uses recursive initialisation and the Adam optimiser, and is deterministic for a fixed number of threads.

scale

Standardise each feature to zero mean and unit variance before embedding? Recommended when features have different units.

seed

Random seed. NULL (default) draws one from R's random number generator, so set.seed() makes results reproducible. See umap_threads() for the role of the number of threads.

n_threads

Number of threads. Defaults to umap_threads().

control

Advanced parameters created by umap_control().

Value

A data frame with one row per row of data, and the columns UMAP1, ..., UMAP<n_components> and knn_dist (the mean distance of the observation to its nearest neighbours in input space). Rows with missing feature values are NA.

Examples

emb <- umap_embed(iris, Sepal.Length:Petal.Width, seed = 1, n_threads = 1)
head(emb)
#>      UMAP1     UMAP2  knn_dist
#> 1 17.70845 2.3416889 0.2206497
#> 2 19.39458 1.1980609 0.2788145
#> 3 18.94581 0.7960742 0.2883166
#> 4 19.18117 0.9736792 0.2761466
#> 5 17.63275 2.0914984 0.2452016
#> 6 16.48945 2.6869674 0.4382381

# Matrices work too
emb <- umap_embed(as.matrix(iris[1:4]), seed = 1, n_threads = 1)