sklearn.decomposition.PCA
class sklearn.decomposition.PCA(n_components=None, *, copy=True, whiten=False, svd_solver='auto', tol=0.0, iterated_power='auto', random_state=None) [source]

Principal component analysis (PCA). Linear dimensionality reduction using Singular Value Decomposition of the data to project it to a lower dimensional space. The input data is centered but not scaled for each feature before applying the SVD. It uses the LAPACK implementation of the full SVD or a randomized truncated SVD by the method of Halko et al. 2009, depending on the shape of the input data and the number of components to extract. It can also use the scipy.sparse.linalg ARPACK implementation of the truncated SVD. Notice that this class does not support sparse input. See TruncatedSVD for an alternative with sparse data. Read more in the User Guide.  Parameters

n_componentsint, float or ‘mle’, default=None

Number of components to keep. if n_components is not set all components are kept: n_components == min(n_samples, n_features)
 If n_components == 'mle' and svd_solver == 'full', Minka’s MLE is used to guess the dimension. Use of n_components == 'mle' will interpret svd_solver == 'auto' as svd_solver == 'full'. If 0 < n_components < 1 and svd_solver == 'full', select the number of components such that the amount of variance that needs to be explained is greater than the percentage specified by n_components. If svd_solver == 'arpack', the number of components must be strictly less than the minimum of n_features and n_samples. Hence, the None case results in: n_components == min(n_samples, n_features) - 1

copybool, default=True

If False, data passed to fit are overwritten and running fit(X).transform(X) will not yield the expected results, use fit_transform(X) instead.
whitenbool, default=False

When True (False by default) the components_ vectors are multiplied by the square root of n_samples and then divided by the singular values to ensure uncorrelated outputs with unit component-wise variances. Whitening will remove some information from the transformed signal (the relative variance scales of the components) but can sometime improve the predictive accuracy of the downstream estimators by making their data respect some hard-wired assumptions.
svd_solver{‘auto’, ‘full’, ‘arpack’, ‘randomized’}, default=’auto’

 If auto :

The solver is selected by a default policy based on X.shape and n_components: if the input data is larger than 500x500 and the number of components to extract is lower than 80% of the smallest dimension of the data, then the more efficient ‘randomized’ method is enabled. Otherwise the exact full SVD is computed and optionally truncated afterwards.  If full :

run exact full SVD calling the standard LAPACK solver via scipy.linalg.svd and select the components by postprocessing  If arpack :

run SVD truncated to n_components calling ARPACK solver via scipy.sparse.linalg.svds. It requires strictly 0 < n_components < min(X.shape)  If randomized :

run randomized SVD by the method of Halko et al.    New in version 0.18.0.
tolfloat, default=0.0

Tolerance for singular values computed by svd_solver == ‘arpack’. Must be of range [0.0, infinity).  New in version 0.18.0.
iterated_powerint or ‘auto’, default=’auto’

Number of iterations for the power method computed by svd_solver == ‘randomized’. Must be of range [0, infinity).  New in version 0.18.0.
random_stateint, RandomState instance or None, default=None

Used when the ‘arpack’ or ‘randomized’ solvers are used. Pass an int for reproducible results across multiple function calls. See Glossary.  New in version 0.18.0.     Attributes

components_ndarray of shape (n_components, n_features)

Principal axes in feature space, representing the directions of maximum variance in the data. The components are sorted by explained_variance_.
explained_variance_ndarray of shape (n_components,)

The amount of variance explained by each of the selected components. Equal to n_components largest eigenvalues of the covariance matrix of X.  New in version 0.18.
explained_variance_ratio_ndarray of shape (n_components,)

Percentage of variance explained by each of the selected components. If n_components is not set then all components are stored and the sum of the ratios is equal to 1.0.
singular_values_ndarray of shape (n_components,)

The singular values corresponding to each of the selected components. The singular values are equal to the 2-norms of the n_components variables in the lower-dimensional space.  New in version 0.19.
mean_ndarray of shape (n_features,)

Per-feature empirical mean, estimated from the training set. Equal to X.mean(axis=0).
n_components_int

The estimated number of components. When n_components is set to ‘mle’ or a number between 0 and 1 (with svd_solver == ‘full’) this number is estimated from input data. Otherwise it equals the parameter n_components, or the lesser value of n_features and n_samples if n_components is None.
n_features_int

Number of features in the training data.
n_samples_int

Number of samples in the training data.
noise_variance_float

The estimated noise covariance following the Probabilistic PCA model from Tipping and Bishop 1999. See “Pattern Recognition and Machine Learning” by C. Bishop, 12.2.1 p. 574 or http://www.miketipping.com/papers/met-mppca.pdf. It is required to compute the estimated data covariance and score samples. Equal to the average of (min(n_features, n_samples) - n_components) smallest eigenvalues of the covariance matrix of X.      See also
KernelPCA

Kernel Principal Component Analysis.
SparsePCA

Sparse Principal Component Analysis.
TruncatedSVD

Dimensionality reduction using truncated SVD.
IncrementalPCA

Incremental Principal Component Analysis.    References For n_components == ‘mle’, this class uses the method of Minka, T. P. “Automatic choice of dimensionality for PCA”. In NIPS, pp. 598-604 Implements the probabilistic PCA model from: Tipping, M. E., and Bishop, C. M. (1999). “Probabilistic principal component analysis”. Journal of the Royal Statistical Society: Series B (Statistical Methodology), 61(3), 611-622. via the score and score_samples methods. See http://www.miketipping.com/papers/met-mppca.pdf For svd_solver == ‘arpack’, refer to scipy.sparse.linalg.svds. For svd_solver == ‘randomized’, see: Halko, N., Martinsson, P. G., and Tropp, J. A. (2011). “Finding structure with randomness: Probabilistic algorithms for constructing approximate matrix decompositions”. SIAM review, 53(2), 217-288. and also Martinsson, P. G., Rokhlin, V., and Tygert, M. (2011). “A randomized algorithm for the decomposition of matrices”. Applied and Computational Harmonic Analysis, 30(1), 47-68. Examples >>> import numpy as np
>>> from sklearn.decomposition import PCA
>>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
>>> pca = PCA(n_components=2)
>>> pca.fit(X)
PCA(n_components=2)
>>> print(pca.explained_variance_ratio_)
[0.9924... 0.0075...]
>>> print(pca.singular_values_)
[6.30061... 0.54980...]
 >>> pca = PCA(n_components=2, svd_solver='full')
>>> pca.fit(X)
PCA(n_components=2, svd_solver='full')
>>> print(pca.explained_variance_ratio_)
[0.9924... 0.00755...]
>>> print(pca.singular_values_)
[6.30061... 0.54980...]
 >>> pca = PCA(n_components=1, svd_solver='arpack')
>>> pca.fit(X)
PCA(n_components=1, svd_solver='arpack')
>>> print(pca.explained_variance_ratio_)
[0.99244...]
>>> print(pca.singular_values_)
[6.30061...]
 Methods
fit(X[, y]) Fit the model with X.
fit_transform(X[, y]) Fit the model with X and apply the dimensionality reduction on X.
get_covariance() Compute data covariance with the generative model.
get_params([deep]) Get parameters for this estimator.
get_precision() Compute data precision matrix with the generative model.
inverse_transform(X) Transform data back to its original space.
score(X[, y]) Return the average log-likelihood of all samples.
score_samples(X) Return the log-likelihood of each sample.
set_params(**params) Set the parameters of this estimator.
transform(X) Apply dimensionality reduction to X.
fit(X, y=None) [source]

Fit the model with X.  Parameters

Xarray-like of shape (n_samples, n_features)

Training data, where n_samples is the number of samples and n_features is the number of features.
yIgnored
  Returns

selfobject

Returns the instance itself.

fit_transform(X, y=None) [source]

Fit the model with X and apply the dimensionality reduction on X.  Parameters

Xarray-like of shape (n_samples, n_features)

Training data, where n_samples is the number of samples and n_features is the number of features.
yIgnored
  Returns

X_newndarray of shape (n_samples, n_components)

Transformed values.     Notes This method returns a Fortran-ordered array. To convert it to a C-ordered array, use ‘np.ascontiguousarray’.

get_covariance() [source]

Compute data covariance with the generative model. cov = components_.T * S**2 * components_ + sigma2 * eye(n_features) where S**2 contains the explained variances, and sigma2 contains the noise variances.  Returns

covarray, shape=(n_features, n_features)

Estimated covariance of data.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

get_precision() [source]

Compute data precision matrix with the generative model. Equals the inverse of the covariance but computed with the matrix inversion lemma for efficiency.  Returns

precisionarray, shape=(n_features, n_features)

Estimated precision of data.

inverse_transform(X) [source]

Transform data back to its original space. In other words, return an input X_original whose transform would be X.  Parameters

Xarray-like, shape (n_samples, n_components)

New data, where n_samples is the number of samples and n_components is the number of components.    Returns
 X_original array-like, shape (n_samples, n_features)
   Notes If whitening is enabled, inverse_transform will compute the exact inverse operation, which includes reversing whitening.

score(X, y=None) [source]

Return the average log-likelihood of all samples. See. “Pattern Recognition and Machine Learning” by C. Bishop, 12.2.1 p. 574 or http://www.miketipping.com/papers/met-mppca.pdf  Parameters

Xarray-like of shape (n_samples, n_features)

The data.
yIgnored
  Returns

llfloat

Average log-likelihood of the samples under the current model.

score_samples(X) [source]

Return the log-likelihood of each sample. See. “Pattern Recognition and Machine Learning” by C. Bishop, 12.2.1 p. 574 or http://www.miketipping.com/papers/met-mppca.pdf  Parameters

