Skip to content

NMF

Non-negative matrix factorisation of the counts into gene programmes.

HALS NMF, factorising genes by cells into gene loadings (w, genes by k) and cell usages (h, k by cells). One run, random restarts, consensus NMF in the cNMF style, and a sweep over k.

Start with nmf_k_sweep to pick k: it runs the consensus step for every k in the range and returns stability and reconstruction error per k. High stability while the error is still falling is the sweet spot. Then fit consensus_nmf at that k. nmf is one run, stabilised_nmf keeps all the random restarts and get_best_run pulls out the lowest-loss one.

What lands where. Nothing is written to the experiment. Every function returns a result object, and get_w gives the gene loadings as a frame. get_data turns the cell usages of an NmfResult or ConsensusNmfResult into an obs frame, one comp_XX column per component, for sc.add_obs. All functions take a SingleCells, a SingleCellsSubset or a MetaCells. Genes default to the HVGs, so run bv.pp.find_hvg first or pass gene_ids; cells default to the kept ones.

bv.pp.find_hvg(sc, hvg_no=500)
sweep = bv.nmf.nmf_k_sweep(sc, k_range=range(3, 8), n_runs=10)
sweep.frame
res = bv.nmf.consensus_nmf(sc, k=5, n_runs=10)
sc.add_obs(bv.nmf.get_data(res))
loadings = bv.nmf.get_w(res)

Gotchas. The factorisation uses the normalised counts; pass use_second_layer=False for the raw ones. The consensus step needs k and n_runs of at least 2 and raises when the restarts do not agree, with a message on what to change (a higher density_threshold in NmfConsensusParams, more runs, another k). In nmf_k_sweep a failing k gets a null stability and a warning instead. consensus_target="w" clusters in cell space and gets expensive past 20,000 cells. Indices are 0-based, the comp_XX and component_id names count from 1.

Worked through in Gene set analysis and GRN inference on PBMCs.

Choosing k

Non-negative matrix factorisation of the counts into gene programmes.

HALS NMF, factorising genes by cells into gene loadings (w, genes by k) and cell usages (h, k by cells). One run, random restarts, consensus NMF in the cNMF style, and a sweep over k.

Start with nmf_k_sweep to pick k: it runs the consensus step for every k in the range and returns stability and reconstruction error per k. High stability while the error is still falling is the sweet spot. Then fit consensus_nmf at that k. nmf is one run, stabilised_nmf keeps all the random restarts and get_best_run pulls out the lowest-loss one.

What lands where. Nothing is written to the experiment. Every function returns a result object, and get_w gives the gene loadings as a frame. get_data turns the cell usages of an NmfResult or ConsensusNmfResult into an obs frame, one comp_XX column per component, for sc.add_obs. All functions take a SingleCells, a SingleCellsSubset or a MetaCells. Genes default to the HVGs, so run bv.pp.find_hvg first or pass gene_ids; cells default to the kept ones.

bv.pp.find_hvg(sc, hvg_no=500)
sweep = bv.nmf.nmf_k_sweep(sc, k_range=range(3, 8), n_runs=10)
sweep.frame
res = bv.nmf.consensus_nmf(sc, k=5, n_runs=10)
sc.add_obs(bv.nmf.get_data(res))
loadings = bv.nmf.get_w(res)

Gotchas. The factorisation uses the normalised counts; pass use_second_layer=False for the raw ones. The consensus step needs k and n_runs of at least 2 and raises when the restarts do not agree, with a message on what to change (a higher density_threshold in NmfConsensusParams, more runs, another k). In nmf_k_sweep a failing k gets a null stability and a warning instead. consensus_target="w" clusters in cell space and gets expensive past 20,000 cells. Indices are 0-based, the comp_XX and component_id names count from 1.

NmfKSweepResult dataclass

NmfKSweepResult(
    frame: DataFrame,
    source_class: str,
    params: dict[str, object],
)

A consensus NMF k sweep.

Attributes:

Name Type Description
frame DataFrame

One row per k: k, stability (null where the consensus step failed), best_error, median_error, consensus_failed, n_dropped, n_empty_clusters and n_converged.

source_class str

"SingleCells" or "MetaCells".

params dict[str, object]

The parameters of the sweep.

nmf_k_sweep

