Skip to content

CDiscover · discover.nmf

Non-negative matrix factorization

Which additive parts combine to make up these non-negative measurements?

Factorizes a table of non-negative numbers (counts, amounts, intensities) into a few non-negative parts: each row is a weighted sum of basis profiles, so components read as "ingredients" rather than contrasts. Frobenius multiplicative updates from a host-drawn start, identical in both engines; basis rows are scaled to sum to 1 and ordered by their total weight.

Verified in Python and R Python and R agree to 6 decimals Seeded Also called NMF, non-negative factorization, parts-based decomposition

A real result

Example “Usarrests two”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Non-negative matrix factorizationRecorded · Python and R agreeRecorded 2026-11-25 · 16 values compared
R

NMF found 2 additive parts in 4 variables; relative reconstruction error 14.1%.

Parts
2
Relative error
14.1%

Plots

Part weights 1 × 2Which rows group together, and how well separated are the groups?
View data
GroupPart 1Part 2
All rows2.1790.3916
All rows2.3510.4396
All rows1.9510.9421
All rows1.5970.4495
All rows2.0301.163
All rows1.6761.042
All rows0.49791.129
All rows1.3560.8573
All rows2.8160.6465
All rows2.5210.3227
All rows0.51151.267
All rows0.63680.7760
All rows1.8730.9141
All rows1.0710.8385
All rows0.28230.8849
All rows0.92180.8803
All rows1.2960.5092
All rows2.4090.4400
All rows0.36930.7438
All rows2.3030.5864
All rows0.78741.215
All rows2.2530.7567
All rows0.39461.022
All rows2.5660.0092
All rows1.5760.8358
All rows0.94520.6594
All rows0.71030.8784
All rows2.3570.9321
All rows0.25850.8611
All rows1.1221.179
All rows2.2920.6704
All rows1.9720.9459
All rows2.5760.0587
All rows0.12200.7060
All rows1.0610.9982
All rows1.1420.8694
All rows1.1430.9564
All rows0.84000.9618
All rows0.67961.218
All rows2.5390.1477
All rows0.63930.6064
All rows2.0520.4842
All rows1.9280.8344
All rows0.66991.237
All rows0.38130.4729
All rows1.3760.7164
All rows0.92851.086
All rows0.78270.4234
All rows0.25291.022
All rows1.1860.6949

Parts (each column sums to 1: how the part is made up)

VariablePart 1Part 2
Murder31.9%0.9%
Assault31.0%11.1%
UrbanPop16.0%64.4%
Rape21.1%23.6%

How much of the data each part carries

PartShare of total weightMostly made of
163.8%Murder, Assault, Rape
236.2%UrbanPop, Rape, Assault
Python

NMF found 2 additive parts in 4 variables; relative reconstruction error 14.1%.

Parts
2
Relative error
14.1%

To keep this page light, the plots are shown once, under the R tab.

Parts (each column sums to 1: how the part is made up)

VariablePart 1Part 2
Murder31.9%0.9%
Assault31.0%11.1%
UrbanPop16.0%64.4%
Rape21.1%23.6%

How much of the data each part carries

PartShare of total weightMostly made of
163.8%Murder, Assault, Rape
236.2%UrbanPop, Rape, Assault

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Usarrests twoml_usarrests · features: Murder, Assault, UrbanPop, Rape
  • Iris rawml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species

In the guides

Where it sits in the decision guides

  • Dimensionality reduction (PCA, ICA, NMF) · DS & ML Decision Guide · Discover — find structure without labels

What you need

Variablesnumeric · 2–2000 columns
Non-negative numbers (counts, amounts, shares); rows with a missing value are left out.
Color points bycategorical / boolean · 0–1 column
Optional: colors the component map only.

Choices you make

model

Componentsdefault 3

Number of additive parts to find.

preprocess

Scale variablesdefault max

Put variables on comparable ranges first so large-unit columns don't dominate.

  • Divide by the column maximum(default) — Keeps zeros at zero and every value in 0–1.
  • No scaling — Use the raw values (same units across columns).

Advanced

Iterationsdefault 500

Multiplicative-update passes over the data.

What it reports

n
How many independent units the analysis used; it sets precision and power.
n_variables
How many independent units the analysis used; it sets precision and power.
n_components
How many independent units the analysis used; it sets precision and power.
rel_error
Splits non-negative data into a few additive parts so every row is a weighted sum of part profiles.

Per group, level or term: basis[<k>:<variable>], weight_share[<k>], score_check[<k>]

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses numpy; R uses codesplashr.

