Skip to content

CDiscover · discover.archetypes

Archetypal analysis

Which extreme "pure types" is every row a mix of?

Finds k archetypes — extreme profiles on the edge of the data, each a mixture of real rows — and describes every row as a mix of them (memberships that sum to 1). Cutler and Breiman's model, fitted by projected gradient on both mixtures from a deterministic furthest-sum start, identical in both engines. Each row's largest membership gives its segment; the membership columns can be saved. Outliers can become archetypes, so each archetype is shown with the closest real row.

Verified in Python and R Python and R agree to 6 decimals Also called archetypes, AA, pure types…

A real result

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

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

Archetypal analysis with k = 3: the archetypes explain 82% of the variation; each row is a mix of them (membership columns).

Clusters
3
Mean silhouette
0.3470

Plots

ClustersWhich rows group together, and how well separated are the groups?
View data
CenterClusterRowPC1 (62%)PC2 (25%)
false3Alabama0.9856−1.133
false2Alaska1.950−1.073
false2Arizona1.7630.7460
false3Arkansas−0.1414−1.120
false2California2.5241.543
false2Colorado1.5150.9876
false1Connecticut−1.3591.089
false1Delaware0.04770.3254
false2Florida3.013−0.0392
false3Georgia1.639−1.279
false1Hawaii−0.91271.570
false1Idaho−1.640−0.2110
false2Illinois1.3790.6818
false1Indiana−0.50550.1516
false1Iowa−2.2540.1041
false1Kansas−0.79690.2702
false1Kentucky−0.7509−0.9584
false3Louisiana1.565−0.8711
false1Maine−2.397−0.3764
false2Maryland1.763−0.4277
false1Massachusetts−0.48621.474
false2Michigan2.1080.1554
false1Minnesota−1.6930.6323
false3Mississippi0.9965−2.394
false2Missouri0.69680.2634
false1Montana−1.185−0.5369
false1Nebraska−1.2660.1940
false2Nevada2.8740.7756
false1New Hampshire−2.3840.0181
false2New Jersey0.18161.450
false2New Mexico1.980−0.1428
false2New York1.6830.8232
false3North Carolina1.123−2.228
false1North Dakota−2.992−0.5991
false1Ohio−0.22600.7422
false1Oklahoma−0.31180.2879
false2Oregon0.05910.5414
false1Pennsylvania−0.88840.5711
false1Rhode Island−0.86381.492
false3South Carolina1.321−1.933
false1South Dakota−1.988−0.8233
false3Tennessee0.9997−0.8603
false2Texas1.3550.4125
false1Utah−0.55061.472
false1Vermont−2.801−1.402
false1Virginia−0.0963−0.1997
false1Washington−0.21690.9701
false1West Virginia−2.109−1.425
false1Wisconsin−2.0800.6113
false1Wyoming−0.6294−0.3210
true1center 1−2.5090.0416
true2center 22.4471.481
true3center 31.038−2.336
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
Murder1.75Archetype 1−1.400
Assault49.2Archetype 1−1.473
UrbanPop55.6Archetype 1−0.6905
Rape9.15Archetype 1−1.303
Murder9.18Archetype 20.3220
Assault 274Archetype 21.250
UrbanPop90.6Archetype 21.747
Rape39.3Archetype 21.950
Murder15.8Archetype 31.866
Assault 259Archetype 31.072
UrbanPop44.2Archetype 3−1.491
Rape18.3Archetype 3−0.3157
Silhouette widthsHow well does each row fit its cluster compared with the next-nearest cluster?
View data
ClusterSilhouette width
10.5941
10.5885
10.5819
10.5758
10.5705
10.5341
10.5284
10.5134
10.5044
10.5019
10.4759
10.4685
10.4406
10.4039
10.3661
10.3489
10.3486
10.3461
10.3267
10.3023
10.2956
10.2795
10.2673
10.1832
10.1309
10.1266
10.1024
20.4495
20.4301
20.4194
20.3757
20.3741
20.3505
20.3266
20.2533
20.1996
20.1888
20.1831
20.0268
20.0197
2−0.0803
2−0.1031
30.5581
30.5505
30.4968
30.4517
30.3955
30.3470
30.3078
30.1238

Clusters

ClusterSizeShareMurderAssaultUrbanPopRape
12754.0%4.630108.3363.07415.211
21530.0%10.193244.2776.26731.973
3816.0%13.938243.6353.75021.413

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

ArchetypeClosest rowMean membershipMurderAssaultUrbanPopRape
12942.3%1.75349.23555.6459.153
2533.9%9.177273.8690.56739.310
32423.8%15.832259.1844.17618.305
Python

Archetypal analysis with k = 3: the archetypes explain 82% of the variation; each row is a mix of them (membership columns).

Clusters
3
Mean silhouette
0.3470

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

Clusters

ClusterSizeShareMurderAssaultUrbanPopRape
12754.0%4.630108.3363.07415.211
21530.0%10.193244.2776.26731.973
3816.0%13.938243.6353.75021.413

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