nmf_k_sweep(
    sc: ScOrMc,
    k_range: Sequence[int] | range,
    *,
    cell_ids: Sequence[str] | None = None,
    gene_ids: Sequence[str] | None = None,
    preprocessing: Preprocessing = "none",
    use_second_layer: bool = True,
    nmf_hals_params: NmfHalsParams | None = None,
    nmf_consensus_params: NmfConsensusParams | None = None,
    n_runs: int = 30,
    seed: int = 42,
    verbose: Verbose = True,
) -> NmfKSweepResult

Consensus NMF over a range of k.

High stability while the error is still falling is the sweet spot. A k whose consensus step fails gets a null stability and a warning.

Parameters:

Name Type Description Default
sc ScOrMc

The experiment, a subset or meta cells.

required
k_range Sequence[int] | range

The ranks, unique and at least 2.

required
cell_ids Sequence[str] | None

Cell (meta cell) ids. None for the kept cells.

None
gene_ids Sequence[str] | None

Gene ids. None for the HVGs.

None
preprocessing Preprocessing

"none", per gene "sd" or "sqrt_sd" scaling.

'none'
use_second_layer bool

Factorise the normalised rather than the raw counts.

True
nmf_hals_params NmfHalsParams | None

The solver.

None
nmf_consensus_params NmfConsensusParams | None

The consensus step. None uses the defaults.

None
n_runs int

Restarts per k, at least 2.

30
seed int

Base seed of the restarts and the consensus k-means.

42
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
NmfKSweepResult

The NmfKSweepResult.

Raises:

Type Description
ValueError

On an invalid k_range or n_runs, or without genes.

References

Kotliar, et al., eLife, 2019.

Examples:

>>> sweep = bv.nmf.nmf_k_sweep(sc, k_range=range(3, 8), n_runs=10)
>>> sweep.frame

Consensus NMF

Non-negative matrix factorisation of the counts into gene programmes.

HALS NMF, factorising genes by cells into gene loadings (w, genes by k) and cell usages (h, k by cells). One run, random restarts, consensus NMF in the cNMF style, and a sweep over k.

Start with nmf_k_sweep to pick k: it runs the consensus step for every k in the range and returns stability and reconstruction error per k. High stability while the error is still falling is the sweet spot. Then fit consensus_nmf at that k. nmf is one run, stabilised_nmf keeps all the random restarts and get_best_run pulls out the lowest-loss one.

What lands where. Nothing is written to the experiment. Every function returns a result object, and get_w gives the gene loadings as a frame. get_data turns the cell usages of an NmfResult or ConsensusNmfResult into an obs frame, one comp_XX column per component, for sc.add_obs. All functions take a SingleCells, a SingleCellsSubset or a MetaCells. Genes default to the HVGs, so run bv.pp.find_hvg first or pass gene_ids; cells default to the kept ones.

bv.pp.find_hvg(sc, hvg_no=500)
sweep = bv.nmf.nmf_k_sweep(sc, k_range=range(3, 8), n_runs=10)
sweep.frame
res = bv.nmf.consensus_nmf(sc, k=5, n_runs=10)
sc.add_obs(bv.nmf.get_data(res))
loadings = bv.nmf.get_w(res)

Gotchas. The factorisation uses the normalised counts; pass use_second_layer=False for the raw ones. The consensus step needs k and n_runs of at least 2 and raises when the restarts do not agree, with a message on what to change (a higher density_threshold in NmfConsensusParams, more runs, another k). In nmf_k_sweep a failing k gets a null stability and a warning instead. consensus_target="w" clusters in cell space and gets expensive past 20,000 cells. Indices are 0-based, the comp_XX and component_id names count from 1.

ConsensusNmfResult dataclass

ConsensusNmfResult(
    w: ndarray,
    h: ndarray,
    gene_ids: tuple[str, ...],
    cell_ids: tuple[str, ...],
    cell_indices: ndarray,
    stability: float,
    rel_error: float,
    rel_run_errors: ndarray,
    clusters: DataFrame,
    cluster_sizes: DataFrame,
    n_dropped: int,
    n_empty_clusters: int,
    source_class: str,
    params: dict[str, object],
)

Consensus HALS NMF.

Attributes:

Name Type Description
w ndarray

(n_genes, k) consensus gene loadings.

h ndarray

(k, n_cells) cell usages refit against them.

gene_ids tuple[str, ...]

The genes.

cell_ids tuple[str, ...]

The cells (meta cells).

cell_indices ndarray

0-based store index (meta cell row) of each cell.

stability float

Mean silhouette of the consensus clustering.

rel_error float

