confusius.decomposition¶
decomposition ¶
Decomposition techniques for fUSI data.
Modules:
-
pca–Principal component decomposition for
(time, ...)fUSI DataArrays.
Classes:
-
PCA–Principal component analysis for fUSI data.
PCA ¶
Bases: BaseEstimator, TransformerMixin
Principal component analysis for fUSI data.
This estimator wraps sklearn.decomposition.PCA but
keeps xarray metadata through transform and inverse_transform:
- Input data are expected as
(time, ...)where...are spatial dimensions. transformreturns a(time, component)DataArray.inverse_transformreconstructs to(time, ...)using the fitted spatial coordinates.
Parameters:
-
(n_components¶(int, float or mle), default:None) –Number of components to keep. if
n_componentsis not set all components are kept:n_components == min(n_samples, 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".If
0 < n_components < 1andsvd_solver == "full", select the number of components such that the amount of variance that needs to be explained is greater than the percentage specified byn_components.If
svd_solver == "arpack", the number of components must be strictly less than the minimum ofn_featuresandn_samples.Hence, the None case results in:
n_components == min(n_samples, n_features) - 1. -
(whiten¶bool, default:False) –When
True(Falseby default) thecomponents_vectors are multiplied by the square root ofn_samplesand 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, covariance_eigh, arpack, randomized), default:"auto") –"auto": The solver is selected by a default "auto" policy based on
X.shapeandn_components: if the input data has fewer than 1000 features and more than 10 times as many samples, then the "covariance_eigh" solver is used. Otherwise, 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 selected. Otherwise the exact "full" SVD is computed and optionally truncated afterwards."full": Run exact full SVD calling the standard LAPACK solver via
scipy.linalg.svdand select the components by postprocessing."covariance_eigh": Precompute the covariance matrix (on centered data), run a classical eigenvalue decomposition on the covariance matrix typically using LAPACK and select the components by postprocessing. This solver is very efficient for
n_samples >> n_featuresand smalln_features. It is, however, not tractable otherwise for largen_features(large memory footprint required to materialize the covariance matrix). Also note that compared to the "full" solver, this solver effectively doubles the condition number and is therefore less numerically stable (e.g. on input data with a large range of singular values)."arpack": Run SVD truncated to
n_componentscalling ARPACK solver viascipy.sparse.linalg.svds. It requires strictly0 < n_components < min(X.shape)."randomized": Run randomized SVD by the method of Halko et al.
-
(tol¶float, default:0.0) –Tolerance for singular values computed by
svd_solver == "arpack". Must be of range[0.0, infinity). -
(iterated_power¶int or auto, default:"auto") –Number of iterations for the power method computed by
svd_solver == "randomized". Must be of range[0, infinity). -
(n_oversamples¶int, default:10) –This parameter is only relevant when
svd_solver="randomized". It corresponds to the additional number of random vectors to sample the range ofXso as to ensure proper conditioning. Seerandomized_svdfor more details. -
(power_iteration_normalizer¶(auto, QR, LU, none), default:"auto") –Power iteration normalizer for randomized SVD solver. Not used by ARPACK. See
randomized_svdfor more details. -
(random_state¶int or None, default:None) –Used when the "arpack" or "randomized" solvers are used. Pass an int for reproducible results across multiple function calls.
Attributes:
-
components_((n_components, ...) xarray.DataArray) –Principal axes in feature space, representing the directions of maximum variance in the data. Equivalently, the right singular vectors of the centered input data, parallel to its eigenvectors. The components are sorted by decreasing
explained_variance_and reshaped to the original spatial geometry. -
explained_variance_((n_components,) xarray.DataArray) –The amount of variance explained by each of the selected components. The variance estimation uses
n_samples - 1degrees of freedom.Equal to
n_componentslargest eigenvalues of the covariance matrix ofX. -
explained_variance_ratio_((n_components,) xarray.DataArray) –Percentage of variance explained by each of the selected components.
If
n_componentsis not set then all components are stored and the sum of the ratios is equal to 1.0. -
singular_values_((n_components,) xarray.DataArray) –The singular values corresponding to each of the selected components. The singular values are equal to the 2-norms of the
n_componentsvariables in the lower-dimensional space. -
mean_((...) xarray.DataArray) –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_componentsis set to "mle" or a number between 0 and 1 (withsvd_solver == "full") this number is estimated from input data. Otherwise it equals the parameter n_components, or the lesser value ofn_featuresandn_samplesifn_componentsisNone. -
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_componentssmallest eigenvalues of the covariance matrix ofX. -
n_features_in_(int) –Number of features seen during fit.
-
feature_names_in_((n_features_in_,) numpy.ndarray) –Feature names seen during
fit. Defined only when flattened feature labels are all strings.
Examples:
>>> import numpy as np
>>> import xarray as xr
>>> from confusius.decomposition import PCA
>>>
>>> rng = np.random.default_rng(0)
>>> data = xr.DataArray(
... rng.standard_normal((200, 10, 20)),
... dims=["time", "y", "x"],
... )
>>>
>>> pca = PCA(n_components=5, random_state=0)
>>> signals = pca.fit_transform(data)
>>> signals.dims
('time', 'component')
>>> reconstructed = pca.inverse_transform(signals)
>>> reconstructed.dims
('time', 'y', 'x')
Methods:
-
fit–Fit PCA on
(time, ...)fUSI data. -
fit_transform–Fit PCA on
Xand return transformed component signals. -
get_metadata_routing–Get metadata routing of this object.
-
get_params–Get parameters for this estimator.
-
inverse_transform–Reconstruct data from PCA component signals.
-
set_output–Set output container.
-
set_params–Set the parameters of this estimator.
-
transform–Project data into PCA component space.
fit ¶
Fit PCA on (time, ...) fUSI data.
Parameters:
-
(X¶(time, ...) xarray.DataArray) –Input fUSI data.
-
(y¶None, default:None) –Ignored. Present for scikit-learn API compatibility.
Returns:
-
PCA–Fitted estimator.
Raises:
-
ValueError–If input has no
timedimension, fewer than 2 timepoints, or no spatial dimensions. -
TypeError–If additional fit parameters are provided.
fit_transform ¶
Fit PCA on X and return transformed component signals.
Parameters:
-
(X¶(time, ...) xarray.DataArray) –Input fUSI data.
-
(y¶None, default:None) –Ignored. Present for scikit-learn API compatibility.
-
(**fit_params¶object, default:{}) –Additional fit parameters. Unsupported for this estimator.
Returns:
-
(time, component) xarray.DataArray–PCA signals in component space.
Raises:
-
TypeError–If additional fit parameters are provided.
get_metadata_routing ¶
Get metadata routing of this object.
Please check :ref:User Guide <metadata_routing> on how the routing
mechanism works.
Returns:
-
routing(MetadataRequest) –A :class:
~sklearn.utils.metadata_routing.MetadataRequestencapsulating routing information.
inverse_transform ¶
Reconstruct data from PCA component signals.
Parameters:
-
(X¶(time, component) xarray.DataArray or (time, component) numpy.ndarray) –Signals in PCA component space.
Returns:
-
(time, ...) xarray.DataArray–Reconstructed data in the fitted spatial geometry.
Raises:
-
ValueError–If
Xhas invalid shape or component count. -
TypeError–If
Xis neitherxarray.DataArraynornumpy.ndarray.
set_output ¶
set_output(*, transform=None)
Set output container.
See :ref:sphx_glr_auto_examples_miscellaneous_plot_set_output.py
for an example on how to use the API.
Parameters:
-
(transform¶(default, pandas, polars), default:"default") –Configure output of
transformandfit_transform."default": Default output format of a transformer"pandas": DataFrame output"polars": Polars outputNone: Transform configuration is unchanged
.. versionadded:: 1.4
"polars"option was added.
Returns:
-
self(estimator instance) –Estimator instance.
set_params ¶
set_params(**params)
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects
(such as :class:~sklearn.pipeline.Pipeline). The latter have
parameters of the form <component>__<parameter> so that it's
possible to update each component of a nested object.
Parameters:
Returns:
-
self(estimator instance) –Estimator instance.
transform ¶
Project data into PCA component space.
X is projected on the first principal components previously extracted from a
training set.
Parameters:
-
(X¶(time, ...) xarray.DataArray) –Input fUSI data with the same spatial dimensions and sizes as the data used during fit.
Returns:
-
(time, component) xarray.DataArray–PCA signals in component space.