liana.ms.estimate_elbow

Contents

liana.ms.estimate_elbow#

liana.ms.estimate_elbow(X, k_range, verbose=False, **kwargs)#

Estimate the rank of an NMF factorization from the elbow of its error curve.

Parameters:
X NDArray[number] | csc_matrix | csr_matrix | csc_array | csr_array

Non-negative matrix to factorize.

k_range range

Ranks to fit. The elbow is located among these, so None is returned if no knee is found within them.

verbose bool (default: False)

Whether to show a progress bar and report the estimated rank.

kwargs object

Keyword arguments passed to sklearn.decomposition.NMF.

Return type:

tuple[DataFrame, int | None]

Returns:

A tuple of the reconstruction error per rank (a DataFrame with columns k and error) and the estimated rank.

Examples

Called by liana.ms.nmf() when n_components is None. Unlike nmf it takes a plain non-negative matrix, not an AnnData. This one is built from two blocks, so its true rank is 2:

>>> import numpy as np
>>> import liana as li
>>> W = np.repeat(np.eye(2), 6, axis=0)
>>> H = np.array([[3.0, 2.0, 1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0, 2.0, 3.0]])
>>> errors, rank = li.ms.estimate_elbow(W @ H, k_range=range(1, 6), random_state=0, max_iter=500)

rank is the knee of the error curve – 2 here, since the error collapses as soon as k reaches the true rank and cannot improve after.

If no knee can be located within k_range, rank comes back as None – widen the range. A k_range that starts above the true rank returns its own lowest value.