Relative reconstruction error of the consensus fit.

rel_run_errors ndarray

Relative error per restart.

clusters DataFrame

One row per pooled component: component_id, run, component, pooled_idx, cluster (null when dropped), local_density, silhouette (null when dropped) and kept.

cluster_sizes DataFrame

cluster and n.

n_dropped int

Components the density filter dropped.

n_empty_clusters int

Clusters left empty.

source_class str

"SingleCells" or "MetaCells".

params dict[str, object]

The parameters of the run.

shape property

shape: tuple[int, int, int]

(n_genes, n_cells, k).

consensus_nmf

consensus_nmf(
    sc: ScOrMc,
    k: int,
    *,
    cell_ids: Sequence[str] | None = None,
    gene_ids: Sequence[str] | None = None,
    preprocessing: Preprocessing = "none",
    use_second_layer: bool = True,
    nmf_hals_params: NmfHalsParams | None = None,
    nmf_consensus_params: NmfConsensusParams | None = None,
    n_runs: int = 30,
    seed: int = 42,
    verbose: Verbose = True,
) -> ConsensusNmfResult

Consensus HALS NMF (cNMF).

Pools the components of n_runs random restarts, drops the ones in sparse neighbourhoods, clusters the rest into k programmes and takes each cluster's median; the usages are refit against it. The k-means of the consensus step is seeded from seed.

Parameters:

Name Type Description Default
sc ScOrMc

The experiment, a subset or meta cells.

required
k int

Number of components, at least 2.

required
cell_ids Sequence[str] | None

Cell (meta cell) ids. None for the kept cells.

None
gene_ids Sequence[str] | None

Gene ids. None for the HVGs.

None
preprocessing Preprocessing

"none", per gene "sd" or "sqrt_sd" scaling.

'none'
use_second_layer bool

Factorise the normalised rather than the raw counts.

True
nmf_hals_params NmfHalsParams | None

The solver.

None
nmf_consensus_params NmfConsensusParams | None

The consensus step. None uses the defaults.

None
n_runs int

Number of restarts, at least 2.

30
seed int

Base seed of the restarts and the consensus k-means.

42
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
ConsensusNmfResult

The ConsensusNmfResult.

Raises:

Type Description
ValueError

On k or n_runs below 2, without genes, or when the consensus step fails (the message says what to try).

References

Kotliar, et al., eLife, 2019.

Examples:

>>> res = bv.nmf.consensus_nmf(sc, k=5, n_runs=10)
>>> sc.add_obs(bv.nmf.get_data(res))
>>> stability = bv.nmf.get_stability(res)

get_stability

get_stability(x: ConsensusNmfResult) -> dict[str, object]

The consensus diagnostics.

Parameters:

Name Type Description Default
x ConsensusNmfResult

The consensus NMF result.

required

Single and repeated runs

Non-negative matrix factorisation of the counts into gene programmes.

HALS NMF, factorising genes by cells into gene loadings (w, genes by k) and cell usages (h, k by cells). One run, random restarts, consensus NMF in the cNMF style, and a sweep over k.

Start with nmf_k_sweep to pick k: it runs the consensus step for every k in the range and returns stability and reconstruction error per k. High stability while the error is still falling is the sweet spot. Then fit consensus_nmf at that k. nmf is one run, stabilised_nmf keeps all the random restarts and get_best_run pulls out the lowest-loss one.

What lands where. Nothing is written to the experiment. Every function returns a result object, and get_w gives the gene loadings as a frame. get_data turns the cell usages of an NmfResult or ConsensusNmfResult into an obs frame, one comp_XX column per component, for sc.add_obs. All functions take a SingleCells, a SingleCellsSubset or a MetaCells. Genes default to the HVGs, so run bv.pp.find_hvg first or pass gene_ids; cells default to the kept ones.

bv.pp.find_hvg(sc, hvg_no=500)
sweep = bv.nmf.nmf_k_sweep(sc, k_range=range(3, 8), n_runs=10)
sweep.frame
res = bv.nmf.consensus_nmf(sc, k=5, n_runs=10)
sc.add_obs(bv.nmf.get_data(res))
loadings = bv.nmf.get_w(res)

Gotchas. The factorisation uses the normalised counts; pass use_second_layer=False for the raw ones. The consensus step needs k and n_runs of at least 2 and raises when the restarts do not agree, with a message on what to change (a higher density_threshold in NmfConsensusParams, more runs, another k). In nmf_k_sweep a failing k gets a null stability and a warning instead. consensus_target="w" clusters in cell space and gets expensive past 20,000 cells. Indices are 0-based, the comp_XX and component_id names count from 1.