Xarray-like of shape (n_samples, n_features)

The data.    Returns

llndarray of shape (n_samples,)

Log-likelihood of each sample under the current model.

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

transform(X) [source]

Apply dimensionality reduction to X. X is projected on the first principal components previously extracted from a training set.  Parameters

Xarray-like, shape (n_samples, n_features)

New data, where n_samples is the number of samples and n_features is the number of features.    Returns

X_newarray-like, shape (n_samples, n_components)
   Examples >>> import numpy as np
>>> from sklearn.decomposition import IncrementalPCA
>>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
>>> ipca = IncrementalPCA(n_components=2, batch_size=3)
>>> ipca.fit(X)
IncrementalPCA(batch_size=3, n_components=2)
>>> ipca.transform(X)

 Examples using sklearn.decomposition.PCA

  A demo of K-Means clustering on the handwritten digits data

  Principal Component Regression vs Partial Least Squares Regression

  The Iris Dataset

  PCA example with Iris Data-set

  Incremental PCA

  Comparison of LDA and PCA 2D projection of Iris dataset

  Factor Analysis (with rotation) to visualize patterns

  Blind source separation using FastICA

  Principal components analysis (PCA)

  FastICA on 2D point clouds

  Kernel PCA

  Model selection with Probabilistic PCA and Factor Analysis (FA)

  Faces dataset decompositions

  Faces recognition example using eigenfaces and SVMs

  Multi-dimensional scaling

  Multilabel classification

  Explicit feature map approximation for RBF kernels

  Balance model complexity and cross-validated score

  Kernel Density Estimation

  Dimensionality Reduction with Neighborhood Components Analysis

  Concatenating multiple feature extraction methods

  Pipelining: chaining a PCA and a logistic regression

  Selecting dimensionality reduction with Pipeline and GridSearchCV

  Importance of Feature Scaling


fit(X, y=None) [source]

Fit the model with X.  Parameters

Xarray-like of shape (n_samples, n_features)

Training data, where n_samples is the number of samples and n_features is the number of features.
yIgnored
  Returns

selfobject

Returns the instance itself.


fit_transform(X, y=None) [source]

Fit the model with X and apply the dimensionality reduction on X.  Parameters

Xarray-like of shape (n_samples, n_features)

Training data, where n_samples is the number of samples and n_features is the number of features.
yIgnored
  Returns

X_newndarray of shape (n_samples, n_components)

Transformed values.     Notes This method returns a Fortran-ordered array. To convert it to a C-ordered array, use ‘np.ascontiguousarray’.


get_covariance() [source]

Compute data covariance with the generative model. cov = components_.T * S**2 * components_ + sigma2 * eye(n_features) where S**2 contains the explained variances, and sigma2 contains the noise variances.  Returns

covarray, shape=(n_features, n_features)

Estimated covariance of data.


get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.


get_precision() [source]

Compute data precision matrix with the generative model. Equals the inverse of the covariance but computed with the matrix inversion lemma for efficiency.  Returns

precisionarray, shape=(n_features, n_features)

Estimated precision of data.


inverse_transform(X) [source]

Transform data back to its original space. In other words, return an input X_original whose transform would be X.  Parameters

Xarray-like, shape (n_samples, n_components)

New data, where n_samples is the number of samples and n_components is the number of components.    Returns
 X_original array-like, shape (n_samples, n_features)
   Notes If whitening is enabled, inverse_transform will compute the exact inverse operation, which includes reversing whitening.


score(X, y=None) [source]

Return the average log-likelihood of all samples. See. “Pattern Recognition and Machine Learning” by C. Bishop, 12.2.1 p. 574 or http://www.miketipping.com/papers/met-mppca.pdf  Parameters

Xarray-like of shape (n_samples, n_features)

The data.
yIgnored
  Returns

llfloat

Average log-likelihood of the samples under the current model.


score_samples(X) [source]

Return the log-likelihood of each sample. See. “Pattern Recognition and Machine Learning” by C. Bishop, 12.2.1 p. 574 or http://www.miketipping.com/papers/met-mppca.pdf  Parameters

Xarray-like of shape (n_samples, n_features)

The data.    Returns

llndarray of shape (n_samples,)

Log-likelihood of each sample under the current model.


set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.


transform(X) [source]

Apply dimensionality reduction to X. X is projected on the first principal components previously extracted from a training set.  Parameters

Xarray-like, shape (n_samples, n_features)

New data, where n_samples is the number of samples and n_features is the number of features.    Returns

X_newarray-like, shape (n_samples, n_components)
   Examples >>> import numpy as np
>>> from sklearn.decomposition import IncrementalPCA
>>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
>>> ipca = IncrementalPCA(n_components=2, batch_size=3)
>>> ipca.fit(X)
IncrementalPCA(batch_size=3, n_components=2)
>>> ipca.transform(X)


class sklearn.decomposition.SparseCoder(dictionary, *, transform_algorithm='omp', transform_n_nonzero_coefs=None, transform_alpha=None, split_sign=False, n_jobs=None, positive_code=False, transform_max_iter=1000) [source]

Sparse coding Finds a sparse representation of data against a fixed, precomputed dictionary. Each row of the result is the solution to a sparse coding problem. The goal is to find a sparse array code such that: X ~= code * dictionary
 Read more in the User Guide.  Parameters

dictionaryndarray of shape (n_components, n_features)

The dictionary atoms used for sparse coding. Lines are assumed to be normalized to unit norm.
transform_algorithm{‘lasso_lars’, ‘lasso_cd’, ‘lars’, ‘omp’, ‘threshold’}, default=’omp’

Algorithm used to transform the data:
'lars': uses the least angle regression method (linear_model.lars_path);
'lasso_lars': uses Lars to compute the Lasso solution;
'lasso_cd': uses the coordinate descent method to compute the Lasso solution (linear_model.Lasso). 'lasso_lars' will be faster if the estimated components are sparse;
'omp': uses orthogonal matching pursuit to estimate the sparse solution;
'threshold': squashes to zero all coefficients less than alpha from the projection dictionary * X'.
transform_n_nonzero_coefsint, default=None

Number of nonzero coefficients to target in each column of the solution. This is only used by algorithm='lars' and algorithm='omp' and is overridden by alpha in the omp case. If None, then transform_n_nonzero_coefs=int(n_features / 10).
transform_alphafloat, default=None

If algorithm='lasso_lars' or algorithm='lasso_cd', alpha is the penalty applied to the L1 norm. If algorithm='threshold', alpha is the absolute value of the threshold below which coefficients will be squashed to zero. If algorithm='omp', alpha is the tolerance parameter: the value of the reconstruction error targeted. In this case, it overrides n_nonzero_coefs. If None, default to 1.
split_signbool, default=False

Whether to split the sparse feature vector into the concatenation of its negative part and its positive part. This can improve the performance of downstream classifiers.
n_jobsint, default=None

Number of parallel jobs to run. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.
positive_codebool, default=False

Whether to enforce positivity when finding the code.  New in version 0.20.
transform_max_iterint, default=1000

Maximum number of iterations to perform if algorithm='lasso_cd' or lasso_lars.  New in version 0.22.     Attributes

components_ndarray of shape (n_components, n_features)

The unchanged dictionary atoms.  Deprecated since version 0.24: This attribute is deprecated in 0.24 and will be removed in 1.1 (renaming of 0.26). Use dictionary instead.       See also
DictionaryLearning

MiniBatchDictionaryLearning

SparsePCA

MiniBatchSparsePCA

sparse_encode

  Examples >>> import numpy as np
>>> from sklearn.decomposition import SparseCoder
>>> X = np.array([[-1, -1, -1], [0, 0, 3]])
>>> dictionary = np.array(
...     [[0, 1, 0],
...      [-1, -1, 2],
...      [1, 1, 1],
...      [0, 1, 1],
...      [0, 2, 1]],
...    dtype=np.float64
... )
>>> coder = SparseCoder(
...     dictionary=dictionary, transform_algorithm='lasso_lars',
...     transform_alpha=1e-10,
... )
>>> coder.transform(X)
array([[ 0.,  0., -1.,  0.,  0.],
       [ 0.,  1.,  1.,  0.,  0.]])
 Methods
fit(X[, y]) Do nothing and return the estimator unchanged.
fit_transform(X[, y]) Fit to data, then transform it.
get_params([deep]) Get parameters for this estimator.
set_params(**params) Set the parameters of this estimator.
transform(X[, y]) Encode the data as a sparse combination of the dictionary atoms.
fit(X, y=None) [source]

Do nothing and return the estimator unchanged. This method is just there to implement the usual API and hence work in pipelines.  Parameters

XIgnored

yIgnored
  Returns

selfobject

fit_transform(X, y=None, **fit_params) [source]

Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.  Parameters

Xarray-like of shape (n_samples, n_features)

Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None

Target values (None for unsupervised transformations).
**fit_paramsdict

Additional fit parameters.    Returns

X_newndarray array of shape (n_samples, n_features_new)

Transformed array.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

transform(X, y=None) [source]

Encode the data as a sparse combination of the dictionary atoms. Coding method is determined by the object parameter transform_algorithm.  Parameters

Xndarray 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.    Returns

X_newndarray of shape (n_samples, n_components)

Transformed data.


sklearn.decomposition.SparseCoder
class sklearn.decomposition.SparseCoder(dictionary, *, transform_algorithm='omp', transform_n_nonzero_coefs=None, transform_alpha=None, split_sign=False, n_jobs=None, positive_code=False, transform_max_iter=1000) [source]

