Title: | The Uniform Manifold Approximation and Projection (UMAP) Method for Dimensionality Reduction |
---|---|
Description: | An implementation of the Uniform Manifold Approximation and Projection dimensionality reduction by McInnes et al. (2018) <doi:10.48550/arXiv.1802.03426>. It also provides means to transform new data and to carry out supervised dimensionality reduction. An implementation of the related LargeVis method of Tang et al. (2016) <doi:10.48550/arXiv.1602.00370> is also provided. This is a complete re-implementation in R (and C++, via the 'Rcpp' package): no Python installation is required. See the uwot website (<https://github.com/jlmelville/uwot>) for more documentation and examples. |
Authors: | James Melville [aut, cre, cph], Aaron Lun [ctb], Mohamed Nadhir Djekidel [ctb], Yuhan Hao [ctb], Dirk Eddelbuettel [ctb] |
Maintainer: | James Melville <[email protected]> |
License: | GPL (>= 3) |
Version: | 0.2.2.9000 |
Built: | 2024-11-06 05:29:45 UTC |
Source: | https://github.com/jlmelville/uwot |
Functions to write a UMAP model to a file, and to restore.
load_uwot(file, verbose = FALSE)
load_uwot(file, verbose = FALSE)
file |
name of the file where the model is to be saved or read from. |
verbose |
if |
The model saved at file
, for use with
umap_transform
. Additionally, it contains an extra item:
mod_dir
, which contains the path to the temporary working directory
used during loading of the model. This directory cannot be removed until
this model has been unloaded by using unload_uwot
.
library(RSpectra) iris_train <- iris[c(1:10, 51:60), ] iris_test <- iris[100:110, ] # create model model <- umap(iris_train, ret_model = TRUE, n_epochs = 20) # save without unloading: this leaves behind a temporary working directory model_file <- tempfile("iris_umap") model <- save_uwot(model, file = model_file) # The model can continue to be used test_embedding <- umap_transform(iris_test, model) # To manually unload the model from memory when finished and to clean up # the working directory (this doesn't touch your model file) unload_uwot(model) # At this point, model cannot be used with umap_transform, this would fail: # test_embedding2 <- umap_transform(iris_test, model) # restore the model: this also creates a temporary working directory model2 <- load_uwot(file = model_file) test_embedding2 <- umap_transform(iris_test, model2) # Unload and clean up the loaded model temp directory unload_uwot(model2) # clean up the model file unlink(model_file) # save with unloading: this deletes the temporary working directory but # doesn't allow the model to be re-used model3 <- umap(iris_train, ret_model = TRUE, n_epochs = 20) model_file3 <- tempfile("iris_umap") model3 <- save_uwot(model3, file = model_file3, unload = TRUE)
library(RSpectra) iris_train <- iris[c(1:10, 51:60), ] iris_test <- iris[100:110, ] # create model model <- umap(iris_train, ret_model = TRUE, n_epochs = 20) # save without unloading: this leaves behind a temporary working directory model_file <- tempfile("iris_umap") model <- save_uwot(model, file = model_file) # The model can continue to be used test_embedding <- umap_transform(iris_test, model) # To manually unload the model from memory when finished and to clean up # the working directory (this doesn't touch your model file) unload_uwot(model) # At this point, model cannot be used with umap_transform, this would fail: # test_embedding2 <- umap_transform(iris_test, model) # restore the model: this also creates a temporary working directory model2 <- load_uwot(file = model_file) test_embedding2 <- umap_transform(iris_test, model2) # Unload and clean up the loaded model temp directory unload_uwot(model2) # clean up the model file unlink(model_file) # save with unloading: this deletes the temporary working directory but # doesn't allow the model to be re-used model3 <- umap(iris_train, ret_model = TRUE, n_epochs = 20) model_file3 <- tempfile("iris_umap") model3 <- save_uwot(model3, file = model_file3, unload = TRUE)
Carry out dimensionality reduction of a dataset using a method similar to LargeVis (Tang et al., 2016).
lvish( X, perplexity = 50, n_neighbors = perplexity * 3, n_components = 2, metric = "euclidean", n_epochs = -1, learning_rate = 1, scale = "maxabs", init = "lvrandom", init_sdev = NULL, repulsion_strength = 7, negative_sample_rate = 5, nn_method = NULL, n_trees = 50, search_k = 2 * n_neighbors * n_trees, n_threads = NULL, n_sgd_threads = 0, grain_size = 1, kernel = "gauss", pca = NULL, pca_center = TRUE, pcg_rand = TRUE, fast_sgd = FALSE, ret_nn = FALSE, ret_extra = c(), tmpdir = tempdir(), verbose = getOption("verbose", TRUE), batch = FALSE, opt_args = NULL, epoch_callback = NULL, pca_method = NULL, binary_edge_weights = FALSE, nn_args = list() )
lvish( X, perplexity = 50, n_neighbors = perplexity * 3, n_components = 2, metric = "euclidean", n_epochs = -1, learning_rate = 1, scale = "maxabs", init = "lvrandom", init_sdev = NULL, repulsion_strength = 7, negative_sample_rate = 5, nn_method = NULL, n_trees = 50, search_k = 2 * n_neighbors * n_trees, n_threads = NULL, n_sgd_threads = 0, grain_size = 1, kernel = "gauss", pca = NULL, pca_center = TRUE, pcg_rand = TRUE, fast_sgd = FALSE, ret_nn = FALSE, ret_extra = c(), tmpdir = tempdir(), verbose = getOption("verbose", TRUE), batch = FALSE, opt_args = NULL, epoch_callback = NULL, pca_method = NULL, binary_edge_weights = FALSE, nn_args = list() )
X |
Input data. Can be a |
perplexity |
Controls the size of the local neighborhood used for
manifold approximation. This is the analogous to |
n_neighbors |
The number of neighbors to use when calculating the
|
n_components |
The dimension of the space to embed into. This defaults
to |
metric |
Type of distance metric to use to find nearest neighbors. For
For
If rnndescent is
installed and
For more details see the package documentation of If Each metric calculation results in a separate fuzzy simplicial set, which are intersected together to produce the final set. Metric names can be repeated. Because non-numeric columns are removed from the data frame, it is safer to use column names than integer ids. Factor columns can also be used by specifying the metric name
For a given data block, you may override the |
n_epochs |
Number of epochs to use during the optimization of the
embedded coordinates. The default is calculate the number of epochs
dynamically based on dataset size, to give the same number of edge samples
as the LargeVis defaults. This is usually substantially larger than the
UMAP defaults. If |
learning_rate |
Initial learning rate used in optimization of the coordinates. |
scale |
Scaling to apply to
For lvish, the default is |
init |
Type of initialization for the coordinates. Options are:
For spectral initializations, ( |
init_sdev |
If non- |
repulsion_strength |
Weighting applied to negative samples in low dimensional embedding optimization. Values higher than one will result in greater weight being given to negative samples. |
negative_sample_rate |
The number of negative edge/1-simplex samples to use per positive edge/1-simplex sample in optimizing the low dimensional embedding. |
nn_method |
Method for finding nearest neighbors. Options are:
By default, if
Multiple nearest neighbor data (e.g. from two different precomputed
metrics) can be passed by passing a list containing the nearest neighbor
data lists as items.
The |
n_trees |
Number of trees to build when constructing the nearest
neighbor index. The more trees specified, the larger the index, but the
better the results. With |
search_k |
Number of nodes to search during the neighbor retrieval. The
larger k, the more the accurate results, but the longer the search takes.
With |
n_threads |
Number of threads to use (except during stochastic gradient
descent). Default is half the number of concurrent threads supported by the
system. For nearest neighbor search, only applies if
|
n_sgd_threads |
Number of threads to use during stochastic gradient
descent. If set to > 1, then be aware that if |
grain_size |
The minimum amount of work to do on each thread. If this
value is set high enough, then less than |
kernel |
Type of kernel function to create input probabilities. Can be
one of |
pca |
If set to a positive integer value, reduce data to this number of
columns using PCA. Doesn't applied if the distance |
pca_center |
If |
pcg_rand |
If |
fast_sgd |
If |
ret_nn |
If |
ret_extra |
A vector indicating what extra data to return. May contain any combination of the following strings:
|
tmpdir |
Temporary directory to store nearest neighbor indexes during
nearest neighbor search. Default is |
verbose |
If |
batch |
If |
opt_args |
A list of optimizer parameters, used when
|
epoch_callback |
A function which will be invoked at the end of every
epoch. Its signature should be:
|
pca_method |
Method to carry out any PCA dimensionality reduction when
the
|
binary_edge_weights |
If |
nn_args |
A list containing additional arguments to pass to the nearest
neighbor method. For
For
|
lvish
differs from the official LargeVis implementation in the
following:
Only the nearest-neighbor index search phase is multi-threaded.
Matrix input data is not normalized.
The n_trees
parameter cannot be dynamically chosen based on
data set size.
Nearest neighbor results are not refined via the
neighbor-of-my-neighbor method. The search_k
parameter is twice
as large than default to compensate.
Gradient values are clipped to 4.0
rather than 5.0
.
Negative edges are generated by uniform sampling of vertexes rather than their degree ^ 0.75.
The default number of samples is much reduced. The default number of
epochs, n_epochs
, is set to 5000
, much larger than for
umap
, but may need to be increased further depending on your
dataset. Using init = "spectral"
can help.
A matrix of optimized coordinates, or:
if ret_nn = TRUE
(or ret_extra
contains "nn"
),
returns the nearest neighbor data as a list called nn
. This
contains one list for each metric
calculated, itself containing a
matrix idx
with the integer ids of the neighbors; and a matrix
dist
with the distances. The nn
list (or a sub-list) can be
used as input to the nn_method
parameter.
if ret_extra
contains "P"
, returns the high
dimensional probability matrix as a sparse matrix called P
, of
type dgCMatrix-class.
if ret_extra
contains "sigma"
, returns a vector of
the high dimensional gaussian bandwidths for each point, and
"dint"
a vector of estimates of the intrinsic dimensionality at
each point, based on the method given by Lee and co-workers (2015).
The returned list contains the combined data from any combination of
specifying ret_nn
and ret_extra
.
Belkin, M., & Niyogi, P. (2002). Laplacian eigenmaps and spectral techniques for embedding and clustering. In Advances in neural information processing systems (pp. 585-591). http://papers.nips.cc/paper/1961-laplacian-eigenmaps-and-spectral-techniques-for-embedding-and-clustering.pdf
Böhm, J. N., Berens, P., & Kobak, D. (2020). A unifying perspective on neighbor embeddings along the attraction-repulsion spectrum. arXiv preprint arXiv:2007.08902. https://arxiv.org/abs/2007.08902
Damrich, S., & Hamprecht, F. A. (2021). On UMAP's true loss function. Advances in Neural Information Processing Systems, 34. https://proceedings.neurips.cc/paper/2021/hash/2de5d16682c3c35007e4e92982f1a2ba-Abstract.html
Dong, W., Moses, C., & Li, K. (2011, March). Efficient k-nearest neighbor graph construction for generic similarity measures. In Proceedings of the 20th international conference on World Wide Web (pp. 577-586). ACM. doi:10.1145/1963405.1963487.
Kingma, D. P., & Ba, J. (2014). Adam: A method for stochastic optimization. arXiv preprint arXiv:1412.6980. https://arxiv.org/abs/1412.6980
Lee, J. A., Peluffo-Ordóñez, D. H., & Verleysen, M. (2015). Multi-scale similarities in stochastic neighbour embedding: Reducing dimensionality while preserving both local and global structure. Neurocomputing, 169, 246-261.
Malkov, Y. A., & Yashunin, D. A. (2018). Efficient and robust approximate nearest neighbor search using hierarchical navigable small world graphs. IEEE transactions on pattern analysis and machine intelligence, 42(4), 824-836.
McInnes, L., Healy, J., & Melville, J. (2018). UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction arXiv preprint arXiv:1802.03426. https://arxiv.org/abs/1802.03426
O’Neill, M. E. (2014). PCG: A family of simple fast space-efficient statistically good algorithms for random number generation (Report No. HMC-CS-2014-0905). Harvey Mudd College.
Tang, J., Liu, J., Zhang, M., & Mei, Q. (2016, April). Visualizing large-scale and high-dimensional data. In Proceedings of the 25th International Conference on World Wide Web (pp. 287-297). International World Wide Web Conferences Steering Committee. https://arxiv.org/abs/1602.00370
Van der Maaten, L., & Hinton, G. (2008). Visualizing data using t-SNE. Journal of Machine Learning Research, 9 (2579-2605). https://www.jmlr.org/papers/v9/vandermaaten08a.html
Wang, Y., Huang, H., Rudin, C., & Shaposhnik, Y. (2021). Understanding How Dimension Reduction Tools Work: An Empirical Approach to Deciphering t-SNE, UMAP, TriMap, and PaCMAP for Data Visualization. Journal of Machine Learning Research, 22(201), 1-73. https://www.jmlr.org/papers/v22/20-1061.html
# Default number of epochs is much larger than for UMAP, assumes random # initialization. Use perplexity rather than n_neighbors to control the size # of the local neighborhood 20 epochs may be too small for a random # initialization iris_lvish <- lvish(iris, perplexity = 50, learning_rate = 0.5, init = "random", n_epochs = 20 )
# Default number of epochs is much larger than for UMAP, assumes random # initialization. Use perplexity rather than n_neighbors to control the size # of the local neighborhood 20 epochs may be too small for a random # initialization iris_lvish <- lvish(iris, perplexity = 50, learning_rate = 0.5, init = "random", n_epochs = 20 )
Carry out dimensionality reduction on an input graph, where the distances in
the low dimensional space attempt to reproduce the neighbor relations in the
input data. By default, the cost function used to optimize the output
coordinates use the Uniform Manifold Approximation and Projection (UMAP)
method (McInnes et al., 2018), but the approach from LargeVis (Tang et al.,
2016) can also be used. This function can be used to produce a low
dimensional representation of the graph produced by
similarity_graph
.
optimize_graph_layout( graph, X = NULL, n_components = 2, n_epochs = NULL, learning_rate = 1, init = "spectral", init_sdev = NULL, spread = 1, min_dist = 0.01, repulsion_strength = 1, negative_sample_rate = 5, a = NULL, b = NULL, method = "umap", approx_pow = FALSE, pcg_rand = TRUE, fast_sgd = FALSE, n_sgd_threads = 0, grain_size = 1, verbose = getOption("verbose", TRUE), batch = FALSE, opt_args = NULL, epoch_callback = NULL, pca_method = NULL, binary_edge_weights = FALSE )
optimize_graph_layout( graph, X = NULL, n_components = 2, n_epochs = NULL, learning_rate = 1, init = "spectral", init_sdev = NULL, spread = 1, min_dist = 0.01, repulsion_strength = 1, negative_sample_rate = 5, a = NULL, b = NULL, method = "umap", approx_pow = FALSE, pcg_rand = TRUE, fast_sgd = FALSE, n_sgd_threads = 0, grain_size = 1, verbose = getOption("verbose", TRUE), batch = FALSE, opt_args = NULL, epoch_callback = NULL, pca_method = NULL, binary_edge_weights = FALSE )
graph |
A sparse, symmetric N x N weighted adjacency matrix representing a graph. Non-zero entries indicate an edge between two nodes with a given edge weight. There can be a varying number of non-zero entries in each row/column. |
X |
Optional input data. Used only for PCA-based initialization. |
n_components |
The dimension of the space to embed into. This defaults
to |
n_epochs |
Number of epochs to use during the optimization of the
embedded coordinates. By default, this value is set to |
learning_rate |
Initial learning rate used in optimization of the coordinates. |
init |
Type of initialization for the coordinates. Options are:
For spectral initializations, ( |
init_sdev |
If non- |
spread |
The effective scale of embedded points. In combination with
|
min_dist |
The effective minimum distance between embedded points.
Smaller values will result in a more clustered/clumped embedding where
nearby points on the manifold are drawn closer together, while larger
values will result on a more even dispersal of points. The value should be
set relative to the |
repulsion_strength |
Weighting applied to negative samples in low dimensional embedding optimization. Values higher than one will result in greater weight being given to negative samples. |
negative_sample_rate |
The number of negative edge/1-simplex samples to use per positive edge/1-simplex sample in optimizing the low dimensional embedding. |
a |
More specific parameters controlling the embedding. If |
b |
More specific parameters controlling the embedding. If |
method |
Cost function to optimize. One of:
|
approx_pow |
If |
pcg_rand |
If |
fast_sgd |
If |
n_sgd_threads |
Number of threads to use during stochastic gradient
descent. If set to > 1, then be aware that if |
grain_size |
The minimum amount of work to do on each thread. If this
value is set high enough, then less than |
verbose |
If |
batch |
If |
opt_args |
A list of optimizer parameters, used when
|
epoch_callback |
A function which will be invoked at the end of every
epoch. Its signature should be:
|
pca_method |
Method to carry out any PCA dimensionality reduction when
the
|
binary_edge_weights |
If |
A matrix of optimized coordinates.
Kingma, D. P., & Ba, J. (2014). Adam: A method for stochastic optimization. arXiv preprint arXiv:1412.6980. https://arxiv.org/abs/1412.6980
McInnes, L., Healy, J., & Melville, J. (2018). UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction arXiv preprint arXiv:1802.03426. https://arxiv.org/abs/1802.03426
O’Neill, M. E. (2014). PCG: A family of simple fast space-efficient statistically good algorithms for random number generation (Report No. HMC-CS-2014-0905). Harvey Mudd College.
Tang, J., Liu, J., Zhang, M., & Mei, Q. (2016, April). Visualizing large-scale and high-dimensional data. In Proceedings of the 25th International Conference on World Wide Web (pp. 287-297). International World Wide Web Conferences Steering Committee. https://arxiv.org/abs/1602.00370
iris30 <- iris[c(1:10, 51:60, 101:110), ] # return a 30 x 30 sparse matrix with similarity data based on 10 nearest # neighbors per item iris30_sim_graph <- similarity_graph(iris30, n_neighbors = 10) # produce 2D coordinates replicating the neighbor relations in the similarity # graph set.seed(42) iris30_opt <- optimize_graph_layout(iris30_sim_graph, X = iris30) # the above two steps are the same as: # set.seed(42); iris_umap <- umap(iris30, n_neighbors = 10)
iris30 <- iris[c(1:10, 51:60, 101:110), ] # return a 30 x 30 sparse matrix with similarity data based on 10 nearest # neighbors per item iris30_sim_graph <- similarity_graph(iris30, n_neighbors = 10) # produce 2D coordinates replicating the neighbor relations in the similarity # graph set.seed(42) iris30_opt <- optimize_graph_layout(iris30_sim_graph, X = iris30) # the above two steps are the same as: # set.seed(42); iris_umap <- umap(iris30, n_neighbors = 10)
Functions to write a UMAP model to a file, and to restore.
save_uwot(model, file, unload = FALSE, verbose = FALSE)
save_uwot(model, file, unload = FALSE, verbose = FALSE)
model |
a UMAP model create by |
file |
name of the file where the model is to be saved or read from. |
unload |
if |
verbose |
if |
model
with one extra item: mod_dir
, which contains the
path to the working directory. If unload = FALSE
then this directory
still exists after this function returns, and can be cleaned up with
unload_uwot
. If you don't care about cleaning up this
directory, or unload = TRUE
, then you can ignore the return value.
iris_train <- iris[c(1:10, 51:60), ] iris_test <- iris[100:110, ] # create model model <- umap(iris_train, ret_model = TRUE, n_epochs = 20) # save without unloading: this leaves behind a temporary working directory model_file <- tempfile("iris_umap") model <- save_uwot(model, file = model_file) # The model can continue to be used test_embedding <- umap_transform(iris_test, model) # To manually unload the model from memory when finished and to clean up # the working directory (this doesn't touch your model file) unload_uwot(model) # At this point, model cannot be used with umap_transform, this would fail: # test_embedding2 <- umap_transform(iris_test, model) # restore the model: this also creates a temporary working directory model2 <- load_uwot(file = model_file) test_embedding2 <- umap_transform(iris_test, model2) # Unload and clean up the loaded model temp directory unload_uwot(model2) # clean up the model file unlink(model_file) # save with unloading: this deletes the temporary working directory but # doesn't allow the model to be re-used model3 <- umap(iris_train, ret_model = TRUE, n_epochs = 20) model_file3 <- tempfile("iris_umap") model3 <- save_uwot(model3, file = model_file3, unload = TRUE)
iris_train <- iris[c(1:10, 51:60), ] iris_test <- iris[100:110, ] # create model model <- umap(iris_train, ret_model = TRUE, n_epochs = 20) # save without unloading: this leaves behind a temporary working directory model_file <- tempfile("iris_umap") model <- save_uwot(model, file = model_file) # The model can continue to be used test_embedding <- umap_transform(iris_test, model) # To manually unload the model from memory when finished and to clean up # the working directory (this doesn't touch your model file) unload_uwot(model) # At this point, model cannot be used with umap_transform, this would fail: # test_embedding2 <- umap_transform(iris_test, model) # restore the model: this also creates a temporary working directory model2 <- load_uwot(file = model_file) test_embedding2 <- umap_transform(iris_test, model2) # Unload and clean up the loaded model temp directory unload_uwot(model2) # clean up the model file unlink(model_file) # save with unloading: this deletes the temporary working directory but # doesn't allow the model to be re-used model3 <- umap(iris_train, ret_model = TRUE, n_epochs = 20) model_file3 <- tempfile("iris_umap") model3 <- save_uwot(model3, file = model_file3, unload = TRUE)
Create a graph (as a sparse symmetric weighted adjacency matrix) representing the similarities between items in a data set. No dimensionality reduction is carried out. By default, the similarities are calculated using the merged fuzzy simplicial set approach in the Uniform Manifold Approximation and Projection (UMAP) method (McInnes et al., 2018), but the approach from LargeVis (Tang et al., 2016) can also be used.
similarity_graph( X = NULL, n_neighbors = NULL, metric = "euclidean", scale = NULL, set_op_mix_ratio = 1, local_connectivity = 1, nn_method = NULL, n_trees = 50, search_k = 2 * n_neighbors * n_trees, perplexity = 50, method = "umap", y = NULL, target_n_neighbors = n_neighbors, target_metric = "euclidean", target_weight = 0.5, pca = NULL, pca_center = TRUE, ret_extra = c(), n_threads = NULL, grain_size = 1, kernel = "gauss", tmpdir = tempdir(), verbose = getOption("verbose", TRUE), pca_method = NULL, binary_edge_weights = FALSE, nn_args = list() )
similarity_graph( X = NULL, n_neighbors = NULL, metric = "euclidean", scale = NULL, set_op_mix_ratio = 1, local_connectivity = 1, nn_method = NULL, n_trees = 50, search_k = 2 * n_neighbors * n_trees, perplexity = 50, method = "umap", y = NULL, target_n_neighbors = n_neighbors, target_metric = "euclidean", target_weight = 0.5, pca = NULL, pca_center = TRUE, ret_extra = c(), n_threads = NULL, grain_size = 1, kernel = "gauss", tmpdir = tempdir(), verbose = getOption("verbose", TRUE), pca_method = NULL, binary_edge_weights = FALSE, nn_args = list() )
X |
Input data. Can be a |
n_neighbors |
The size of local neighborhood (in terms of number of
neighboring sample points) used for manifold approximation. Larger values
result in more global views of the manifold, while smaller values result in
more local data being preserved. In general values should be in the range
|
metric |
Type of distance metric to use to find nearest neighbors. For
For
If rnndescent is
installed and
For more details see the package documentation of If Each metric calculation results in a separate fuzzy simplicial set, which are intersected together to produce the final set. Metric names can be repeated. Because non-numeric columns are removed from the data frame, it is safer to use column names than integer ids. Factor columns can also be used by specifying the metric name
For a given data block, you may override the |
scale |
Scaling to apply to
For |
set_op_mix_ratio |
Interpolate between (fuzzy) union and intersection as
the set operation used to combine local fuzzy simplicial sets to obtain a
global fuzzy simplicial sets. Both fuzzy set operations use the product
t-norm. The value of this parameter should be between |
local_connectivity |
The local connectivity required – i.e. the number
of nearest neighbors that should be assumed to be connected at a local
level. The higher this value the more connected the manifold becomes
locally. In practice this should be not more than the local intrinsic
dimension of the manifold. Ignored if |
nn_method |
Method for finding nearest neighbors. Options are:
By default, if
or a sparse distance matrix of type |
n_trees |
Number of trees to build when constructing the nearest
neighbor index. The more trees specified, the larger the index, but the
better the results. With |
search_k |
Number of nodes to search during the neighbor retrieval. The
larger k, the more the accurate results, but the longer the search takes.
With |
perplexity |
Used only if |
method |
How to generate the similarities between items. One of:
|
y |
Optional target data to add supervised or semi-supervised weighting
to the similarity graph . Can be a vector, matrix or data frame. Use the
Unlike |
target_n_neighbors |
Number of nearest neighbors to use to construct the
target simplicial set. Default value is |
target_metric |
The metric used to measure distance for |
target_weight |
Weighting factor between data topology and target
topology. A value of 0.0 weights entirely on data, a value of 1.0 weights
entirely on target. The default of 0.5 balances the weighting equally
between data and target. Only applies if |
pca |
If set to a positive integer value, reduce data to this number of
columns using PCA. Doesn't applied if the distance |
pca_center |
If |
ret_extra |
A vector indicating what extra data to return. May contain any combination of the following strings:
|
n_threads |
Number of threads to use. Default is half the number of
concurrent threads supported by the system. For nearest neighbor search,
only applies if |
grain_size |
The minimum amount of work to do on each thread. If this
value is set high enough, then less than |
kernel |
Used only if |
tmpdir |
Temporary directory to store nearest neighbor indexes during
nearest neighbor search. Default is |
verbose |
If |
pca_method |
Method to carry out any PCA dimensionality reduction when
the
|
binary_edge_weights |
If |
nn_args |
A list containing additional arguments to pass to the nearest
neighbor method. For
For
|
This is equivalent to running umap
with the
ret_extra = c("fgraph")
parameter, but without the overhead of
calculating (or returning) the optimized low-dimensional coordinates.
A sparse symmetrized matrix of the similarities between the items in
X
or if nn_method
contains pre-computed nearest neighbor
data, the items in nn_method
. Because of the symmetrization, there
may be more non-zero items in each column than the specified value of
n_neighbors
(or pre-computed neighbors in nn_method
).
If ret_extra
is specified then the return value will be a list
containing:
similarity_graph
the similarity graph as a sparse matrix
as described above.
nn
(if ret_extra
contained "nn"
) the nearest
neighbor data as a list called nn
. This contains one list for each
metric
calculated, itself containing a matrix idx
with the
integer ids of the neighbors; and a matrix dist
with the
distances. The nn
list (or a sub-list) can be used as input to the
nn_method
parameter.
sigma
(if ret_extra
contains "sigma"
),
a vector of calibrated parameters, one for each item in the input data,
reflecting the local data density for that item. The exact definition of
the values depends on the choice of the method
parameter.
rho
(if ret_extra
contains "sigma"
), a
vector containing the largest distance to the locally connected neighbors
of each item in the input data. This will exist only if
method = "umap"
.
localr
(if ret_extra
contains "localr"
) a
vector of the estimated local radii, the sum of "sigma"
and
"rho"
. This will exist only if method = "umap"
.
Dong, W., Moses, C., & Li, K. (2011, March). Efficient k-nearest neighbor graph construction for generic similarity measures. In Proceedings of the 20th international conference on World Wide Web (pp. 577-586). ACM. doi:10.1145/1963405.1963487.
Malkov, Y. A., & Yashunin, D. A. (2018). Efficient and robust approximate nearest neighbor search using hierarchical navigable small world graphs. IEEE transactions on pattern analysis and machine intelligence, 42(4), 824-836.
McInnes, L., Healy, J., & Melville, J. (2018). UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction arXiv preprint arXiv:1802.03426. https://arxiv.org/abs/1802.03426
Tang, J., Liu, J., Zhang, M., & Mei, Q. (2016, April). Visualizing large-scale and high-dimensional data. In Proceedings of the 25th International Conference on World Wide Web (pp. 287-297). International World Wide Web Conferences Steering Committee. https://arxiv.org/abs/1602.00370
iris30 <- iris[c(1:10, 51:60, 101:110), ] # return a 30 x 30 sparse matrix with similarity data based on 10 nearest # neighbors per item iris30_sim_graph <- similarity_graph(iris30, n_neighbors = 10) # Default is to use the UMAP method of calculating similarities, but LargeVis # is also available: for that method, use perplexity instead of n_neighbors # to control neighborhood size. Use ret_extra = "nn" to return nearest # neighbor data as well as the similarity graph. Return value is a list # containing similarity_graph' and 'nn' items. iris30_lv_graph <- similarity_graph(iris30, perplexity = 10, method = "largevis", ret_extra = "nn" ) # If you have the neighbor information you don't need the original data iris30_lv_graph_nn <- similarity_graph( nn_method = iris30_lv_graph$nn, perplexity = 10, method = "largevis" ) all(iris30_lv_graph_nn == iris30_lv_graph$similarity_graph)
iris30 <- iris[c(1:10, 51:60, 101:110), ] # return a 30 x 30 sparse matrix with similarity data based on 10 nearest # neighbors per item iris30_sim_graph <- similarity_graph(iris30, n_neighbors = 10) # Default is to use the UMAP method of calculating similarities, but LargeVis # is also available: for that method, use perplexity instead of n_neighbors # to control neighborhood size. Use ret_extra = "nn" to return nearest # neighbor data as well as the similarity graph. Return value is a list # containing similarity_graph' and 'nn' items. iris30_lv_graph <- similarity_graph(iris30, perplexity = 10, method = "largevis", ret_extra = "nn" ) # If you have the neighbor information you don't need the original data iris30_lv_graph_nn <- similarity_graph( nn_method = iris30_lv_graph$nn, perplexity = 10, method = "largevis" ) all(iris30_lv_graph_nn == iris30_lv_graph$similarity_graph)
Combine two similarity graphs by treating them as fuzzy topological sets and forming the intersection.
simplicial_set_intersect(x, y, weight = 0.5, n_threads = NULL, verbose = FALSE)
simplicial_set_intersect(x, y, weight = 0.5, n_threads = NULL, verbose = FALSE)
x |
A sparse matrix representing the first similarity graph in the intersection operation. |
y |
A sparse matrix representing the second similarity graph in the intersection operation. |
weight |
A value between |
n_threads |
Number of threads to use when resetting the local metric. Default is half the number of concurrent threads supported by the system. |
verbose |
If |
A sparse matrix containing the intersection of x
and
y
.
# Form two different "views" of the same data iris30 <- iris[c(1:10, 51:60, 101:110), ] iris_sg12 <- similarity_graph(iris30[, 1:2], n_neighbors = 5) iris_sg34 <- similarity_graph(iris30[, 3:4], n_neighbors = 5) # Combine the two representations into one iris_combined <- simplicial_set_intersect(iris_sg12, iris_sg34) # Optimize the layout based on the combined view iris_combined_umap <- optimize_graph_layout(iris_combined, n_epochs = 100)
# Form two different "views" of the same data iris30 <- iris[c(1:10, 51:60, 101:110), ] iris_sg12 <- similarity_graph(iris30[, 1:2], n_neighbors = 5) iris_sg34 <- similarity_graph(iris30[, 3:4], n_neighbors = 5) # Combine the two representations into one iris_combined <- simplicial_set_intersect(iris_sg12, iris_sg34) # Optimize the layout based on the combined view iris_combined_umap <- optimize_graph_layout(iris_combined, n_epochs = 100)
Combine two similarity graphs by treating them as fuzzy topological sets and forming the union.
simplicial_set_union(x, y, n_threads = NULL, verbose = FALSE)
simplicial_set_union(x, y, n_threads = NULL, verbose = FALSE)
x |
A sparse matrix representing the first similarity graph in the union operation. |
y |
A sparse matrix representing the second similarity graph in the union operation. |
n_threads |
Number of threads to use when resetting the local metric. Default is half the number of concurrent threads supported by the system. |
verbose |
If |
A sparse matrix containing the union of x
and y
.
# Form two different "views" of the same data iris30 <- iris[c(1:10, 51:60, 101:110), ] iris_sg12 <- similarity_graph(iris30[, 1:2], n_neighbors = 5) iris_sg34 <- similarity_graph(iris30[, 3:4], n_neighbors = 5) # Combine the two representations into one iris_combined <- simplicial_set_union(iris_sg12, iris_sg34) # Optimize the layout based on the combined view iris_combined_umap <- optimize_graph_layout(iris_combined, n_epochs = 100)
# Form two different "views" of the same data iris30 <- iris[c(1:10, 51:60, 101:110), ] iris_sg12 <- similarity_graph(iris30[, 1:2], n_neighbors = 5) iris_sg34 <- similarity_graph(iris30[, 3:4], n_neighbors = 5) # Combine the two representations into one iris_combined <- simplicial_set_union(iris_sg12, iris_sg34) # Optimize the layout based on the combined view iris_combined_umap <- optimize_graph_layout(iris_combined, n_epochs = 100)
A faster (but less flexible) version of the UMAP (McInnes et al, 2018)
gradient. For more detail on UMAP, see the umap
function.
tumap( X, n_neighbors = 15, n_components = 2, metric = "euclidean", n_epochs = NULL, learning_rate = 1, scale = FALSE, init = "spectral", init_sdev = NULL, set_op_mix_ratio = 1, local_connectivity = 1, bandwidth = 1, repulsion_strength = 1, negative_sample_rate = 5, nn_method = NULL, n_trees = 50, search_k = 2 * n_neighbors * n_trees, n_threads = NULL, n_sgd_threads = 0, grain_size = 1, y = NULL, target_n_neighbors = n_neighbors, target_metric = "euclidean", target_weight = 0.5, pca = NULL, pca_center = TRUE, pcg_rand = TRUE, fast_sgd = FALSE, ret_model = FALSE, ret_nn = FALSE, ret_extra = c(), tmpdir = tempdir(), verbose = getOption("verbose", TRUE), batch = FALSE, opt_args = NULL, epoch_callback = NULL, pca_method = NULL, binary_edge_weights = FALSE, seed = NULL, nn_args = list() )
tumap( X, n_neighbors = 15, n_components = 2, metric = "euclidean", n_epochs = NULL, learning_rate = 1, scale = FALSE, init = "spectral", init_sdev = NULL, set_op_mix_ratio = 1, local_connectivity = 1, bandwidth = 1, repulsion_strength = 1, negative_sample_rate = 5, nn_method = NULL, n_trees = 50, search_k = 2 * n_neighbors * n_trees, n_threads = NULL, n_sgd_threads = 0, grain_size = 1, y = NULL, target_n_neighbors = n_neighbors, target_metric = "euclidean", target_weight = 0.5, pca = NULL, pca_center = TRUE, pcg_rand = TRUE, fast_sgd = FALSE, ret_model = FALSE, ret_nn = FALSE, ret_extra = c(), tmpdir = tempdir(), verbose = getOption("verbose", TRUE), batch = FALSE, opt_args = NULL, epoch_callback = NULL, pca_method = NULL, binary_edge_weights = FALSE, seed = NULL, nn_args = list() )
X |
Input data. Can be a |
n_neighbors |
The size of local neighborhood (in terms of number of
neighboring sample points) used for manifold approximation. Larger values
result in more global views of the manifold, while smaller values result in
more local data being preserved. In general values should be in the range
|
n_components |
The dimension of the space to embed into. This defaults
to |
metric |
Type of distance metric to use to find nearest neighbors. For
For
If rnndescent is
installed and
For more details see the package documentation of If Each metric calculation results in a separate fuzzy simplicial set, which are intersected together to produce the final set. Metric names can be repeated. Because non-numeric columns are removed from the data frame, it is safer to use column names than integer ids. Factor columns can also be used by specifying the metric name
For a given data block, you may override the |
n_epochs |
Number of epochs to use during the optimization of the
embedded coordinates. By default, this value is set to |
learning_rate |
Initial learning rate used in optimization of the coordinates. |
scale |
Scaling to apply to
For t-UMAP, the default is |
init |
Type of initialization for the coordinates. Options are:
For spectral initializations, ( |
init_sdev |
If non- |
set_op_mix_ratio |
Interpolate between (fuzzy) union and intersection as
the set operation used to combine local fuzzy simplicial sets to obtain a
global fuzzy simplicial sets. Both fuzzy set operations use the product
t-norm. The value of this parameter should be between |
local_connectivity |
The local connectivity required – i.e. the number of nearest neighbors that should be assumed to be connected at a local level. The higher this value the more connected the manifold becomes locally. In practice this should be not more than the local intrinsic dimension of the manifold. |
bandwidth |
The effective bandwidth of the kernel if we view the algorithm as similar to Laplacian Eigenmaps. Larger values induce more connectivity and a more global view of the data, smaller values concentrate more locally. |
repulsion_strength |
Weighting applied to negative samples in low dimensional embedding optimization. Values higher than one will result in greater weight being given to negative samples. |
negative_sample_rate |
The number of negative edge/1-simplex samples to use per positive edge/1-simplex sample in optimizing the low dimensional embedding. |
nn_method |
Method for finding nearest neighbors. Options are:
By default, if
or a sparse distance matrix of type |
n_trees |
Number of trees to build when constructing the nearest
neighbor index. The more trees specified, the larger the index, but the
better the results. With |
search_k |
Number of nodes to search during the neighbor retrieval. The
larger k, the more the accurate results, but the longer the search takes.
With |
n_threads |
Number of threads to use (except during stochastic gradient
descent). Default is half the number of concurrent threads supported by the
system. For nearest neighbor search, only applies if
|
n_sgd_threads |
Number of threads to use during stochastic gradient
descent. If set to > 1, then be aware that if |
grain_size |
The minimum amount of work to do on each thread. If this
value is set high enough, then less than |
y |
Optional target data for supervised dimension reduction. Can be a
vector, matrix or data frame. Use the
Unlike |
target_n_neighbors |
Number of nearest neighbors to use to construct the
target simplicial set. Default value is |
target_metric |
The metric used to measure distance for |
target_weight |
Weighting factor between data topology and target
topology. A value of 0.0 weights entirely on data, a value of 1.0 weights
entirely on target. The default of 0.5 balances the weighting equally
between data and target. Only applies if |
pca |
If set to a positive integer value, reduce data to this number of
columns using PCA. Doesn't applied if the distance |
pca_center |
If |
pcg_rand |
If |
fast_sgd |
If |
ret_model |
If |
ret_nn |
If |
ret_extra |
A vector indicating what extra data to return. May contain any combination of the following strings:
|
tmpdir |
Temporary directory to store nearest neighbor indexes during
nearest neighbor search. Default is |
verbose |
If |
batch |
If |
opt_args |
A list of optimizer parameters, used when
|
epoch_callback |
A function which will be invoked at the end of every
epoch. Its signature should be:
|
pca_method |
Method to carry out any PCA dimensionality reduction when
the
|
binary_edge_weights |
If |
seed |
Integer seed to use to initialize the random number generator
state. Combined with |
nn_args |
A list containing additional arguments to pass to the nearest
neighbor method. For
For
For
|
By setting the UMAP curve parameters a
and b
to 1
, you
get back the Cauchy distribution as used in t-SNE (van der Maaten and Hinton,
2008) and LargeVis (Tang et al., 2016). It also results in a substantially
simplified gradient expression. This can give a speed improvement of around
50%.
A matrix of optimized coordinates, or:
if ret_model = TRUE
(or ret_extra
contains
"model"
), returns a list containing extra information that can be
used to add new data to an existing embedding via
umap_transform
. In this case, the coordinates are available
in the list item embedding
. NOTE: The contents of
the model
list should not be considered stable or part of
the public API, and are purposely left undocumented.
if ret_nn = TRUE
(or ret_extra
contains "nn"
),
returns the nearest neighbor data as a list called nn
. This
contains one list for each metric
calculated, itself containing a
matrix idx
with the integer ids of the neighbors; and a matrix
dist
with the distances. The nn
list (or a sub-list) can be
used as input to the nn_method
parameter.
if ret_extra
contains "fgraph"
returns the high
dimensional fuzzy graph as a sparse matrix called fgraph
, of type
dgCMatrix-class.
if ret_extra
contains "sigma"
, returns a vector of the
smooth knn distance normalization terms for each observation as
"sigma"
and a vector "rho"
containing the largest
distance to the locally connected neighbors of each observation.
if ret_extra
contains "localr"
, returns a vector of
the estimated local radii, the sum of "sigma"
and "rho"
.
The returned list contains the combined data from any combination of
specifying ret_model
, ret_nn
and ret_extra
.
Belkin, M., & Niyogi, P. (2002). Laplacian eigenmaps and spectral techniques for embedding and clustering. In Advances in neural information processing systems (pp. 585-591). http://papers.nips.cc/paper/1961-laplacian-eigenmaps-and-spectral-techniques-for-embedding-and-clustering.pdf
Böhm, J. N., Berens, P., & Kobak, D. (2020). A unifying perspective on neighbor embeddings along the attraction-repulsion spectrum. arXiv preprint arXiv:2007.08902. https://arxiv.org/abs/2007.08902
Damrich, S., & Hamprecht, F. A. (2021). On UMAP's true loss function. Advances in Neural Information Processing Systems, 34. https://proceedings.neurips.cc/paper/2021/hash/2de5d16682c3c35007e4e92982f1a2ba-Abstract.html
Dong, W., Moses, C., & Li, K. (2011, March). Efficient k-nearest neighbor graph construction for generic similarity measures. In Proceedings of the 20th international conference on World Wide Web (pp. 577-586). ACM. doi:10.1145/1963405.1963487.
Kingma, D. P., & Ba, J. (2014). Adam: A method for stochastic optimization. arXiv preprint arXiv:1412.6980. https://arxiv.org/abs/1412.6980
Malkov, Y. A., & Yashunin, D. A. (2018). Efficient and robust approximate nearest neighbor search using hierarchical navigable small world graphs. IEEE transactions on pattern analysis and machine intelligence, 42(4), 824-836.
McInnes, L., Healy, J., & Melville, J. (2018). UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction arXiv preprint arXiv:1802.03426. https://arxiv.org/abs/1802.03426
O’Neill, M. E. (2014). PCG: A family of simple fast space-efficient statistically good algorithms for random number generation (Report No. HMC-CS-2014-0905). Harvey Mudd College.
Tang, J., Liu, J., Zhang, M., & Mei, Q. (2016, April). Visualizing large-scale and high-dimensional data. In Proceedings of the 25th International Conference on World Wide Web (pp. 287-297). International World Wide Web Conferences Steering Committee. https://arxiv.org/abs/1602.00370
Van der Maaten, L., & Hinton, G. (2008). Visualizing data using t-SNE. Journal of Machine Learning Research, 9 (2579-2605). https://www.jmlr.org/papers/v9/vandermaaten08a.html
Wang, Y., Huang, H., Rudin, C., & Shaposhnik, Y. (2021). Understanding How Dimension Reduction Tools Work: An Empirical Approach to Deciphering t-SNE, UMAP, TriMap, and PaCMAP for Data Visualization. Journal of Machine Learning Research, 22(201), 1-73. https://www.jmlr.org/papers/v22/20-1061.html
iris_tumap <- tumap(iris, n_neighbors = 50, learning_rate = 0.5)
iris_tumap <- tumap(iris, n_neighbors = 50, learning_rate = 0.5)
Carry out dimensionality reduction of a dataset using the Uniform Manifold Approximation and Projection (UMAP) method (McInnes et al., 2018). Some of the following help text is lifted verbatim from the Python reference implementation at https://github.com/lmcinnes/umap.
umap( X, n_neighbors = 15, n_components = 2, metric = "euclidean", n_epochs = NULL, learning_rate = 1, scale = FALSE, init = "spectral", init_sdev = NULL, spread = 1, min_dist = 0.01, set_op_mix_ratio = 1, local_connectivity = 1, bandwidth = 1, repulsion_strength = 1, negative_sample_rate = 5, a = NULL, b = NULL, nn_method = NULL, n_trees = 50, search_k = 2 * n_neighbors * n_trees, approx_pow = FALSE, y = NULL, target_n_neighbors = n_neighbors, target_metric = "euclidean", target_weight = 0.5, pca = NULL, pca_center = TRUE, pcg_rand = TRUE, fast_sgd = FALSE, ret_model = FALSE, ret_nn = FALSE, ret_extra = c(), n_threads = NULL, n_sgd_threads = 0, grain_size = 1, tmpdir = tempdir(), verbose = getOption("verbose", TRUE), batch = FALSE, opt_args = NULL, epoch_callback = NULL, pca_method = NULL, binary_edge_weights = FALSE, dens_scale = NULL, seed = NULL, nn_args = list() )
umap( X, n_neighbors = 15, n_components = 2, metric = "euclidean", n_epochs = NULL, learning_rate = 1, scale = FALSE, init = "spectral", init_sdev = NULL, spread = 1, min_dist = 0.01, set_op_mix_ratio = 1, local_connectivity = 1, bandwidth = 1, repulsion_strength = 1, negative_sample_rate = 5, a = NULL, b = NULL, nn_method = NULL, n_trees = 50, search_k = 2 * n_neighbors * n_trees, approx_pow = FALSE, y = NULL, target_n_neighbors = n_neighbors, target_metric = "euclidean", target_weight = 0.5, pca = NULL, pca_center = TRUE, pcg_rand = TRUE, fast_sgd = FALSE, ret_model = FALSE, ret_nn = FALSE, ret_extra = c(), n_threads = NULL, n_sgd_threads = 0, grain_size = 1, tmpdir = tempdir(), verbose = getOption("verbose", TRUE), batch = FALSE, opt_args = NULL, epoch_callback = NULL, pca_method = NULL, binary_edge_weights = FALSE, dens_scale = NULL, seed = NULL, nn_args = list() )
X |
Input data. Can be a |
n_neighbors |
The size of local neighborhood (in terms of number of
neighboring sample points) used for manifold approximation. Larger values
result in more global views of the manifold, while smaller values result in
more local data being preserved. In general values should be in the range
|
n_components |
The dimension of the space to embed into. This defaults
to |
metric |
Type of distance metric to use to find nearest neighbors. For
For
If rnndescent is
installed and
For more details see the package documentation of If Each metric calculation results in a separate fuzzy simplicial set, which are intersected together to produce the final set. Metric names can be repeated. Because non-numeric columns are removed from the data frame, it is safer to use column names than integer ids. Factor columns can also be used by specifying the metric name
For a given data block, you may override the |
n_epochs |
Number of epochs to use during the optimization of the
embedded coordinates. By default, this value is set to |
learning_rate |
Initial learning rate used in optimization of the coordinates. |
scale |
Scaling to apply to
For UMAP, the default is |
init |
Type of initialization for the coordinates. Options are:
For spectral initializations, ( |
init_sdev |
If non- |
spread |
The effective scale of embedded points. In combination with
|
min_dist |
The effective minimum distance between embedded points.
Smaller values will result in a more clustered/clumped embedding where
nearby points on the manifold are drawn closer together, while larger
values will result on a more even dispersal of points. The value should be
set relative to the |
set_op_mix_ratio |
Interpolate between (fuzzy) union and intersection as
the set operation used to combine local fuzzy simplicial sets to obtain a
global fuzzy simplicial sets. Both fuzzy set operations use the product
t-norm. The value of this parameter should be between |
local_connectivity |
The local connectivity required – i.e. the number of nearest neighbors that should be assumed to be connected at a local level. The higher this value the more connected the manifold becomes locally. In practice this should be not more than the local intrinsic dimension of the manifold. |
bandwidth |
The effective bandwidth of the kernel if we view the algorithm as similar to Laplacian Eigenmaps. Larger values induce more connectivity and a more global view of the data, smaller values concentrate more locally. |
repulsion_strength |
Weighting applied to negative samples in low dimensional embedding optimization. Values higher than one will result in greater weight being given to negative samples. |
negative_sample_rate |
The number of negative edge/1-simplex samples to use per positive edge/1-simplex sample in optimizing the low dimensional embedding. |
a |
More specific parameters controlling the embedding. If |
b |
More specific parameters controlling the embedding. If |
nn_method |
Method for finding nearest neighbors. Options are:
By default, if
or a sparse distance matrix of type |
n_trees |
Number of trees to build when constructing the nearest
neighbor index. The more trees specified, the larger the index, but the
better the results. With |
search_k |
Number of nodes to search during the neighbor retrieval. The
larger k, the more the accurate results, but the longer the search takes.
With |
approx_pow |
If |
y |
Optional target data for supervised dimension reduction. Can be a
vector, matrix or data frame. Use the
Unlike |
target_n_neighbors |
Number of nearest neighbors to use to construct the
target simplicial set. Default value is |
target_metric |
The metric used to measure distance for |
target_weight |
Weighting factor between data topology and target
topology. A value of 0.0 weights entirely on data, a value of 1.0 weights
entirely on target. The default of 0.5 balances the weighting equally
between data and target. Only applies if |
pca |
If set to a positive integer value, reduce data to this number of
columns using PCA. Doesn't applied if the distance |
pca_center |
If |
pcg_rand |
If |
fast_sgd |
If |
ret_model |
If |
ret_nn |
If |
ret_extra |
A vector indicating what extra data to return. May contain any combination of the following strings:
|
n_threads |
Number of threads to use (except during stochastic gradient
descent). Default is half the number of concurrent threads supported by the
system. For nearest neighbor search, only applies if
|
n_sgd_threads |
Number of threads to use during stochastic gradient
descent. If set to > 1, then be aware that if |
grain_size |
The minimum amount of work to do on each thread. If this
value is set high enough, then less than |
tmpdir |
Temporary directory to store nearest neighbor indexes during
nearest neighbor search. Default is |
verbose |
If |
batch |
If |
opt_args |
A list of optimizer parameters, used when
|
epoch_callback |
A function which will be invoked at the end of every
epoch. Its signature should be:
|
pca_method |
Method to carry out any PCA dimensionality reduction when
the
|
binary_edge_weights |
If |
dens_scale |
A value between 0 and 1. If > 0 then the output attempts
to preserve relative local density around each observation. This uses an
approximation to the densMAP method (Narayan and co-workers, 2021). The
larger the value of |
seed |
Integer seed to use to initialize the random number generator
state. Combined with |
nn_args |
A list containing additional arguments to pass to the nearest
neighbor method. For
For
|
A matrix of optimized coordinates, or:
if ret_model = TRUE
(or ret_extra
contains
"model"
), returns a list containing extra information that can be
used to add new data to an existing embedding via
umap_transform
. In this case, the coordinates are available
in the list item embedding
. NOTE: The contents of
the model
list should not be considered stable or part of
the public API, and are purposely left undocumented.
if ret_nn = TRUE
(or ret_extra
contains "nn"
),
returns the nearest neighbor data as a list called nn
. This
contains one list for each metric
calculated, itself containing a
matrix idx
with the integer ids of the neighbors; and a matrix
dist
with the distances. The nn
list (or a sub-list) can be
used as input to the nn_method
parameter.
if ret_extra
contains "fgraph"
, returns the high
dimensional fuzzy graph as a sparse matrix called fgraph
, of type
dgCMatrix-class.
if ret_extra
contains "sigma"
, returns a vector of the
smooth knn distance normalization terms for each observation as
"sigma"
and a vector "rho"
containing the largest
distance to the locally connected neighbors of each observation.
if ret_extra
contains "localr"
, returns a vector of
the estimated local radii, the sum of "sigma"
and "rho"
.
The returned list contains the combined data from any combination of
specifying ret_model
, ret_nn
and ret_extra
.
Belkin, M., & Niyogi, P. (2002). Laplacian eigenmaps and spectral techniques for embedding and clustering. In Advances in neural information processing systems (pp. 585-591). http://papers.nips.cc/paper/1961-laplacian-eigenmaps-and-spectral-techniques-for-embedding-and-clustering.pdf
Böhm, J. N., Berens, P., & Kobak, D. (2020). A unifying perspective on neighbor embeddings along the attraction-repulsion spectrum. arXiv preprint arXiv:2007.08902. https://arxiv.org/abs/2007.08902
Damrich, S., & Hamprecht, F. A. (2021). On UMAP's true loss function. Advances in Neural Information Processing Systems, 34. https://proceedings.neurips.cc/paper/2021/hash/2de5d16682c3c35007e4e92982f1a2ba-Abstract.html
Dong, W., Moses, C., & Li, K. (2011, March). Efficient k-nearest neighbor graph construction for generic similarity measures. In Proceedings of the 20th international conference on World Wide Web (pp. 577-586). ACM. doi:10.1145/1963405.1963487.
Kingma, D. P., & Ba, J. (2014). Adam: A method for stochastic optimization. arXiv preprint arXiv:1412.6980. https://arxiv.org/abs/1412.6980
Malkov, Y. A., & Yashunin, D. A. (2018). Efficient and robust approximate nearest neighbor search using hierarchical navigable small world graphs. IEEE transactions on pattern analysis and machine intelligence, 42(4), 824-836.
McInnes, L., Healy, J., & Melville, J. (2018). UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction arXiv preprint arXiv:1802.03426. https://arxiv.org/abs/1802.03426
Narayan, A., Berger, B., & Cho, H. (2021). Assessing single-cell transcriptomic variability through density-preserving data visualization. Nature biotechnology, 39(6), 765-774. doi:10.1038/s41587-020-00801-7
O’Neill, M. E. (2014). PCG: A family of simple fast space-efficient statistically good algorithms for random number generation (Report No. HMC-CS-2014-0905). Harvey Mudd College.
Tang, J., Liu, J., Zhang, M., & Mei, Q. (2016, April). Visualizing large-scale and high-dimensional data. In Proceedings of the 25th International Conference on World Wide Web (pp. 287-297). International World Wide Web Conferences Steering Committee. https://arxiv.org/abs/1602.00370
Van der Maaten, L., & Hinton, G. (2008). Visualizing data using t-SNE. Journal of Machine Learning Research, 9 (2579-2605). https://www.jmlr.org/papers/v9/vandermaaten08a.html
Wang, Y., Huang, H., Rudin, C., & Shaposhnik, Y. (2021). Understanding How Dimension Reduction Tools Work: An Empirical Approach to Deciphering t-SNE, UMAP, TriMap, and PaCMAP for Data Visualization. Journal of Machine Learning Research, 22(201), 1-73. https://www.jmlr.org/papers/v22/20-1061.html
iris30 <- iris[c(1:10, 51:60, 101:110), ] # Non-numeric columns are automatically removed so you can pass data frames # directly in a lot of cases without pre-processing iris_umap <- umap(iris30, n_neighbors = 5, learning_rate = 0.5, init = "random", n_epochs = 20) # Faster approximation to the gradient and return nearest neighbors iris_umap <- umap(iris30, n_neighbors = 5, approx_pow = TRUE, ret_nn = TRUE, n_epochs = 20) # Can specify min_dist and spread parameters to control separation and size # of clusters and reuse nearest neighbors for efficiency nn <- iris_umap$nn iris_umap <- umap(iris30, n_neighbors = 5, min_dist = 1, spread = 5, nn_method = nn, n_epochs = 20) # Supervised dimension reduction using the 'Species' factor column iris_sumap <- umap(iris30, n_neighbors = 5, min_dist = 0.001, y = iris30$Species, target_weight = 0.5, n_epochs = 20 ) # Calculate Petal and Sepal neighbors separately (uses intersection of the resulting sets): iris_umap <- umap(iris30, metric = list( "euclidean" = c("Sepal.Length", "Sepal.Width"), "euclidean" = c("Petal.Length", "Petal.Width") ))
iris30 <- iris[c(1:10, 51:60, 101:110), ] # Non-numeric columns are automatically removed so you can pass data frames # directly in a lot of cases without pre-processing iris_umap <- umap(iris30, n_neighbors = 5, learning_rate = 0.5, init = "random", n_epochs = 20) # Faster approximation to the gradient and return nearest neighbors iris_umap <- umap(iris30, n_neighbors = 5, approx_pow = TRUE, ret_nn = TRUE, n_epochs = 20) # Can specify min_dist and spread parameters to control separation and size # of clusters and reuse nearest neighbors for efficiency nn <- iris_umap$nn iris_umap <- umap(iris30, n_neighbors = 5, min_dist = 1, spread = 5, nn_method = nn, n_epochs = 20) # Supervised dimension reduction using the 'Species' factor column iris_sumap <- umap(iris30, n_neighbors = 5, min_dist = 0.001, y = iris30$Species, target_weight = 0.5, n_epochs = 20 ) # Calculate Petal and Sepal neighbors separately (uses intersection of the resulting sets): iris_umap <- umap(iris30, metric = list( "euclidean" = c("Sepal.Length", "Sepal.Width"), "euclidean" = c("Petal.Length", "Petal.Width") ))
Carry out an embedding of new data using an existing embedding. Requires
using the result of calling umap
or tumap
with
ret_model = TRUE
.
umap_transform( X = NULL, model = NULL, nn_method = NULL, init_weighted = TRUE, search_k = NULL, tmpdir = tempdir(), n_epochs = NULL, n_threads = NULL, n_sgd_threads = 0, grain_size = 1, verbose = FALSE, init = "weighted", batch = NULL, learning_rate = NULL, opt_args = NULL, epoch_callback = NULL, ret_extra = NULL, seed = NULL )
umap_transform( X = NULL, model = NULL, nn_method = NULL, init_weighted = TRUE, search_k = NULL, tmpdir = tempdir(), n_epochs = NULL, n_threads = NULL, n_sgd_threads = 0, grain_size = 1, verbose = FALSE, init = "weighted", batch = NULL, learning_rate = NULL, opt_args = NULL, epoch_callback = NULL, ret_extra = NULL, seed = NULL )
X |
The new data to be transformed, either a matrix of data frame. Must
have the same columns in the same order as the input data used to generate
the |
model |
Data associated with an existing embedding. |
nn_method |
Optional pre-calculated nearest neighbor data. There are two supported formats. The first is a list consisting of two elements:
The second supported format is a sparse distance matrix of type
|
init_weighted |
If |
search_k |
Number of nodes to search during the neighbor retrieval. The
larger k, the more the accurate results, but the longer the search takes.
Default is the value used in building the |
tmpdir |
Temporary directory to store nearest neighbor indexes during
nearest neighbor search. Default is |
n_epochs |
Number of epochs to use during the optimization of the
embedded coordinates. A value between |
n_threads |
Number of threads to use, (except during stochastic gradient descent). Default is half the number of concurrent threads supported by the system. |
n_sgd_threads |
Number of threads to use during stochastic gradient
descent. If set to > 1, then be aware that if |
grain_size |
Minimum batch size for multithreading. If the number of
items to process in a thread falls below this number, then no threads will
be used. Used in conjunction with |
verbose |
If |
init |
how to initialize the transformed coordinates. One of:
This parameter should be used in preference to |
batch |
If |
learning_rate |
Initial learning rate used in optimization of the
coordinates. This overrides the value associated with the |
opt_args |
A list of optimizer parameters, used when
If |
epoch_callback |
A function which will be invoked at the end of every
epoch. Its signature should be:
|
ret_extra |
A vector indicating what extra data to return. May contain any combination of the following strings:
|
seed |
Integer seed to use to initialize the random number generator
state. Combined with |
Note that some settings are incompatible with the production of a UMAP model
via umap
: external neighbor data (passed via a list to the
argument of the nn_method
parameter), and factor columns that were
included in the UMAP calculation via the metric
parameter. In the
latter case, the model produced is based only on the numeric data.
A transformation is possible, but factor columns in the new data are ignored.
A matrix of coordinates for X
transformed into the space
of the model
, or if ret_extra
is specified, a list
containing:
embedding
the matrix of optimized coordinates.
if ret_extra
contains "fgraph"
, an item of the same
name containing the high-dimensional fuzzy graph as a sparse matrix, of
type dgCMatrix-class.
if ret_extra
contains "sigma"
, returns a vector of
the smooth knn distance normalization terms for each observation as
"sigma"
and a vector "rho"
containing the largest
distance to the locally connected neighbors of each observation.
if ret_extra
contains "localr"
, an item of the same
name containing a vector of the estimated local radii, the sum of
"sigma"
and "rho"
.
if ret_extra
contains "nn"
, an item of the same name
containing the nearest neighbors of each item in X
(with respect
to the items that created the model
).
iris_train <- iris[1:100, ] iris_test <- iris[101:150, ] # You must set ret_model = TRUE to return extra data needed iris_train_umap <- umap(iris_train, ret_model = TRUE) iris_test_umap <- umap_transform(iris_test, iris_train_umap)
iris_train <- iris[1:100, ] iris_test <- iris[101:150, ] # You must set ret_model = TRUE to return extra data needed iris_train_umap <- umap(iris_train, ret_model = TRUE) iris_test_umap <- umap_transform(iris_test, iris_train_umap)
Carry out dimensionality reduction of a dataset using the Uniform Manifold Approximation and Projection (UMAP) method (McInnes et al., 2018).
umap2( X, n_neighbors = 15, n_components = 2, metric = "euclidean", n_epochs = NULL, learning_rate = 1, scale = FALSE, init = "spectral", init_sdev = "range", spread = 1, min_dist = 0.1, set_op_mix_ratio = 1, local_connectivity = 1, bandwidth = 1, repulsion_strength = 1, negative_sample_rate = 5, a = NULL, b = NULL, nn_method = NULL, n_trees = 50, search_k = 2 * n_neighbors * n_trees, approx_pow = FALSE, y = NULL, target_n_neighbors = n_neighbors, target_metric = "euclidean", target_weight = 0.5, pca = NULL, pca_center = TRUE, pcg_rand = TRUE, fast_sgd = FALSE, ret_model = FALSE, ret_nn = FALSE, ret_extra = c(), n_threads = NULL, n_sgd_threads = 0, grain_size = 1, tmpdir = tempdir(), verbose = getOption("verbose", TRUE), batch = TRUE, opt_args = NULL, epoch_callback = NULL, pca_method = NULL, binary_edge_weights = FALSE, dens_scale = NULL, seed = NULL, nn_args = list() )
umap2( X, n_neighbors = 15, n_components = 2, metric = "euclidean", n_epochs = NULL, learning_rate = 1, scale = FALSE, init = "spectral", init_sdev = "range", spread = 1, min_dist = 0.1, set_op_mix_ratio = 1, local_connectivity = 1, bandwidth = 1, repulsion_strength = 1, negative_sample_rate = 5, a = NULL, b = NULL, nn_method = NULL, n_trees = 50, search_k = 2 * n_neighbors * n_trees, approx_pow = FALSE, y = NULL, target_n_neighbors = n_neighbors, target_metric = "euclidean", target_weight = 0.5, pca = NULL, pca_center = TRUE, pcg_rand = TRUE, fast_sgd = FALSE, ret_model = FALSE, ret_nn = FALSE, ret_extra = c(), n_threads = NULL, n_sgd_threads = 0, grain_size = 1, tmpdir = tempdir(), verbose = getOption("verbose", TRUE), batch = TRUE, opt_args = NULL, epoch_callback = NULL, pca_method = NULL, binary_edge_weights = FALSE, dens_scale = NULL, seed = NULL, nn_args = list() )
X |
Input data. Can be a |
n_neighbors |
The size of local neighborhood (in terms of number of
neighboring sample points) used for manifold approximation. Larger values
result in more global views of the manifold, while smaller values result in
more local data being preserved. In general values should be in the range
|
n_components |
The dimension of the space to embed into. This defaults
to |
metric |
Type of distance metric to use to find nearest neighbors. For
For
If rnndescent is
installed and
For more details see the package documentation of If Each metric calculation results in a separate fuzzy simplicial set, which are intersected together to produce the final set. Metric names can be repeated. Because non-numeric columns are removed from the data frame, it is safer to use column names than integer ids. Factor columns can also be used by specifying the metric name
For a given data block, you may override the |
n_epochs |
Number of epochs to use during the optimization of the
embedded coordinates. By default, this value is set to |
learning_rate |
Initial learning rate used in optimization of the coordinates. |
scale |
Scaling to apply to
For UMAP, the default is |
init |
Type of initialization for the coordinates. Options are:
For spectral initializations, ( |
init_sdev |
If non- |
spread |
The effective scale of embedded points. In combination with
|
min_dist |
The effective minimum distance between embedded points.
Smaller values will result in a more clustered/clumped embedding where
nearby points on the manifold are drawn closer together, while larger
values will result on a more even dispersal of points. The value should be
set relative to the |
set_op_mix_ratio |
Interpolate between (fuzzy) union and intersection as
the set operation used to combine local fuzzy simplicial sets to obtain a
global fuzzy simplicial sets. Both fuzzy set operations use the product
t-norm. The value of this parameter should be between |
local_connectivity |
The local connectivity required – i.e. the number of nearest neighbors that should be assumed to be connected at a local level. The higher this value the more connected the manifold becomes locally. In practice this should be not more than the local intrinsic dimension of the manifold. |
bandwidth |
The effective bandwidth of the kernel if we view the algorithm as similar to Laplacian Eigenmaps. Larger values induce more connectivity and a more global view of the data, smaller values concentrate more locally. |
repulsion_strength |
Weighting applied to negative samples in low dimensional embedding optimization. Values higher than one will result in greater weight being given to negative samples. |
negative_sample_rate |
The number of negative edge/1-simplex samples to use per positive edge/1-simplex sample in optimizing the low dimensional embedding. |
a |
More specific parameters controlling the embedding. If |
b |
More specific parameters controlling the embedding. If |
nn_method |
Method for finding nearest neighbors. Options are:
By default, if
or a sparse distance matrix of type |
n_trees |
Number of trees to build when constructing the nearest
neighbor index. The more trees specified, the larger the index, but the
better the results. With |
search_k |
Number of nodes to search during the neighbor retrieval. The
larger k, the more the accurate results, but the longer the search takes.
With |
approx_pow |
If |
y |
Optional target data for supervised dimension reduction. Can be a
vector, matrix or data frame. Use the
Unlike |
target_n_neighbors |
Number of nearest neighbors to use to construct the
target simplicial set. Default value is |
target_metric |
The metric used to measure distance for |
target_weight |
Weighting factor between data topology and target
topology. A value of 0.0 weights entirely on data, a value of 1.0 weights
entirely on target. The default of 0.5 balances the weighting equally
between data and target. Only applies if |
pca |
If set to a positive integer value, reduce data to this number of
columns using PCA. Doesn't applied if the distance |
pca_center |
If |
pcg_rand |
If |
fast_sgd |
If |
ret_model |
If |
ret_nn |
If |
ret_extra |
A vector indicating what extra data to return. May contain any combination of the following strings:
|
n_threads |
Number of threads to use (except during stochastic gradient
descent). Default is half the number of concurrent threads supported by the
system. For nearest neighbor search, only applies if
|
n_sgd_threads |
Number of threads to use during stochastic gradient
descent. If set to > 1, then be aware that if |
grain_size |
The minimum amount of work to do on each thread. If this
value is set high enough, then less than |
tmpdir |
Temporary directory to store nearest neighbor indexes during
nearest neighbor search. Default is |
verbose |
If |
batch |
If |
opt_args |
A list of optimizer parameters, used when
|
epoch_callback |
A function which will be invoked at the end of every
epoch. Its signature should be:
|
pca_method |
Method to carry out any PCA dimensionality reduction when
the
|
binary_edge_weights |
If |
dens_scale |
A value between 0 and 1. If > 0 then the output attempts
to preserve relative local density around each observation. This uses an
approximation to the densMAP method (Narayan and co-workers, 2021). The
larger the value of |
seed |
Integer seed to use to initialize the random number generator
state. Combined with |
nn_args |
A list containing additional arguments to pass to the nearest
neighbor method. For
For
|
This function behaves like umap
except with some updated
defaults that make it behave more like the Python implementation and which
cannot be added to umap
without breaking backwards
compatibility. In addition:
if RcppHNSW is installed, it will be used in preference to Annoy if a compatible metric is requested.
if RcppHNSW is not present, but rnndescent is installed, it will be used in preference to Annoy if a compatible metric is requested.
if batch = TRUE
then the default n_sgd_threads
is set
to the same value as n_threads
.
if the input data X
is a sparse matrix, it is interpreted
similarly to a dense matrix or dataframe, and not as a distance matrix.
This requires rnndescent
package to be installed.
A matrix of optimized coordinates, or:
if ret_model = TRUE
(or ret_extra
contains
"model"
), returns a list containing extra information that can be
used to add new data to an existing embedding via
umap_transform
. In this case, the coordinates are available
in the list item embedding
. NOTE: The contents of
the model
list should not be considered stable or part of
the public API, and are purposely left undocumented.
if ret_nn = TRUE
(or ret_extra
contains "nn"
),
returns the nearest neighbor data as a list called nn
. This
contains one list for each metric
calculated, itself containing a
matrix idx
with the integer ids of the neighbors; and a matrix
dist
with the distances. The nn
list (or a sub-list) can be
used as input to the nn_method
parameter.
if ret_extra
contains "fgraph"
, returns the high
dimensional fuzzy graph as a sparse matrix called fgraph
, of type
dgCMatrix-class.
if ret_extra
contains "sigma"
, returns a vector of the
smooth knn distance normalization terms for each observation as
"sigma"
and a vector "rho"
containing the largest
distance to the locally connected neighbors of each observation.
if ret_extra
contains "localr"
, returns a vector of
the estimated local radii, the sum of "sigma"
and "rho"
.
The returned list contains the combined data from any combination of
specifying ret_model
, ret_nn
and ret_extra
.
Belkin, M., & Niyogi, P. (2002). Laplacian eigenmaps and spectral techniques for embedding and clustering. In Advances in neural information processing systems (pp. 585-591). http://papers.nips.cc/paper/1961-laplacian-eigenmaps-and-spectral-techniques-for-embedding-and-clustering.pdf
Böhm, J. N., Berens, P., & Kobak, D. (2020). A unifying perspective on neighbor embeddings along the attraction-repulsion spectrum. arXiv preprint arXiv:2007.08902. https://arxiv.org/abs/2007.08902
Damrich, S., & Hamprecht, F. A. (2021). On UMAP's true loss function. Advances in Neural Information Processing Systems, 34. https://proceedings.neurips.cc/paper/2021/hash/2de5d16682c3c35007e4e92982f1a2ba-Abstract.html
Dong, W., Moses, C., & Li, K. (2011, March). Efficient k-nearest neighbor graph construction for generic similarity measures. In Proceedings of the 20th international conference on World Wide Web (pp. 577-586). ACM. doi:10.1145/1963405.1963487.
Kingma, D. P., & Ba, J. (2014). Adam: A method for stochastic optimization. arXiv preprint arXiv:1412.6980. https://arxiv.org/abs/1412.6980
Malkov, Y. A., & Yashunin, D. A. (2018). Efficient and robust approximate nearest neighbor search using hierarchical navigable small world graphs. IEEE transactions on pattern analysis and machine intelligence, 42(4), 824-836.
McInnes, L., Healy, J., & Melville, J. (2018). UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction arXiv preprint arXiv:1802.03426. https://arxiv.org/abs/1802.03426
Narayan, A., Berger, B., & Cho, H. (2021). Assessing single-cell transcriptomic variability through density-preserving data visualization. Nature biotechnology, 39(6), 765-774. doi:10.1038/s41587-020-00801-7
O’Neill, M. E. (2014). PCG: A family of simple fast space-efficient statistically good algorithms for random number generation (Report No. HMC-CS-2014-0905). Harvey Mudd College.
Tang, J., Liu, J., Zhang, M., & Mei, Q. (2016, April). Visualizing large-scale and high-dimensional data. In Proceedings of the 25th International Conference on World Wide Web (pp. 287-297). International World Wide Web Conferences Steering Committee. https://arxiv.org/abs/1602.00370
Van der Maaten, L., & Hinton, G. (2008). Visualizing data using t-SNE. Journal of Machine Learning Research, 9 (2579-2605). https://www.jmlr.org/papers/v9/vandermaaten08a.html
Wang, Y., Huang, H., Rudin, C., & Shaposhnik, Y. (2021). Understanding How Dimension Reduction Tools Work: An Empirical Approach to Deciphering t-SNE, UMAP, TriMap, and PaCMAP for Data Visualization. Journal of Machine Learning Research, 22(201), 1-73. https://www.jmlr.org/papers/v22/20-1061.html
iris30 <- iris[c(1:10, 51:60, 101:110), ] iris_umap <- umap2(iris30, n_neighbors = 5)
iris30 <- iris[c(1:10, 51:60, 101:110), ] iris_umap <- umap2(iris30, n_neighbors = 5)
Unloads the UMAP model. This prevents the model being used with
umap_transform
, but allows the temporary working directory
associated with saving or loading the model to be removed.
unload_uwot(model, cleanup = TRUE, verbose = FALSE)
unload_uwot(model, cleanup = TRUE, verbose = FALSE)
model |
a UMAP model create by |
cleanup |
if |
verbose |
if |
iris_train <- iris[c(1:10, 51:60), ] iris_test <- iris[100:110, ] # create model model <- umap(iris_train, ret_model = TRUE, n_epochs = 20) # save without unloading: this leaves behind a temporary working directory model_file <- tempfile("iris_umap") model <- save_uwot(model, file = model_file) # The model can continue to be used test_embedding <- umap_transform(iris_test, model) # To manually unload the model from memory when finished and to clean up # the working directory (this doesn't touch your model file) unload_uwot(model) # At this point, model cannot be used with umap_transform, this would fail: # test_embedding2 <- umap_transform(iris_test, model) # restore the model: this also creates a temporary working directory model2 <- load_uwot(file = model_file) test_embedding2 <- umap_transform(iris_test, model2) # Unload and clean up the loaded model temp directory unload_uwot(model2) # clean up the model file unlink(model_file) # save with unloading: this deletes the temporary working directory but # doesn't allow the model to be re-used model3 <- umap(iris_train, ret_model = TRUE, n_epochs = 20) model_file3 <- tempfile("iris_umap") model3 <- save_uwot(model3, file = model_file3, unload = TRUE)
iris_train <- iris[c(1:10, 51:60), ] iris_test <- iris[100:110, ] # create model model <- umap(iris_train, ret_model = TRUE, n_epochs = 20) # save without unloading: this leaves behind a temporary working directory model_file <- tempfile("iris_umap") model <- save_uwot(model, file = model_file) # The model can continue to be used test_embedding <- umap_transform(iris_test, model) # To manually unload the model from memory when finished and to clean up # the working directory (this doesn't touch your model file) unload_uwot(model) # At this point, model cannot be used with umap_transform, this would fail: # test_embedding2 <- umap_transform(iris_test, model) # restore the model: this also creates a temporary working directory model2 <- load_uwot(file = model_file) test_embedding2 <- umap_transform(iris_test, model2) # Unload and clean up the loaded model temp directory unload_uwot(model2) # clean up the model file unlink(model_file) # save with unloading: this deletes the temporary working directory but # doesn't allow the model to be re-used model3 <- umap(iris_train, ret_model = TRUE, n_epochs = 20) model_file3 <- tempfile("iris_umap") model3 <- save_uwot(model3, file = model_file3, unload = TRUE)