NmfResult dataclass

NmfResult(
    w: ndarray,
    h: ndarray,
    gene_ids: tuple[str, ...],
    cell_ids: tuple[str, ...],
    cell_indices: ndarray,
    final_loss: float,
    n_iter: int | None,
    converged: bool,
    source_class: str,
    params: dict[str, object],
)

A single HALS NMF run.

Attributes:

Name Type Description
w ndarray

(n_genes, k) gene loadings.

h ndarray

(k, n_cells) cell usages.

gene_ids tuple[str, ...]

The genes, the rows of w.

cell_ids tuple[str, ...]

The cells (meta cells), the columns of h.

cell_indices ndarray

0-based store index (meta cell row) of each cell.

final_loss float

The final reconstruction loss.

n_iter int | None

Iterations run; None for a run taken from a stabilised fit.

converged bool

Whether the tolerance was met.

source_class str

"SingleCells" or "MetaCells".

params dict[str, object]

The parameters of the run.

shape property

shape: tuple[int, int, int]

(n_genes, n_cells, k).

StabilisedNmfResult dataclass

StabilisedNmfResult(
    w_all: ndarray,
    w_all_columns: tuple[str, ...],
    h_per_run: tuple[ndarray, ...],
    gene_ids: tuple[str, ...],
    cell_ids: tuple[str, ...],
    cell_indices: ndarray,
    losses: ndarray,
    converged: tuple[bool, ...],
    best_idx: int,
    source_class: str,
    params: dict[str, object],
)

Randomly initialised HALS NMF restarts.

Attributes:

Name Type Description
w_all ndarray

(n_genes, k * n_runs) gene loadings, run blocks side by side, columns named in w_all_columns.

w_all_columns tuple[str, ...]

run_01.comp_01, ...

h_per_run tuple[ndarray, ...]

One (k, n_cells) usage matrix per run.

gene_ids tuple[str, ...]

The genes.

cell_ids tuple[str, ...]

The cells (meta cells).

cell_indices ndarray

0-based store index (meta cell row) of each cell.

losses ndarray

Final loss per run.

converged tuple[bool, ...]

Convergence per run.

best_idx int

0-based run with the lowest loss.

source_class str

"SingleCells" or "MetaCells".

params dict[str, object]

The parameters of the run.

nmf

nmf(
    sc: ScOrMc,
    k: int,
    *,
    cell_ids: Sequence[str] | None = None,
    gene_ids: Sequence[str] | None = None,
    preprocessing: Preprocessing = "none",
    use_second_layer: bool = True,
    nmf_hals_params: NmfHalsParams | None = None,
    seed: int = 42,
    verbose: Verbose = True,
) -> NmfResult

One HALS NMF run.

Parameters:

Name Type Description Default
sc ScOrMc

The experiment, a subset or meta cells.

required
k int

Number of components.

required
cell_ids Sequence[str] | None

Cell (meta cell) ids. None for the kept cells.

None
gene_ids Sequence[str] | None

Gene ids. None for the HVGs.

None
preprocessing Preprocessing

"none", per gene "sd" or "sqrt_sd" scaling.

'none'
use_second_layer bool

Factorise the normalised rather than the raw counts.

True
nmf_hals_params NmfHalsParams | None

The solver. None uses the defaults (NNDSVD).

None
seed int

Seed for a random initialisation.

42
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
NmfResult

The NmfResult.

Raises:

Type Description
ValueError

On k below 1 or without genes.

Examples:

>>> res = bv.nmf.nmf(sc, k=5)
>>> res = bv.nmf.nmf(sc, k=5, preprocessing="sd")
>>> sc.add_obs(bv.nmf.get_data(res))

stabilised_nmf

stabilised_nmf(
    sc: ScOrMc,
    k: int,
    *,
    cell_ids: Sequence[str] | None = None,
    gene_ids: Sequence[str] | None = None,
    preprocessing: Preprocessing = "none",
    use_second_layer: bool = True,
    nmf_hals_params: NmfHalsParams | None = None,
    n_runs: int = 30,
    seed: int = 42,
    verbose: Verbose = True,
) -> StabilisedNmfResult

Randomly initialised HALS NMF restarts.

Parameters:

Name Type Description Default
sc ScOrMc

The experiment, a subset or meta cells.