Sparse coding Finds a sparse representation of data against a fixed, precomputed dictionary. Each row of the result is the solution to a sparse coding problem. The goal is to find a sparse array code such that: X ~= code * dictionary
 Read more in the User Guide.  Parameters

dictionaryndarray of shape (n_components, n_features)

The dictionary atoms used for sparse coding. Lines are assumed to be normalized to unit norm.
transform_algorithm{‘lasso_lars’, ‘lasso_cd’, ‘lars’, ‘omp’, ‘threshold’}, default=’omp’

Algorithm used to transform the data:
'lars': uses the least angle regression method (linear_model.lars_path);
'lasso_lars': uses Lars to compute the Lasso solution;
'lasso_cd': uses the coordinate descent method to compute the Lasso solution (linear_model.Lasso). 'lasso_lars' will be faster if the estimated components are sparse;
'omp': uses orthogonal matching pursuit to estimate the sparse solution;
'threshold': squashes to zero all coefficients less than alpha from the projection dictionary * X'.
transform_n_nonzero_coefsint, default=None

Number of nonzero coefficients to target in each column of the solution. This is only used by algorithm='lars' and algorithm='omp' and is overridden by alpha in the omp case. If None, then transform_n_nonzero_coefs=int(n_features / 10).
transform_alphafloat, default=None

If algorithm='lasso_lars' or algorithm='lasso_cd', alpha is the penalty applied to the L1 norm. If algorithm='threshold', alpha is the absolute value of the threshold below which coefficients will be squashed to zero. If algorithm='omp', alpha is the tolerance parameter: the value of the reconstruction error targeted. In this case, it overrides n_nonzero_coefs. If None, default to 1.
split_signbool, default=False

Whether to split the sparse feature vector into the concatenation of its negative part and its positive part. This can improve the performance of downstream classifiers.
n_jobsint, default=None

Number of parallel jobs to run. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.
positive_codebool, default=False

Whether to enforce positivity when finding the code.  New in version 0.20.
transform_max_iterint, default=1000

Maximum number of iterations to perform if algorithm='lasso_cd' or lasso_lars.  New in version 0.22.     Attributes

components_ndarray of shape (n_components, n_features)

The unchanged dictionary atoms.  Deprecated since version 0.24: This attribute is deprecated in 0.24 and will be removed in 1.1 (renaming of 0.26). Use dictionary instead.       See also
DictionaryLearning

MiniBatchDictionaryLearning

SparsePCA

MiniBatchSparsePCA

sparse_encode

  Examples >>> import numpy as np
>>> from sklearn.decomposition import SparseCoder
>>> X = np.array([[-1, -1, -1], [0, 0, 3]])
>>> dictionary = np.array(
...     [[0, 1, 0],
...      [-1, -1, 2],
...      [1, 1, 1],
...      [0, 1, 1],
...      [0, 2, 1]],
...    dtype=np.float64
... )
>>> coder = SparseCoder(
...     dictionary=dictionary, transform_algorithm='lasso_lars',
...     transform_alpha=1e-10,
... )
>>> coder.transform(X)
array([[ 0.,  0., -1.,  0.,  0.],
       [ 0.,  1.,  1.,  0.,  0.]])
 Methods
fit(X[, y]) Do nothing and return the estimator unchanged.
fit_transform(X[, y]) Fit to data, then transform it.
get_params([deep]) Get parameters for this estimator.
set_params(**params) Set the parameters of this estimator.
transform(X[, y]) Encode the data as a sparse combination of the dictionary atoms.
fit(X, y=None) [source]

Do nothing and return the estimator unchanged. This method is just there to implement the usual API and hence work in pipelines.  Parameters

XIgnored

yIgnored
  Returns

selfobject

fit_transform(X, y=None, **fit_params) [source]

Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.  Parameters

Xarray-like of shape (n_samples, n_features)

Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None

Target values (None for unsupervised transformations).
**fit_paramsdict

Additional fit parameters.    Returns

X_newndarray array of shape (n_samples, n_features_new)

Transformed array.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

transform(X, y=None) [source]

Encode the data as a sparse combination of the dictionary atoms. Coding method is determined by the object parameter transform_algorithm.  Parameters

Xndarray 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.    Returns

X_newndarray of shape (n_samples, n_components)

Transformed data.

 Examples using sklearn.decomposition.SparseCoder

  Sparse coding with a precomputed dictionary


fit(X, y=None) [source]

Do nothing and return the estimator unchanged. This method is just there to implement the usual API and hence work in pipelines.  Parameters

XIgnored

yIgnored
  Returns

selfobject


fit_transform(X, y=None, **fit_params) [source]

Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.  Parameters

Xarray-like of shape (n_samples, n_features)

Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None

Target values (None for unsupervised transformations).
**fit_paramsdict

Additional fit parameters.    Returns

X_newndarray array of shape (n_samples, n_features_new)

Transformed array.


transform(X, y=None) [source]

Encode the data as a sparse combination of the dictionary atoms. Coding method is determined by the object parameter transform_algorithm.  Parameters

Xndarray 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.    Returns

X_newndarray of shape (n_samples, n_components)

Transformed data.


class sklearn.decomposition.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) [source]

Sparse Principal Components Analysis (SparsePCA). 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. Read more in the User Guide.  Parameters

n_componentsint, default=None

Number of sparse atoms to extract.
alphafloat, default=1

Sparsity controlling parameter. Higher values lead to sparser components.
ridge_alphafloat, default=0.01

Amount of ridge shrinkage to apply in order to improve conditioning when calling the transform method.
max_iterint, default=1000

Maximum number of iterations to perform.
tolfloat, default=1e-8

Tolerance for the stopping condition.
method{‘lars’, ‘cd’}, default=’lars’

lars: uses the least angle regression method to solve the lasso problem (linear_model.lars_path) cd: uses the coordinate descent method to compute the Lasso solution (linear_model.Lasso). Lars will be faster if the estimated components are sparse.
n_jobsint, default=None

Number of parallel jobs to run. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.
U_initndarray of shape (n_samples, n_components), default=None

Initial values for the loadings for warm restart scenarios.
V_initndarray of shape (n_components, n_features), default=None

Initial values for the components for warm restart scenarios.
verboseint or bool, default=False

Controls the verbosity; the higher, the more messages. Defaults to 0.
random_stateint, RandomState instance or None, default=None

Used during dictionary learning. Pass an int for reproducible results across multiple function calls. See Glossary.    Attributes

components_ndarray of shape (n_components, n_features)

Sparse components extracted from the data.
error_ndarray

Vector of errors at each iteration.
n_components_int

Estimated number of components.  New in version 0.23.
n_iter_int

Number of iterations run.
mean_ndarray of shape (n_features,)

Per-feature empirical mean, estimated from the training set. Equal to X.mean(axis=0).      See also
PCA

MiniBatchSparsePCA

DictionaryLearning

  Examples >>> import numpy as np
>>> from sklearn.datasets import make_friedman1
>>> from sklearn.decomposition import SparsePCA
>>> X, _ = make_friedman1(n_samples=200, n_features=30, random_state=0)
>>> transformer = SparsePCA(n_components=5, random_state=0)
>>> transformer.fit(X)
SparsePCA(...)
>>> X_transformed = transformer.transform(X)
>>> X_transformed.shape
(200, 5)
>>> # most values in the components_ are zero (sparsity)
>>> np.mean(transformer.components_ == 0)
0.9666...
 Methods
fit(X[, y]) Fit the model from data in X.
fit_transform(X[, y]) Fit to data, then transform it.
get_params([deep]) Get parameters for this estimator.
set_params(**params) Set the parameters of this estimator.
transform(X) Least Squares projection of the data onto the sparse components.
fit(X, y=None) [source]

Fit the model from data in X.  Parameters

Xarray-like of shape (n_samples, n_features)

Training vector, where n_samples in the number of samples and n_features is the number of features.
yIgnored
  Returns

selfobject

Returns the instance itself.

fit_transform(X, y=None, **fit_params) [source]

Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.  Parameters

Xarray-like of shape (n_samples, n_features)

Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None

Target values (None for unsupervised transformations).
**fit_paramsdict

Additional fit parameters.    Returns

X_newndarray array of shape (n_samples, n_features_new)

Transformed array.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

transform(X) [source]

Least Squares projection of the data onto the sparse components. To avoid instability issues in case the system is under-determined, 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.  Parameters

Xndarray 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.    Returns

X_newndarray of shape (n_samples, n_components)

Transformed data.


sklearn.decomposition.SparsePCA
class sklearn.decomposition.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) [source]

Sparse Principal Components Analysis (SparsePCA). 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. Read more in the User Guide.  Parameters

n_componentsint, default=None

Number of sparse atoms to extract.
alphafloat, default=1

Sparsity controlling parameter. Higher values lead to sparser components.
ridge_alphafloat, default=0.01

Amount of ridge shrinkage to apply in order to improve conditioning when calling the transform method.
max_iterint, default=1000

Maximum number of iterations to perform.
tolfloat, default=1e-8

Tolerance for the stopping condition.
method{‘lars’, ‘cd’}, default=’lars’

lars: uses the least angle regression method to solve the lasso problem (linear_model.lars_path) cd: uses the coordinate descent method to compute the Lasso solution (linear_model.Lasso). Lars will be faster if the estimated components are sparse.
n_jobsint, default=None

Number of parallel jobs to run. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.
U_initndarray of shape (n_samples, n_components), default=None

Initial values for the loadings for warm restart scenarios.
V_initndarray of shape (n_components, n_features), default=None

Initial values for the components for warm restart scenarios.
verboseint or bool, default=False

