Warning

You are reading the documentation related to the development version. Go here if you are looking for the documentation of the stable release.

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 matrix X. 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 the set_log_level method or by changing the log_level attribute.

  • 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_start is True, the existing fitted model attributes is used to initialize the new model in a subsequent call to fit.

  • alpha_H (a float or any of [‘same’], optional, default: 'same') – Constant that multiplies the regularization terms of H . Set it to zeroto have no regularization on H . If “same” (default), it takes the samevalue as alpha_W .

  • alpha_W (float, optional, default: 0.0) – Constant that multiplies the regularization terms of W . Set it to zero(default) to have no regularization on W .

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

    • nndsvdar NNDSVD 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 (when init == ‘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

EFA

Perform an Evolving Factor Analysis (forward and reverse).

FastICA

Perform Independent Component Analysis with a fast algorithm.

IRIS

Integral inversion solver for spectroscopic data.

MCRALS

Perform MCR-ALS of a dataset knowing the initial \(C\) or \(S^T\) matrix.

PCA

Perform Principal Components Analysis.

SIMPLISMA

SIMPLe to use Interactive Self-modeling Mixture Analysis.

SVD

Perform a Singular Value Decomposition.

Attributes Summary

X

Return the X input dataset (eventually modified by the model).

Y

The Y input.

alpha_H

Constant that multiplies the regularization terms of H .

alpha_W

Constant that multiplies the regularization terms of W .

beta_loss

Beta divergence to be minimized, measuring the distance between Xand the dot product WH.

components

NDDataset with components in feature space (n_components, n_features).

config

traitlets.config.Config object.

init

Method used to initialize the procedure.

l1_ratio

The regularization mixing parameter, with 0 <= l1_ratio <= 1.

log

Return log output.

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.

shuffle

If true, randomize the order of coordinates in the CD solver.

solver

Numerical solver to use: - 'cd' is a Coordinate Descent solver.

tol

Tolerance of the stopping condition.

Methods Summary

fit(X)

Fit the NMF model on X.

fit_transform(X[, Y])

Fit the model with X and apply the dimensionality reduction on X.

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 params method.

params([default])

Current or default configuration values.

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

Y

The Y input.

alpha_H

Constant that multiplies the regularization terms of H . Set it to zeroto have no regularization on H . If “same” (default), it takes the samevalue as alpha_W .

alpha_W

Constant that multiplies the regularization terms of W . Set it to zero(default) to have no regularization on W .

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

NDDataset with components in feature space (n_components, n_features).

See also

get_components

Retrieve only the specified number of components.

config

traitlets.config.Config object.

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)

  • nndsvdar NNDSVD 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 log output.

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 (NDDataset or array-like of shape (n_observations, n_features)) – Training data.

Returns

self – The fitted instance itself.

See also

fit_transform

Fit the model with an input dataset X and apply the dimensionality reduction on X.

fit_reduce

Alias of fit_transform (Deprecated).

fit_transform(X, Y=None, **kwargs)[source]

Fit the model with X and apply the dimensionality reduction on X.

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 the fit process.

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. If None, 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_original whose reduce/transform would be X_transform.

Parameters
  • X_transform (array-like of shape (n_observations, n_components), optional) – Reduced X data, where n_observations is the number of observations and n_components is the number of components. If X_transform is not provided, a transform of X provided in fit is 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 the fit process.

See also

reconstruct

Alias of inverse_transform (Deprecated).

parameters(replace="params", removed="0.7.1") def parameters(self, default=False)[source]

Alias for params method.

params(default=False)[source]

Current or default configuration values.

Parameters

default (bool, optional, default: False) – If default is True, the default parameters are returned, else the current values.

Returns

dict – Current or default configuration values.

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 X attribute is used for \(X\)and \(\hat{X}\)is computed by the inverse_transform method

Parameters
  • X (NDDataset, optional) – Original dataset. If is not provided (default), the X attribute is used and X_hat is computed using inverse_transform.

  • X_hat (NDDataset, optional) – Inverse transformed dataset. if X is provided, X_hat must also be provided as compuyed externally.

  • **kwargs (keyword parameters, optional) – See Other Parameters.

Returns

Axes – Matplotlib subplot axe.

Other Parameters
  • colors (tuple or ndarray of 3 colors, optional) – Colors for X , X_hat and residuals E . in the case of 2D, The default colormap is used for X . By default, the three colors are NBlue , NGreen and NRed (which are colorblind friendly).

  • offset (float, optional, default: None) – Specify the separation (in percent) between the \(X\) , \(X_hat\) and \(E\).

  • nb_traces (int or 'all', optional) – Number of lines to display. Default is 'all'.

  • **others (Other keywords parameters) – Parameters passed to the internal plot method of the X dataset.

reconstruct(X_transform=None, **kwargs)[source]

Transform data back to its original space.

In other words, return an input X_original whose reduce/transform would be X_transform.

Parameters
  • X_transform (array-like of shape (n_observations, n_components), optional) – Reduced X data, where n_observations is the number of observations and n_components is the number of components. If X_transform is not provided, a transform of X provided in fit is 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 the fit process.

See also

reconstruct

Alias of inverse_transform (Deprecated).

Notes

Deprecated in version 0.6.

reduce(X=None, **kwargs)[source]

Apply dimensionality reduction to X.

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 the fit process.

Notes

Deprecated in version 0.6.

reset()[source]

Reset configuration parameters to their default values

to_dict()[source]

Return config value in a dict form.

Returns

dict – A regular dictionary.

transform(X=None, **kwargs)

Apply dimensionality reduction to X.

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 the fit process.

Examples using spectrochempy.NMF

NMF analysis example

NMF analysis example