spectrochempy.NMFο
- class NMF(*, log_level='WARNING', warm_start=False, alpha_H='same', alpha_W=0.0, beta_loss='frobenius', init=None, l1_ratio=0.0, max_iter=200, n_components=2, random_state=None, shuffle=False, solver='cd', tol=0.0001)[source]ο
Non-Negative Matrix Factorization (NMF).
Use
sklearn.decomposition.NMF.Find two non-negative matrices, i.e., matrices with all non-negative elements, (
W,H) whose product approximates the non-negative matrixX. This factorization can be used for example for dimensionality reduction, source separation or topic extraction.- 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_levelmethod or by changing thelog_levelattribute.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_startisTrue, the existing fitted model attributes is used to initialize the new model in a subsequent call tofit.alpha_H (a float or any of [βsameβ], optional, default:
'same') β Constant that multiplies the regularization terms ofH. Set it to zeroto have no regularization onH. If βsameβ (default), it takes the samevalue asalpha_W.alpha_W (
float, optional, default: 0.0) β Constant that multiplies the regularization terms ofW. Set it to zero(default) to have no regularization onW.beta_loss (a float or any of [βfrobeniusβ, βkullback-leiblerβ, βitakura-saitoβ], optional, default:
'frobenius') β Beta divergence to be minimized, measuring the distance between Xand the dot product WH. Note that values different from βfrobeniusβ (or 2) and βkullback-leiblerβ (or 1) lead to significantly slower fits. Note that for beta_loss <= 0 (or βitakura-saitoβ), the input matrix X cannot contain zeros. Used only in βmuβ solver.init (any value of [
'random','nndsvd','nndsvda','nndsvdar','custom'], optional, default:None) β Method used to initialize the procedure.Valid options:
None: βnndsvdaβ if n_components <= min(n_samples, n_features), otherwise random.random: non-negative random matrices, scaled with: sqrt(X.mean() / n_components)nndsvd: Nonnegative Double Singular Value Decomposition (NNDSVD) initialization (better for sparseness)nndsvda: NNDSVD with zeros filled with the average of X (better when sparsity is not desired)nndsvdarNNDSVD with zeros filled with small random values (generally faster, less accurate alternative to NNDSVDa for when sparsity is not desired)custom: use custom matrices W and H.
l1_ratio (
float, optional, default: 0.0) β The regularization mixing parameter, with 0 <= l1_ratio <= 1. - For l1_ratio = 0 the penalty is an elementwise L2 penalty (aka Frobenius Norm). - For l1_ratio = 1 it is an elementwise L1 penalty. - For 0 < l1_ratio < 1, the penalty is a combination of L1 and L2.max_iter (
int, optional, default: 200) β Maximum number of iterations before timing out.n_components (
int, optional, default: 2) β Number of components to use.random_state (an int or a RandomState, optional, default:
None) β Used for initialisation (wheninit== βnndsvdarβ or βrandomβ), and in Coordinate Descent. Pass an int, for reproducible results across multiple function calls.shuffle (
bool, optional, default: False) β If true, randomize the order of coordinates in the CD solver.solver (any value of [
'cd','mu'], optional, default:'cd') β Numerical solver to use: - βcdβ is a Coordinate Descent solver. - βmuβ is a Multiplicative Update solver.tol (
float, optional, default: 0.0001) β Tolerance of the stopping condition.
See also
EFAPerform an Evolving Factor Analysis (forward and reverse).
FastICAPerform Independent Component Analysis with a fast algorithm.
IRISIntegral inversion solver for spectroscopic data.
MCRALSPerform MCR-ALS of a dataset knowing the initial \(C\) or \(S^T\) matrix.
PCAPerform Principal Components Analysis.
SIMPLISMASIMPLe to use Interactive Self-modeling Mixture Analysis.
SVDPerform 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
Yinput.Constant that multiplies the regularization terms of
H.Constant that multiplies the regularization terms of
W.Beta divergence to be minimized, measuring the distance between Xand the dot product WH.
NDDatasetwith components in feature space (n_components, n_features).traitlets.config.Configobject.Method used to initialize the procedure.
The regularization mixing parameter, with 0 <= l1_ratio <= 1.
Return
logoutput.Maximum number of iterations before timing out.
Number of components to use.
Object name
Used for initialisation (when
init== 'nndsvdar' or 'random'), and in Coordinate Descent.If true, randomize the order of coordinates in the CD solver.
Numerical solver to use: - 'cd' is a Coordinate Descent solver.
Tolerance of the stopping condition.
Methods Summary
fit(X)Fit the NMF model on X.
fit_transform(X[,Β Y])Fit the model with
Xand 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
paramsmethod.params([default])Return current or default configuration values.
plot_merit([X,Β X_hat])Plot the input (
X), reconstructed (X_hat) and residuals.plotmerit([X,Β X_hat])Plot the input (
X), reconstructed (X_hat) and residuals.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.
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).
- alpha_Hο
Constant that multiplies the regularization terms of
H. Set it to zeroto have no regularization onH. If βsameβ (default), it takes the samevalue asalpha_W.
- alpha_Wο
Constant that multiplies the regularization terms of
W. Set it to zero(default) to have no regularization onW.
- beta_lossο
Beta divergence to be minimized, measuring the distance between Xand the dot product WH. Note that values different from βfrobeniusβ (or 2) and βkullback-leiblerβ (or 1) lead to significantly slower fits. Note that for beta_loss <= 0 (or βitakura-saitoβ), the input matrix X cannot contain zeros. Used only in βmuβ solver.
- componentsο
NDDatasetwith components in feature space (n_components, n_features).See also
get_componentsRetrieve only the specified number of components.
- configο
traitlets.config.Configobject.
- initο
Method used to initialize the procedure.
Valid options:
None: βnndsvdaβ if n_components <= min(n_samples, n_features), otherwise random.random: non-negative random matrices, scaled with: sqrt(X.mean() / n_components)nndsvd: Nonnegative Double Singular Value Decomposition (NNDSVD) initialization (better for sparseness)nndsvda: NNDSVD with zeros filled with the average of X (better when sparsity is not desired)nndsvdarNNDSVD with zeros filled with small random values (generally faster, less accurate alternative to NNDSVDa for when sparsity is not desired)custom: use custom matrices W and H.
- l1_ratioο
The regularization mixing parameter, with 0 <= l1_ratio <= 1. - For l1_ratio = 0 the penalty is an elementwise L2 penalty (aka Frobenius Norm). - For l1_ratio = 1 it is an elementwise L1 penalty. - For 0 < l1_ratio < 1, the penalty is a combination of L1 and L2.
- logο
Return
logoutput.
- max_iterο
Maximum number of iterations before timing out.
- n_componentsο
Number of components to use.
- nameο
Object name
- random_stateο
Used for initialisation (when
init== βnndsvdarβ or βrandomβ), and in Coordinate Descent. Pass an int, for reproducible results across multiple function calls.
- shuffleο
If true, randomize the order of coordinates in the CD solver.
- solverο
Numerical solver to use: - βcdβ is a Coordinate Descent solver. - βmuβ is a Multiplicative Update solver.
- tolο
Tolerance of the stopping condition.
Methods Documentation
- fit(X)[source]ο
Fit the NMF model on X.
- Parameters:
X (
NDDatasetor array-like of shape (n_observations, n_features)) β Training data.- Returns:
self β The fitted instance itself.
See also
fit_transformFit the model with an input dataset
Xand apply the dimensionality reduction onX.fit_reduceAlias of
fit_transform(Deprecated).
- fit_transform(X, Y=None, **kwargs)[source]ο
Fit the model with
Xand apply the dimensionality reduction onX.- Parameters:
X (
NDDatasetor 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 thefitprocess.
- 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_originalwhose reduce/transform would beX_transform.- Parameters:
X_transform (array-like of shape (n_observations, n_components), optional) β Reduced
Xdata, wheren_observationsis the number of observations andn_componentsis the number of components. IfX_transformis not provided, a transform ofXprovided infitis 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 thefitprocess.
See also
reconstructAlias of inverse_transform (Deprecated).
- parameters(replace="params", removed="0.8.0") def parameters(self, default=False)[source]ο
Alias for
paramsmethod.Deprecated since version 0.8.0: Use
paramsinstead.
- plot_merit(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
Xattribute is used for \(X`and :math:\)hat{X}`is computed by theinverse_transformmethod- Parameters:
X (
NDDataset, optional) β Original dataset. If is not provided (default), theXattribute is used and X_hat is computed usinginverse_transform.X_hat (
NDDataset, optional) β Inverse transformed dataset. ifXis provided,X_hatmust also be provided as compuyed externally.
- Returns:
Axesβ Matplotlib subplot axe.- Other Parameters:
exp_c (color, colormap, or list of colors, optional) β Color(s) for experimental spectra. - None: use unified semantic resolver (auto-detect categorical/sequential) - Single color: use for all experimental spectra - Colormap name/object: sample colors from colormap - List/tuple: use as explicit color cycle
calc_c (color, colormap, or list of colors, optional) β Color(s) for calculated spectra. - None: use default blue β#2a6fbbβ - Single color: use for all calculated spectra - Colormap name/object: sample colors from colormap - List/tuple: use as explicit color cycle
resid_c (color, colormap, or list of colors, optional) β Color(s) for residual spectra. - None: use default grey β0.4β - Single color: use for all residual spectra - Colormap name/object: sample colors from colormap - List/tuple: use as explicit color cycle
exp_linestyle (str, optional) β Line style for experimental spectra. Default: β-β.
calc_linestyle (str, optional) β Line style for calculated spectra. Default: βββ.
resid_linestyle (str, optional) β Line style for residual spectra. Default: β-β.
exp_linewidth (float, optional) β Line width for experimental spectra. Default: 1.2.
calc_linewidth (float, optional) β Line width for calculated spectra. Default: 1.0.
resid_linewidth (float, optional) β Line width for residual spectra. Default: 1.0.
min_contrast (float, optional) β Minimum contrast ratio for sequential colormaps. Default: 1.5.
offset (
float, optional, default:None) β Specify the separation (in percent) between the \(X\) , \(X_hat\) and \(E\).nb_traces (
intor'all', optional) β Number of lines to display. Default is'all'.**others (Other keywords parameters) β Parameters passed to the internal
plotmethod of theXdataset.
- 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
Xattribute is used for \(X`and :math:\)hat{X}`is computed by theinverse_transformmethod- Parameters:
X (
NDDataset, optional) β Original dataset. If is not provided (default), theXattribute is used and X_hat is computed usinginverse_transform.X_hat (
NDDataset, optional) β Inverse transformed dataset. ifXis provided,X_hatmust also be provided as compuyed externally.
- Returns:
Axesβ Matplotlib subplot axe.- Other Parameters:
exp_c (color, colormap, or list of colors, optional) β Color(s) for experimental spectra. - None: use unified semantic resolver (auto-detect categorical/sequential) - Single color: use for all experimental spectra - Colormap name/object: sample colors from colormap - List/tuple: use as explicit color cycle
calc_c (color, colormap, or list of colors, optional) β Color(s) for calculated spectra. - None: use default blue β#2a6fbbβ - Single color: use for all calculated spectra - Colormap name/object: sample colors from colormap - List/tuple: use as explicit color cycle
resid_c (color, colormap, or list of colors, optional) β Color(s) for residual spectra. - None: use default grey β0.4β - Single color: use for all residual spectra - Colormap name/object: sample colors from colormap - List/tuple: use as explicit color cycle
exp_linestyle (str, optional) β Line style for experimental spectra. Default: β-β.
calc_linestyle (str, optional) β Line style for calculated spectra. Default: βββ.
resid_linestyle (str, optional) β Line style for residual spectra. Default: β-β.
exp_linewidth (float, optional) β Line width for experimental spectra. Default: 1.2.
calc_linewidth (float, optional) β Line width for calculated spectra. Default: 1.0.
resid_linewidth (float, optional) β Line width for residual spectra. Default: 1.0.
min_contrast (float, optional) β Minimum contrast ratio for sequential colormaps. Default: 1.5.
offset (
float, optional, default:None) β Specify the separation (in percent) between the \(X\) , \(X_hat\) and \(E\).nb_traces (
intor'all', optional) β Number of lines to display. Default is'all'.**others (Other keywords parameters) β Parameters passed to the internal
plotmethod of theXdataset.
- reconstruct(X_transform=None, **kwargs)[source]ο
Transform data back to its original space.
In other words, return an input
X_originalwhose reduce/transform would beX_transform.- Parameters:
X_transform (array-like of shape (n_observations, n_components), optional) β Reduced
Xdata, wheren_observationsis the number of observations andn_componentsis the number of components. IfX_transformis not provided, a transform ofXprovided infitis 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 thefitprocess.
See also
reconstructAlias of inverse_transform (Deprecated).
Notes
Deprecated in version 0.6.
- reduce(X=None, **kwargs)[source]ο
Apply dimensionality reduction to
X.- Parameters:
X (
NDDatasetor 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 thefitmethod 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 thefitprocess.
Notes
Deprecated in version 0.6.
- transform(X=None, **kwargs)ο
Apply dimensionality reduction to
X.- Parameters:
X (
NDDatasetor 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 thefitmethod 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 thefitprocess.
Examples using spectrochempy.NMF