liana.ms.nmf

Contents

liana.ms.nmf#

liana.ms.nmf(adata=None, df=None, n_components=None, k_range=range(1, 11), use_raw=False, layer=None, inplace=None, verbose=False, **kwargs)#

Fits NMF to an AnnData object.

Parameters:
adata AnnData | None (default: None)

Annotated data object.

df DataFrame | None (default: None)

Alternative input for data as a DataFrame, only used if adata is None.

n_components int | None (default: None)

Number of components to use. If None, the number of components is estimated using the elbow method.

k_range range (default: range(1, 11))

Range of components to test. Default: range(1, 10).

use_raw bool (default: False)

Whether to use the .raw attribute of adata. Defaults to False (uses .X).

layer str | None (default: None)

Layer in anndata.AnnData.layers to use. If None, use anndata.AnnData.X.

inplace bool | None (default: None)

Whether to store the factors on adata, or else to return them. Defaults to None, which stores them when adata is given and returns them on the df route. Passing inplace=True together with df raises, since there is no object to store them on.

**kwargs object

Keyword arguments to pass to sklearn.decomposition.NMF.

Return type:

tuple[ndarray, ndarray, DataFrame | None, int | None] | None

Returns:

If inplace is True, it will add NMF_W and NMF_H to the adata.obsm and adata.varm. If n_components is None, it will also add nfm_errors and nfm_rank to adata.uns.

If inplace is False, it will return W and H, and if n_components is None, it will also return errors and n_components. If n_components is None and inplace, errors and n_components will be assigned to adata.uns. If df is provided, only inplace=False is accepted – there is nothing to write to.

Raises:

ValueError – If adata is provided but it’s not a valid instance of an AnnData object, if neither an AnnData or DataFrame intance is provided as input, if inplace=True is combined with df, or if n_components is None and no elbow is found within k_range

Examples

nmf expects a non-negative matrix – typically the local ligand-receptor scores from liana.mt.bivariate:

>>> import liana as li
>>> adata = li.ds.generate_toy_spatial()
>>> lrdata = li.mt.bivariate(adata, resource_name="consensus", local_name="cosine", global_name=None, n_perms=None)
>>> li.ms.nmf(lrdata, n_components=3, random_state=0)

Leaving n_components as None instead estimates the rank with liana.ms.estimate_elbow(); inspect the curve with liana.pl.elbow().

Read the factors out with liana.ms.get_factor_scores() and liana.ms.get_variable_loadings().