Controls the verbosity; the higher, the more messages. Defaults to 0.
random_stateint, RandomState instance or None, default=None

Used during dictionary learning. Pass an int for reproducible results across multiple function calls. See Glossary.    Attributes

components_ndarray of shape (n_components, n_features)

Sparse components extracted from the data.
error_ndarray

Vector of errors at each iteration.
n_components_int

Estimated number of components.  New in version 0.23.
n_iter_int

Number of iterations run.
mean_ndarray of shape (n_features,)

Per-feature empirical mean, estimated from the training set. Equal to X.mean(axis=0).      See also
PCA

MiniBatchSparsePCA

DictionaryLearning

  Examples >>> import numpy as np
>>> from sklearn.datasets import make_friedman1
>>> from sklearn.decomposition import SparsePCA
>>> X, _ = make_friedman1(n_samples=200, n_features=30, random_state=0)
>>> transformer = SparsePCA(n_components=5, random_state=0)
>>> transformer.fit(X)
SparsePCA(...)
>>> X_transformed = transformer.transform(X)
>>> X_transformed.shape
(200, 5)
>>> # most values in the components_ are zero (sparsity)
>>> np.mean(transformer.components_ == 0)
0.9666...
 Methods
fit(X[, y]) Fit the model from data in X.
fit_transform(X[, y]) Fit to data, then transform it.
get_params([deep]) Get parameters for this estimator.
set_params(**params) Set the parameters of this estimator.
transform(X) Least Squares projection of the data onto the sparse components.
fit(X, y=None) [source]

Fit the model from data in X.  Parameters

Xarray-like of shape (n_samples, n_features)

Training vector, where n_samples in the number of samples and n_features is the number of features.
yIgnored
  Returns

selfobject

Returns the instance itself.

fit_transform(X, y=None, **fit_params) [source]

Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.  Parameters

Xarray-like of shape (n_samples, n_features)

Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None

Target values (None for unsupervised transformations).
**fit_paramsdict

Additional fit parameters.    Returns

X_newndarray array of shape (n_samples, n_features_new)

Transformed array.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

transform(X) [source]

Least Squares projection of the data onto the sparse components. To avoid instability issues in case the system is under-determined, 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.  Parameters

Xndarray 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.    Returns

X_newndarray of shape (n_samples, n_components)

Transformed data.


fit(X, y=None) [source]

Fit the model from data in X.  Parameters

Xarray-like of shape (n_samples, n_features)

Training vector, where n_samples in the number of samples and n_features is the number of features.
yIgnored
  Returns

selfobject

Returns the instance itself.


transform(X) [source]

Least Squares projection of the data onto the sparse components. To avoid instability issues in case the system is under-determined, 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.  Parameters

Xndarray 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.    Returns

X_newndarray of shape (n_samples, n_components)

Transformed data.


sklearn.decomposition.sparse_encode(X, dictionary, *, gram=None, cov=None, algorithm='lasso_lars', n_nonzero_coefs=None, alpha=None, copy_cov=True, init=None, max_iter=1000, n_jobs=None, check_input=True, verbose=0, positive=False) [source]

Sparse coding Each row of the result is the solution to a sparse coding problem. The goal is to find a sparse array code such that: X ~= code * dictionary
 Read more in the User Guide.  Parameters

Xndarray of shape (n_samples, n_features)

Data matrix.
dictionaryndarray of shape (n_components, n_features)

The dictionary matrix against which to solve the sparse coding of the data. Some of the algorithms assume normalized rows for meaningful output.
gramndarray of shape (n_components, n_components), default=None

Precomputed Gram matrix, dictionary * dictionary'.
covndarray of shape (n_components, n_samples), default=None

Precomputed covariance, dictionary' * X.
algorithm{‘lasso_lars’, ‘lasso_cd’, ‘lars’, ‘omp’, ‘threshold’}, default=’lasso_lars’

The algorithm used:
'lars': uses the least angle regression method (linear_model.lars_path);
'lasso_lars': uses Lars to compute the Lasso solution;
'lasso_cd': uses the coordinate descent method to compute the Lasso solution (linear_model.Lasso). lasso_lars will be faster if the estimated components are sparse;
'omp': uses orthogonal matching pursuit to estimate the sparse solution;
'threshold': squashes to zero all coefficients less than regularization from the projection dictionary * data'.
n_nonzero_coefsint, default=None

Number of nonzero coefficients to target in each column of the solution. This is only used by algorithm='lars' and algorithm='omp' and is overridden by alpha in the omp case. If None, then n_nonzero_coefs=int(n_features / 10).
alphafloat, default=None

If algorithm='lasso_lars' or algorithm='lasso_cd', alpha is the penalty applied to the L1 norm. If algorithm='threshold', alpha is the absolute value of the threshold below which coefficients will be squashed to zero. If algorithm='omp', alpha is the tolerance parameter: the value of the reconstruction error targeted. In this case, it overrides n_nonzero_coefs. If None, default to 1.
copy_covbool, default=True

Whether to copy the precomputed covariance matrix; if False, it may be overwritten.
initndarray of shape (n_samples, n_components), default=None

Initialization value of the sparse codes. Only used if algorithm='lasso_cd'.
max_iterint, default=1000

Maximum number of iterations to perform if algorithm='lasso_cd' or 'lasso_lars'.
n_jobsint, default=None

Number of parallel jobs to run. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.
check_inputbool, default=True

If False, the input arrays X and dictionary will not be checked.
verboseint, default=0

Controls the verbosity; the higher, the more messages.
positivebool, default=False

Whether to enforce positivity when finding the encoding.  New in version 0.20.     Returns

codendarray of shape (n_samples, n_components)

The sparse codes      See also
sklearn.linear_model.lars_path

sklearn.linear_model.orthogonal_mp

sklearn.linear_model.Lasso

SparseCoder


class sklearn.decomposition.TruncatedSVD(n_components=2, *, algorithm='randomized', n_iter=5, random_state=None, tol=0.0) [source]

Dimensionality reduction using truncated SVD (aka LSA). This transformer performs linear dimensionality reduction by means of truncated singular value decomposition (SVD). Contrary to PCA, this estimator does not center the data before computing the singular value decomposition. This means it can work with sparse matrices efficiently. In particular, truncated SVD works on term count/tf-idf matrices as returned by the vectorizers in sklearn.feature_extraction.text. In that context, it is known as latent semantic analysis (LSA). This estimator supports two algorithms: a fast randomized SVD solver, and a “naive” algorithm that uses ARPACK as an eigensolver on X * X.T or X.T * X, whichever is more efficient. Read more in the User Guide.  Parameters

n_componentsint, default=2

Desired dimensionality of output data. Must be strictly less than the number of features. The default value is useful for visualisation. For LSA, a value of 100 is recommended.
algorithm{‘arpack’, ‘randomized’}, default=’randomized’

SVD solver to use. Either “arpack” for the ARPACK wrapper in SciPy (scipy.sparse.linalg.svds), or “randomized” for the randomized algorithm due to Halko (2009).
n_iterint, default=5

Number of iterations for randomized SVD solver. Not used by ARPACK. The default is larger than the default in randomized_svd to handle sparse matrices that may have large slowly decaying spectrum.
random_stateint, RandomState instance or None, default=None

Used during randomized svd. Pass an int for reproducible results across multiple function calls. See Glossary.
tolfloat, default=0.

Tolerance for ARPACK. 0 means machine precision. Ignored by randomized SVD solver.    Attributes

components_ndarray of shape (n_components, n_features)

explained_variance_ndarray of shape (n_components,)

The variance of the training samples transformed by a projection to each component.
explained_variance_ratio_ndarray of shape (n_components,)

Percentage of variance explained by each of the selected components.
singular_values_ndarray od shape (n_components,)

The singular values corresponding to each of the selected components. The singular values are equal to the 2-norms of the n_components variables in the lower-dimensional space.      See also
PCA

  Notes SVD suffers from a problem called “sign indeterminacy”, which means the sign of the components_ and the output from transform depend on the algorithm and random state. To work around this, fit instances of this class to data once, then keep the instance around to do transformations. References Finding structure with randomness: Stochastic algorithms for constructing approximate matrix decompositions Halko, et al., 2009 (arXiv:909) https://arxiv.org/pdf/0909.4061.pdf Examples >>> from sklearn.decomposition import TruncatedSVD
>>> from scipy.sparse import random as sparse_random
>>> X = sparse_random(100, 100, density=0.01, format='csr',
...                   random_state=42)
>>> svd = TruncatedSVD(n_components=5, n_iter=7, random_state=42)
>>> svd.fit(X)
TruncatedSVD(n_components=5, n_iter=7, random_state=42)
>>> print(svd.explained_variance_ratio_)
[0.0646... 0.0633... 0.0639... 0.0535... 0.0406...]
>>> print(svd.explained_variance_ratio_.sum())
0.286...
>>> print(svd.singular_values_)
[1.553... 1.512...  1.510... 1.370... 1.199...]
 Methods
fit(X[, y]) Fit model on training data X.
fit_transform(X[, y]) Fit model to X and perform dimensionality reduction on X.
get_params([deep]) Get parameters for this estimator.
inverse_transform(X) Transform X back to its original space.
set_params(**params) Set the parameters of this estimator.
transform(X) Perform dimensionality reduction on X.
fit(X, y=None) [source]

Fit model on training data X.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

Training data.
yIgnored
  Returns

selfobject

Returns the transformer object.

fit_transform(X, y=None) [source]

Fit model to X and perform dimensionality reduction on X.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

Training data.
yIgnored
  Returns

X_newndarray of shape (n_samples, n_components)

