mojolearn.PCA#

class mojolearn.PCA(n_components=None, *, copy=True, whiten=False, svd_solver='auto', tol=0.0, iterated_power='auto', n_oversamples=10, power_iteration_normalizer='auto', random_state=None)[source]#

Bases: NumericModeMixin

Principal component analysis.

Centers the data and projects it onto its leading principal axes. Input is converted to C-order float32; a scipy.sparse matrix is densified. Use IncrementalPCA for fitting in batches.

The default svd_solver="auto" always runs the covariance eigendecomposition (covariance matrix, then a Jacobi eigensolver), unlike scikit-learn, where "auto" chooses a solver from the data shape. svd_solver="full" is a different algorithm, an SVD of the centered data that never forms the covariance and so is more accurate on ill-conditioned data.

Parameters:
  • n_components (int, float, “mle” or None, default None) – Number of components to keep. An int in [1, n_features]; None keeps min(n_samples, n_features); a float in (0, 1) keeps the fewest components whose cumulative explained variance ratio exceeds it; "mle" uses Minka’s MLE (requires n_samples >= n_features).

  • copy (bool, default True) – Accepted for compatibility; the input is never modified.

  • whiten (bool, default False) – Scale the projected columns to unit sample variance (using the fitted sample count, never the size of the transform batch). inverse_transform undoes the scaling. Columns whose singular value is below 1e-10 are not divided by it, so they do not reach unit variance.

  • svd_solver ({“auto”, “covariance_eigh”, “jacobi”, “full”, “randomized”}, default “auto”) – "auto", "covariance_eigh" and "jacobi" all run the covariance eigendecomposition. "full" runs a QR-based SVD of the centered data; outside the "identical" numeric mode it needs n_samples >= n_features and raises NotImplementedError otherwise. "randomized" runs randomized_svd() and needs n_components < min(n_samples, n_features). "arpack" raises NotImplementedError.

  • tol (float, default 0.0) – Only 0.0 is accepted (it is ARPACK’s tolerance); any other value raises NotImplementedError.

  • iterated_power (int or “auto”, default “auto”) – Power iterations for "randomized"; "auto" uses 7 when n_components < 0.1 * min(n_samples, n_features), else 4.

  • n_oversamples (int, default 10) – Extra random vectors for "randomized".

  • power_iteration_normalizer (str, default “auto”) – Normalizer between power iterations for "randomized".

  • random_state (int or None, default None) – Seed for "randomized"; None means seed 0.

Variables:
  • components_ (Array of shape (n_components_, n_features), float32) – Principal axes, sorted by decreasing explained variance.

  • mean_ (Array of shape (n_features,), float32) – Per-feature mean of the training data.

  • explained_variance_ (Array of shape (n_components_,), float32) – Variance explained by each component.

  • explained_variance_ratio_ (Array of shape (n_components_,), float32) – Fraction of total variance explained by each component.

  • singular_values_ (Array of shape (n_components_,), float32) – Singular values of the centered data for each component.

  • noise_variance_ (float) – Mean of the discarded eigenvalues of the covariance.

  • n_components_ (int) – Number of components kept.

  • n_features_in_ (int) – Number of features seen during fit.

  • n_samples_ (int) – Number of training rows.

  • input_copied_ (bool) – Whether X had to be copied to C-order float32.

Examples

>>> import numpy as np, mojolearn
>>> X = np.random.default_rng(0).random((1000, 8), dtype=np.float32)
>>> pca = mojolearn.PCA(n_components=3).fit(X)
>>> Z = pca.transform(X)
>>> X_back = pca.inverse_transform(Z)
__init__(n_components=None, *, copy=True, whiten=False, svd_solver='auto', tol=0.0, iterated_power='auto', n_oversamples=10, power_iteration_normalizer='auto', random_state=None)[source]#

Methods

fit(X[, y])

Fit the model to X.

fit_transform(X[, y])

Fit to X and return its projection.

get_params([deep])

inverse_transform(X)

Map projected data back to the original feature space.

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 path as an .npz file.

set_params(**params)

Set constructor parameters.

transform(X)

Project X onto the principal components.

vendor_used()

The GPU backend this estimator runs on.

fit(X, y=None)[source]#

Fit the model to X.

Parameters:
  • X (array-like of shape (n_samples, n_features)) – Training data; at least 2 rows and 2 features. Must be finite when whiten=True.

  • y (ignored)

Returns:

self (PCA) – The fitted estimator.

Raises:
  • ValueError – If X is too small or n_components is out of range.

  • NotImplementedError – For an unsupported svd_solver, a nonzero tol, or svd_solver="full" on a wide matrix outside "identical" mode.

transform(X)[source]#

Project X onto the principal components.

Parameters:

X (array-like of shape (n_samples, n_features)) – Data with the training feature count.

Returns:

Z (Array of shape (n_samples, n_components_), float32) – The projected (and, with whiten=True, whitened) data.

Raises:

ValueError – If the model is not fitted or the feature count differs.

fit_transform(X, y=None)[source]#

Fit to X and return its projection.

Parameters:
  • X (array-like of shape (n_samples, n_features)) – Training data.

  • y (ignored)

Returns:

Z (Array of shape (n_samples, n_components_), float32) – The projected data.

inverse_transform(X)[source]#

Map projected data back to the original feature space.

Parameters:

X (array-like of shape (n_samples, n_components_)) – Projected data, as returned by transform.

Returns:

X_original (Array of shape (n_samples, n_features), float32) – The reconstruction (undoing whitening when whiten=True).

Raises:

ValueError – If the component count differs from the fit.

save(path)[source]#

Save the fitted model to path as an .npz file.

A model restored with PCA.load or mojolearn.host_model(path) transforms (whitened or not), including on a CPU-only install.

Parameters:

path (str or path-like) – Destination file.

Raises:

RuntimeError – If the model is not fitted.

classmethod load(path)[source]#

Load a model written by save.

The loaded model transforms; it does not refit.

Parameters:

path (str or path-like) – File written by PCA.save.

Returns:

model (PCA) – The restored model.

Raises:

ValueError – If the file is not a PCA model or its arrays are inconsistent.