Skip to content

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.

Advanced ~14 min10 steps

What runs in CodeSplash

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

Read first

01

Sums of parts

Read

Counts, 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

X≈WH,W≥0,  H≥0.X \approx W H, \qquad W \ge 0,\; H \ge 0 .

Each row is an additive mix (weights in WW) of non-negative parts (rows of HH). Nothing can cancel, so parts tend to be localized: a few words for a topic, a few frequencies for a sound.

02

How it's fitted

Read

With squared error, Lee and Seung's multiplicative updates alternate

H←H⊙W⊤XW⊤WH,W←W⊙XH⊤WHH⊤.H \leftarrow H \odot \frac{W^\top X}{W^\top W H}, \qquad W \leftarrow W \odot \frac{X H^\top}{W H H^\top}.

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.

03

Parts from bars

Explore

AExplorable · 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?

How sure?
10
200
0.30
0.05
40
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

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.

04

NMF on US arrests

Read
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
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"))
))
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
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".

05

Not unique, not global

Read
  • WH=(WD)(D−1H)WH = (WD)(D^{-1}H) for any positive diagonal DD, 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.
06

Archetypes: extremes, not averages

Read

Archetypal 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:

min⁡A,B∥X−ABX∥F2,rows of A,B≥0 and summing to 1.\min_{A, B} \lVert X - A B X\rVert_F^2, \quad \text{rows of } A, B \ge 0 \text{ and summing to } 1 .

Rows of AA 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.

07

Corners recovered

Read
Archetypal analysisRecorded · Python and R agreeRecorded 2026-11-25 · 57 values compared
R

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

Plots

ClustersWhich rows group together, and how well separated are the groups?
View data
CenterClusterPC1 (62%)PC2 (38%)
false36.956−3.062
false1−6.497−3.218
false20.52776.355
false20.07140.7195
false33.527−0.3142
false2−2.5922.099
false2−0.00765.624
false2−1.6891.970
false1−3.916−1.437
false1−2.0751.140
false2−1.0932.732
false1−4.352−1.785
false1−2.7141.009
false33.883−0.2344
false1−0.9144−2.935
false20.52483.814
false22.4861.886
false1−2.4991.005
false10.1331−0.6407
false2−0.63334.127
false33.9180.1091
false33.591−1.956
false1−4.854−1.827
false31.458−2.462
false21.6594.434
false2−1.8712.735
false1−4.907−1.280
false30.5422−0.5398
false1−1.862−2.048
false23.0462.174
false36.097−2.737
false1−2.397−2.098
false1−2.279−3.159
false1−2.393−0.7996
false1−1.930−2.747
false2−0.43094.763
false32.2090.1479
false1−4.610−2.434
false1−0.7122−2.162
false1−0.8692−0.7999
false1−2.152−2.543
false32.360−0.2768
false2−1.9061.139
false33.236−2.369
false34.429−0.9506
false1−2.039−0.8721
false31.159−0.8047
false21.1081.403
false2−1.1010.9592
false36.157−2.112
false2−0.83161.548
false34.0290.6832
false2−1.7591.132
false1−3.6730.0259
false21.9571.445
false1−1.510−2.546
false35.822−1.546
false32.114−1.107
false2−1.3832.896
false31.451−2.273

First 60 of 63 rows.

Archetype profiles (scaled; cell text in the original units)What do the values of a square or rectangular result matrix look like at a glance?
View data
VariableValueArchetypeScaled value
a 8Archetype 18
b 1Archetype 11
c 0Archetype 10
d 6Archetype 16
a 3Archetype 23
b 9Archetype 29
c 4Archetype 24
d 0Archetype 20
a 0Archetype 30
b 0Archetype 30
c 10Archetype 310
d 2Archetype 32
Silhouette widthsHow well does each row fit its cluster compared with the next-nearest cluster?
View data
ClusterSilhouette width
10.6351
10.6306
10.6081
10.6072
10.6021
10.6021
10.6002
10.5932
10.5757
10.5654
10.5462
10.5248
10.5084
10.4768
10.4257
10.4251
10.4049
10.3279
10.0836
10.0504
10.0413
1−0.1228
20.5794
20.5756
20.5704
20.5427
20.5302
20.5149
20.4909
20.4622
20.4423
20.3897
20.3665
20.2698
20.2582
20.2163
20.1883
20.1185
20.0834
20.0671
20.0547
2−0.0124
30.6439
30.6336
30.6085
30.6024
30.5932
30.5879
30.5867
30.5818
30.5432
30.5403
30.5172
30.4570
30.4460
30.3418
30.3400
30.3273
30.3033
30.0578

Clusters

ClusterSizeShareabcd
12236.7%5.5832.2542.6154.160
22033.3%3.7465.7773.9321.719
31830.0%1.8931.9547.1852.250

Archetypes (in the original units) and the closest real row

ArchetypeClosest rowMean membershipabcd
1235.9%8106
2333.1%3940
3131.0%00102
  • 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"
  ))
))
Python

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

ClusterSizeShareabcd
12236.7%5.5832.2542.6154.160
22033.3%3.7465.7773.9321.719
31830.0%1.8931.9547.1852.250

Archetypes (in the original units) and the closest real row

ArchetypeClosest rowMean membershipabcd
1235.9%8106
2333.1%3940
3131.0%00102
  • 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.

08

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.
09

Check: NMF and archetypes

Checkpoint

Check 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.

10

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