confusius.decomposition¶
decomposition ¶
Decomposition techniques for fUSI data.
Modules:
-
fastica–FastICA decomposition for
(time, ...)fUSI DataArrays. -
pca–Principal component decomposition for
(time, ...)fUSI DataArrays.
Classes:
-
FastICA–Fast independent component analysis (ICA) for fUSI data.
-
PCA–Principal component analysis (PCA) for fUSI data.
FastICA ¶
Bases: _BaseFUSIDecomposer
Fast independent component analysis (ICA) for fUSI data.
The FastICA algorithm is based on Hyvarinen et al. (2000).
This estimator wraps
sklearn.decomposition.FastICA while keeping
xarray metadata through transform and
inverse_transform:
- Input data are expected as
(time, ...)where...are spatial dimensions. transformreturns a(time, component)DataArray of IC time courses.inverse_transformreconstructs to(time, ...)using the fitted spatial coordinates.
Two ICA modes are supported, selected via the mode parameter.
Spatial ICA (mode="spatial", default, matches FSL MELODIC):
Maximises independence across the spatial dimension. The independent components
are spatial maps; time courses are derived by projecting the data onto those maps.
This is the appropriate choice when different brain regions are assumed to have
independently fluctuating activity, which is the standard prior for network
discovery. It is also better conditioned for fUSI data where the number of voxels
greatly exceeds the number of time points.
Temporal ICA (mode="temporal"):
Maximises independence across the time dimension. The independent components
are temporal signals; the spatial maps are the corresponding mixing weights.
Suitable when temporal independence is the relevant prior.
Parameters:
-
(n_components¶int, default:None) –Number of components to use. If not provided, all are used.
-
(mode¶(spatial, temporal), default:"spatial") –Whether to find spatially or temporally independent components:
"spatial": fit on(voxels, time). The independent components are spatial maps; the projected time courses are their temporal mixing weights. Matches FSL MELODIC's default for single-subject data."temporal": fit on(time, voxels). The independent components are time courses; the spatial maps are their voxel-wise mixing weights.
-
(algorithm¶(parallel, deflation), default:"parallel") –Specify which algorithm to use for FastICA.
-
(whiten¶(unit - variance, arbitrary - variance), default:"unit-variance") –Specify the whitening strategy to use.
- If
"arbitrary-variance", a whitening with arbitrary variance is used. - If
"unit-variance", the whitening matrix is rescaled to ensure that each recovered source has unit variance. - If
False, the data are already considered whitened, and no whitening is performed.
- If
-
(fun¶(logcosh, exp, cube), default:"logcosh") –The functional form of the
Gfunction used in the approximation to neg-entropy. Can be either"logcosh","exp", or"cube".Default is
"cube"to align with FSL MELODIC (pow3).You can also provide your own function. It should return a tuple containing the value of the function and its derivative at the point. The derivative should be averaged along its last dimension.
-
(fun_args¶dict[str, Any], default:None) –Arguments to send to the functional form. If empty or
Noneandfun="logcosh",fun_argsdefaults to{"alpha": 1.0}. -
(max_iter¶int, default:500) –Maximum number of iterations during fit. Default matches FSL MELODIC (
--maxit=500). -
(tol¶float, default:1e-4) –A positive scalar giving the tolerance at which the un-mixing matrix is considered to have converged.
-
(w_init¶(n_components, n_components) numpy.ndarray, default:None) –Initial un-mixing array. If not provided, values drawn from a normal distribution are used.
-
(whiten_solver¶(svd, eigh), default:"svd") –The solver to use for whitening.
"svd"is more stable numerically if the problem is degenerate, and often faster whenn_samples <= n_features."eigh"is generally more memory efficient whenn_samples >= n_features, and can be faster whenn_samples >= 50 * n_features.
-
(random_state¶int, default:None) –Used to initialize
w_initwhen not provided, with a normal distribution. Pass an int for reproducible results across multiple function calls. -
(mask¶DataArray, default:None) –Boolean spatial mask selecting voxels to include during fitting and projection. Must match the spatial dimensions and coordinates of the input data.
Attributes:
-
maps_((n_components, ...) xarray.DataArray) –Spatial maps reshaped to the original spatial geometry.
- In
"spatial"mode: the independent component sources themselves, that is, the spatially independent patterns that FastICA found. These are the ICs in the strict sense. - In
"temporal"mode: the unmixing directions in voxel space, that is, the spatial weights applied to each volume to extract IC time courses. The actual temporal ICs are returned bytransform.
- In
-
mean_((...) xarray.DataArray) –Per-voxel empirical mean from the training set.
-
whitening_((n_components, ...) xarray.DataArray) –Pre-whitening matrix reshaped to the original spatial geometry. Only present in
"temporal"mode whenwhitenis notFalse. -
n_components_(int) –Number of components estimated during fit.
-
n_iter_(int) –If
algorithm="deflation", the maximum number of iterations run across all components. Otherwise, the number of iterations taken to converge. -
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:
Spatial ICA (default, matches FSL MELODIC):
>>> import numpy as np
>>> import xarray as xr
>>> from confusius.decomposition import FastICA
>>>
>>> rng = np.random.default_rng(0)
>>> data = xr.DataArray(
... rng.standard_normal((200, 5, 10, 20)),
... dims=["time", "z", "y", "x"],
... )
>>>
>>> ica = FastICA(n_components=5, random_state=0)
>>> signals = ica.fit_transform(data)
>>> signals.dims
('time', 'component')
>>> reconstructed = ica.inverse_transform(signals)
>>> reconstructed.dims
('time', 'z', 'y', 'x')
References
-
Hyvarinen, A., and Oja, E. (2000). "Independent component analysis: Algorithms and applications". Neural Networks, 13(4-5), 411-430. ↩
Methods:
-
fit–Fit FastICA on
(time, ...)fUSI data. -
fit_transform–Fit on
Xand return transformed signals. -
get_metadata_routing–Get metadata routing of this object.
-
get_params–Get parameters for this estimator.
-
inverse_transform–Reconstruct data from component signals.
-
set_output–Set output container.
-
set_params–Set the parameters of this estimator.
-
transform–Project data into component space.
fit ¶
Fit FastICA on (time, ...) fUSI data.
Parameters:
-
(X¶(time, ...) xarray.DataArray) –Input fUSI data.
-
(y¶None, default:None) –Ignored. Present for scikit-learn API compatibility.
Returns:
-
FastICA–Fitted estimator.
Raises:
-
ValueError–If input has no
timedimension, fewer than 2 timepoints, or no spatial dimensions. -
ValueError–If
modeis not"spatial"or"temporal".
fit_transform ¶
Fit on X and return transformed 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–Decomposed 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 component signals.
Parameters:
-
(X¶(time, component) xarray.DataArray or (time, component) numpy.ndarray) –Signals in 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.
PCA ¶
Bases: _BaseFUSIDecomposer
Principal component analysis (PCA) for fUSI data.
Linear dimensionality reduction using singular value decomposition (SVD) 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.
This estimator wraps sklearn.decomposition.PCA while
keeping 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 provided 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", the number of components will be selected 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, theNonecase results in:n_components == min(n_samples, n_features) - 1.
- If
-
(whiten¶bool, default:False) –Whether to multiply the loading vectors by the square root of
n_samplesand then divide them 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 sometimes 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 policy based on data shape andn_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 an exact full SVD calling the standard LAPACK solver viascipy.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 forn_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 ton_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, default:None) –Used when the
"arpack"or"randomized"solvers are used. Pass an int for reproducible results across multiple function calls. -
(mode¶(temporal, spatial), default:"temporal") –Whether to fit PCA along temporal or spatial orientation:
"temporal": fit on(time, voxels). The principal axes are spatial maps; the projected components are temporal time courses that capture dominant variance across voxels."spatial": fit on(voxels, time). The principal axes are time courses; the projected components are spatial maps that capture dominant variance across time.
-
(mask¶DataArray, default:None) –Boolean spatial mask selecting voxels to include during fitting and projection. Must match the spatial dimensions and coordinates of the input data.
Attributes:
-
maps_((n_components, ...) xarray.DataArray) –Principal directions in feature space (loadings), representing the axes of maximum variance. Equivalently, the right singular vectors of the centered input data, parallel to its eigenvectors. 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 ton_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, 5, 10, 20)),
... dims=["time", "z", "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', 'z', 'y', 'x')
References
-
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. ↩
Methods:
-
fit–Fit PCA on
(time, ...)fUSI data. -
fit_transform–Fit on
Xand return transformed signals. -
get_metadata_routing–Get metadata routing of this object.
-
get_params–Get parameters for this estimator.
-
inverse_transform–Reconstruct data from component signals.
-
set_output–Set output container.
-
set_params–Set the parameters of this estimator.
-
transform–Project data into 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. -
ValueError–If
modeis not"temporal"or"spatial".
fit_transform ¶
Fit on X and return transformed 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–Decomposed 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 component signals.
Parameters:
-
(X¶(time, component) xarray.DataArray or (time, component) numpy.ndarray) –Signals in 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.