Default traps between the two languages

  • Both engines run the multiplicative-update twin also used by discover.topics (start from the shared random stream). scikit-learn's NMF (coordinate descent, NNDSVD start) and R's NMF package give different, equally valid local optima; this implementation reports the same one in both engines.
Python

The exact script CodeSplash ran for example “Usarrests two” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Non-negative matrix factorization
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.nmf 1.0.0 · spec 367d072a96a16db9
# Dataset: ml_usarrests (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import discover_ext as dx
from codesplash.ml import embed as csembed
from codesplash.ml import text as cstext

def chart_rows(n, cap=2000):
    return np.arange(n) if n <= cap else np.unique(np.linspace(0, n - 1, cap).round().astype(int))

# %% Data
FEATURES = ["Murder", "Assault", "UrbanPop", "Rape"]
LABEL = None
SEED = 42
df = pd.read_parquet("tests/parity/fixtures/ml_usarrests.parquet", columns=list(dict.fromkeys(FEATURES + ([LABEL] if LABEL else []))))
n_input = len(df)
warnings = []
rows = csembed.complete_rows(df, FEATURES)
if len(rows) < n_input:
    warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a value was missing.")
X = csembed.numeric_matrix(df, FEATURES, rows)
if np.any(X < 0):
    bad = [f for j, f in enumerate(FEATURES) if np.any(X[:, j] < 0)]
    raise ValueError(f"NMF needs non-negative values; {', '.join(bad)} contain negative numbers.")
top = X.max(axis=0)
top[top == 0] = 1.0
X = X / top  # each variable on 0–1, zeros stay zero

# %% Factorization (multiplicative updates from a host-drawn start; twin of discover.topics' NMF)
K = min(2, len(FEATURES))
W, H = cstext.nmf(X, K, iterations=500, seed=SEED)
W, H = dx.nmf_canonical(W, H)
rel_error = float(np.linalg.norm(X - W @ H) / np.linalg.norm(X))
share = W.sum(axis=0) / W.sum()

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/discover.nmf/usarrests_two/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64)})
for j in range(K):
    emb[f"dim_{j + 1}"] = W[:, j]
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)

# %% Result
values = {"n": len(rows), "n_variables": len(FEATURES), "n_components": K, "rel_error": rel_error}
for j in range(K):
    values[f"weight_share[{j + 1}]"] = float(share[j])
    values[f"score_check[{j + 1}]"] = csembed.checksum(W[:, j], rows)
    for i, f in enumerate(FEATURES):
        values[f"basis[{j + 1}:{f}]"] = float(H[j, i])
tables = [{
    "key": "basis",
    "title": "Parts (each column sums to 1: how the part is made up)",
    "columns": [{"key": "variable", "label": "Variable"}] + [{"key": f"part{j + 1}", "label": f"Part {j + 1}", "type": "percent"} for j in range(K)],
    "rows": [dict({"variable": f}, **{f"part{j + 1}": float(H[j, i]) for j in range(K)}) for i, f in enumerate(FEATURES)],
}, {
    "key": "parts",
    "title": "How much of the data each part carries",
    "columns": [{"key": "part", "label": "Part", "type": "integer"}, {"key": "share", "label": "Share of total weight", "type": "percent"},
                {"key": "top", "label": "Mostly made of"}],
    "rows": [{"part": j + 1, "share": float(share[j]),
              "top": ", ".join(FEATURES[i] for i in np.argsort(-H[j], kind="stable")[:3])} for j in range(K)],
}]
charts = []
if K >= 2:
    pick = chart_rows(len(rows))
    groups = ["All rows"] * len(pick) if LABEL is None else [("(missing)" if pd.isna(v) else str(v)) for v in df[LABEL].iloc[rows[pick]]]
    charts.append(cs.chart("map", "cluster-scatter", "Part weights 1 × 2", {
        "x": cs.col("Part 1", W[pick, 0], "numeric"),
        "y": cs.col("Part 2", W[pick, 1], "numeric"),
        "cluster": cs.col(LABEL or "Group", groups, "categorical"),
    }))
cs.publish({
    "title": "Non-negative matrix factorization",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": len(rows),
    "summary": f"NMF found {K} additive parts in {len(FEATURES)} variables; relative reconstruction error {rel_error:.1%}.",
    "statistics": [
        {"key": "n_components", "label": "Parts", "value": K, "format": "integer"},
        {"key": "rel_error", "label": "Relative error", "value": rel_error, "format": "percent"},
    ],
    "tables": tables,
    "charts": charts,
    "values": values,
    "warnings": warnings,
    "artifacts": [{"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"}],
})
R

The exact script CodeSplash ran for example “Usarrests two” · R version 4.5.1 (2025-06-13)

# Non-negative matrix factorization
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.nmf 1.0.0 · spec 367d072a96a16db9
# Dataset: ml_usarrests (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

