scikit-learn/sklearn/decomposition/sparse_pca.py

285 lines
9.2 KiB
Python
Raw Normal View History

2011-07-27 04:41:31 +08:00
"""Matrix factorization with Sparse PCA"""
2011-06-15 07:44:18 +08:00
# Author: Vlad Niculae, Gael Varoquaux, Alexandre Gramfort
# License: BSD 3 clause
2011-06-15 07:44:18 +08:00
import numpy as np
2011-06-12 21:22:54 +08:00
from ..utils import check_random_state, check_array
from ..utils.validation import check_is_fitted
from ..linear_model import ridge_regression
2011-05-26 07:08:39 +08:00
from ..base import BaseEstimator, TransformerMixin
from .dict_learning import dict_learning, dict_learning_online
2011-07-22 08:15:07 +08:00
2011-08-25 00:57:05 +08:00
2011-05-10 19:43:06 +08:00
class SparsePCA(BaseEstimator, TransformerMixin):
"""Sparse Principal Components Analysis (SparsePCA)
2011-05-26 07:08:39 +08:00
Finds the set of sparse components that can optimally reconstruct
the data. The amount of sparseness is controllable by the coefficient
of the L1 penalty, given by the parameter alpha.
2011-05-26 18:15:52 +08:00
2015-06-03 12:24:04 +08:00
Read more in the :ref:`User Guide <SparsePCA>`.
2011-05-26 18:15:52 +08:00
Parameters
----------
n_components : int,
2011-07-16 04:37:33 +08:00
Number of sparse atoms to extract.
alpha : float,
Sparsity controlling parameter. Higher values lead to sparser
components.
ridge_alpha : float,
2011-07-31 20:33:45 +08:00
Amount of ridge shrinkage to apply in order to improve
conditioning when calling the transform method.
max_iter : int,
2011-07-16 04:37:33 +08:00
Maximum number of iterations to perform.
tol : float,
2011-07-16 04:37:33 +08:00
Tolerance for the stopping condition.
method : {'lars', 'cd'}
2011-09-19 17:11:33 +08:00
lars: uses the least angle regression method to solve the lasso problem
2011-08-25 00:57:05 +08:00
(linear_model.lars_path)
2011-09-19 17:11:33 +08:00
cd: uses the coordinate descent method to compute the
Lasso solution (linear_model.Lasso). Lars will be faster if
the estimated components are sparse.
2011-05-26 18:15:52 +08:00
n_jobs : int,
2011-07-16 04:37:33 +08:00
Number of parallel jobs to run.
2011-05-26 18:15:52 +08:00
U_init : array of shape (n_samples, n_components),
2011-07-16 04:37:33 +08:00
Initial values for the loadings for warm restart scenarios.
2011-07-09 18:20:25 +08:00
V_init : array of shape (n_components, n_features),
2011-07-16 04:37:33 +08:00
Initial values for the components for warm restart scenarios.
2011-05-26 18:15:52 +08:00
verbose :
2011-07-16 04:37:33 +08:00
Degree of verbosity of the printed output.
random_state : int or RandomState
2011-07-09 18:20:25 +08:00
Pseudo number generator state used for random sampling.
2011-05-26 18:15:52 +08:00
Attributes
----------
components_ : array, [n_components, n_features]
2011-07-16 04:37:33 +08:00
Sparse components extracted from the data.
2011-06-13 21:41:50 +08:00
error_ : array
2011-07-16 04:37:33 +08:00
Vector of errors at each iteration.
2011-05-26 18:15:52 +08:00
n_iter_ : int
Number of iterations run.
See also
--------
PCA
2011-12-20 18:06:59 +08:00
MiniBatchSparsePCA
DictionaryLearning
2011-05-10 19:43:06 +08:00
"""
def __init__(self, n_components=None, alpha=1, ridge_alpha=0.01,
max_iter=1000, tol=1e-8, method='lars', n_jobs=1, U_init=None,
V_init=None, verbose=False, random_state=None):
2011-05-10 19:43:06 +08:00
self.n_components = n_components
self.alpha = alpha
2011-07-31 20:33:45 +08:00
self.ridge_alpha = ridge_alpha
2011-05-10 19:43:06 +08:00
self.max_iter = max_iter
self.tol = tol
self.method = method
self.n_jobs = n_jobs
self.U_init = U_init
self.V_init = V_init
self.verbose = verbose
2011-07-09 18:20:25 +08:00
self.random_state = random_state
2011-05-10 19:43:06 +08:00
2011-08-23 21:21:05 +08:00
def fit(self, X, y=None):
2011-05-26 18:15:52 +08:00
"""Fit the model from data in X.
Parameters
----------
X: array-like, shape (n_samples, n_features)
Training vector, where n_samples in the number of samples
and n_features is the number of features.
Returns
-------
2011-07-15 17:16:48 +08:00
self : object
Returns the instance itself.
2011-05-26 18:15:52 +08:00
"""
random_state = check_random_state(self.random_state)
X = check_array(X)
if self.n_components is None:
n_components = X.shape[1]
2012-06-27 01:00:51 +08:00
else:
n_components = self.n_components
2011-07-29 03:38:41 +08:00
code_init = self.V_init.T if self.V_init is not None else None
dict_init = self.U_init.T if self.U_init is not None else None
Vt, _, E, self.n_iter_ = dict_learning(X.T, n_components, self.alpha,
tol=self.tol,
max_iter=self.max_iter,
method=self.method,
n_jobs=self.n_jobs,
verbose=self.verbose,
random_state=random_state,
code_init=code_init,
dict_init=dict_init,
return_n_iter=True
)
2011-07-16 21:26:12 +08:00
self.components_ = Vt.T
2011-05-10 19:43:06 +08:00
self.error_ = E
return self
2011-07-31 20:33:45 +08:00
def transform(self, X, ridge_alpha=None):
"""Least Squares projection of the data onto the sparse components.
To avoid instability issues in case the system is under-determined,
2011-07-16 22:13:37 +08:00
regularization can be applied (Ridge regression) via the
`ridge_alpha` parameter.
Note that Sparse PCA components orthogonality is not enforced as in PCA
hence one cannot use a simple linear projection.
2011-05-26 18:15:52 +08:00
Parameters
----------
X: array of shape (n_samples, n_features)
Test data to be transformed, must have the same number of
features as the data used to train the model.
2011-06-13 21:41:50 +08:00
ridge_alpha: float, default: 0.01
2011-07-16 04:41:30 +08:00
Amount of ridge shrinkage to apply in order to improve
conditioning.
2011-05-26 18:15:52 +08:00
Returns
-------
X_new array, shape (n_samples, n_components)
2011-07-16 04:41:30 +08:00
Transformed data.
2011-05-26 18:15:52 +08:00
"""
check_is_fitted(self, 'components_')
X = check_array(X)
2011-07-31 20:33:45 +08:00
ridge_alpha = self.ridge_alpha if ridge_alpha is None else ridge_alpha
2011-07-16 00:30:42 +08:00
U = ridge_regression(self.components_.T, X.T, ridge_alpha,
solver='cholesky')
s = np.sqrt((U ** 2).sum(axis=0))
s[s == 0] = 1
U /= s
2011-05-10 20:13:34 +08:00
return U
2011-07-22 08:38:11 +08:00
2011-07-22 19:53:47 +08:00
class MiniBatchSparsePCA(SparsePCA):
"""Mini-batch Sparse Principal Components Analysis
2011-07-22 08:38:11 +08:00
Finds the set of sparse components that can optimally reconstruct
the data. The amount of sparseness is controllable by the coefficient
of the L1 penalty, given by the parameter alpha.
2015-06-03 12:24:04 +08:00
Read more in the :ref:`User Guide <SparsePCA>`.
Parameters
----------
n_components : int,
number of sparse atoms to extract
alpha : int,
Sparsity controlling parameter. Higher values lead to sparser
components.
ridge_alpha : float,
2011-07-31 20:33:45 +08:00
Amount of ridge shrinkage to apply in order to improve
conditioning when calling the transform method.
n_iter : int,
number of iterations to perform for each mini batch
callback : callable,
callable that gets invoked every five iterations
batch_size : int,
2011-07-22 22:31:34 +08:00
the number of features to take in each mini batch
verbose :
degree of output the procedure will print
shuffle : boolean,
whether to shuffle the data before splitting it in batches
n_jobs : int,
number of parallel jobs to run, or -1 to autodetect.
method : {'lars', 'cd'}
2011-09-19 17:11:33 +08:00
lars: uses the least angle regression method to solve the lasso problem
2011-08-25 00:57:05 +08:00
(linear_model.lars_path)
2011-09-19 17:11:33 +08:00
cd: uses the coordinate descent method to compute the
Lasso solution (linear_model.Lasso). Lars will be faster if
the estimated components are sparse.
random_state : int or RandomState
Pseudo number generator state used for random sampling.
2011-12-20 18:06:59 +08:00
Attributes
----------
components_ : array, [n_components, n_features]
2011-12-20 18:06:59 +08:00
Sparse components extracted from the data.
error_ : array
2011-12-20 18:06:59 +08:00
Vector of errors at each iteration.
n_iter_ : int
Number of iterations run.
2011-12-20 18:06:59 +08:00
See also
--------
PCA
SparsePCA
DictionaryLearning
2011-07-22 08:38:11 +08:00
"""
def __init__(self, n_components=None, alpha=1, ridge_alpha=0.01,
n_iter=100, callback=None, batch_size=3, verbose=False,
shuffle=True, n_jobs=1, method='lars', random_state=None):
2011-07-22 08:38:11 +08:00
self.n_components = n_components
self.alpha = alpha
2011-07-31 20:33:45 +08:00
self.ridge_alpha = ridge_alpha
2011-07-22 08:38:11 +08:00
self.n_iter = n_iter
self.callback = callback
self.batch_size = batch_size
2011-07-22 08:38:11 +08:00
self.verbose = verbose
self.shuffle = shuffle
self.n_jobs = n_jobs
self.method = method
self.random_state = random_state
2011-08-23 21:21:05 +08:00
def fit(self, X, y=None):
2011-07-22 08:38:11 +08:00
"""Fit the model from data in X.
Parameters
----------
X: array-like, shape (n_samples, n_features)
Training vector, where n_samples in the number of samples
and n_features is the number of features.
Returns
-------
self : object
Returns the instance itself.
"""
random_state = check_random_state(self.random_state)
X = check_array(X)
if self.n_components is None:
n_components = X.shape[1]
2012-06-27 01:00:51 +08:00
else:
n_components = self.n_components
Vt, _, self.n_iter_ = dict_learning_online(
X.T, n_components, alpha=self.alpha,
n_iter=self.n_iter, return_code=True,
dict_init=None, verbose=self.verbose,
callback=self.callback,
batch_size=self.batch_size,
shuffle=self.shuffle,
n_jobs=self.n_jobs, method=self.method,
random_state=random_state,
2015-06-03 12:24:04 +08:00
return_n_iter=True)
2011-07-22 08:38:11 +08:00
self.components_ = Vt.T
return self