mojolearn.SparsePCA#

class mojolearn.SparsePCA(n_components=None, *, alpha=1, ridge_alpha=0.01, max_iter=1000, tol=1e-08, method='lars', n_jobs=None, U_init=None, V_init=None, verbose=False, random_state=None, numeric_mode=None)[source]#

Bases: _BaseSparsePCA

Sparse principal component analysis.

Follows scikit-learn’s SparsePCA: finds components with few nonzero loadings by dictionary learning on the centered, transposed data. Each component is scaled to unit norm.

Parameters:
  • n_components (int or None, default None) – Number of components; None uses n_features.

  • alpha (float, default 1) – Sparsity penalty; larger values give sparser components.

  • ridge_alpha (float, default 0.01) – Ridge penalty used by transform.

  • max_iter (int, default 1000) – Maximum number of iterations.

  • tol (float, default 1e-8) – Convergence tolerance.

  • method ({“lars”, “cd”}, default “lars”) – Lasso solver name (both give the same optimum).

  • n_jobs (ignored)

  • U_init (array-like of shape (n_samples, n_components) or None, default None) – Starting sample loadings; used only together with V_init.

  • V_init (array-like of shape (n_components, n_features) or None, default None) – Starting components; used only together with U_init.

  • verbose (ignored)

  • random_state (int or None, default None) – Seed used to resample unused atoms; None means 0.

  • numeric_mode ({“identical”, “fast”} or None, default None) – Numeric mode for this estimator. None uses the package default ("identical" unless changed). "identical" gives the same bits on NVIDIA and AMD GPUs; "fast" applies on Apple GPUs.

Variables:
  • components_ (ndarray of shape (n_components, n_features)) – Sparse components, each scaled to unit norm.

  • n_components_ (int)

  • mean_ (ndarray of shape (n_features,))

  • n_iter_ (int)

  • n_features_in_ (int)

  • error_ (list of float) – Objective value at each iteration.

Raises:

ValueError – If method is not "lars" or "cd".

Examples

>>> import numpy as np, mojolearn
>>> X = np.random.default_rng(0).random((500, 8), dtype=np.float32)
>>> spca = mojolearn.SparsePCA(n_components=3, max_iter=20, random_state=0).fit(X)
>>> Z = spca.transform(X)
__init__(n_components=None, *, alpha=1, ridge_alpha=0.01, max_iter=1000, tol=1e-08, method='lars', n_jobs=None, U_init=None, V_init=None, verbose=False, random_state=None, numeric_mode=None)[source]#

Methods

fit(X[, y])

Fit the sparse components.

fit_transform(X[, y])

Fit to X, then return transform(X).

get_params([deep])

Return this estimator's constructor parameters.

inverse_transform(X)

Map projected data back: X @ components_ + mean_.

set_params(**params)

Set constructor parameters by keyword.

transform(X)

Project X onto the sparse components by ridge regression.

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

Fit the sparse components.

Parameters:
  • X (array-like of shape (n_samples, n_features))

  • y (ignored)

Returns:

self