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.
A real result
Example “Usarrests three”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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
View data
| Center | Cluster | Row | PC1 (62%) | PC2 (25%) |
|---|---|---|---|---|
| false | 3 | Alabama | 0.9856 | −1.133 |
| false | 2 | Alaska | 1.950 | −1.073 |
| false | 2 | Arizona | 1.763 | 0.7460 |
| false | 3 | Arkansas | −0.1414 | −1.120 |
| false | 2 | California | 2.524 | 1.543 |
| false | 2 | Colorado | 1.515 | 0.9876 |
| false | 1 | Connecticut | −1.359 | 1.089 |
| false | 1 | Delaware | 0.0477 | 0.3254 |
| false | 2 | Florida | 3.013 | −0.0392 |
| false | 3 | Georgia | 1.639 | −1.279 |
| false | 1 | Hawaii | −0.9127 | 1.570 |
| false | 1 | Idaho | −1.640 | −0.2110 |
| false | 2 | Illinois | 1.379 | 0.6818 |
| false | 1 | Indiana | −0.5055 | 0.1516 |
| false | 1 | Iowa | −2.254 | 0.1041 |
| false | 1 | Kansas | −0.7969 | 0.2702 |
| false | 1 | Kentucky | −0.7509 | −0.9584 |
| false | 3 | Louisiana | 1.565 | −0.8711 |
| false | 1 | Maine | −2.397 | −0.3764 |
| false | 2 | Maryland | 1.763 | −0.4277 |
| false | 1 | Massachusetts | −0.4862 | 1.474 |
| false | 2 | Michigan | 2.108 | 0.1554 |
| false | 1 | Minnesota | −1.693 | 0.6323 |
| false | 3 | Mississippi | 0.9965 | −2.394 |
| false | 2 | Missouri | 0.6968 | 0.2634 |
| false | 1 | Montana | −1.185 | −0.5369 |
| false | 1 | Nebraska | −1.266 | 0.1940 |
| false | 2 | Nevada | 2.874 | 0.7756 |
| false | 1 | New Hampshire | −2.384 | 0.0181 |
| false | 2 | New Jersey | 0.1816 | 1.450 |
| false | 2 | New Mexico | 1.980 | −0.1428 |
| false | 2 | New York | 1.683 | 0.8232 |
| false | 3 | North Carolina | 1.123 | −2.228 |
| false | 1 | North Dakota | −2.992 | −0.5991 |
| false | 1 | Ohio | −0.2260 | 0.7422 |
| false | 1 | Oklahoma | −0.3118 | 0.2879 |
| false | 2 | Oregon | 0.0591 | 0.5414 |
| false | 1 | Pennsylvania | −0.8884 | 0.5711 |
| false | 1 | Rhode Island | −0.8638 | 1.492 |
| false | 3 | South Carolina | 1.321 | −1.933 |
| false | 1 | South Dakota | −1.988 | −0.8233 |
| false | 3 | Tennessee | 0.9997 | −0.8603 |
| false | 2 | Texas | 1.355 | 0.4125 |
| false | 1 | Utah | −0.5506 | 1.472 |
| false | 1 | Vermont | −2.801 | −1.402 |
| false | 1 | Virginia | −0.0963 | −0.1997 |
| false | 1 | Washington | −0.2169 | 0.9701 |
| false | 1 | West Virginia | −2.109 | −1.425 |
| false | 1 | Wisconsin | −2.080 | 0.6113 |
| false | 1 | Wyoming | −0.6294 | −0.3210 |
| true | 1 | center 1 | −2.509 | 0.0416 |
| true | 2 | center 2 | 2.447 | 1.481 |
| true | 3 | center 3 | 1.038 | −2.336 |
View data
| Variable | Value | Archetype | Scaled value |
|---|---|---|---|
| Murder | 1.75 | Archetype 1 | −1.400 |
| Assault | 49.2 | Archetype 1 | −1.473 |
| UrbanPop | 55.6 | Archetype 1 | −0.6905 |
| Rape | 9.15 | Archetype 1 | −1.303 |
| Murder | 9.18 | Archetype 2 | 0.3220 |
| Assault | 274 | Archetype 2 | 1.250 |
| UrbanPop | 90.6 | Archetype 2 | 1.747 |
| Rape | 39.3 | Archetype 2 | 1.950 |
| Murder | 15.8 | Archetype 3 | 1.866 |
| Assault | 259 | Archetype 3 | 1.072 |
| UrbanPop | 44.2 | Archetype 3 | −1.491 |
| Rape | 18.3 | Archetype 3 | −0.3157 |
View data
| Cluster | Silhouette width |
|---|---|
| 1 | 0.5941 |
| 1 | 0.5885 |
| 1 | 0.5819 |
| 1 | 0.5758 |
| 1 | 0.5705 |
| 1 | 0.5341 |
| 1 | 0.5284 |
| 1 | 0.5134 |
| 1 | 0.5044 |
| 1 | 0.5019 |
| 1 | 0.4759 |
| 1 | 0.4685 |
| 1 | 0.4406 |
| 1 | 0.4039 |
| 1 | 0.3661 |
| 1 | 0.3489 |
| 1 | 0.3486 |
| 1 | 0.3461 |
| 1 | 0.3267 |
| 1 | 0.3023 |
| 1 | 0.2956 |
| 1 | 0.2795 |
| 1 | 0.2673 |
| 1 | 0.1832 |
| 1 | 0.1309 |
| 1 | 0.1266 |
| 1 | 0.1024 |
| 2 | 0.4495 |
| 2 | 0.4301 |
| 2 | 0.4194 |
| 2 | 0.3757 |
| 2 | 0.3741 |
| 2 | 0.3505 |
| 2 | 0.3266 |
| 2 | 0.2533 |
| 2 | 0.1996 |
| 2 | 0.1888 |
| 2 | 0.1831 |
| 2 | 0.0268 |
| 2 | 0.0197 |
| 2 | −0.0803 |
| 2 | −0.1031 |
| 3 | 0.5581 |
| 3 | 0.5505 |
| 3 | 0.4968 |
| 3 | 0.4517 |
| 3 | 0.3955 |
| 3 | 0.3470 |
| 3 | 0.3078 |
| 3 | 0.1238 |
Clusters
| Cluster | Size | Share | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|
| 1 | 27 | 54.0% | 4.630 | 108.33 | 63.074 | 15.211 |
| 2 | 15 | 30.0% | 10.193 | 244.27 | 76.267 | 31.973 |
| 3 | 8 | 16.0% | 13.938 | 243.63 | 53.750 | 21.413 |
Archetypes (in the original units) and the closest real row
| Archetype | Closest row | Mean membership | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|
| 1 | 29 | 42.3% | 1.753 | 49.235 | 55.645 | 9.153 |
| 2 | 5 | 33.9% | 9.177 | 273.86 | 90.567 | 39.310 |
| 3 | 24 | 23.8% | 15.832 | 259.18 | 44.176 | 18.305 |
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
| Cluster | Size | Share | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|
| 1 | 27 | 54.0% | 4.630 | 108.33 | 63.074 | 15.211 |
| 2 | 15 | 30.0% | 10.193 | 244.27 | 76.267 | 31.973 |
| 3 | 8 | 16.0% | 13.938 | 243.63 | 53.750 | 21.413 |
Archetypes (in the original units) and the closest real row
| Archetype | Closest row | Mean membership | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|
| 1 | 29 | 42.3% | 1.753 | 49.235 | 55.645 | 9.153 |
| 2 | 5 | 33.9% | 9.177 | 273.86 | 90.567 | 39.310 |
| 3 | 24 | 23.8% | 15.832 | 259.18 | 44.176 | 18.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.
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",
}},
})
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.