Parts and extremes: NMF and archetypal analysis
When nothing can be negative, a row is better described as a sum of parts than as a mean plus signed directions. NMF finds additive parts; archetypal analysis describes rows as mixtures of extreme profiles at the edges of the data.
What runs in CodeSplash
- REP016Nonnegative matrix factorization (NMF) Runs in CodeSplash
- REP017Archetypal analysis Runs in CodeSplash
- Non-negative matrix factorization Verified in Python and R
- Archetypal analysis Verified in Python and R
You will be able to
- Write the NMF objective, its multiplicative updates and the two common losses
- Explain why NMF factors are not unique and depend on initialization
- Describe archetypes as convex combinations of rows and contrast them with cluster centers
Sums of parts
ReadCounts, intensities, spectra and spending can't go below zero. PCA describes them as a mean plus or minus signed directions, which produces "negative spending" components that are hard to read.
Non-negative matrix factorizationNon-negative matrix factorizationSplits non-negative data into a few additive parts so every row is a weighted sum of part profiles. fits
Each row is an additive mix (weights in ) of non-negative parts (rows of ). Nothing can cancel, so parts tend to be localized: a few words for a topic, a few frequencies for a sound.
How it's fitted
ReadWith squared error, Lee and Seung's multiplicative updates alternate
Multiplying by a non-negative ratio keeps entries non-negative, and each update never raises the loss. The reference's example checks exactly that over 200 updates; its final loss was 0.0213.
Two losses are common: squared error (Gaussian-like noise) and generalized KL (Poisson-like counts, as in topic models). They weight large and small entries differently, so choose deliberately.
Parts from bars
ExploreAExplorable · NMF finds the parts
Why does a factorization that can only add find parts that look like the pieces the data were built from?
At the same rank, which reconstructs the images more closely?
Commit your prediction above to see the result
Make your prediction to see the result.
Images made by adding horizontal and vertical bars. NMF's parts come out as bars because it can only add; the SVD's components mix positive and negative pixels. At the same rank the SVD always reconstructs a little better, and it needs one part fewer than NMF to rebuild these images.
NMF on US arrests
ReadNMF 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 |
The exact R script · R 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"))
))
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 |
The exact Python script · Python 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"}],
})
Two parts rebuild the table with relative error 0.141. Part 2 is mostly urban population (basis weight 0.64); part 1 spreads over the three crime rates. Each state is a non-negative mix of "crime" and "city".
Not unique, not global
Read- for any positive diagonal , and parts can be reordered, so normalize before comparing.
- Some data allow much broader transformations, so two good fits can show different parts.
- The loss has many local optima: initialization changes the answer. Compare several starts.
- Shifting centered data to make it positive changes the problem; NMF is for data that are non-negative to begin with.
Archetypes: extremes, not averages
ReadArchetypal analysisArchetypal analysisFinds k extreme profiles (mixtures of real rows on the data's edge) and writes every row as a mix of them. looks for a few extreme profiles. Each archetype is a convex combination of rows, so it lies on the edge of the data cloud; each row is a convex combination of archetypes:
Rows of are membershipsArchetype membershipHow much of an archetype a row is made of; a row's memberships are non-negative and sum to 1.: "70% budget shopper, 30% premium". Cluster centers sit in the middle of groups; archetypes sit at the corners.
Corners recovered
ReadArchetypal analysis with k = 3: the archetypes explain 100% of the variation; each row is a mix of them (membership columns).
- Clusters
- 3
- Mean silhouette
- 0.4189
Plots
View data
| Center | Cluster | PC1 (62%) | PC2 (38%) |
|---|---|---|---|
| false | 3 | 6.956 | −3.062 |
| false | 1 | −6.497 | −3.218 |
| false | 2 | 0.5277 | 6.355 |
| false | 2 | 0.0714 | 0.7195 |
| false | 3 | 3.527 | −0.3142 |
| false | 2 | −2.592 | 2.099 |
| false | 2 | −0.0076 | 5.624 |
| false | 2 | −1.689 | 1.970 |
| false | 1 | −3.916 | −1.437 |
| false | 1 | −2.075 | 1.140 |
| false | 2 | −1.093 | 2.732 |
| false | 1 | −4.352 | −1.785 |
| false | 1 | −2.714 | 1.009 |
| false | 3 | 3.883 | −0.2344 |
| false | 1 | −0.9144 | −2.935 |
| false | 2 | 0.5248 | 3.814 |
| false | 2 | 2.486 | 1.886 |
| false | 1 | −2.499 | 1.005 |
| false | 1 | 0.1331 | −0.6407 |
| false | 2 | −0.6333 | 4.127 |
| false | 3 | 3.918 | 0.1091 |
| false | 3 | 3.591 | −1.956 |
| false | 1 | −4.854 | −1.827 |
| false | 3 | 1.458 | −2.462 |
| false | 2 | 1.659 | 4.434 |
| false | 2 | −1.871 | 2.735 |
| false | 1 | −4.907 | −1.280 |
| false | 3 | 0.5422 | −0.5398 |
| false | 1 | −1.862 | −2.048 |
| false | 2 | 3.046 | 2.174 |
| false | 3 | 6.097 | −2.737 |
| false | 1 | −2.397 | −2.098 |
| false | 1 | −2.279 | −3.159 |
| false | 1 | −2.393 | −0.7996 |
| false | 1 | −1.930 | −2.747 |
| false | 2 | −0.4309 | 4.763 |
| false | 3 | 2.209 | 0.1479 |
| false | 1 | −4.610 | −2.434 |
| false | 1 | −0.7122 | −2.162 |
| false | 1 | −0.8692 | −0.7999 |
| false | 1 | −2.152 | −2.543 |
| false | 3 | 2.360 | −0.2768 |
| false | 2 | −1.906 | 1.139 |
| false | 3 | 3.236 | −2.369 |
| false | 3 | 4.429 | −0.9506 |
| false | 1 | −2.039 | −0.8721 |
| false | 3 | 1.159 | −0.8047 |
| false | 2 | 1.108 | 1.403 |
| false | 2 | −1.101 | 0.9592 |
| false | 3 | 6.157 | −2.112 |
| false | 2 | −0.8316 | 1.548 |
| false | 3 | 4.029 | 0.6832 |
| false | 2 | −1.759 | 1.132 |
| false | 1 | −3.673 | 0.0259 |
| false | 2 | 1.957 | 1.445 |
| false | 1 | −1.510 | −2.546 |
| false | 3 | 5.822 | −1.546 |
| false | 3 | 2.114 | −1.107 |
| false | 2 | −1.383 | 2.896 |
| false | 3 | 1.451 | −2.273 |
First 60 of 63 rows.
View data
| Variable | Value | Archetype | Scaled value |
|---|---|---|---|
| a | 8 | Archetype 1 | 8 |
| b | 1 | Archetype 1 | 1 |
| c | 0 | Archetype 1 | 0 |
| d | 6 | Archetype 1 | 6 |
| a | 3 | Archetype 2 | 3 |
| b | 9 | Archetype 2 | 9 |
| c | 4 | Archetype 2 | 4 |
| d | 0 | Archetype 2 | 0 |
| a | 0 | Archetype 3 | 0 |
| b | 0 | Archetype 3 | 0 |
| c | 10 | Archetype 3 | 10 |
| d | 2 | Archetype 3 | 2 |
View data
| Cluster | Silhouette width |
|---|---|
| 1 | 0.6351 |
| 1 | 0.6306 |
| 1 | 0.6081 |
| 1 | 0.6072 |
| 1 | 0.6021 |
| 1 | 0.6021 |
| 1 | 0.6002 |
| 1 | 0.5932 |
| 1 | 0.5757 |
| 1 | 0.5654 |
| 1 | 0.5462 |
| 1 | 0.5248 |
| 1 | 0.5084 |
| 1 | 0.4768 |
| 1 | 0.4257 |
| 1 | 0.4251 |
| 1 | 0.4049 |
| 1 | 0.3279 |
| 1 | 0.0836 |
| 1 | 0.0504 |
| 1 | 0.0413 |
| 1 | −0.1228 |
| 2 | 0.5794 |
| 2 | 0.5756 |
| 2 | 0.5704 |
| 2 | 0.5427 |
| 2 | 0.5302 |
| 2 | 0.5149 |
| 2 | 0.4909 |
| 2 | 0.4622 |
| 2 | 0.4423 |
| 2 | 0.3897 |
| 2 | 0.3665 |
| 2 | 0.2698 |
| 2 | 0.2582 |
| 2 | 0.2163 |
| 2 | 0.1883 |
| 2 | 0.1185 |
| 2 | 0.0834 |
| 2 | 0.0671 |
| 2 | 0.0547 |
| 2 | −0.0124 |
| 3 | 0.6439 |
| 3 | 0.6336 |
| 3 | 0.6085 |
| 3 | 0.6024 |
| 3 | 0.5932 |
| 3 | 0.5879 |
| 3 | 0.5867 |
| 3 | 0.5818 |
| 3 | 0.5432 |
| 3 | 0.5403 |
| 3 | 0.5172 |
| 3 | 0.4570 |
| 3 | 0.4460 |
| 3 | 0.3418 |
| 3 | 0.3400 |
| 3 | 0.3273 |
| 3 | 0.3033 |
| 3 | 0.0578 |
Clusters
| Cluster | Size | Share | a | b | c | d |
|---|---|---|---|---|---|---|
| 1 | 22 | 36.7% | 5.583 | 2.254 | 2.615 | 4.160 |
| 2 | 20 | 33.3% | 3.746 | 5.777 | 3.932 | 1.719 |
| 3 | 18 | 30.0% | 1.893 | 1.954 | 7.185 | 2.250 |
Archetypes (in the original units) and the closest real row
| Archetype | Closest row | Mean membership | a | b | c | d |
|---|---|---|---|---|---|---|
| 1 | 2 | 35.9% | 8 | 1 | 0 | 6 |
| 2 | 3 | 33.1% | 3 | 9 | 4 | 0 |
| 3 | 1 | 31.0% | 0 | 0 | 10 | 2 |
- Archetype 1 sits on row 2, which is extreme in at least one variable; outliers pull archetypes outward.
- Archetype 2 sits on row 3, which is extreme in at least one variable; outliers pull archetypes outward.
- Archetype 3 sits on row 1, which is extreme in at least one variable; outliers pull archetypes outward.
The exact R script · R R version 4.5.1 (2025-06-13)
# Archetypal analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.archetypes 1.0.0 · spec 380f335c032ed4a4
# Dataset: rep1_simplex (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
FEATURES <- c("a", "b", "c", "d")
LABEL <- NULL # known groups (external validation only)
ROW_ID <- NULL # row labels for charts
SEED <- 42
KINDS <- list(
a = "numeric",
b = "numeric",
c = "numeric",
d = "numeric"
)
LEVELS <- list(
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/rep1_simplex.parquet", col_select = unique(c(FEATURES, LABEL, ROW_ID))))
n_input <- nrow(df)
prep <- cs_ml_cluster_prepare(df, FEATURES, KINDS, LEVELS, missing = "drop", scale = "none")
X <- prep$X; rows <- prep$rows; names_ <- prep$names; frame <- prep$frame
warnings <- list()
if (length(rows) < n_input) {
warnings <- c(warnings, sprintf("%d of %d rows were left out because a feature was missing.", n_input - length(rows), n_input))
}
if (length(rows) < 3) stop("Clustering needs at least three rows with every feature present.")
truth <- if (!is.null(LABEL)) as.character(frame[[LABEL]]) else NULL
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.archetypes/simplex_corners/out-r")
values <- list(n_used = length(rows))
centers <- NULL
center_ids <- NULL
D <- NULL
extra <- list()
tables <- list()
charts <- list()
summary <- NULL
# %% Clustering
K <- 3
if (!all(is.finite(X))) stop("Archetypal analysis needs finite values; remove or recode infinite values first.")
if (K >= length(rows)) cs_error("CS_E_TOO_FEW_ROWS", what = sprintf("Archetypal analysis with k = %d", K), min = K + 1, n = length(rows))
# Projected gradient on both simplex factors from a furthest-sum start (no random draws).
fit <- cs_rep_archetypes(X, K, max_iter = 500)
if (!fit$converged) warnings <- c(warnings, sprintf("Archetypal analysis stopped after %d iterations before its tolerance; raise the iteration limit.", fit$iterations))
o <- cs_rep_archetype_order(fit$A) # the clustering driver's canonical order, so cluster c is archetype c
A <- fit$A[, o, drop = FALSE]
Cw <- fit$C[o, , drop = FALSE]
Zc <- Cw %*% X
raw <- max.col(A, ties.method = "first") - 1L
centers <- Zc
for (j in seq_len(K)) extra[[sprintf("membership_%d", j)]] <- A[, j]
sst <- sum(sweep(X, 2, colMeans(X))^2)
values$n_archetypes <- K
values$rss <- fit$sse
values$var_explained <- if (sst > 0) 1 - fit$sse / sst else NaN
X_raw <- as.matrix(as.data.frame(lapply(frame[, FEATURES, drop = FALSE], function(x) as.numeric(as.character(x)))))
for (j in seq_len(ncol(X_raw))) { # filled cells take the column median, as the design did
gap <- is.na(X_raw[, j])
if (any(gap)) X_raw[gap, j] <- stats::median(X_raw[, j], na.rm = TRUE)
}
Z_raw <- Cw %*% X_raw # archetypes as mixtures of real rows, in the original units
arch_rows <- list()
for (j in seq_len(K)) {
d <- sqrt(rowSums(sweep(X, 2, Zc[j, ])^2))
near <- which.min(d)
values[[sprintf("nearest_row[%d]", j)]] <- rows[near] + 1L
values[[sprintf("nearest_distance[%d]", j)]] <- d[near]
values[[sprintf("mean_membership[%d]", j)]] <- mean(A[, j])
r <- list(archetype = j, nearest = rows[near] + 1L, membership = mean(A[, j]))
for (i in seq_along(FEATURES)) {
values[[sprintf("archetype[%d,%s]", j, FEATURES[i])]] <- Z_raw[j, i]
r[[FEATURES[i]]] <- Z_raw[j, i]
}
arch_rows[[j]] <- r
top <- which.max(Cw[j, ])
if (Cw[j, top] >= 0.9 && max(abs(X[top, ])) > 4) {
warnings <- c(warnings, sprintf("Archetype %d sits on row %d, which is extreme in at least one variable; outliers pull archetypes outward.", j, rows[top] + 1L))
}
}
tables[[length(tables) + 1L]] <- list(
key = "archetypes", title = "Archetypes (in the original units) and the closest real row",
columns = c(list(list(key = "archetype", label = "Archetype", type = "integer"),
list(key = "nearest", label = "Closest row", type = "integer"),
list(key = "membership", label = "Mean membership", type = "percent")),
lapply(FEATURES, function(f) list(key = f, label = f, type = "number"))),
rows = arch_rows
)
names_a <- paste("Archetype", seq_len(K))
charts[[length(charts) + 1L]] <- cs_chart("profiles", "matrix-heatmap", "Archetype profiles (scaled; cell text in the original units)", list(
row = cs_col("Archetype", rep(names_a, each = length(FEATURES)), "categorical", levels = names_a),
col = cs_col("Variable", rep(FEATURES, times = K), "categorical", levels = FEATURES),
value = cs_col("Scaled value", as.vector(t(Zc)), "numeric"),
label = cs_col("Value", formatC(as.vector(t(Z_raw)), digits = 3, format = "g"), "categorical")
))
summary <- sprintf("Archetypal analysis with k = %d: the archetypes explain %.0f%% of the variation; each row is a mix of them (membership columns).",
K, 100 * values$var_explained)
# %% Canonical labels and validation
labels <- cs_ml_canonical(raw)
ids <- sort(unique(labels[labels != -1]))
k <- length(ids)
values$k <- k
values$n_noise <- sum(labels == -1)
if (!is.null(centers)) {
cid <- if (is.null(center_ids)) seq_len(nrow(centers)) - 1L else center_ids
raw_of <- vapply(ids, function(c) raw[which(labels == c)[1]], numeric(1))
centers <- centers[match(raw_of, cid), , drop = FALSE]
for (i in seq_along(ids)) for (j in seq_along(names_)) {
values[[sprintf("center[%d,%s]", ids[i], names_[j])]] <- centers[i, j]
}
}
sz <- cs_ml_cluster_sizes(labels)
for (c in names(sz)) values[[sprintf("size[%s]", c)]] <- sz[[c]]
check <- cs_ml_cluster_validation(X, labels, truth, D = D, cap = 3000, seed = SEED)
widths <- check$.widths
check$.widths <- NULL
values <- c(values, check)
profile_rows <- list()
for (c in ids) {
member <- labels == c
row <- list(cluster = c, size = sum(member), share = mean(member))
for (f in FEATURES) {
if (identical(KINDS[[f]], "numeric")) {
m <- mean(suppressWarnings(as.numeric(frame[[f]]))[member], na.rm = TRUE)
row[[f]] <- m
values[[sprintf("mean[%d,%s]", c, f)]] <- m
} else {
v <- as.character(frame[[f]])[member]
v <- v[!is.na(v)]
top <- if (length(v)) sort(table(v), decreasing = TRUE) else NULL
row[[f]] <- if (length(top)) sprintf("%s (%.0f%%)", names(top)[1], 100 * top[[1]] / sum(member)) else ""
}
}
profile_rows[[length(profile_rows) + 1L]] <- row
}
tables <- c(list(list(
key = "clusters", title = "Clusters",
columns = c(list(list(key = "cluster", label = "Cluster", type = "integer"),
list(key = "size", label = "Size", type = "integer"),
list(key = "share", label = "Share", type = "percent")),
lapply(FEATURES, function(f) list(key = f, label = f, type = if (identical(KINDS[[f]], "numeric")) "number" else "string"))),
rows = profile_rows
)), tables)
# %% Labels file and charts
path <- do.call(cs_ml_write_labels, c(list(out, rows, labels), extra))
name_of <- function(c) as.character(c) # noise stays "-1" (drawn gray, listed last)
pr <- cs_ml_project2(X, centers, names_)
show <- cs_ml_even_sample(length(rows))
xs <- pr$P[show + 1L, 1]; ys <- pr$P[show + 1L, 2]
cl <- name_of(labels[show + 1L])
cent <- rep(FALSE, length(show))
lab <- if (!is.null(ROW_ID)) as.character(frame[[ROW_ID]])[show + 1L] else NULL
if (!is.null(pr$C)) {
xs <- c(xs, pr$C[, 1]); ys <- c(ys, pr$C[, 2])
cl <- c(cl, name_of(ids)); cent <- c(cent, rep(TRUE, length(ids)))
if (!is.null(lab)) lab <- c(lab, sprintf("center %d", ids))
}
level_names <- c(as.character(ids), if (values$n_noise > 0) "-1")
charts <- c(list(cs_chart(
"clusters", "cluster-scatter", "Clusters",
list(x = cs_col(pr$labels[1], xs, "numeric"), y = cs_col(pr$labels[2], ys, "numeric"),
cluster = cs_col("Cluster", cl, "categorical", levels = level_names),
centroid = if (!is.null(pr$C)) cs_col("Center", cent, "boolean"),
label = if (!is.null(lab)) cs_col("Row", lab, "categorical")),
note = if (length(show) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(show), big.mark = ","), format(length(rows), big.mark = ","))
)), charts)
if (!is.nan(values$silhouette)) {
wl <- labels[widths$pick + 1L]
o <- order(wl, -widths$width)
charts[[length(charts) + 1L]] <- cs_chart(
"silhouette", "silhouette-plot", "Silhouette widths",
list(cluster = cs_col("Cluster", as.character(wl[o]), "categorical", levels = as.character(ids)),
width = cs_col("Silhouette width", widths$width[o], "numeric")),
note = if (length(widths$pick) == sum(labels != -1)) NULL else sprintf("%s rows sampled for the silhouette.", format(length(widths$pick), big.mark = ","))
)
}
# %% Result
if (is.null(summary)) {
summary <- sprintf("%d cluster%s in %s rows", k, if (k != 1) "s" else "", format(length(rows), big.mark = ","))
if (values$n_noise > 0) summary <- paste0(summary, sprintf(" (%s noise points)", format(values$n_noise, big.mark = ",")))
if (!is.nan(values$silhouette)) summary <- paste0(summary, sprintf("; mean silhouette %.2f", values$silhouette))
summary <- paste0(summary, ".")
}
cs_publish(list(
title = "Archetypal analysis",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = length(rows),
summary = summary,
statistics = list(list(key = "k", label = "Clusters", value = k, format = "integer"),
list(key = "silhouette", label = "Mean silhouette", value = values$silhouette)),
tables = tables,
values = values,
charts = charts,
warnings = warnings,
artifacts = list(list(key = "labels", path = path, format = "parquet")),
model = list(kind = "clusterer", features = I(names_), params = list(
k = 3,
max_iter = 500,
scale = "none",
missing = "drop"
))
))
Archetypal analysis with k = 3: the archetypes explain 100% of the variation; each row is a mix of them (membership columns).
- Clusters
- 3
- Mean silhouette
- 0.4189
To keep this page light, the plots are shown once, under the R tab.
Clusters
| Cluster | Size | Share | a | b | c | d |
|---|---|---|---|---|---|---|
| 1 | 22 | 36.7% | 5.583 | 2.254 | 2.615 | 4.160 |
| 2 | 20 | 33.3% | 3.746 | 5.777 | 3.932 | 1.719 |
| 3 | 18 | 30.0% | 1.893 | 1.954 | 7.185 | 2.250 |
Archetypes (in the original units) and the closest real row
| Archetype | Closest row | Mean membership | a | b | c | d |
|---|---|---|---|---|---|---|
| 1 | 2 | 35.9% | 8 | 1 | 0 | 6 |
| 2 | 3 | 33.1% | 3 | 9 | 4 | 0 |
| 3 | 1 | 31.0% | 0 | 0 | 10 | 2 |
- Archetype 1 sits on row 2, which is extreme in at least one variable; outliers pull archetypes outward.
- Archetype 2 sits on row 3, which is extreme in at least one variable; outliers pull archetypes outward.
- Archetype 3 sits on row 1, which is extreme in at least one variable; outliers pull archetypes outward.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Archetypal analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.archetypes 1.0.0 · spec 380f335c032ed4a4
# Dataset: rep1_simplex (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import cluster as csc
from codesplash.stats.rng import Rng
from codesplash.ml import rep_linear as rl
# %% Data
FEATURES = ["a", "b", "c", "d"]
LABEL = None # known groups (external validation only)
ROW_ID = None # row labels for charts
SEED = 42
KINDS = {
"a": "numeric",
"b": "numeric",
"c": "numeric",
"d": "numeric",
}
LEVELS = {
}
df = pd.read_parquet("tests/parity/fixtures/rep1_simplex.parquet", columns=list(dict.fromkeys(FEATURES + [c for c in (LABEL, ROW_ID) if c])))
n_input = len(df)
X, rows, names, frame = csc.prepare(df, FEATURES, KINDS, LEVELS, missing="drop", scale="none")
warnings = []
if len(rows) < n_input:
warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a feature was missing.")
if len(rows) < 3:
raise ValueError("Clustering needs at least three rows with every feature present.")
truth = frame[LABEL].astype("object").to_numpy() if LABEL else None
out = csml.out_dir("target/academy-parity/run-8142/discover.archetypes/simplex_corners/out-python")
values = {"n_used": len(rows)}
centers = None
center_ids = None
D = None
extra = {}
tables = []
charts = []
summary = None
# %% Clustering
K = 3
if not np.all(np.isfinite(X)): # the R driver stops in its scaling step on infinite values; stop here too
raise ValueError("Archetypal analysis needs finite values; remove or recode infinite values first.")
if K >= len(rows):
cs.cs_error("CS_E_TOO_FEW_ROWS", what=f"Archetypal analysis with k = {K}", min=K + 1, n=len(rows))
# Projected gradient on both simplex factors from a furthest-sum start (no random draws).
A, Cw, sse, iterations, converged, start = rl.archetypes(X, K, max_iter=500)
if not converged:
warnings.append(f"Archetypal analysis stopped after {iterations} iterations before its tolerance; raise the iteration limit.")
o = rl.archetype_order(A) # the clustering driver's canonical order, so cluster c is archetype c
A = A[:, o]
Cw = Cw[o]
Zc = Cw @ X
raw = np.argmax(A, axis=1).astype(np.int64)
centers = Zc
for j in range(K):
extra[f"membership_{j + 1}"] = A[:, j]
sst = float(np.sum((X - X.mean(axis=0)) ** 2))
values["n_archetypes"] = K
values["rss"] = float(sse)
values["var_explained"] = 1.0 - float(sse) / sst if sst > 0 else float("nan")
X_raw = frame[FEATURES].apply(pd.to_numeric, errors="coerce").to_numpy(dtype=np.float64, copy=True)
for j in range(X_raw.shape[1]): # filled cells take the column median, as the design did
gap = np.isnan(X_raw[:, j])
if gap.any():
X_raw[gap, j] = np.nanmedian(X_raw[:, j])
Z_raw = Cw @ X_raw # archetypes as mixtures of real rows, in the original units
arch_rows = []
for j in range(K):
d = np.sqrt(np.sum((X - Zc[j]) ** 2, axis=1))
near = int(np.argmin(d))
values[f"nearest_row[{j + 1}]"] = int(rows[near]) + 1
values[f"nearest_distance[{j + 1}]"] = float(d[near])
values[f"mean_membership[{j + 1}]"] = float(A[:, j].mean())
row = {"archetype": j + 1, "nearest": int(rows[near]) + 1, "membership": float(A[:, j].mean())}
for i, f in enumerate(FEATURES):
values[f"archetype[{j + 1},{f}]"] = float(Z_raw[j, i])
row[f] = float(Z_raw[j, i])
arch_rows.append(row)
top = int(np.argmax(Cw[j]))
if Cw[j, top] >= 0.9 and float(np.max(np.abs(X[top]))) > 4:
warnings.append(f"Archetype {j + 1} sits on row {int(rows[top]) + 1}, which is extreme in at least one variable; outliers pull archetypes outward.")
tables.append({
"key": "archetypes",
"title": "Archetypes (in the original units) and the closest real row",
"columns": [
{"key": "archetype", "label": "Archetype", "type": "integer"},
{"key": "nearest", "label": "Closest row", "type": "integer"},
{"key": "membership", "label": "Mean membership", "type": "percent"},
]
+ [{"key": f, "label": f, "type": "number"} for f in FEATURES],
"rows": arch_rows,
})
names_a = [f"Archetype {j + 1}" for j in range(K)]
charts.append(cs.chart(
"profiles",
"matrix-heatmap",
"Archetype profiles (scaled; cell text in the original units)",
{
"row": cs.col("Archetype", [a for a in names_a for _ in FEATURES], "categorical", levels=names_a),
"col": cs.col("Variable", [f for _ in names_a for f in FEATURES], "categorical", levels=FEATURES),
"value": cs.col("Scaled value", [float(Zc[j, i]) for j in range(K) for i in range(len(FEATURES))], "numeric"),
"label": cs.col("Value", [f"{Z_raw[j, i]:.3g}" for j in range(K) for i in range(len(FEATURES))], "categorical"),
},
))
summary = (
f"Archetypal analysis with k = {K}: the archetypes explain {values['var_explained']:.0%} of the variation; "
"each row is a mix of them (membership columns)."
)
# %% Canonical labels and validation
labels = csc.canonical(raw)
ids = [int(c) for c in sorted(set(labels.tolist())) if c != -1]
k = len(ids)
values["k"] = k
values["n_noise"] = int(np.sum(labels == -1))
if centers is not None:
# reorder centers to canonical ids: the raw id of each canonical cluster
raw_of = {c: raw[np.flatnonzero(labels == c)[0]] for c in ids}
pos = {int(r): i for i, r in enumerate(center_ids if center_ids is not None else range(len(centers)))}
centers = np.array([centers[pos[int(raw_of[c])]] for c in ids])
for c, row in zip(ids, centers):
for name, v in zip(names, row):
values[f"center[{c},{name}]"] = float(v)
for c, m in csc.sizes(labels).items():
values[f"size[{c}]"] = m
check = csc.validation(X, labels, truth, D=D, cap=3000, seed=SEED)
widths, picked = check.pop("_widths")
values.update(check)
# per-cluster means of numeric features in their own units (interpretation)
profile_rows = []
for c in ids:
member = labels == c
row = {"cluster": c, "size": int(member.sum()), "share": float(member.mean())}
for f in FEATURES:
if KINDS[f] == "numeric":
m = float(np.nanmean(pd.to_numeric(frame[f], errors="coerce").to_numpy(dtype=np.float64)[member]))
row[f] = m
values[f"mean[{c},{f}]"] = m
else:
top = pd.Series(frame[f].astype("object").to_numpy()[member]).dropna().astype(str).value_counts()
row[f] = f"{top.index[0]} ({top.iloc[0] / member.sum():.0%})" if len(top) else ""
profile_rows.append(row)
tables.insert(0, {
"key": "clusters",
"title": "Clusters",
"columns": [
{"key": "cluster", "label": "Cluster", "type": "integer"},
{"key": "size", "label": "Size", "type": "integer"},
{"key": "share", "label": "Share", "type": "percent"},
]
+ [{"key": f, "label": f, "type": "number" if KINDS[f] == "numeric" else "string"} for f in FEATURES],
"rows": profile_rows,
})
# %% Labels file and charts
path = csc.write_labels(out, rows, labels, **extra)
name_of = lambda c: str(c) # noqa: E731 — noise stays "-1" (drawn gray, listed last)
P, C, axes = csc.project2(X, centers, names)
show = csc.even_sample(len(rows))
point_labels = [str(v) for v in frame[ROW_ID].astype("object").to_numpy()[show]] if ROW_ID else None
xs, ys = list(P[show, 0]), list(P[show, 1])
cl = [name_of(c) for c in labels[show]]
cent = [False] * len(show)
lab = point_labels
if C is not None:
xs += list(C[:, 0])
ys += list(C[:, 1])
cl += [name_of(c) for c in ids]
cent += [True] * len(ids)
lab = None if lab is None else lab + [f"center {c}" for c in ids]
level_names = [str(c) for c in ids] + (["-1"] if values["n_noise"] else [])
charts.insert(0, cs.chart(
"clusters", "cluster-scatter", "Clusters",
{
"x": cs.col(axes[0], xs, "numeric"),
"y": cs.col(axes[1], ys, "numeric"),
"cluster": cs.col("Cluster", cl, "categorical", levels=level_names),
"centroid": cs.col("Center", cent, "boolean") if C is not None else None,
"label": cs.col("Row", lab, "categorical") if lab is not None else None,
},
note=None if len(show) == len(rows) else f"{len(show):,} of {len(rows):,} rows shown.",
))
if not np.isnan(values["silhouette"]):
wl = labels[picked]
order = np.lexsort((-widths, wl))
charts.append(cs.chart(
"silhouette", "silhouette-plot", "Silhouette widths",
{"cluster": cs.col("Cluster", [str(c) for c in wl[order]], "categorical", levels=[str(c) for c in ids]),
"width": cs.col("Silhouette width", list(widths[order]), "numeric")},
note=None if len(picked) == int(np.sum(labels != -1)) else f"{len(picked):,} rows sampled for the silhouette.",
))
# %% Result
if summary is None:
summary = f"{k} cluster{'s' if k != 1 else ''} in {len(rows):,} rows"
if values["n_noise"]:
summary += f" ({values['n_noise']:,} noise points)"
if not np.isnan(values["silhouette"]):
summary += f"; mean silhouette {values['silhouette']:.2f}"
summary += "."
cs.publish({
"title": "Archetypal analysis",
"engine": cs.engine_info("numpy", "numpy", "pandas"),
"n": len(rows),
"summary": summary,
"statistics": [
{"key": "k", "label": "Clusters", "value": k, "format": "integer"},
{"key": "silhouette", "label": "Mean silhouette", "value": values["silhouette"]},
],
"tables": tables,
"values": values,
"charts": charts,
"warnings": warnings,
"artifacts": [{"key": "labels", "path": path, "format": "parquet"}],
"model": {"kind": "clusterer", "features": names, "params": {
"k": 3,
"max_iter": 500,
"scale": "none",
"missing": "drop",
}},
})
On data mixed from three known corners, the three archetypes land on rows at distance 0 from the true corners and explain 100% of the variance.
On US arrests, one archetype is low on everything, one high on every crime and urban, and one high on murder in less urban states: three ends of a triangle every state sits inside.
Archetype pitfalls
Read- Outliers become archetypes, because extremes are what the method looks for. Check the closest real row to each archetype.
- Mixtures of extremes are the model. Curved or multi-peaked structure doesn't fit it.
- Archetypes need not be actual rows, and they aren't medoids.
Check: NMF and archetypes
CheckpointCheck yourself
Why do NMF factors tend to look like parts, while PCA components look like contrasts?
Show the answer
Answer: a
With no subtraction, a row must be built from pieces that each contribute positively.
Check yourself
Two NMF runs with different starting points give different-looking parts with nearly the same error. Is one wrong?
Show the answer
Answer: a
Scaling, reordering and sometimes broader transformations leave the fit unchanged. Compare several starts and report how stable the parts are.
Check yourself
Your table holds word counts, many of them small. Which NMF loss matches that data best?
Show the answer
Answer: a
Squared error lets large counts dominate. KL treats each count as a Poisson outcome, the assumption behind topic models.
Check yourself
How do archetypes differ from k-means centers?
Show the answer
Answer: a
Archetypes are convex combinations of rows chosen to enclose the data; each row is then a mixture of them.
Check yourself
One archetype is almost identical to a single row that looks like a data-entry error. What happened?
Show the answer
Answer: a
Check each archetype's closest real row, and clean or down-weight gross errors first.
Recap
Recap- NMF writes non-negative data as additive parts; choose squared error or KL by the data's noise.
- NMF is non-unique and start-dependent; compare several runs.
- Archetypes are extreme convex profiles; rows are mixtures of them, and outliers can take over.
Concepts in this lesson