Skip to content

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.
  • transform returns a (time, component) DataArray.
  • inverse_transform reconstructs to (time, ...) using the fitted spatial coordinates.

Parameters:

  • n_components

    ((int, 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.

  • whiten

    (bool, 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, covariance_eigh, arpack, randomized), default: "auto" ) –

    "auto": The solver is selected by a default "auto" policy based on X.shape and n_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.svd and 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_features and small n_features. It is, however, not tractable otherwise for large n_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_components calling ARPACK solver via scipy.sparse.linalg.svds. It requires strictly 0 < 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 of X so as to ensure proper conditioning. See randomized_svd for more details.

  • power_iteration_normalizer

    ((auto, QR, LU, none), default: "auto" ) –

    Power iteration normalizer for randomized SVD solver. Not used by ARPACK. See randomized_svd for 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 - 1 degrees of freedom.

    Equal to n_components largest eigenvalues of the covariance matrix of X.

  • explained_variance_ratio_ ((n_components,) xarray.DataArray) –

    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_ ((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_components variables 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_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_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.

  • 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(X: DataArray, y: None = None) -> PCA

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 time dimension, fewer than 2 timepoints, or no spatial dimensions.

  • TypeError

    If additional fit parameters are provided.

fit_transform

fit_transform(
    X: DataArray, y: None = None, **fit_params: object
) -> DataArray

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()

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.MetadataRequest encapsulating routing information.

get_params

get_params(deep=True)

Get parameters for this estimator.

Parameters:

  • deep
    (bool, default: True ) –

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

Returns:

  • params ( dict ) –

    Parameter names mapped to their values.

inverse_transform

inverse_transform(
    X: DataArray | NDArray[floating],
) -> DataArray

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 X has invalid shape or component count.

  • TypeError

    If X is neither xarray.DataArray nor numpy.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 transform and fit_transform.

    • "default": Default output format of a transformer
    • "pandas": DataFrame output
    • "polars": Polars output
    • None: 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:

  • **params
    (dict, default: {} ) –

    Estimator parameters.

Returns:

  • self ( estimator instance ) –

    Estimator instance.

transform

transform(X: DataArray) -> DataArray

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.