Reduced version of X. This will always be a dense array.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

inverse_transform(X) [source]

Transform X back to its original space. Returns an array X_original whose transform would be X.  Parameters

Xarray-like of shape (n_samples, n_components)

New data.    Returns

X_originalndarray of shape (n_samples, n_features)

Note that this is always a dense array.

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

transform(X) [source]

Perform dimensionality reduction on X.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

New data.    Returns

X_newndarray of shape (n_samples, n_components)

Reduced version of X. This will always be a dense array.


sklearn.decomposition.TruncatedSVD
class sklearn.decomposition.TruncatedSVD(n_components=2, *, algorithm='randomized', n_iter=5, random_state=None, tol=0.0) [source]

Dimensionality reduction using truncated SVD (aka LSA). This transformer performs linear dimensionality reduction by means of truncated singular value decomposition (SVD). Contrary to PCA, this estimator does not center the data before computing the singular value decomposition. This means it can work with sparse matrices efficiently. In particular, truncated SVD works on term count/tf-idf matrices as returned by the vectorizers in sklearn.feature_extraction.text. In that context, it is known as latent semantic analysis (LSA). This estimator supports two algorithms: a fast randomized SVD solver, and a “naive” algorithm that uses ARPACK as an eigensolver on X * X.T or X.T * X, whichever is more efficient. Read more in the User Guide.  Parameters

n_componentsint, default=2

Desired dimensionality of output data. Must be strictly less than the number of features. The default value is useful for visualisation. For LSA, a value of 100 is recommended.
algorithm{‘arpack’, ‘randomized’}, default=’randomized’

SVD solver to use. Either “arpack” for the ARPACK wrapper in SciPy (scipy.sparse.linalg.svds), or “randomized” for the randomized algorithm due to Halko (2009).
n_iterint, default=5

Number of iterations for randomized SVD solver. Not used by ARPACK. The default is larger than the default in randomized_svd to handle sparse matrices that may have large slowly decaying spectrum.
random_stateint, RandomState instance or None, default=None

Used during randomized svd. Pass an int for reproducible results across multiple function calls. See Glossary.
tolfloat, default=0.

Tolerance for ARPACK. 0 means machine precision. Ignored by randomized SVD solver.    Attributes

components_ndarray of shape (n_components, n_features)

explained_variance_ndarray of shape (n_components,)

The variance of the training samples transformed by a projection to each component.
explained_variance_ratio_ndarray of shape (n_components,)

Percentage of variance explained by each of the selected components.
singular_values_ndarray od shape (n_components,)

The singular values corresponding to each of the selected components. The singular values are equal to the 2-norms of the n_components variables in the lower-dimensional space.      See also
PCA

  Notes SVD suffers from a problem called “sign indeterminacy”, which means the sign of the components_ and the output from transform depend on the algorithm and random state. To work around this, fit instances of this class to data once, then keep the instance around to do transformations. References Finding structure with randomness: Stochastic algorithms for constructing approximate matrix decompositions Halko, et al., 2009 (arXiv:909) https://arxiv.org/pdf/0909.4061.pdf Examples >>> from sklearn.decomposition import TruncatedSVD
>>> from scipy.sparse import random as sparse_random
>>> X = sparse_random(100, 100, density=0.01, format='csr',
...                   random_state=42)
>>> svd = TruncatedSVD(n_components=5, n_iter=7, random_state=42)
>>> svd.fit(X)
TruncatedSVD(n_components=5, n_iter=7, random_state=42)
>>> print(svd.explained_variance_ratio_)
[0.0646... 0.0633... 0.0639... 0.0535... 0.0406...]
>>> print(svd.explained_variance_ratio_.sum())
0.286...
>>> print(svd.singular_values_)
[1.553... 1.512...  1.510... 1.370... 1.199...]
 Methods
fit(X[, y]) Fit model on training data X.
fit_transform(X[, y]) Fit model to X and perform dimensionality reduction on X.
get_params([deep]) Get parameters for this estimator.
inverse_transform(X) Transform X back to its original space.
set_params(**params) Set the parameters of this estimator.
transform(X) Perform dimensionality reduction on X.
fit(X, y=None) [source]

Fit model on training data X.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

Training data.
yIgnored
  Returns

selfobject

Returns the transformer object.

fit_transform(X, y=None) [source]

Fit model to X and perform dimensionality reduction on X.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

Training data.
yIgnored
  Returns

X_newndarray of shape (n_samples, n_components)

Reduced version of X. This will always be a dense array.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

inverse_transform(X) [source]

Transform X back to its original space. Returns an array X_original whose transform would be X.  Parameters

Xarray-like of shape (n_samples, n_components)

New data.    Returns

X_originalndarray of shape (n_samples, n_features)

Note that this is always a dense array.

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

transform(X) [source]

Perform dimensionality reduction on X.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

New data.    Returns

X_newndarray of shape (n_samples, n_components)

Reduced version of X. This will always be a dense array.

 Examples using sklearn.decomposition.TruncatedSVD

  Hashing feature transformation using Totally Random Trees

  Manifold learning on handwritten digits: Locally Linear Embedding, Isomap…

  Column Transformer with Heterogeneous Data Sources

  Clustering text documents using k-means


fit(X, y=None) [source]

Fit model on training data X.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

Training data.
yIgnored
  Returns

selfobject

Returns the transformer object.


fit_transform(X, y=None) [source]

Fit model to X and perform dimensionality reduction on X.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

Training data.
yIgnored
  Returns

X_newndarray of shape (n_samples, n_components)

Reduced version of X. This will always be a dense array.


get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.


inverse_transform(X) [source]

Transform X back to its original space. Returns an array X_original whose transform would be X.  Parameters

Xarray-like of shape (n_samples, n_components)

New data.    Returns

X_originalndarray of shape (n_samples, n_features)

Note that this is always a dense array.


set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.


transform(X) [source]

Perform dimensionality reduction on X.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

New data.    Returns

X_newndarray of shape (n_samples, n_components)

Reduced version of X. This will always be a dense array.


class sklearn.discriminant_analysis.LinearDiscriminantAnalysis(solver='svd', shrinkage=None, priors=None, n_components=None, store_covariance=False, tol=0.0001, covariance_estimator=None) [source]

Linear Discriminant Analysis A classifier with a linear decision boundary, generated by fitting class conditional densities to the data and using Bayes’ rule. The model fits a Gaussian density to each class, assuming that all classes share the same covariance matrix. The fitted model can also be used to reduce the dimensionality of the input by projecting it to the most discriminative directions, using the transform method.  New in version 0.17: LinearDiscriminantAnalysis.  Read more in the User Guide.  Parameters

solver{‘svd’, ‘lsqr’, ‘eigen’}, default=’svd’

 Solver to use, possible values:

 ‘svd’: Singular value decomposition (default). Does not compute the covariance matrix, therefore this solver is recommended for data with a large number of features. ‘lsqr’: Least squares solution. Can be combined with shrinkage or custom covariance estimator. ‘eigen’: Eigenvalue decomposition. Can be combined with shrinkage or custom covariance estimator.
shrinkage‘auto’ or float, default=None

 Shrinkage parameter, possible values:

 None: no shrinkage (default). ‘auto’: automatic shrinkage using the Ledoit-Wolf lemma. float between 0 and 1: fixed shrinkage parameter.    This should be left to None if covariance_estimator is used. Note that shrinkage works only with ‘lsqr’ and ‘eigen’ solvers.
priorsarray-like of shape (n_classes,), default=None

The class prior probabilities. By default, the class proportions are inferred from the training data.
n_componentsint, default=None

Number of components (<= min(n_classes - 1, n_features)) for dimensionality reduction. If None, will be set to min(n_classes - 1, n_features). This parameter only affects the transform method.
store_covariancebool, default=False

If True, explicitely compute the weighted within-class covariance matrix when solver is ‘svd’. The matrix is always computed and stored for the other solvers.  New in version 0.17.
tolfloat, default=1.0e-4

Absolute threshold for a singular value of X to be considered significant, used to estimate the rank of X. Dimensions whose singular values are non-significant are discarded. Only used if solver is ‘svd’.  New in version 0.17.
covariance_estimatorcovariance estimator, default=None

If not None, covariance_estimator is used to estimate the covariance matrices instead of relying on the empirical covariance estimator (with potential shrinkage). The object should have a fit method and a covariance_ attribute like the estimators in sklearn.covariance. if None the shrinkage parameter drives the estimate. This should be left to None if shrinkage is used. Note that covariance_estimator works only with ‘lsqr’ and ‘eigen’ solvers.  New in version 0.24.     Attributes

coef_ndarray of shape (n_features,) or (n_classes, n_features)

Weight vector(s).
intercept_ndarray of shape (n_classes,)

Intercept term.
covariance_array-like of shape (n_features, n_features)

Weighted within-class covariance matrix. It corresponds to sum_k prior_k * C_k where C_k is the covariance matrix of the samples in class k. The C_k are estimated using the (potentially shrunk) biased estimator of covariance. If solver is ‘svd’, only exists when store_covariance is True.
explained_variance_ratio_ndarray of shape (n_components,)

Percentage of variance explained by each of the selected components. If n_components is not set then all components are stored and the sum of explained variances is equal to 1.0. Only available when eigen or svd solver is used.
means_array-like of shape (n_classes, n_features)

Class-wise means.
priors_array-like of shape (n_classes,)

Class priors (sum to 1).
scalings_array-like of shape (rank, n_classes - 1)

Scaling of the features in the space spanned by the class centroids. Only available for ‘svd’ and ‘eigen’ solvers.
xbar_array-like of shape (n_features,)

