spectrochempy.PCA
- class PCA(*, log_level='WARNING', warm_start=False, iterated_power='auto', n_components=None, n_oversamples=10, power_iteration_normalizer='auto', random_state=None, scaled=False, standardized=False, svd_solver='auto', tol=0.0, whiten=False)[source]
Principal Component Anamysis (PCA).
The Principal Component Analysis analysis is using the
sklearn.decomposition.PCA
model.- Parameters:
log_level (any of [
"INFO"
,"DEBUG"
,"WARNING"
,"ERROR"
], optional, default:"WARNING"
) – The log level at startup. It can be changed later on using theset_log_level
method or by changing thelog_level
attribute.warm_start (
bool
, optional, default:False
) – When fitting repeatedly on the same dataset, but for multiple parameter values (such as to find the value maximizing performance), it may be possible to reuse previous model learned from the previous parameter value, saving time.When
warm_start
isTrue
, the existing fitted model attributes is used to initialize the new model in a subsequent call tofit
.iterated_power (an int or any of [‘auto’], optional, default:
'auto'
) – Number of iterations for the power method computed by svd_solver == ‘randomized’. Must be of range [0, infinity).n_components (any of [‘mle’] or an int or a float, optional, default:
None
) – Number of components to keep. ifn_components
is not set all components are kept:n_components == min(n_observations, n_features)
If
n_components == 'mle'
andsvd_solver == 'full'
, Minka’s MLE is used to guess the dimension. Use ofn_components == 'mle'
will interpretsvd_solver == 'auto'
assvd_solver == 'full'
. If0 < n_components < 1
andsvd_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. Ifsvd_solver == 'arpack'
, the number of components must be strictly less than the minimum of n_features and n_observations. Hence, the None case results in:n_components == min(n_observations, n_features) - 1.
n_oversamples (
int
, optional, default: 10) – This parameter is only relevant whensvd_solver="randomized"
. It corresponds to the additional number of random vectors to sample the range ofX
so as to ensure proper conditioning. Seerandomized_svd
for more details.power_iteration_normalizer (any value of [
'auto'
,'QR'
,'LU'
,'none'
], optional, default:'auto'
) – Power iteration normalizer for randomized SVD solver. Not used by ARPACK. Seerandomized_svd
for more details.random_state (an int or a RandomState, optional, default:
None
) – Used when the ‘arpack’ or ‘randomized’ solvers are used. Pass an int for reproducible results across multiple function calls.scaled (
bool
, optional, default: False) – If True the data are scaled in the interval[0-1]
: \(X' = (X - min(X)) / (max(X)-min(X))\).standardized (
bool
, optional, default: False) – If True the data are scaled to unit standard deviation: \(X' = X / \sigma\).svd_solver (any value of [
'auto'
,'full'
,'arpack'
,'randomized'
], optional, default:'auto'
) – If auto : The solver is selected by a default policy based onX.shape
andn_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 viascipy.linalg.svd
and select the components by postprocessing If arpack : run SVD truncated to n_components calling ARPACK solver viascipy.sparse.linalg.svds
. It requires strictly 0 < n_components < min(X.shape) If randomized : run randomized SVD by the method of Halko et al.tol (
float
, optional, default: 0.0) – Tolerance for singular values computed by svd_solver == ‘arpack’. Must be of range [0.0, infinity).whiten (
bool
, optional, default: False) – When True (False by default) thecomponents_
vectors are multiplied by the square root of n_observations 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.
See also
EFA
Perform an Evolving Factor Analysis (forward and reverse).
FastICA
Perform Independent Component Analysis with a fast algorithm.
IRIS
Integral inversion solver for spectroscopic data.
MCRALS
Perform MCR-ALS of a dataset knowing the initial \(C\) or \(S^T\) matrix.
NMF
Non-Negative Matrix Factorization.
SIMPLISMA
SIMPLe to use Interactive Self-modeling Mixture Analysis.
SVD
Perform a Singular Value Decomposition.
Initialize the BaseConfigurable class.
- Parameters:
log_level (int, optional) – The log level at startup. Default is logging.WARNING.
**kwargs (dict) – Additional keyword arguments for configuration.
Attributes Summary
Return the X input dataset (eventually modified by the model).
The
Y
input.NDDataset
with components in feature space (n_components, n_features).traitlets.config.Config
object.Number of iterations for the power method computed by svd_solver == 'randomized'.
Return PCA loadings.
Return
log
output.Number of components to keep. if
n_components
is not set all components are kept::.This parameter is only relevant when
svd_solver="randomized"
.Object name
Power iteration normalizer for randomized SVD solver.
Used when the 'arpack' or 'randomized' solvers are used.
\(X' = (X - min(X)) / (max(X)-min(X))\).
Returns PCA scores.
\(X' = X / \sigma\).
If auto: The solver is selected by a default policy based on
X.shape
andn_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.Tolerance for singular values computed by svd_solver == 'arpack'.
When True (False by default) the
components_
vectors are multiplied by the square root of n_observations and then divided by the singular values to ensure uncorrelated outputs with unit component-wise variances.Methods Summary
fit
(X)Fit the PCA model on X.
fit_transform
(X[, Y])Fit the model with
X
and apply the dimensionality reduction onX
.get_components
([n_components])Return the component's dataset: (selected n_components, n_features).
inverse_transform
([X_transform])Transform data back to its original space.
parameters
([replace, removed, default])Alias for
params
method.params
([default])Return current or default configuration values.
plotmerit
([X, X_hat])Plot the input (
X
), reconstructed (X_hat
) and residuals.printev
([n_components])Print PCA figures of merit.
reconstruct
([X_transform])Transform data back to its original space.
reduce
([X])Apply dimensionality reduction to
X
.reset
()Reset configuration parameters to their default values.
scoreplot
(self, *args[, colormap, ...])2D or 3D scoreplot of observations.
screeplot
([n_components])Scree plot of explained variance + cumulative variance by PCA.
to_dict
()Return config value in a dict form.
transform
([X])Apply dimensionality reduction to
X
.Attributes Documentation
- X
Return the X input dataset (eventually modified by the model).
- components
NDDataset
with components in feature space (n_components, n_features).See also
get_components
Retrieve only the specified number of components.
- config
traitlets.config.Config
object.
- iterated_power
Number of iterations for the power method computed by svd_solver == ‘randomized’. Must be of range [0, infinity).
- loadings
Return PCA loadings.
- log
Return
log
output.
- n_components
Number of components to keep. if
n_components
is not set all components are kept:n_components == min(n_observations, n_features)
If
n_components == 'mle'
andsvd_solver == 'full'
, Minka’s MLE is used to guess the dimension. Use ofn_components == 'mle'
will interpretsvd_solver == 'auto'
assvd_solver == 'full'
. If0 < n_components < 1
andsvd_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. Ifsvd_solver == 'arpack'
, the number of components must be strictly less than the minimum of n_features and n_observations. Hence, the None case results in:n_components == min(n_observations, n_features) - 1.
- n_oversamples
This parameter is only relevant when
svd_solver="randomized"
. It corresponds to the additional number of random vectors to sample the range ofX
so as to ensure proper conditioning. Seerandomized_svd
for more details.
- name
Object name
- power_iteration_normalizer
Power iteration normalizer for randomized SVD solver. Not used by ARPACK. See
randomized_svd
for more details.
- random_state
Used when the ‘arpack’ or ‘randomized’ solvers are used. Pass an int for reproducible results across multiple function calls.
- scaled
\(X' = (X - min(X)) / (max(X)-min(X))\).
- Type:
If True the data are scaled in the interval
[0-1]
- scores
Returns PCA scores.
- standardized
\(X' = X / \sigma\).
- Type:
If True the data are scaled to unit standard deviation
- svd_solver
If auto: The solver is selected by a default policy based on
X.shape
andn_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 viascipy.linalg.svd
and select the components by postprocessing If arpack : run SVD truncated to n_components calling ARPACK solver viascipy.sparse.linalg.svds
. It requires strictly 0 < n_components < min(X.shape) If randomized : run randomized SVD by the method of Halko et al.
- tol
Tolerance for singular values computed by svd_solver == ‘arpack’. Must be of range [0.0, infinity).
- whiten
When True (False by default) the
components_
vectors are multiplied by the square root of n_observations 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.
Methods Documentation
- fit(X)[source]
Fit the PCA model on X.
- Parameters:
X (
NDDataset
or array-like of shape (n_observations, n_features)) – Training data.- Returns:
self – The fitted instance itself.
See also
fit_transform
Fit the model with an input dataset
X
and apply the dimensionality reduction onX
.fit_reduce
Alias of
fit_transform
(Deprecated).
- fit_transform(X, Y=None, **kwargs)[source]
Fit the model with
X
and apply the dimensionality reduction onX
.- Parameters:
X (
NDDataset
or array-like of shape (n_observations, n_features)) – Training data.Y (any) – Depends on the model.
**kwargs (keyword parameters, optional) – See Other Parameters.
- Returns:
NDDataset
– Dataset with shape (n_observations, n_components).- Other Parameters:
n_components (
int
, optional) – The number of components to use for the reduction. If not given the number of components is eventually the one specified or determined in thefit
process.
- get_components(n_components=None)
Return the component’s dataset: (selected n_components, n_features).
- Parameters:
n_components (
int
, optional, default:None
) – The number of components to keep in the output dataset. IfNone
, all calculated components are returned.- Returns:
NDDataset
– Dataset with shape (n_components, n_features)
- inverse_transform(X_transform=None, **kwargs)
Transform data back to its original space.
In other words, return an input
X_original
whose reduce/transform would beX_transform
.- Parameters:
X_transform (array-like of shape (n_observations, n_components), optional) – Reduced
X
data, wheren_observations
is the number of observations andn_components
is the number of components. IfX_transform
is not provided, a transform ofX
provided infit
is performed first.**kwargs (keyword parameters, optional) – See Other Parameters.
- Returns:
NDDataset
– Dataset with shape (n_observations, n_features).- Other Parameters:
n_components (
int
, optional) – The number of components to use for the reduction. If not given the number of components is eventually the one specified or determined in thefit
process.
See also
reconstruct
Alias of inverse_transform (Deprecated).
- parameters(replace="params", removed="0.8.0") def parameters(self, default=False)[source]
Alias for
params
method.Deprecated since version 0.8.0: Use
params
instead.
- plotmerit(X=None, X_hat=None, **kwargs)[source]
Plot the input (
X
), reconstructed (X_hat
) and residuals.\(X\) and \(\hat{X}\) can be passed as arguments. If not, the
X
attribute is used for \(X`and :math:\)hat{X}`is computed by theinverse_transform
method- Parameters:
X (
NDDataset
, optional) – Original dataset. If is not provided (default), theX
attribute is used and X_hat is computed usinginverse_transform
.X_hat (
NDDataset
, optional) – Inverse transformed dataset. ifX
is provided,X_hat
must also be provided as compuyed externally.**kwargs (keyword parameters, optional) – See Other Parameters.
- Returns:
Axes
– Matplotlib subplot axe.- Other Parameters:
colors (
tuple
orndarray
of 3 colors, optional) – Colors forX
,X_hat
and residualsE
. in the case of 2D, The default colormap is used forX
. By default, the three colors areNBlue
,NGreen
andNRed
(which are colorblind friendly).offset (
float
, optional, default:None
) – Specify the separation (in percent) between the \(X\) , \(X_hat\) and \(E\).nb_traces (
int
or'all'
, optional) – Number of lines to display. Default is'all'
.**others (Other keywords parameters) – Parameters passed to the internal
plot
method of theX
dataset.
- printev(n_components=None)[source]
Print PCA figures of merit.
Prints eigenvalues and explained variance for all or first n_pc PC’s.
- Parameters:
n_components (int, optional) – The number of components to print.
- reconstruct(X_transform=None, **kwargs)[source]
Transform data back to its original space.
In other words, return an input
X_original
whose reduce/transform would beX_transform
.- Parameters:
X_transform (array-like of shape (n_observations, n_components), optional) – Reduced
X
data, wheren_observations
is the number of observations andn_components
is the number of components. IfX_transform
is not provided, a transform ofX
provided infit
is performed first.**kwargs (keyword parameters, optional) – See Other Parameters.
- Returns:
NDDataset
– Dataset with shape (n_observations, n_features).- Other Parameters:
n_components (
int
, optional) – The number of components to use for the reduction. If not given the number of components is eventually the one specified or determined in thefit
process.
See also
reconstruct
Alias of inverse_transform (Deprecated).
Notes
Deprecated in version 0.6.
- reduce(X=None, **kwargs)[source]
Apply dimensionality reduction to
X
.- Parameters:
X (
NDDataset
or array-like of shape (n_observations, n_features), optional) – New data, where n_observations is the number of observations and n_features is the number of features. if not provided, the input dataset of thefit
method will be used.**kwargs (keyword parameters, optional) – See Other Parameters.
- Returns:
NDDataset
– Dataset with shape (n_observations, n_components).- Other Parameters:
n_components (
int
, optional) – The number of components to use for the reduction. If not given the number of components is eventually the one specified or determined in thefit
process.
Notes
Deprecated in version 0.6.
- scoreplot(self, *args, colormap='viridis', color_mapping='index', show_labels=False, labels_column=0, labels_every=1, **kwargs)[source]
2D or 3D scoreplot of observations.
Plots the projection of each observation/spectrum onto the span of two or three selected principal components.
- Parameters:
*args (
NDDataset
and/or series of 2 or 3 ints or iterabble of 2 or 3 int, optional) – TheNDDataset
contains the sores to plot. If not providedPCA.scores
is used. The 2 or 3 int are the PC on which the projection is shown. If not provided, default to [1,2], i.e. bidimensional plot on PCs #1 and #2.colormap (str) – A matplotlib colormap.
color_mapping (‘index’ or ‘labels’) – If ‘index’, then the colors of each n_scores is mapped sequentially on the colormap. If labels, the labels of the n_observations are used for color mapping.
show_labels (bool, optional, default: False) – If True each observation will be annotated with its label.
labels_column (int, optional, default:0) – If several columns of labels are present indicates which column has to be used to show labels.
labels_every (int, optional, default: 1) – Do not label all points, but only every value indicated by this parameter.
- Returns:
Axes
– The matplotlib axes.
Notes
the markersize is defined from preferences (prefs) as the square of the
prefs.lines.markersize
.
- screeplot(n_components=None, **kwargs)[source]
Scree plot of explained variance + cumulative variance by PCA.
Explained variance by each PC is plot as a bar graph (left y axis) and cumulative explained variance is plot as a scatter plot with lines (right y axis).
- transform(X=None, **kwargs)
Apply dimensionality reduction to
X
.- Parameters:
X (
NDDataset
or array-like of shape (n_observations, n_features), optional) – New data, where n_observations is the number of observations and n_features is the number of features. if not provided, the input dataset of thefit
method will be used.**kwargs (keyword parameters, optional) – See Other Parameters.
- Returns:
NDDataset
– Dataset with shape (n_observations, n_components).- Other Parameters:
n_components (
int
, optional) – The number of components to use for the reduction. If not given the number of components is eventually the one specified or determined in thefit
process.
Examples using spectrochempy.PCA