spectrochempy.tensor.CP#
- class CP(*, log_level='WARNING', warm_start=False, cvg_criterion='abs_rec_error', fixed_modes, hard_sparsity=None, init='svd', l1_reg=None, l2_reg=None, l2_square_reg=None, monotonicity=None, n_components=0, n_iter_max=100, n_iter_max_inner=10, non_negative=False, normalize=None, normalized_sparsity=None, random_state=None, return_errors=False, simplex=None, smoothness=None, soft_sparsity=None, svd='truncated_svd', tol_inner=1e-06, tol_outer=1e-08, unimodality=None, verbose=0)#
CP/PARAFAC decomposition of 3D datasets using TensorLy.
CP (Canonical Polyadic) decomposition, also known as PARAFAC, factorizes a 3D tensor into a sum of rank-1 tensors. By default, this implementation uses TensorLy’s
parafacfunction. When constraints or penalties are active (e.g.,non_negative,l1_reg,smoothness, etc.), it automatically switches to TensorLy’sconstrained_parafacfunction with AO-ADMM optimization.Note:
fixed_modesis supported by bothparafacandconstrained_parafac, so usingfixed_modesalone does not trigger the constrained path.Only 3D datasets are supported. For 2D data, use PCA, NMF, or SVD instead.
- Parameters:
cvg_criterion ({“abs_rec_error”, “rec_error”}, default=”abs_rec_error”) – Stopping criterion for ALS. “abs_rec_error” uses absolute difference, “rec_error” uses relative difference.
fixed_modes (list of int, optional) – Modes for which initial values are not modified during optimization. The last mode cannot be fixed.
hard_sparsity (float, list, or dict, optional) – Applies hard thresholding with the given threshold.
init ({“random”, “svd”, “CPTensor”}, default=”svd”) – Type of factor matrix initialization. If a CPTensor is passed, it is used directly.
l1_reg (float, list, or dict, optional) – L1 norm regularization parameter for sparsity. Applied to factors.
l2_reg (float, list, or dict, optional) – L2 norm regularization parameter. Applied to factors.
l2_square_reg (float, list, or dict, optional) – L2 square norm regularization parameter. Applied to factors.
monotonicity (bool or dict, optional) – If True, projects factor columns to monotonically decreasing distribution.
n_components (int) – Number of components (rank) for the decomposition.
n_iter_max (int, default=100) – Maximum number of outer iterations for the ALS algorithm.
n_iter_max_inner (int, default=10) – Number of iterations for inner loop (ADMM optimization).
non_negative (bool or dict, default=False) – If True, applies non-negative constraint to all modes. Can also be a dict specifying constraints per mode.
normalize (bool or dict, optional) – If True, normalizes factors by dividing by maximum value.
normalized_sparsity (float, list, or dict, optional) – Normalizes factors with L1 norm after hard thresholding.
random_state (int or np.random.RandomState, optional) – Seed for random number generator or RandomState instance for reproducibility.
return_errors (bool, default=False) – Whether to store iteration errors after fitting. Errors are only available when using constrained_parafac (i.e., when constraints are active). For unconstrained parafac, errors will be None.
simplex (float, list, or dict, optional) – Projects factors onto the simplex with the given parameter.
smoothness (float, list, or dict, optional) – Optimizes factors by solving a banded system for smoothness.
soft_sparsity (float, list, or dict, optional) – Imposes L1 norm bound on factor columns.
svd ({“numpy_svd”, “truncated_svd”, “randomized_svd”}, default=”truncated_svd”) – Function to use for SVD computation during initialization.
tol_inner (float, default=1e-6) – Absolute reconstruction error tolerance for inner loop (ADMM optimization).
tol_outer (float, default=1e-8) – Relative reconstruction error tolerance for outer loop convergence.
unimodality (bool or dict, optional) – If True, enforces unimodality constraint on all modes.
verbose (int, default=0) – Level of verbosity for iteration logging.
Notes
This method requires the optional dependency
tensorly. Install it with:pip install spectrochempy-tensor
CP decomposition is sensitive to initialization and rank choice. The results may vary with different random seeds. Use
random_statefor reproducibility.Core consistency (CORCONDIA) helps assess model validity. Values close to 100% indicate a good fit, while negative values suggest overfactoring.
See also
PCAPrincipal Component Analysis for 2D data.
SVDSingular Value Decomposition for 2D data.
Examples
>>> import spectrochempy as scp >>> import numpy as np >>> X = np.random.rand(6, 8, 10) >>> ds = scp.NDDataset(X) >>> cp = scp.tensor.CP(n_components=2) >>> _ = cp.fit(ds) >>> A, B, C = cp.result.factors >>> Xr = cp.inverse_transform()
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 factor matrix A (mode 0 loadings).
Return factor matrix B (mode 1 loadings).
Return factor matrix C (mode 2 loadings).
Return Sum of Squared Errors.
Return factor B (mode 1) as components, following PCA convention.
Return CORCONDIA (Core Consistency) diagnostic.
Stopping criterion for ALS, works if
tolis not None.Return iteration errors if return_errors was True.
Return explained variance percentage.
A list of modes for which the initial value is not modified.
Hard thresholding with the given threshold.
Type of factor matrix initialization.
Penalizes the factor with the l1 norm using the input value as regularization parameter.
Penalizes the factor with the l2 norm using the input value as regularization parameter.
Penalizes the factor with the l2 square norm using the input value as regularization parameter.
Return tuple of factor matrices (A, B, C).
Projects columns to monotonically decreasing distribution.
Number of components (this is the 'rank' parameter used in TensorLy).
Maximum number of outer iterations.
Number of iterations for inner loop (ADMM optimization).
This constraint clips negative values to '0'.
This constraint divides all the values by maximum value of the input array.
Normalizes with the norm after hard thresholding.
If int, used to set the seed of the random number generator.
Return the CP analysis result.
Activate return of iteration errors.
Projects on the simplex with the given parameter.
Optimizes the factors by solving a banded system.
Impose that the columns of factors have L1 norm bounded by a user-defined threshold.
Function to use to compute the SVD.
Absolute reconstruction error tolerance for factor update during inner loop, i.e., ADMM optimization.
Relative reconstruction error tolerance for outer loop.
If True, enforces unimodality constraint on all modes.
Level of verbosity.
Return the weights from CP decomposition.
Methods Summary
fit(X)Fit the CP model on X.
fit_transform(X, **kwargs)Fit the CP model on X and return the factors.
inverse_transform([X_transform])Transform data back to its original space.
Attributes Documentation
- A#
Return factor matrix A (mode 0 loadings).
- B#
Return factor matrix B (mode 1 loadings).
- C#
Return factor matrix C (mode 2 loadings).
- SSE#
Return Sum of Squared Errors.
- components#
Return factor B (mode 1) as components, following PCA convention.
- Returns:
NDDataset – Factor B with shape (mode_1_size, n_components).
- core_consistency#
Return CORCONDIA (Core Consistency) diagnostic.
- Returns:
float – Core consistency value. Can be negative if overfactoring occurred.
- cvg_criterion#
Stopping criterion for ALS, works if
tolis not None.If ‘rec_error’, ALS stops at current iteration if
(previous rec_error - current rec_error) < tol. If ‘abs_rec_error’, ALS terminates when|previous rec_error - current rec_error| < tol.
- errors#
Return iteration errors if return_errors was True.
- explained_variance#
Return explained variance percentage.
- fixed_modes#
A list of modes for which the initial value is not modified. The last mode cannot be fixed due to error computation.
- hard_sparsity#
Hard thresholding with the given threshold.
- init#
Type of factor matrix initialization.
If a CPTensor is passed, this is directly used for initialization. See
initialize_factors.
- l1_reg#
Penalizes the factor with the l1 norm using the input value as regularization parameter.
- l2_reg#
Penalizes the factor with the l2 norm using the input value as regularization parameter.
- l2_square_reg#
Penalizes the factor with the l2 square norm using the input value as regularization parameter.
- loadings#
Return tuple of factor matrices (A, B, C).
- monotonicity#
Projects columns to monotonically decreasing distribution. Applied to each column separately. If True, monotonicity constraint is applied to all modes.
- n_components#
Number of components (this is the ‘rank’ parameter used in TensorLy).
- n_iter_max#
Maximum number of outer iterations.
- n_iter_max_inner#
Number of iterations for inner loop (ADMM optimization).
- non_negative#
This constraint clips negative values to ‘0’.
If True, non-negative constraint is applied to all modes.
- normalize#
This constraint divides all the values by maximum value of the input array. If True, normalize constraint is applied to all modes.
- normalized_sparsity#
Normalizes with the norm after hard thresholding.
- random_state#
If int, used to set the seed of the random number generator. If numpy.random.RandomState, used to initialize factor matrices with uniform distribution.
- result#
Return the CP analysis result.
- Returns:
AnalysisResult – Result containing the primary CP outputs and fit diagnostics.
- Raises:
NotFittedError – If the estimator has not been fitted yet.
- return_errors#
Activate return of iteration errors.
- simplex#
Projects on the simplex with the given parameter. Applied to each column separately.
- smoothness#
Optimizes the factors by solving a banded system.
- soft_sparsity#
Impose that the columns of factors have L1 norm bounded by a user-defined threshold.
- svd#
Function to use to compute the SVD. Maps to tensorly SVD functions.
- tol_inner#
Absolute reconstruction error tolerance for factor update during inner loop, i.e., ADMM optimization.
- tol_outer#
Relative reconstruction error tolerance for outer loop.
The algorithm is considered to have found a local minimum when the reconstruction error is less than
tol_outer.
- unimodality#
If True, enforces unimodality constraint on all modes. Applied to each mode separately.
- verbose#
Level of verbosity.
- weights#
Return the weights from CP decomposition.
Methods Documentation
- fit(X)[source]#
Fit the CP model on X.
- Parameters:
X (NDDataset) – 3D dataset to decompose.
- Returns:
self (CP) – The fitted CP instance.
- fit_transform(X, **kwargs)[source]#
Fit the CP model on X and return the factors.
- Parameters:
X (NDDataset) – 3D dataset to decompose.
**kwargs – Additional keyword arguments passed to fit.
- Returns:
tuple of NDDataset – The factor matrices (A, B, C).
- inverse_transform(X_transform=None, **kwargs)[source]#
Transform data back to its original space.
Reconstruct the original tensor from the CP factors.
- Parameters:
X_transform (None) – Ignored. Present for API compatibility.
**kwargs – Additional keyword arguments (ignored).
- Returns:
NDDataset – Reconstructed dataset with shape matching the input.
Examples using spectrochempy.tensor.CP