Overall mean. Only present if solver is ‘svd’.
classes_array-like of shape (n_classes,)

Unique class labels.      See also
QuadraticDiscriminantAnalysis

Quadratic Discriminant Analysis.    Examples >>> import numpy as np
>>> from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
>>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
>>> y = np.array([1, 1, 1, 2, 2, 2])
>>> clf = LinearDiscriminantAnalysis()
>>> clf.fit(X, y)
LinearDiscriminantAnalysis()
>>> print(clf.predict([[-0.8, -1]]))
[1]
 Methods
decision_function(X) Apply decision function to an array of samples.
fit(X, y) Fit LinearDiscriminantAnalysis model according to the given
fit_transform(X[, y]) Fit to data, then transform it.
get_params([deep]) Get parameters for this estimator.
predict(X) Predict class labels for samples in X.
predict_log_proba(X) Estimate log probability.
predict_proba(X) Estimate probability.
score(X, y[, sample_weight]) Return the mean accuracy on the given test data and labels.
set_params(**params) Set the parameters of this estimator.
transform(X) Project data to maximize class separation.
decision_function(X) [source]

Apply decision function to an array of samples. The decision function is equal (up to a constant factor) to the log-posterior of the model, i.e. log p(y = k | x). In a binary classification setting this instead corresponds to the difference log p(y = 1 | x) - log p(y = 0 | x). See Mathematical formulation of the LDA and QDA classifiers.  Parameters

Xarray-like of shape (n_samples, n_features)

Array of samples (test vectors).    Returns

Cndarray of shape (n_samples,) or (n_samples, n_classes)

Decision function values related to each class, per sample. In the two-class case, the shape is (n_samples,), giving the log likelihood ratio of the positive class.

fit(X, y) [source]

 Fit LinearDiscriminantAnalysis model according to the given

training data and parameters.  Changed in version 0.19: store_covariance has been moved to main constructor.   Changed in version 0.19: tol has been moved to main constructor.     Parameters

Xarray-like of shape (n_samples, n_features)

Training data.
yarray-like of shape (n_samples,)

Target values.

fit_transform(X, y=None, **fit_params) [source]

Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.  Parameters

Xarray-like of shape (n_samples, n_features)

Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None

Target values (None for unsupervised transformations).
**fit_paramsdict

Additional fit parameters.    Returns

X_newndarray array of shape (n_samples, n_features_new)

Transformed array.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

predict(X) [source]

Predict class labels for samples in X.  Parameters

Xarray-like or sparse matrix, shape (n_samples, n_features)

Samples.    Returns

Carray, shape [n_samples]

Predicted class label per sample.

predict_log_proba(X) [source]

Estimate log probability.  Parameters

Xarray-like of shape (n_samples, n_features)

Input data.    Returns

Cndarray of shape (n_samples, n_classes)

Estimated log probabilities.

predict_proba(X) [source]

Estimate probability.  Parameters

Xarray-like of shape (n_samples, n_features)

Input data.    Returns

Cndarray of shape (n_samples, n_classes)

Estimated probabilities.

score(X, y, sample_weight=None) [source]

Return the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.  Parameters

Xarray-like of shape (n_samples, n_features)

Test samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True labels for X.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

scorefloat

Mean accuracy of self.predict(X) wrt. y.

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

transform(X) [source]

Project data to maximize class separation.  Parameters

Xarray-like of shape (n_samples, n_features)

Input data.    Returns

X_newndarray of shape (n_samples, n_components)

Transformed data.


sklearn.discriminant_analysis.LinearDiscriminantAnalysis
class sklearn.discriminant_analysis.LinearDiscriminantAnalysis(solver='svd', shrinkage=None, priors=None, n_components=None, store_covariance=False, tol=0.0001, covariance_estimator=None) [source]

Linear Discriminant Analysis A classifier with a linear decision boundary, generated by fitting class conditional densities to the data and using Bayes’ rule. The model fits a Gaussian density to each class, assuming that all classes share the same covariance matrix. The fitted model can also be used to reduce the dimensionality of the input by projecting it to the most discriminative directions, using the transform method.  New in version 0.17: LinearDiscriminantAnalysis.  Read more in the User Guide.  Parameters

solver{‘svd’, ‘lsqr’, ‘eigen’}, default=’svd’

 Solver to use, possible values:

 ‘svd’: Singular value decomposition (default). Does not compute the covariance matrix, therefore this solver is recommended for data with a large number of features. ‘lsqr’: Least squares solution. Can be combined with shrinkage or custom covariance estimator. ‘eigen’: Eigenvalue decomposition. Can be combined with shrinkage or custom covariance estimator.
shrinkage‘auto’ or float, default=None

 Shrinkage parameter, possible values:

 None: no shrinkage (default). ‘auto’: automatic shrinkage using the Ledoit-Wolf lemma. float between 0 and 1: fixed shrinkage parameter.    This should be left to None if covariance_estimator is used. Note that shrinkage works only with ‘lsqr’ and ‘eigen’ solvers.
priorsarray-like of shape (n_classes,), default=None

The class prior probabilities. By default, the class proportions are inferred from the training data.
n_componentsint, default=None

Number of components (<= min(n_classes - 1, n_features)) for dimensionality reduction. If None, will be set to min(n_classes - 1, n_features). This parameter only affects the transform method.
store_covariancebool, default=False

If True, explicitely compute the weighted within-class covariance matrix when solver is ‘svd’. The matrix is always computed and stored for the other solvers.  New in version 0.17.
tolfloat, default=1.0e-4

Absolute threshold for a singular value of X to be considered significant, used to estimate the rank of X. Dimensions whose singular values are non-significant are discarded. Only used if solver is ‘svd’.  New in version 0.17.
covariance_estimatorcovariance estimator, default=None

If not None, covariance_estimator is used to estimate the covariance matrices instead of relying on the empirical covariance estimator (with potential shrinkage). The object should have a fit method and a covariance_ attribute like the estimators in sklearn.covariance. if None the shrinkage parameter drives the estimate. This should be left to None if shrinkage is used. Note that covariance_estimator works only with ‘lsqr’ and ‘eigen’ solvers.  New in version 0.24.     Attributes

coef_ndarray of shape (n_features,) or (n_classes, n_features)

Weight vector(s).
intercept_ndarray of shape (n_classes,)

Intercept term.
covariance_array-like of shape (n_features, n_features)

Weighted within-class covariance matrix. It corresponds to sum_k prior_k * C_k where C_k is the covariance matrix of the samples in class k. The C_k are estimated using the (potentially shrunk) biased estimator of covariance. If solver is ‘svd’, only exists when store_covariance is True.
explained_variance_ratio_ndarray of shape (n_components,)

Percentage of variance explained by each of the selected components. If n_components is not set then all components are stored and the sum of explained variances is equal to 1.0. Only available when eigen or svd solver is used.
means_array-like of shape (n_classes, n_features)

Class-wise means.
priors_array-like of shape (n_classes,)

Class priors (sum to 1).
scalings_array-like of shape (rank, n_classes - 1)

Scaling of the features in the space spanned by the class centroids. Only available for ‘svd’ and ‘eigen’ solvers.
xbar_array-like of shape (n_features,)

Overall mean. Only present if solver is ‘svd’.
classes_array-like of shape (n_classes,)

Unique class labels.      See also
QuadraticDiscriminantAnalysis

Quadratic Discriminant Analysis.    Examples >>> import numpy as np
>>> from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
>>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
>>> y = np.array([1, 1, 1, 2, 2, 2])
>>> clf = LinearDiscriminantAnalysis()
>>> clf.fit(X, y)
LinearDiscriminantAnalysis()
>>> print(clf.predict([[-0.8, -1]]))
[1]
 Methods
decision_function(X) Apply decision function to an array of samples.
fit(X, y) Fit LinearDiscriminantAnalysis model according to the given
fit_transform(X[, y]) Fit to data, then transform it.
get_params([deep]) Get parameters for this estimator.
predict(X) Predict class labels for samples in X.
predict_log_proba(X) Estimate log probability.
predict_proba(X) Estimate probability.
score(X, y[, sample_weight]) Return the mean accuracy on the given test data and labels.
set_params(**params) Set the parameters of this estimator.
transform(X) Project data to maximize class separation.
decision_function(X) [source]

Apply decision function to an array of samples. The decision function is equal (up to a constant factor) to the log-posterior of the model, i.e. log p(y = k | x). In a binary classification setting this instead corresponds to the difference log p(y = 1 | x) - log p(y = 0 | x). See Mathematical formulation of the LDA and QDA classifiers.  Parameters

Xarray-like of shape (n_samples, n_features)

Array of samples (test vectors).    Returns

Cndarray of shape (n_samples,) or (n_samples, n_classes)

Decision function values related to each class, per sample. In the two-class case, the shape is (n_samples,), giving the log likelihood ratio of the positive class.

fit(X, y) [source]

 Fit LinearDiscriminantAnalysis model according to the given

training data and parameters.  Changed in version 0.19: store_covariance has been moved to main constructor.   Changed in version 0.19: tol has been moved to main constructor.     Parameters

Xarray-like of shape (n_samples, n_features)

Training data.
yarray-like of shape (n_samples,)

Target values.

fit_transform(X, y=None, **fit_params) [source]

Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.  Parameters

Xarray-like of shape (n_samples, n_features)

Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None

Target values (None for unsupervised transformations).
**fit_paramsdict

Additional fit parameters.    Returns

X_newndarray array of shape (n_samples, n_features_new)

Transformed array.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

predict(X) [source]

Predict class labels for samples in X.  Parameters

Xarray-like or sparse matrix, shape (n_samples, n_features)