chart_rows <- function(n, cap = 2000) if (n <= cap) seq_len(n) else unique(round(seq(1, n, length.out = cap)))

# %% Data
FEATURES <- c("Murder", "Assault", "UrbanPop", "Rape")
LABEL <- NULL
SEED <- 42
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_usarrests.parquet", col_select = unique(c(FEATURES, LABEL))))
n_input <- nrow(df)
warnings <- list()
rows <- cs_ml_complete_rows(df, FEATURES)
if (length(rows) < n_input) {
  warnings <- c(warnings, sprintf("%d of %d rows were left out because a value was missing.", n_input - length(rows), n_input))
}
X <- cs_ml_numeric_matrix(df, FEATURES, rows)
if (any(X < 0)) {
  bad <- FEATURES[apply(X, 2, function(v) any(v < 0))]
  stop(sprintf("NMF needs non-negative values; %s contain negative numbers.", paste(bad, collapse = ", ")))
}
top <- apply(X, 2, max)
top[top == 0] <- 1
X <- sweep(X, 2, top, "/")  # each variable on 0–1, zeros stay zero

# %% Factorization (multiplicative updates from a host-drawn start; twin of discover.topics' NMF)
K <- min(2, length(FEATURES))
f <- cs_ml_nmf(X, K, iterations = 500, seed = SEED)
f <- cs_ml_nmf_canonical(f$W, f$H)
W <- f$W; H <- f$H
rel_error <- sqrt(sum((X - W %*% H)^2)) / sqrt(sum(X^2))
share <- colSums(W) / sum(W)

# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.nmf/usarrests_two/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(K)) emb[[paste0("dim_", j)]] <- W[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))

# %% Result
values <- list(n = length(rows), n_variables = length(FEATURES), n_components = K, rel_error = rel_error)
for (j in seq_len(K)) {
  values[[sprintf("weight_share[%d]", j)]] <- share[j]
  values[[sprintf("score_check[%d]", j)]] <- cs_ml_checksum(W[, j], rows)
  for (i in seq_along(FEATURES)) values[[sprintf("basis[%d:%s]", j, FEATURES[i])]] <- H[j, i]
}
tables <- list(
  list(key = "basis", title = "Parts (each column sums to 1: how the part is made up)",
       columns = c(list(list(key = "variable", label = "Variable")),
                   lapply(seq_len(K), function(j) list(key = paste0("part", j), label = paste("Part", j), type = "percent"))),
       rows = lapply(seq_along(FEATURES), function(i) {
         r <- list(variable = FEATURES[i])
         for (j in seq_len(K)) r[[paste0("part", j)]] <- H[j, i]
         r
       })),
  list(key = "parts", title = "How much of the data each part carries",
       columns = list(list(key = "part", label = "Part", type = "integer"), list(key = "share", label = "Share of total weight", type = "percent"),
                      list(key = "top", label = "Mostly made of")),
       rows = lapply(seq_len(K), function(j) list(part = j, share = share[j],
                                                  top = paste(FEATURES[utils::head(order(-H[j, ], seq_along(FEATURES)), 3)], collapse = ", "))))
)
charts <- list()
if (K >= 2) {
  pick <- chart_rows(length(rows))
  groups <- if (is.null(LABEL)) rep("All rows", length(pick)) else {
    g <- as.character(df[[LABEL]][rows[pick] + 1L]); g[is.na(g)] <- "(missing)"; g
  }
  charts[[1]] <- cs_chart("map", "cluster-scatter", "Part weights 1 × 2", list(
    x = cs_col("Part 1", W[pick, 1], "numeric"),
    y = cs_col("Part 2", W[pick, 2], "numeric"),
    cluster = cs_col(if (is.null(LABEL)) "Group" else LABEL, groups, "categorical")
  ))
}
cs_publish(list(
  title = "Non-negative matrix factorization",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(rows),
  summary = sprintf("NMF found %d additive parts in %d variables; relative reconstruction error %.1f%%.", K, length(FEATURES), 100 * rel_error),
  statistics = list(list(key = "n_components", label = "Parts", value = K, format = "integer"),
                    list(key = "rel_error", label = "Relative error", value = rel_error, format = "percent")),
  tables = tables,
  charts = charts,
  values = values,
  warnings = warnings,
  artifacts = list(list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"))
))

Sources

  • Lee DD, Seung HS (1999). Learning the parts of objects by non-negative matrix factorization. Nature 401:788–791.
  • Lee DD, Seung HS (2001). Algorithms for non-negative matrix factorization. NIPS 13.

From the CodeSplash method registry · discover.nmf v1.0.0.