required
k int

Number of components.

required
cell_ids Sequence[str] | None

Cell (meta cell) ids. None for the kept cells.

None
gene_ids Sequence[str] | None

Gene ids. None for the HVGs.

None
preprocessing Preprocessing

"none", per gene "sd" or "sqrt_sd" scaling.

'none'
use_second_layer bool

Factorise the normalised rather than the raw counts.

True
nmf_hals_params NmfHalsParams | None

The solver; nmf_init is ignored, the restarts are random.

None
n_runs int

Number of restarts.

30
seed int

Base seed of the restarts.

42
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
StabilisedNmfResult

The StabilisedNmfResult.

Raises:

Type Description
ValueError

On k or n_runs below 1, or without genes.

Examples:

>>> stab = bv.nmf.stabilised_nmf(sc, k=5, n_runs=10)
>>> best = bv.nmf.get_best_run(stab)

get_best_run

get_best_run(x: StabilisedNmfResult) -> NmfResult

The lowest loss run as an NmfResult.

Parameters:

Name Type Description Default
x StabilisedNmfResult

The stabilised NMF result.

required

Reading results

Non-negative matrix factorisation of the counts into gene programmes.

HALS NMF, factorising genes by cells into gene loadings (w, genes by k) and cell usages (h, k by cells). One run, random restarts, consensus NMF in the cNMF style, and a sweep over k.

Start with nmf_k_sweep to pick k: it runs the consensus step for every k in the range and returns stability and reconstruction error per k. High stability while the error is still falling is the sweet spot. Then fit consensus_nmf at that k. nmf is one run, stabilised_nmf keeps all the random restarts and get_best_run pulls out the lowest-loss one.

What lands where. Nothing is written to the experiment. Every function returns a result object, and get_w gives the gene loadings as a frame. get_data turns the cell usages of an NmfResult or ConsensusNmfResult into an obs frame, one comp_XX column per component, for sc.add_obs. All functions take a SingleCells, a SingleCellsSubset or a MetaCells. Genes default to the HVGs, so run bv.pp.find_hvg first or pass gene_ids; cells default to the kept ones.

bv.pp.find_hvg(sc, hvg_no=500)
sweep = bv.nmf.nmf_k_sweep(sc, k_range=range(3, 8), n_runs=10)
sweep.frame
res = bv.nmf.consensus_nmf(sc, k=5, n_runs=10)
sc.add_obs(bv.nmf.get_data(res))
loadings = bv.nmf.get_w(res)

Gotchas. The factorisation uses the normalised counts; pass use_second_layer=False for the raw ones. The consensus step needs k and n_runs of at least 2 and raises when the restarts do not agree, with a message on what to change (a higher density_threshold in NmfConsensusParams, more runs, another k). In nmf_k_sweep a failing k gets a null stability and a warning instead. consensus_target="w" clusters in cell space and gets expensive past 20,000 cells. Indices are 0-based, the comp_XX and component_id names count from 1.

get_w

get_w(
    x: NmfResult | StabilisedNmfResult | ConsensusNmfResult,
) -> DataFrame

The gene loadings: gene_id and one column per component (comp_01, ..., or run_01.comp_01, ... for restarts).

Parameters:

Name Type Description Default
x NmfResult | StabilisedNmfResult | ConsensusNmfResult

A single, stabilised or consensus NMF result.

required

get_h

get_h(
    x: NmfResult | StabilisedNmfResult | ConsensusNmfResult,
) -> ndarray | tuple[ndarray, ...]

The cell usages: (k, n_cells), one per run for restarts.

Parameters:

Name Type Description Default
x NmfResult | StabilisedNmfResult | ConsensusNmfResult

A single, stabilised or consensus NMF result.

required

get_data

get_data(x: NmfResult | ConsensusNmfResult) -> DataFrame

The cell usages as an obs frame for add_obs: one comp_XX column per component and the 0-based cell_idx (meta_cell_idx for meta cells).

Parameters:

Name Type Description Default
x NmfResult | ConsensusNmfResult

A single or consensus NMF result.

required

get_params

get_params(
    x: NmfResult
    | StabilisedNmfResult
    | ConsensusNmfResult
    | NmfKSweepResult,
) -> dict[str, object]

The parameters of the run.

Parameters:

Name Type Description Default
x NmfResult | StabilisedNmfResult | ConsensusNmfResult | NmfKSweepResult

Any NMF result, including a k sweep.

required