Samples.    Returns

Carray, shape [n_samples]

Predicted class label per sample.

predict_log_proba(X) [source]

Estimate log probability.  Parameters

Xarray-like of shape (n_samples, n_features)

Input data.    Returns

Cndarray of shape (n_samples, n_classes)

Estimated log probabilities.

predict_proba(X) [source]

Estimate probability.  Parameters

Xarray-like of shape (n_samples, n_features)

Input data.    Returns

Cndarray of shape (n_samples, n_classes)

Estimated probabilities.

score(X, y, sample_weight=None) [source]

Return the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.  Parameters

Xarray-like of shape (n_samples, n_features)

Test samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True labels for X.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

scorefloat

Mean accuracy of self.predict(X) wrt. y.

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

transform(X) [source]

Project data to maximize class separation.  Parameters

Xarray-like of shape (n_samples, n_features)

Input data.    Returns

X_newndarray of shape (n_samples, n_components)

Transformed data.

 Examples using sklearn.discriminant_analysis.LinearDiscriminantAnalysis

  Normal, Ledoit-Wolf and OAS Linear Discriminant Analysis for classification

  Linear and Quadratic Discriminant Analysis with covariance ellipsoid

  Comparison of LDA and PCA 2D projection of Iris dataset

  Manifold learning on handwritten digits: Locally Linear Embedding, Isomap…

  Dimensionality Reduction with Neighborhood Components Analysis


decision_function(X) [source]

Apply decision function to an array of samples. The decision function is equal (up to a constant factor) to the log-posterior of the model, i.e. log p(y = k | x). In a binary classification setting this instead corresponds to the difference log p(y = 1 | x) - log p(y = 0 | x). See Mathematical formulation of the LDA and QDA classifiers.  Parameters

Xarray-like of shape (n_samples, n_features)

Array of samples (test vectors).    Returns

Cndarray of shape (n_samples,) or (n_samples, n_classes)

Decision function values related to each class, per sample. In the two-class case, the shape is (n_samples,), giving the log likelihood ratio of the positive class.


fit(X, y) [source]

 Fit LinearDiscriminantAnalysis model according to the given

training data and parameters.  Changed in version 0.19: store_covariance has been moved to main constructor.   Changed in version 0.19: tol has been moved to main constructor.     Parameters

Xarray-like of shape (n_samples, n_features)

Training data.
yarray-like of shape (n_samples,)

Target values.


fit_transform(X, y=None, **fit_params) [source]

Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.  Parameters

Xarray-like of shape (n_samples, n_features)

Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None

Target values (None for unsupervised transformations).
**fit_paramsdict

Additional fit parameters.    Returns

X_newndarray array of shape (n_samples, n_features_new)

Transformed array.


predict(X) [source]

Predict class labels for samples in X.  Parameters

Xarray-like or sparse matrix, shape (n_samples, n_features)

Samples.    Returns

Carray, shape [n_samples]

Predicted class label per sample.


predict_log_proba(X) [source]

Estimate log probability.  Parameters

Xarray-like of shape (n_samples, n_features)

Input data.    Returns

Cndarray of shape (n_samples, n_classes)

Estimated log probabilities.


predict_proba(X) [source]

Estimate probability.  Parameters

Xarray-like of shape (n_samples, n_features)

Input data.    Returns

Cndarray of shape (n_samples, n_classes)

Estimated probabilities.


score(X, y, sample_weight=None) [source]

Return the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.  Parameters

Xarray-like of shape (n_samples, n_features)

Test samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True labels for X.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

scorefloat

Mean accuracy of self.predict(X) wrt. y.


transform(X) [source]

Project data to maximize class separation.  Parameters

Xarray-like of shape (n_samples, n_features)

Input data.    Returns

X_newndarray of shape (n_samples, n_components)

Transformed data.


class sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis(*, priors=None, reg_param=0.0, store_covariance=False, tol=0.0001) [source]

Quadratic Discriminant Analysis A classifier with a quadratic decision boundary, generated by fitting class conditional densities to the data and using Bayes’ rule. The model fits a Gaussian density to each class.  New in version 0.17: QuadraticDiscriminantAnalysis  Read more in the User Guide.  Parameters

priorsndarray of shape (n_classes,), default=None

Class priors. By default, the class proportions are inferred from the training data.
reg_paramfloat, default=0.0

Regularizes the per-class covariance estimates by transforming S2 as S2 = (1 - reg_param) * S2 + reg_param * np.eye(n_features), where S2 corresponds to the scaling_ attribute of a given class.
store_covariancebool, default=False

If True, the class covariance matrices are explicitely computed and stored in the self.covariance_ attribute.  New in version 0.17.
tolfloat, default=1.0e-4

Absolute threshold for a singular value to be considered significant, used to estimate the rank of Xk where Xk is the centered matrix of samples in class k. This parameter does not affect the predictions. It only controls a warning that is raised when features are considered to be colinear.  New in version 0.17.     Attributes

covariance_list of len n_classes of ndarray of shape (n_features, n_features)

For each class, gives the covariance matrix estimated using the samples of that class. The estimations are unbiased. Only present if store_covariance is True.
means_array-like of shape (n_classes, n_features)

Class-wise means.
priors_array-like of shape (n_classes,)

Class priors (sum to 1).
rotations_list of len n_classes of ndarray of shape (n_features, n_k)

For each class k an array of shape (n_features, n_k), where n_k = min(n_features, number of elements in class k) It is the rotation of the Gaussian distribution, i.e. its principal axis. It corresponds to V, the matrix of eigenvectors coming from the SVD of Xk = U S Vt where Xk is the centered matrix of samples from class k.
scalings_list of len n_classes of ndarray of shape (n_k,)

For each class, contains the scaling of the Gaussian distributions along its principal axes, i.e. the variance in the rotated coordinate system. It corresponds to S^2 /
(n_samples - 1), where S is the diagonal matrix of singular values from the SVD of Xk, where Xk is the centered matrix of samples from class k.
classes_ndarray of shape (n_classes,)

Unique class labels.      See also
LinearDiscriminantAnalysis

Linear Discriminant Analysis.    Examples >>> from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
>>> import numpy as np
>>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
>>> y = np.array([1, 1, 1, 2, 2, 2])
>>> clf = QuadraticDiscriminantAnalysis()
>>> clf.fit(X, y)
QuadraticDiscriminantAnalysis()
>>> print(clf.predict([[-0.8, -1]]))
[1]
 Methods
decision_function(X) Apply decision function to an array of samples.
fit(X, y) Fit the model according to the given training data and parameters.
get_params([deep]) Get parameters for this estimator.
predict(X) Perform classification on an array of test vectors X.
predict_log_proba(X) Return log of posterior probabilities of classification.
predict_proba(X) Return posterior probabilities of classification.
score(X, y[, sample_weight]) Return the mean accuracy on the given test data and labels.
set_params(**params) Set the parameters of this estimator.
decision_function(X) [source]

Apply decision function to an array of samples. The decision function is equal (up to a constant factor) to the log-posterior of the model, i.e. log p(y = k | x). In a binary classification setting this instead corresponds to the difference log p(y = 1 | x) - log p(y = 0 | x). See Mathematical formulation of the LDA and QDA classifiers.  Parameters

Xarray-like of shape (n_samples, n_features)

Array of samples (test vectors).    Returns

Cndarray of shape (n_samples,) or (n_samples, n_classes)

Decision function values related to each class, per sample. In the two-class case, the shape is (n_samples,), giving the log likelihood ratio of the positive class.

fit(X, y) [source]

Fit the model according to the given training data and parameters.  Changed in version 0.19: store_covariances has been moved to main constructor as store_covariance   Changed in version 0.19: tol has been moved to main constructor.   Parameters

Xarray-like of shape (n_samples, n_features)

Training vector, where n_samples is the number of samples and n_features is the number of features.
yarray-like of shape (n_samples,)

Target values (integers)

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

predict(X) [source]

Perform classification on an array of test vectors X. The predicted class C for each sample in X is returned.  Parameters

Xarray-like of shape (n_samples, n_features)
  Returns

Cndarray of shape (n_samples,)

predict_log_proba(X) [source]

Return log of posterior probabilities of classification.  Parameters

Xarray-like of shape (n_samples, n_features)

Array of samples/test vectors.    Returns

Cndarray of shape (n_samples, n_classes)

Posterior log-probabilities of classification per class.

predict_proba(X) [source]

Return posterior probabilities of classification.  Parameters

Xarray-like of shape (n_samples, n_features)

Array of samples/test vectors.    Returns

Cndarray of shape (n_samples, n_classes)

Posterior probabilities of classification per class.

score(X, y, sample_weight=None) [source]

Return the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.  Parameters

Xarray-like of shape (n_samples, n_features)

Test samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True labels for X.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

scorefloat

Mean accuracy of self.predict(X) wrt. y.

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.


sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis
class sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis(*, priors=None, reg_param=0.0, store_covariance=False, tol=0.0001) [source]

Quadratic Discriminant Analysis A classifier with a quadratic decision boundary, generated by fitting class conditional densities to the data and using Bayes’ rule. The model fits a Gaussian density to each class.  New in version 0.17: QuadraticDiscriminantAnalysis  Read more in the User Guide.  Parameters

priorsndarray of shape (n_classes,), default=None

Class priors. By default, the class proportions are inferred from the training data.
reg_paramfloat, default=0.0

Regularizes the per-class covariance estimates by transforming S2 as S2 = (1 - reg_param) * S2 + reg_param * np.eye(n_features), where S2 corresponds to the scaling_ attribute of a given class.
store_covariancebool, default=False