ArchetypeClosest rowMean membershipMurderAssaultUrbanPopRape
12942.3%1.75349.23555.6459.153
2533.9%9.177273.8690.56739.310
32423.8%15.832259.1844.17618.305

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 threeml_usarrests · features: Murder, Assault, UrbanPop, Rape · id: state
  • Simplex cornersrep1_simplex · features: a, b, c, d
  • Iris four knownml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
  • Penguins imputeml_penguins · features: bill_len, bill_dep, flipper_len, body_mass
  • Degenerate n3ml_usarrests · features: Murder, Assault, UrbanPop, Rape · id: state

In the guides

Where it sits in the decision guides

  • Clustering (k-means, hierarchical) · DS & ML Decision Guide · Discover — find structure without labels

What you need

Featuresnumeric · 2–200 columns
Numeric variables that define the profiles; archetypes are mixtures of real rows on these.
Known groupscategorical / boolean · 0–1 column
Optional — compared with the segments (adjusted Rand index, AMI, NMI); never used to fit.
Row labelscategorical / numeric · 0–1 column
Optional names shown on the chart points.

Choices you make

model

Archetypes (k)default 3

Number of pure types. Try a few values and compare the variance explained.

Advanced

Maximum iterationsdefault 500

Upper limit on alternating updates; the fit stops earlier when the error stops falling.

preprocess

Scale numbersdefault standard

Standardize numbers so each counts equally; turn off only when columns already share one unit.

  • Standardize (population SD)(default) — Rescales each number to mean 0 and SD 1 so every column counts equally; the safe choice.
  • No scaling — Keeps raw values, so wide-ranging columns dominate; pick it only when columns share one unit.
Missing valuesdefault drop

Rows with missing values are left out, or filled with the column median.

  • Leave the row out(default) — Leaves out rows with a missing value; the clean choice when few are missing.
  • Fill with the median — Fills numeric gaps with the median; keeps every row, at some cost to the shape.

What it reports

k
How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
n_used
How many independent units the analysis used; it sets precision and power.
n_noise
How many independent units the analysis used; it sets precision and power.
n_archetypes
Finds k extreme profiles (mixtures of real rows on the data's edge) and writes every row as a mix of them.
rss
Squared distance between the scaled rows and their best mixtures of the archetypes, summed over rows.
var_explained
Squared distance between the scaled rows and their best mixtures of the archetypes, summed over rows.
silhouette
How well each point sits in its cluster compared with the nearest other cluster, from −1 to 1.
calinski_harabasz
Between-cluster spread over within-cluster spread. Higher means tighter, better-separated clusters.
davies_bouldin
How much each cluster overlaps its most similar neighbor, on average. Lower is better; 0 is the floor.

Per group, level or term: size[<cluster>], center[<cluster>,<design column>], mean[<cluster>,<feature>], archetype[<a>,<feature>], nearest_row[<a>], nearest_distance[<a>], mean_membership[<a>], ari, ami, nmi

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

  • Values below 1e-6 in absolute size count as equal: when the rows are exact mixtures of the archetypes the error and the distance from an archetype to its closest row converge to rounding noise (about 1e-8), where the two engines' last accepted steps differ.
  • Both engines run the same projected-gradient twin from the same furthest-sum start (step sizes grow by 1.2 after an accepted step and halve after a rejected one; a step counts only when it lowers the error by at least 1e-13 of itself, so rounding can't steer the two engines apart; stop when an iteration lowers the error by less than 1e-9 of itself, or the fit is exact). R's archetypes package (alternating constrained least squares from random starts) can stop at another local optimum.
Python

The exact script CodeSplash ran for example “Usarrests three” · 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 9004302762d025c9
# 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 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 = ["Murder", "Assault", "UrbanPop", "Rape"]
LABEL = None  # known groups (external validation only)
ROW_ID = "state"  # row labels for charts
SEED = 42
KINDS = {
    "Murder": "numeric",
    "Assault": "numeric",
    "UrbanPop": "numeric",
    "Rape": "numeric",
}
LEVELS = {
}
df = pd.read_parquet("tests/parity/fixtures/ml_usarrests.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="standard")
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/usarrests_three/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": "standard",
        "missing": "drop",
    }},
})
R

The exact script CodeSplash ran for example “Usarrests three” · 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 9004302762d025c9
# 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)

# %% Data
FEATURES <- c("Murder", "Assault", "UrbanPop", "Rape")
LABEL <- NULL  # known groups (external validation only)
ROW_ID <- "state"  # row labels for charts
SEED <- 42
KINDS <- list(
  Murder = "numeric",
  Assault = "numeric",
  UrbanPop = "numeric",
  Rape = "numeric"
)
LEVELS <- list(
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_usarrests.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 = "standard")
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/usarrests_three/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 = "standard",
    missing = "drop"
  ))
))

Sources

  • Cutler A, Breiman L (1994). Archetypal analysis. Technometrics 36(4):338–347.
  • Mørup M, Hansen LK (2012). Archetypal analysis for machine learning and data mining. Neurocomputing 80:54–63.
  • Eugster MJA, Leisch F (2009). From Spider-Man to Hero — archetypal analysis in R. J Stat Softw 30(8).

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