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.
A real result
Example “Usarrests two”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
NMF found 2 additive parts in 4 variables; relative reconstruction error 14.1%.
- Parts
- 2
- Relative error
- 14.1%
Plots
View data
| Group | Part 1 | Part 2 |
|---|---|---|
| All rows | 2.179 | 0.3916 |
| All rows | 2.351 | 0.4396 |
| All rows | 1.951 | 0.9421 |
| All rows | 1.597 | 0.4495 |
| All rows | 2.030 | 1.163 |
| All rows | 1.676 | 1.042 |
| All rows | 0.4979 | 1.129 |
| All rows | 1.356 | 0.8573 |
| All rows | 2.816 | 0.6465 |
| All rows | 2.521 | 0.3227 |
| All rows | 0.5115 | 1.267 |
| All rows | 0.6368 | 0.7760 |
| All rows | 1.873 | 0.9141 |
| All rows | 1.071 | 0.8385 |
| All rows | 0.2823 | 0.8849 |
| All rows | 0.9218 | 0.8803 |
| All rows | 1.296 | 0.5092 |
| All rows | 2.409 | 0.4400 |
| All rows | 0.3693 | 0.7438 |
| All rows | 2.303 | 0.5864 |
| All rows | 0.7874 | 1.215 |
| All rows | 2.253 | 0.7567 |
| All rows | 0.3946 | 1.022 |
| All rows | 2.566 | 0.0092 |
| All rows | 1.576 | 0.8358 |
| All rows | 0.9452 | 0.6594 |
| All rows | 0.7103 | 0.8784 |
| All rows | 2.357 | 0.9321 |
| All rows | 0.2585 | 0.8611 |
| All rows | 1.122 | 1.179 |
| All rows | 2.292 | 0.6704 |
| All rows | 1.972 | 0.9459 |
| All rows | 2.576 | 0.0587 |
| All rows | 0.1220 | 0.7060 |
| All rows | 1.061 | 0.9982 |
| All rows | 1.142 | 0.8694 |
| All rows | 1.143 | 0.9564 |
| All rows | 0.8400 | 0.9618 |
| All rows | 0.6796 | 1.218 |
| All rows | 2.539 | 0.1477 |
| All rows | 0.6393 | 0.6064 |
| All rows | 2.052 | 0.4842 |
| All rows | 1.928 | 0.8344 |
| All rows | 0.6699 | 1.237 |
| All rows | 0.3813 | 0.4729 |
| All rows | 1.376 | 0.7164 |
| All rows | 0.9285 | 1.086 |
| All rows | 0.7827 | 0.4234 |
| All rows | 0.2529 | 1.022 |
| All rows | 1.186 | 0.6949 |
Parts (each column sums to 1: how the part is made up)
| Variable | Part 1 | Part 2 |
|---|---|---|
| Murder | 31.9% | 0.9% |
| Assault | 31.0% | 11.1% |
| UrbanPop | 16.0% | 64.4% |
| Rape | 21.1% | 23.6% |
How much of the data each part carries
| Part | Share of total weight | Mostly made of |
|---|---|---|
| 1 | 63.8% | Murder, Assault, Rape |
| 2 | 36.2% | UrbanPop, Rape, Assault |
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)
| Variable | Part 1 | Part 2 |
|---|---|---|
| Murder | 31.9% | 0.9% |
| Assault | 31.0% | 11.1% |
| UrbanPop | 16.0% | 64.4% |
| Rape | 21.1% | 23.6% |
How much of the data each part carries
| Part | Share of total weight | Mostly made of |
|---|---|---|
| 1 | 63.8% | Murder, Assault, Rape |
| 2 | 36.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.
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"}],
})
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.