If True, the class covariance matrices are explicitely computed and stored in the self.covariance_ attribute.  New in version 0.17.
tolfloat, default=1.0e-4

Absolute threshold for a singular value to be considered significant, used to estimate the rank of Xk where Xk is the centered matrix of samples in class k. This parameter does not affect the predictions. It only controls a warning that is raised when features are considered to be colinear.  New in version 0.17.     Attributes

covariance_list of len n_classes of ndarray of shape (n_features, n_features)

For each class, gives the covariance matrix estimated using the samples of that class. The estimations are unbiased. Only present if store_covariance is True.
means_array-like of shape (n_classes, n_features)

Class-wise means.
priors_array-like of shape (n_classes,)

Class priors (sum to 1).
rotations_list of len n_classes of ndarray of shape (n_features, n_k)

For each class k an array of shape (n_features, n_k), where n_k = min(n_features, number of elements in class k) It is the rotation of the Gaussian distribution, i.e. its principal axis. It corresponds to V, the matrix of eigenvectors coming from the SVD of Xk = U S Vt where Xk is the centered matrix of samples from class k.
scalings_list of len n_classes of ndarray of shape (n_k,)

For each class, contains the scaling of the Gaussian distributions along its principal axes, i.e. the variance in the rotated coordinate system. It corresponds to S^2 /
(n_samples - 1), where S is the diagonal matrix of singular values from the SVD of Xk, where Xk is the centered matrix of samples from class k.
classes_ndarray of shape (n_classes,)

Unique class labels.      See also
LinearDiscriminantAnalysis

Linear Discriminant Analysis.    Examples >>> from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
>>> import numpy as np
>>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
>>> y = np.array([1, 1, 1, 2, 2, 2])
>>> clf = QuadraticDiscriminantAnalysis()
>>> clf.fit(X, y)
QuadraticDiscriminantAnalysis()
>>> print(clf.predict([[-0.8, -1]]))
[1]
 Methods
decision_function(X) Apply decision function to an array of samples.
fit(X, y) Fit the model according to the given training data and parameters.
get_params([deep]) Get parameters for this estimator.
predict(X) Perform classification on an array of test vectors X.
predict_log_proba(X) Return log of posterior probabilities of classification.
predict_proba(X) Return posterior probabilities of classification.
score(X, y[, sample_weight]) Return the mean accuracy on the given test data and labels.
set_params(**params) Set the parameters of this estimator.
decision_function(X) [source]

Apply decision function to an array of samples. The decision function is equal (up to a constant factor) to the log-posterior of the model, i.e. log p(y = k | x). In a binary classification setting this instead corresponds to the difference log p(y = 1 | x) - log p(y = 0 | x). See Mathematical formulation of the LDA and QDA classifiers.  Parameters

Xarray-like of shape (n_samples, n_features)

Array of samples (test vectors).    Returns

Cndarray of shape (n_samples,) or (n_samples, n_classes)

Decision function values related to each class, per sample. In the two-class case, the shape is (n_samples,), giving the log likelihood ratio of the positive class.

fit(X, y) [source]

Fit the model according to the given training data and parameters.  Changed in version 0.19: store_covariances has been moved to main constructor as store_covariance   Changed in version 0.19: tol has been moved to main constructor.   Parameters

Xarray-like of shape (n_samples, n_features)

Training vector, where n_samples is the number of samples and n_features is the number of features.
yarray-like of shape (n_samples,)

Target values (integers)

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

predict(X) [source]

Perform classification on an array of test vectors X. The predicted class C for each sample in X is returned.  Parameters

Xarray-like of shape (n_samples, n_features)
  Returns

Cndarray of shape (n_samples,)

predict_log_proba(X) [source]

Return log of posterior probabilities of classification.  Parameters

Xarray-like of shape (n_samples, n_features)

Array of samples/test vectors.    Returns

Cndarray of shape (n_samples, n_classes)

Posterior log-probabilities of classification per class.

predict_proba(X) [source]

Return posterior probabilities of classification.  Parameters

Xarray-like of shape (n_samples, n_features)

Array of samples/test vectors.    Returns

Cndarray of shape (n_samples, n_classes)

Posterior probabilities of classification per class.

score(X, y, sample_weight=None) [source]

Return the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.  Parameters

Xarray-like of shape (n_samples, n_features)

Test samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True labels for X.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

scorefloat

Mean accuracy of self.predict(X) wrt. y.

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

 Examples using sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis

  Classifier comparison

  Linear and Quadratic Discriminant Analysis with covariance ellipsoid


fit(X, y) [source]

Fit the model according to the given training data and parameters.  Changed in version 0.19: store_covariances has been moved to main constructor as store_covariance   Changed in version 0.19: tol has been moved to main constructor.   Parameters

Xarray-like of shape (n_samples, n_features)

Training vector, where n_samples is the number of samples and n_features is the number of features.
yarray-like of shape (n_samples,)

Target values (integers)


get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.


predict(X) [source]

Perform classification on an array of test vectors X. The predicted class C for each sample in X is returned.  Parameters

Xarray-like of shape (n_samples, n_features)
  Returns

Cndarray of shape (n_samples,)


predict_log_proba(X) [source]

Return log of posterior probabilities of classification.  Parameters

Xarray-like of shape (n_samples, n_features)

Array of samples/test vectors.    Returns

Cndarray of shape (n_samples, n_classes)

Posterior log-probabilities of classification per class.


predict_proba(X) [source]

Return posterior probabilities of classification.  Parameters

Xarray-like of shape (n_samples, n_features)

Array of samples/test vectors.    Returns

Cndarray of shape (n_samples, n_classes)

Posterior probabilities of classification per class.


set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.


class sklearn.dummy.DummyClassifier(*, strategy='prior', random_state=None, constant=None) [source]

DummyClassifier is a classifier that makes predictions using simple rules. This classifier is useful as a simple baseline to compare with other (real) classifiers. Do not use it for real problems. Read more in the User Guide.  New in version 0.13.   Parameters

strategy{“stratified”, “most_frequent”, “prior”, “uniform”, “constant”}, default=”prior”

Strategy to use to generate predictions.  “stratified”: generates predictions by respecting the training set’s class distribution. “most_frequent”: always predicts the most frequent label in the training set. “prior”: always predicts the class that maximizes the class prior (like “most_frequent”) and predict_proba returns the class prior. “uniform”: generates predictions uniformly at random.
“constant”: always predicts a constant label that is provided by the user. This is useful for metrics that evaluate a non-majority class  Changed in version 0.24: The default value of strategy has changed to “prior” in version 0.24.
random_stateint, RandomState instance or None, default=None

Controls the randomness to generate the predictions when strategy='stratified' or strategy='uniform'. Pass an int for reproducible output across multiple function calls. See Glossary.
constantint or str or array-like of shape (n_outputs,)

The explicit constant as predicted by the “constant” strategy. This parameter is useful only for the “constant” strategy.    Attributes

classes_ndarray of shape (n_classes,) or list of such arrays

Class labels for each output.
n_classes_int or list of int

Number of label for each output.
class_prior_ndarray of shape (n_classes,) or list of such arrays

Probability of each class for each output.
n_outputs_int

Number of outputs.
sparse_output_bool

True if the array returned from predict is to be in sparse CSC format. Is automatically set to True if the input y is passed in sparse format.     Examples >>> import numpy as np
>>> from sklearn.dummy import DummyClassifier
>>> X = np.array([-1, 1, 1, 1])
>>> y = np.array([0, 1, 1, 1])
>>> dummy_clf = DummyClassifier(strategy="most_frequent")
>>> dummy_clf.fit(X, y)
DummyClassifier(strategy='most_frequent')
>>> dummy_clf.predict(X)
array([1, 1, 1, 1])
>>> dummy_clf.score(X, y)
0.75
 Methods
fit(X, y[, sample_weight]) Fit the random classifier.
get_params([deep]) Get parameters for this estimator.
predict(X) Perform classification on test vectors X.
predict_log_proba(X) Return log probability estimates for the test vectors X.
predict_proba(X) Return probability estimates for the test vectors X.
score(X, y[, sample_weight]) Returns the mean accuracy on the given test data and labels.
set_params(**params) Set the parameters of this estimator.
fit(X, y, sample_weight=None) [source]

Fit the random classifier.  Parameters

Xarray-like of shape (n_samples, n_features)

Training data.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

Target values.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

selfobject

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

predict(X) [source]

Perform classification on test vectors X.  Parameters

Xarray-like of shape (n_samples, n_features)

Test data.    Returns

yarray-like of shape (n_samples,) or (n_samples, n_outputs)

Predicted target values for X.

predict_log_proba(X) [source]

Return log probability estimates for the test vectors X.  Parameters

X{array-like, object with finite length or shape}

Training data, requires length = n_samples    Returns

Pndarray of shape (n_samples, n_classes) or list of such arrays

Returns the log probability of the sample for each class in the model, where classes are ordered arithmetically for each output.

predict_proba(X) [source]

Return probability estimates for the test vectors X.  Parameters

Xarray-like of shape (n_samples, n_features)

Test data.    Returns

Pndarray of shape (n_samples, n_classes) or list of such arrays

Returns the probability of the sample for each class in the model, where classes are ordered arithmetically, for each output.

score(X, y, sample_weight=None) [source]

Returns the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.  Parameters

XNone or array-like of shape (n_samples, n_features)

Test samples. Passing None as test samples gives the same result as passing real test samples, since DummyClassifier operates independently of the sampled observations.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True labels for X.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

scorefloat

Mean accuracy of self.predict(X) wrt. y.

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.