mojolearn.UMAP#
- class mojolearn.UMAP(n_neighbors=15, n_components=2, *, min_dist=0.1, spread=1.0, n_epochs=None, random_state=0, set_op_mix_ratio=1.0, local_connectivity=1.0, metric='euclidean', init='spectral', learning_rate=1.0, repulsion_strength=1.0, negative_sample_rate=5, a=None, b=None, metric_kwds=None, target_n_neighbors=-1, target_metric='categorical', target_weight=0.5, densmap=False, output_metric='euclidean')[source]#
Bases:
NumericModeMixinUniform Manifold Approximation and Projection (UMAP) embedding.
Builds a fuzzy nearest-neighbor graph of the training rows with exact neighbor search, then optimizes a low-dimensional layout. Input is a dense array converted to C-order float32. The neighbor graph is stored in CSR form, so memory grows linearly with
n_samplesfor a boundedn_neighbors; the exact neighbor search still compares every pair of rows. Parameters follow umap-learn; defaults that differ aren_epochs=None(200 epochs) andrandom_state=0.At least
2 * n_components + 4samples are needed for the spectral initialization.- Parameters:
n_neighbors (int, default 15) – Size of the local neighborhood; at least 2 and at most
n_samples.n_components (int, default 2) – Dimension of the embedding, 1 to 32.
min_dist (float, default 0.1) – Minimum distance between embedded points;
0 <= min_dist <= spread.spread (float, default 1.0) – Scale of the embedded points; must be positive.
n_epochs (int or None, default None) – Number of optimization epochs; None uses 200.
random_state (int, default 0) – Seed for the optimizer and random initialization; a nonnegative integer.
set_op_mix_ratio (float, default 1.0) – Mix between fuzzy union (1.0) and fuzzy intersection (0.0), in [0, 1].
local_connectivity (float, default 1.0) – Number of nearest neighbors assumed locally connected; any value
>= 0(umap-learn’s interpolation for fractional values).metric (str, default “euclidean”) – Input distance:
"euclidean"("l2"),"sqeuclidean","cosine","manhattan"("l1","cityblock","taxicab"),"chebyshev"("linf","linfinity","infinity") or"minkowski". A callable or any other name raisesValueError.init ({“spectral”, “random”, “pca”} or array, default “spectral”) – Initial layout.
"random"draws uniform(-10, 10);"pca"is umap-learn’s scaled PCA plus N(0, 1e-4) noise; an array must have shape(n_samples, n_components)and be finite.learning_rate (float, default 1.0) – Initial learning rate; must be positive.
repulsion_strength (float, default 1.0) – Weight of negative samples; must be nonnegative.
negative_sample_rate (int, default 5) – Negative samples per positive sample.
a, b (float or None, default None) – Curve parameters of the low-dimensional similarity. Give both or neither; when None they are derived from
min_distandspread.metric_kwds (dict or None, default None) – Extra metric arguments. Only
{"p": p}for"minkowski"(p > 0, default 2.0); any other key raisesValueError.target_n_neighbors (int, default -1) – Neighbors used for the target graph in supervised fits; -1 uses
n_neighbors, otherwise at least 2.target_metric ({“categorical”, “l2”, “euclidean”}, default “categorical”) – Distance on
yfor supervised fits. With"categorical", the label -1 means unknown. Other values raiseNotImplementedError.target_weight (float, default 0.5) – Weight of the target in [0, 1]; 0 ignores the data, 1 ignores
y.densmap (bool, default False) – densMAP is not supported; True raises
NotImplementedError.output_metric (str, default “euclidean”) – Only
"euclidean"(or"l2") is supported; any other value raisesNotImplementedError.
- Variables:
Notes
transformkeeps private copies of the training data and embedding, addingO(n_samples * (n_features + n_components))memory. It finds each new row’s neighbors among the training rows, initializes it from their weighted embedding and refines it against the frozen training embedding for 100 epochs (max(1, n_epochs // 3)whenn_epochsis set) atlearning_rate / 4. The result for a row does not depend on the other rows in the call.Examples
>>> import numpy as np, mojolearn >>> X = np.random.default_rng(0).random((1000, 8), dtype=np.float32) >>> model = mojolearn.UMAP(n_neighbors=15, n_components=2).fit(X) >>> model.embedding_.shape (1000, 2) >>> Y = model.transform(X[:10])
- __init__(n_neighbors=15, n_components=2, *, min_dist=0.1, spread=1.0, n_epochs=None, random_state=0, set_op_mix_ratio=1.0, local_connectivity=1.0, metric='euclidean', init='spectral', learning_rate=1.0, repulsion_strength=1.0, negative_sample_rate=5, a=None, b=None, metric_kwds=None, target_n_neighbors=-1, target_metric='categorical', target_weight=0.5, densmap=False, output_metric='euclidean')[source]#
Methods
fit(X[, y])Fit the embedding to
X.fit_transform(X[, y])Fit to
Xand return the training embedding.get_params([deep])load(path)Load a model written by
save.numeric_mode_used()The numeric mode this estimator runs in.
save(path)Save the fitted model to
pathas an.npzfile.set_params(**params)Set constructor parameters.
transform(X)Embed new rows in the fitted coordinate system without refitting.
vendor_used()The GPU backend this estimator runs on.
- fit(X, y=None)[source]#
Fit the embedding to
X.- Parameters:
X (array-like of shape (n_samples, n_features)) – Training data; converted to C-order float32 and must be finite.
y (array-like of shape (n_samples,) or (n_samples, n_targets), optional) – Target for supervised UMAP. Categorical labels (one per row, -1 for unknown) or, with
target_metric="l2", finite continuous values.
- Returns:
self (UMAP) – The fitted estimator.
- Raises:
ValueError – If
Xis not finite,n_neighborsexceedsn_samples, there are too few samples for spectral initialization, or a parameter is out of range.NotImplementedError – For
densmap=True, a non-euclideanoutput_metricor an unsupportedtarget_metric.
- fit_transform(X, y=None)[source]#
Fit to
Xand return the training embedding.- Parameters:
X (array-like of shape (n_samples, n_features)) – Training data.
y (array-like, optional) – Target for supervised UMAP (see
fit).
- Returns:
embedding (Array of shape (n_samples, n_components)) – The float32 embedding, the same object as
embedding_.
- transform(X)[source]#
Embed new rows in the fitted coordinate system without refitting.
Each row is embedded independently: a batch of rows returns the same values as embedding the rows one at a time. Passing the exact training data returns a copy of the training embedding. Later edits of
embedding_or of the originalXdo not change the model.- Parameters:
X (array-like of shape (n_queries, n_features)) – New rows; must be finite and have the training feature count.
- Returns:
embedding (Array of shape (n_queries, n_components)) – The float32 embedding of the new rows.
- Raises:
ValueError – If the model is not fitted, the parameters or numeric mode changed since
fit(refit first), the feature count differs, orXis not finite.
- save(path)[source]#
Save the fitted model to
pathas an.npzfile.The file holds the training rows, the embedding, the parameters and the numeric mode. A model loaded with
UMAP.load(ormojolearn.host_model) cantransformnew rows, including on a CPU-only install, but cannot refit.- Parameters:
path (str or path-like) – Destination file.
- Raises:
ValueError – If the model is not fitted.
- classmethod load(path)[source]#
Load a model written by
save.The loaded model transforms new rows against the saved training rows and embedding; it does not refit.
- Parameters:
path (str or path-like) – File written by
UMAP.save.- Returns:
model (UMAP) – The restored model, with
embedding_,n_features_in_andinput_copied_set.- Raises:
ValueError – If the file is not a UMAP model or its contents are inconsistent.