Skip to content

Pure types and a PCA with a likelihood: archetypes and probabilistic PCA

Describe every row as a mix of a few extreme profiles, and give PCA a likelihood so BIC can choose the number of components and fill missing values.

Advanced ~12 min8 steps

What runs in CodeSplash

You will be able to

  • Read archetypes, memberships and each archetype's closest real row
  • Use probabilistic PCA's σ² and BIC to choose a rank
  • Fill missing values with PPCA-EM instead of the column median

Read first

01

Segments at the edges, not the centers

Read

k-means describes each segment by its center, an average customer that nobody actually is. Archetypal analysisArchetypal analysisFinds k extreme profiles (mixtures of real rows on the data's edge) and writes every row as a mix of them. goes the other way. It finds k extreme profiles on the edge of the data and describes every row as a mix of them.

Each archetype is itself a mixture of real rows, so it stays inside the data. Each row's membershipsArchetype membershipHow much of an archetype a row is made of; a row's memberships are non-negative and sum to 1. are non-negative and add to 1, like "70% violent-crime state, 30% urban state".

02

Archetypes of US arrests

Read
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
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 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"
  ))
))
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
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 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",
    }},
})

Three archetypes explain 82% of the variation. The card lists each archetype in the original units, next to the closest real rowClosest real rowThe observed row nearest an archetype, with its distance in scaled units: a concrete example of the pure type., which gives you a concrete state for each pure type.

03

Segments and memberships

Read

Each row's largest membership gives its segment, so profiles, comparisons and saving work as for any clusterer. Save to dataset also writes the membership columns, which are often more useful than the hard segment.

Matrix heatmapWhat do the values of a square or rectangular result matrix look like at a glance?
View data
variablewithr
ageage1
ageBMI0.1207
agesystolic BP0.1471
agecholesterol0.1467
ageglucose0.1912
ageactivity−0.1247
BMIage0.1207
BMIBMI1
BMIsystolic BP0.3132
BMIcholesterol0.3194
BMIglucose0.3629
BMIactivity−0.1770
systolic BPage0.1471
systolic BPBMI0.3132
systolic BPsystolic BP1
systolic BPcholesterol0.4537
systolic BPglucose0.5647
systolic BPactivity−0.3672
cholesterolage0.1467
cholesterolBMI0.3194
cholesterolsystolic BP0.4537
cholesterolcholesterol1
cholesterolglucose0.6006
cholesterolactivity−0.3861
glucoseage0.1912
glucoseBMI0.3629
glucosesystolic BP0.5647
glucosecholesterol0.6006
glucoseglucose1
glucoseactivity−0.4105
activityage−0.1247
activityBMI−0.1770
activitysystolic BP−0.3672
activitycholesterol−0.3861
activityglucose−0.4105
activityactivity1

When the data really are mixtures of a few corners, archetypes find the corners exactly. This fixture mixes three corners in four dimensions. With k = 3, the error is 0.000 and the variance explained is 100%.

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",
    }},
})
04

A PCA with a likelihood

Read

Ordinary PCA has no model, so it can't tell you how many components are signal. Probabilistic PCAProbabilistic PCAPCA as a model: data = loadings × latent scores + equal-variance noise, so it has a likelihood and a BIC. (Tipping and Bishop) treats each row as loadings times a few latent scores plus noise with the same variance in every variable. The components are the same as PCA's, but now there's a likelihood.

Turn on Model: Probabilistic PCA in PCA's settings:

Principal component analysisRecorded · Python and R agreeRecorded 2026-11-21 · 45 values compared
R

PCA of 4 variables: the first component explains 62.0% of the variance.

PC1 variance
62.0%
PC1 + PC2
86.8%

Plots

Scree plotHow many components carry most of the variance?
View data
ComponentCumulativeProportion of variance
10.62010.6201
20.86750.2474
30.95660.0891
410.0434
Biplot (PC1 × PC2)How do rows spread on the main components, and which variables drive each direction?

Loading arrows are rescaled to the score range.

View data
KindLabelPC1PC2
point0.9757−1.122
point1.931−1.062
point1.7450.7385
point−0.1400−1.109
point2.4991.527
point1.4990.9776
point−1.3451.078
point0.04720.3221
point2.983−0.0388
point1.623−1.266
point−0.90351.555
point−1.623−0.2089
point1.3650.6750
point−0.50040.1500
point−2.2310.1030
point−0.78890.2674
point−0.7433−0.9488
point1.549−0.8623
point−2.373−0.3726
point1.746−0.4234
point−0.48131.460
point2.0870.1538
point−1.6760.6259
point0.9865−2.370
point0.68980.2607
point−1.174−0.5315
point−1.2530.1920
point2.8460.7678
point−2.3600.0179
point0.17971.435
point1.960−0.1414
point1.6660.8149
point1.112−2.206
point−2.962−0.5931
point−0.22370.7348
point−0.30860.2850
point0.05850.5360
point−0.87950.5654
point−0.85511.477
point1.307−1.914
point−1.968−0.8151
point0.9897−0.8516
point1.3420.4083
point−0.54501.457
point−2.773−1.388
point−0.0954−0.1977
point−0.21470.9604
point−2.087−1.411
point−2.0590.6051
point−0.6231−0.3178
loadingMurder1.465−1.143
loadingAssault1.594−0.5139
loadingUrbanPop0.76062.386
loadingRape1.4860.4574

Explained variance

ComponentEigenvalueProportionCumulative
12.48062.0%62.0%
20.989824.7%86.8%
30.35668.9%95.7%
40.17344.3%100.0%

Loadings

VariablePC1PC2PC3PC4
Murder0.5359−0.4182−0.3412−0.6492
Assault0.5832−0.1880−0.26810.7434
UrbanPop0.27820.8728−0.3780−0.1339
Rape0.54340.16730.8178−0.0890

Probabilistic PCA by rank (σ² = noise variance; lowest BIC is the best rank)

Rankσ²Log-likelihoodParametersBIC
10.4965−253.479542.15
20.2597−237.8212522.58
30.1700−234.6414524.05
The exact R script · R R version 4.5.1 (2025-06-13)
# Principal component analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.pca 1.2.0 · spec f98441aa79b6edf2
# 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
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()
cs_check_finite_columns(df, FEATURES)
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))
}
cs_check_rows(length(rows), 2, "Principal component analysis")
X <- cs_ml_numeric_matrix(df, FEATURES, rows)

# %% Principal components
SCALE <- TRUE
Z <- sweep(X, 2, colMeans(X))
if (SCALE) {
  s <- apply(X, 2, stats::sd)
  s[s == 0] <- 1
  Z <- sweep(Z, 2, s, "/")
}
k_max <- min(length(rows) - 1L, length(FEATURES))
p <- stats::prcomp(Z, center = FALSE, scale. = FALSE)
eig <- (p$sdev^2)[seq_len(k_max)]
prop <- eig / sum(eig)
cumulative <- cumsum(prop)
rot <- p$rotation[, seq_len(k_max), drop = FALSE]
signs <- cs_rep_canonical_signs(rot)  # largest |loading| positive (near-ties: the first)
loadings <- sweep(rot, 2, signs, "*")
scores <- sweep(p$x[, seq_len(k_max), drop = FALSE], 2, signs, "*")
k <- if (is.null(NULL)) k_max else min(as.integer(NULL), k_max)

# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-95359/discover.pca/usarrests_probabilistic/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(k)) emb[[paste0("dim_", j)]] <- scores[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))

# %% Result
values <- list(n = length(rows), n_variables = length(FEATURES), n_components = k,
               cum2 = if (k_max >= 2) cumulative[2] else NaN)
# Kaiser's "eigenvalue above 1" only means something on the correlation scale (scaled PCA).
if (SCALE) values$kaiser <- sum(eig > 1)
for (j in seq_len(k_max)) {
  values[[sprintf("eigen[%d]", j)]] <- eig[j]
  values[[sprintf("prop[%d]", j)]] <- prop[j]
  values[[sprintf("cumulative[%d]", j)]] <- cumulative[j]
}
for (j in seq_len(k)) {
  values[[sprintf("score_check[%d]", j)]] <- cs_ml_checksum(scores[, j], rows)
  for (i in seq_along(FEATURES)) values[[sprintf("loading[%d:%s]", j, FEATURES[i])]] <- unname(loadings[i, j])
}
ppca_table <- NULL
# Probabilistic PCA (Tipping & Bishop): closed-form ML noise variance, log-likelihood and BIC by rank
profile <- cs_rep_ppca_profile(eig, length(rows), length(FEATURES))
if (length(profile)) {
  want <- min(as.integer(2), length(FEATURES) - 1L)
  qs <- vapply(profile, function(d) d$q, numeric(1))
  bics <- vapply(profile, function(d) d$bic, numeric(1))
  chosen <- profile[[if (any(qs <= want)) max(which(qs <= want)) else 1L]]
  values$latent <- chosen$q
  values$sigma2 <- chosen$sigma2
  values$loglik <- chosen$loglik
  values$bic <- chosen$bic
  values$bic_rank <- qs[order(bics, qs)[1]]
  for (d in profile) values[[sprintf("bic[%d]", d$q)]] <- d$bic
  ppca_table <- list(key = "ppca", title = "Probabilistic PCA by rank (σ² = noise variance; lowest BIC is the best rank)",
                     columns = list(list(key = "q", label = "Rank", type = "integer"),
                                    list(key = "sigma2", label = "σ²", type = "number"),
                                    list(key = "loglik", label = "Log-likelihood", type = "number"),
                                    list(key = "df", label = "Parameters", type = "number"),
                                    list(key = "bic", label = "BIC", type = "number")),
                     rows = lapply(profile, function(d) list(q = d$q, sigma2 = d$sigma2, loglik = d$loglik, df = d$df, bic = d$bic)))
}
show <- min(k, 5L)
tables <- list(
  list(key = "variance", title = "Explained variance",
       columns = list(list(key = "component", label = "Component", type = "integer"),
                      list(key = "eigenvalue", label = "Eigenvalue", type = "number"),
                      list(key = "proportion", label = "Proportion", type = "percent"),
                      list(key = "cumulative", label = "Cumulative", type = "percent")),
       rows = lapply(seq_len(k_max), function(j) list(component = j, eigenvalue = eig[j], proportion = prop[j], cumulative = cumulative[j]))),
  list(key = "loadings", title = "Loadings",
       columns = c(list(list(key = "variable", label = "Variable")),
                   lapply(seq_len(show), function(j) list(key = paste0("pc", j), label = paste0("PC", j), type = "number"))),
       rows = lapply(seq_along(FEATURES), function(i) {
         r <- list(variable = FEATURES[i])
         for (j in seq_len(show)) r[[paste0("pc", j)]] <- unname(loadings[i, j])
         r
       }))
)
if (!is.null(ppca_table)) tables[[length(tables) + 1L]] <- ppca_table
charts <- list(cs_chart("scree", "scree-plot", "Scree plot", list(
  component = cs_col("Component", seq_len(k_max), "numeric"),
  variance = cs_col("Proportion of variance", prop, "numeric"),
  cumulative = cs_col("Cumulative", cumulative, "numeric")
)))
if (k_max >= 2) {
  pick <- chart_rows(length(rows))
  lab <- if (!is.null(LABEL)) as.character(df[[LABEL]][rows[pick] + 1L]) else rep("", length(pick))
  lab[is.na(lab)] <- ""
  reach <- max(abs(scores[pick, 1:2])) / max(max(abs(loadings[, 1:2])), 1e-12) * 0.8
  charts[[2]] <- cs_chart("biplot", "biplot", "Biplot (PC1 × PC2)", list(
    x = cs_col("PC1", c(scores[pick, 1], loadings[, 1] * reach), "numeric"),
    y = cs_col("PC2", c(scores[pick, 2], loadings[, 2] * reach), "numeric"),
    kind = cs_col("Kind", c(rep("point", length(pick)), rep("loading", length(FEATURES))), "categorical"),
    label = cs_col(if (is.null(LABEL)) "Label" else LABEL, c(lab, FEATURES), "categorical")
  ), note = "Loading arrows are rescaled to the score range.")
}
cs_publish(list(
  title = "Principal component analysis",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = length(rows),
  summary = sprintf("PCA of %d variables: the first component explains %.1f%% of the variance.", length(FEATURES), 100 * prop[1]),
  statistics = list(list(key = "prop1", label = "PC1 variance", value = prop[1], format = "percent"),
                    list(key = "cum2", label = "PC1 + PC2", value = values$cum2, format = "percent")),
  tables = tables,
  charts = charts,
  values = values,
  warnings = warnings,
  artifacts = list(list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"))
))
Python

PCA of 4 variables: the first component explains 62.0% of the variance.

PC1 variance
62.0%
PC1 + PC2
86.8%

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

Explained variance

ComponentEigenvalueProportionCumulative
12.48062.0%62.0%
20.989824.7%86.8%
30.35668.9%95.7%
40.17344.3%100.0%

Loadings

VariablePC1PC2PC3PC4
Murder0.5359−0.4182−0.3412−0.6492
Assault0.5832−0.1880−0.26810.7434
UrbanPop0.27820.8728−0.3780−0.1339
Rape0.54340.16730.8178−0.0890

Probabilistic PCA by rank (σ² = noise variance; lowest BIC is the best rank)

Rankσ²Log-likelihoodParametersBIC
10.4965−253.479542.15
20.2597−237.8212522.58
30.1700−234.6414524.05
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Principal component analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.pca 1.2.0 · spec f98441aa79b6edf2
# 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
from sklearn.decomposition import PCA

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import embed as csembed
from codesplash.ml import rep_linear as rl

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
df = pd.read_parquet("tests/parity/fixtures/ml_usarrests.parquet", columns=list(dict.fromkeys(FEATURES + ([LABEL] if LABEL else []))))
n_input = len(df)
warnings = []
cs.check_finite_columns(df, FEATURES)
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.")
cs.check_rows(len(rows), 2, "Principal component analysis")
X = csembed.numeric_matrix(df, FEATURES, rows)

# %% Principal components
SCALE = True
Z = csembed.standardize(X, ddof=1) if SCALE else X - X.mean(axis=0)  # SD with n − 1, like R's scale()
k_max = min(len(rows) - 1, len(FEATURES))
pca = PCA(n_components=k_max, svd_solver="full").fit(Z)
eig = pca.explained_variance_  # divisor n − 1 (= prcomp sdev²)
prop = eig / eig.sum()
cumulative = np.cumsum(prop)
signs = rl.canonical_signs(pca.components_.T)  # largest |loading| positive (near-ties: the first)
loadings = pca.components_.T * signs
scores = pca.transform(Z) * signs
k = k_max if None is None else min(int(None), k_max)

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-95359/discover.pca/usarrests_probabilistic/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64)})
for j in range(k):
    emb[f"dim_{j + 1}"] = scores[:, j]
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)

# %% Result
values = {
    "n": len(rows),
    "n_variables": len(FEATURES),
    "n_components": k,
    "cum2": float(cumulative[1]) if k_max >= 2 else float("nan"),
}
if SCALE:  # Kaiser's "eigenvalue above 1" only means something on the correlation scale
    values["kaiser"] = int(np.sum(eig > 1))
for j in range(k_max):
    values[f"eigen[{j + 1}]"] = float(eig[j])
    values[f"prop[{j + 1}]"] = float(prop[j])
    values[f"cumulative[{j + 1}]"] = float(cumulative[j])
for j in range(k):
    values[f"score_check[{j + 1}]"] = csembed.checksum(scores[:, j], rows)
    for i, f in enumerate(FEATURES):
        values[f"loading[{j + 1}:{f}]"] = float(loadings[i, j])
ppca_table = None
# Probabilistic PCA (Tipping & Bishop): closed-form ML noise variance, log-likelihood and BIC by rank
profile = rl.ppca_profile(eig, len(rows), len(FEATURES))
if profile:
    want = min(int(2), len(FEATURES) - 1)
    pick_q = [d for d in profile if d["q"] <= want] or profile[:1]
    chosen = pick_q[-1]
    values["latent"] = chosen["q"]
    values["sigma2"] = chosen["sigma2"]
    values["loglik"] = chosen["loglik"]
    values["bic"] = chosen["bic"]
    values["bic_rank"] = min(profile, key=lambda d: (d["bic"], d["q"]))["q"]
    for d in profile:
        values[f"bic[{d['q']}]"] = d["bic"]
    ppca_table = {
        "key": "ppca",
        "title": "Probabilistic PCA by rank (σ² = noise variance; lowest BIC is the best rank)",
        "columns": [
            {"key": "q", "label": "Rank", "type": "integer"},
            {"key": "sigma2", "label": "σ²", "type": "number"},
            {"key": "loglik", "label": "Log-likelihood", "type": "number"},
            {"key": "df", "label": "Parameters", "type": "number"},
            {"key": "bic", "label": "BIC", "type": "number"},
        ],
        "rows": [{"q": d["q"], "sigma2": d["sigma2"], "loglik": d["loglik"], "df": d["df"], "bic": d["bic"]} for d in profile],
    }
show = min(k, 5)
tables = [
    {
        "key": "variance",
        "title": "Explained variance",
        "columns": [
            {"key": "component", "label": "Component", "type": "integer"},
            {"key": "eigenvalue", "label": "Eigenvalue", "type": "number"},
            {"key": "proportion", "label": "Proportion", "type": "percent"},
            {"key": "cumulative", "label": "Cumulative", "type": "percent"},
        ],
        "rows": [{"component": j + 1, "eigenvalue": eig[j], "proportion": prop[j], "cumulative": cumulative[j]} for j in range(k_max)],
    },
    {
        "key": "loadings",
        "title": "Loadings",
        "columns": [{"key": "variable", "label": "Variable"}] + [{"key": f"pc{j + 1}", "label": f"PC{j + 1}", "type": "number"} for j in range(show)],
        "rows": [dict({"variable": f}, **{f"pc{j + 1}": loadings[i, j] for j in range(show)}) for i, f in enumerate(FEATURES)],
    },
]
if ppca_table is not None:
    tables.append(ppca_table)
charts = [
    cs.chart(
        "scree",
        "scree-plot",
        "Scree plot",
        {
            "component": cs.col("Component", list(range(1, k_max + 1)), "numeric"),
            "variance": cs.col("Proportion of variance", prop, "numeric"),
            "cumulative": cs.col("Cumulative", cumulative, "numeric"),
        },
    )
]
if k_max >= 2:
    pick = chart_rows(len(rows))
    lab = ["" if LABEL is None else str(v) for v in df.iloc[rows[pick]][LABEL]] if LABEL else [""] * len(pick)
    reach = np.max(np.abs(scores[pick, :2])) / max(np.max(np.abs(loadings[:, :2])), 1e-12) * 0.8
    charts.append(
        cs.chart(
            "biplot",
            "biplot",
            "Biplot (PC1 × PC2)",
            {
                "x": cs.col("PC1", np.concatenate([scores[pick, 0], loadings[:, 0] * reach]), "numeric"),
                "y": cs.col("PC2", np.concatenate([scores[pick, 1], loadings[:, 1] * reach]), "numeric"),
                "kind": cs.col("Kind", ["point"] * len(pick) + ["loading"] * len(FEATURES), "categorical"),
                "label": cs.col(LABEL or "Label", lab + FEATURES, "categorical"),
            },
            note="Loading arrows are rescaled to the score range.",
        )
    )
cs.publish(
    {
        "title": "Principal component analysis",
        "engine": cs.engine_info("scikit-learn", "numpy", "pandas"),
        "n": len(rows),
        "summary": f"PCA of {len(FEATURES)} variables: the first component explains {prop[0]:.1%} of the variance.",
        "statistics": [
            {"key": "prop1", "label": "PC1 variance", "value": float(prop[0]), "format": "percent"},
            {"key": "cum2", "label": "PC1 + PC2", "value": values["cum2"], "format": "percent"},
        ],
        "tables": tables,
        "charts": charts,
        "values": values,
        "warnings": warnings,
        "artifacts": [{"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"}],
    }
)

The card adds the noise variance σ²PPCA noise variance (σ²)Variance left over in each variable beyond the latent components: the mean of the discarded ML eigenvalues. and a BIC for every rank. On US arrests, BIC is lowest at rank 2, a model-based answer to "how many components?" that the Kaiser rule only approximates.

05

Filling gaps with PPCA-EM

Read

The penguins data have a few missing measurements. Median filling ignores the fact that bill length and flipper length move together. Missing values: Fill from probabilistic PCA fits the model to the observed cells by EM and fills each gap with its expected value given the rest of the row.

Principal component analysisRecorded · Python and R agreeRecorded 2026-11-21 · 37 values compared · largest relative difference 1.6e-15
R

PCA of 4 variables: the first component explains 68.8% of the variance.

PC1 variance
68.8%
PC1 + PC2
88.2%

Plots

Scree plotHow many components carry most of the variance?
View data
ComponentCumulativeProportion of variance
10.68840.6884
20.88160.1931
30.97290.0913
410.0271
Biplot (PC1 × PC2)How do rows spread on the main components, and which variables drive each direction?

Loading arrows are rescaled to the score range.

View data
KindLabelPC1PC2
point−1.8410.0476
point−1.305−0.4277
point−1.367−0.1543
point−1.876−0.0020
point−1.9090.8280
point−1.760−0.3510
point−0.80890.5217
point−1.833−0.7685
point−1.1921.025
point−1.728−0.7874
point−1.740−0.6655
point−1.786−0.2357
point−1.9451.010
point−1.5620.5962
point−1.737−0.5939
point−1.5670.0958
point−0.79441.309
point−2.340−0.6317
point−0.99281.983
point−2.394−0.2941
point−2.101−0.1214
point−1.847−0.0938
point−1.494−0.2715
point−1.568−0.5860
point−1.918−0.2809
point−1.7500.1506
point−1.692−0.1793
point−2.699−0.1886
point−1.6690.3024
point−1.867−0.7697
point−1.898−0.3872
point−1.646−0.3184
point−1.5060.3415
point−1.438−0.9768
point−1.4311.073
point−1.6240.5625
point−1.7190.2846
point−2.3950.0786
point−1.1250.3809
point−2.285−0.5824
point−0.96210.1304
point−2.298−0.4397
point−0.56761.069
point−2.000−0.9874
point−0.86950.2336
point−1.9160.3535
point−2.627−0.1284
point−1.774−0.6446
point−1.3981.451
point−1.562−0.3272
point−1.1350.2968
point−1.857−0.7540
point−0.77770.7226
point−2.438−0.7862
point−1.2530.2551
point−1.538−0.4683
point−1.2100.2593
point−2.247−1.180
point−1.5140.0473
point−2.006−1.114

First 60 of 346 rows.

Explained variance

ComponentEigenvalueProportionCumulative
12.75468.8%68.8%
20.772519.3%88.2%
30.36529.1%97.3%
40.10852.7%100.0%

Loadings

VariablePC1PC2PC3
bill_len0.45530.59700.6443
bill_dep−0.40030.7978−0.4184
flipper_len0.57600.0023−0.2321
body_mass0.54840.0844−0.5966
  • 2 of 344 rows were left out because every value was missing.
The exact R script · R R version 4.5.1 (2025-06-13)
# Principal component analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.pca 1.2.0 · spec 51813be1d103d27b
# Dataset: ml_penguins (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("bill_len", "bill_dep", "flipper_len", "body_mass")
LABEL <- NULL
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_penguins.parquet", col_select = unique(c(FEATURES, LABEL))))
n_input <- nrow(df)
warnings <- list()
cs_check_finite_columns(df, FEATURES)
# PPCA-EM: keep rows with at least one value; each missing cell gets its conditional mean under a
# probabilistic PCA with LATENT dimensions, fitted by EM on the observed cells (Ilin & Raiko 2010).
X_all <- as.matrix(as.data.frame(lapply(df[, FEATURES, drop = FALSE], function(x) as.numeric(as.character(x)))))
rows <- which(!apply(is.na(X_all), 1, all)) - 1L
if (length(rows) < n_input) {
  warnings <- c(warnings, sprintf("%d of %d rows were left out because every value was missing.", n_input - length(rows), n_input))
}
cs_check_rows(length(rows), 3, "Probabilistic PCA")
X_obs <- unname(X_all[rows + 1L, , drop = FALSE])
for (j in seq_along(FEATURES)) if (all(is.na(X_obs[, j]))) cs_error("CS_E_ALL_MISSING", column = FEATURES[j])
center_o <- colMeans(X_obs, na.rm = TRUE)
spread_o <- rep(1, length(FEATURES))
if (TRUE) {
  spread_o <- vapply(seq_along(FEATURES), function(j) if (sum(!is.na(X_obs[, j])) > 1) stats::sd(X_obs[, j], na.rm = TRUE) else NA_real_, numeric(1))
  spread_o[is.na(spread_o) | !(spread_o > 0)] <- 1
}
n_imputed <- sum(is.na(X_obs))
LATENT <- min(as.integer(2), length(FEATURES) - 1L)
em <- cs_rep_ppca_em(sweep(sweep(X_obs, 2, center_o), 2, spread_o, "/"), LATENT)
if (!em$converged) warnings <- c(warnings, "PPCA-EM stopped after 1,000 iterations before its tolerance; the filled values are approximate.")
X <- sweep(sweep(em$completed, 2, spread_o, "*"), 2, center_o, "+")

# %% Principal components
SCALE <- TRUE
Z <- sweep(X, 2, colMeans(X))
if (SCALE) {
  s <- apply(X, 2, stats::sd)
  s[s == 0] <- 1
  Z <- sweep(Z, 2, s, "/")
}
k_max <- min(length(rows) - 1L, length(FEATURES))
p <- stats::prcomp(Z, center = FALSE, scale. = FALSE)
eig <- (p$sdev^2)[seq_len(k_max)]
prop <- eig / sum(eig)
cumulative <- cumsum(prop)
rot <- p$rotation[, seq_len(k_max), drop = FALSE]
signs <- cs_rep_canonical_signs(rot)  # largest |loading| positive (near-ties: the first)
loadings <- sweep(rot, 2, signs, "*")
scores <- sweep(p$x[, seq_len(k_max), drop = FALSE], 2, signs, "*")
k <- if (is.null(3)) k_max else min(as.integer(3), k_max)

# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-95359/discover.pca/penguins_ppca_em/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(k)) emb[[paste0("dim_", j)]] <- scores[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))

# %% Result
values <- list(n = length(rows), n_variables = length(FEATURES), n_components = k,
               cum2 = if (k_max >= 2) cumulative[2] else NaN)
# Kaiser's "eigenvalue above 1" only means something on the correlation scale (scaled PCA).
if (SCALE) values$kaiser <- sum(eig > 1)
for (j in seq_len(k_max)) {
  values[[sprintf("eigen[%d]", j)]] <- eig[j]
  values[[sprintf("prop[%d]", j)]] <- prop[j]
  values[[sprintf("cumulative[%d]", j)]] <- cumulative[j]
}
for (j in seq_len(k)) {
  values[[sprintf("score_check[%d]", j)]] <- cs_ml_checksum(scores[, j], rows)
  for (i in seq_along(FEATURES)) values[[sprintf("loading[%d:%s]", j, FEATURES[i])]] <- unname(loadings[i, j])
}
ppca_table <- NULL
# Probabilistic PCA fitted by EM: noise variance and the observed-data log-likelihood (scaled units)
q_df <- length(FEATURES) * LATENT - LATENT * (LATENT - 1) / 2 + 1 + length(FEATURES)
values$latent <- LATENT
values$sigma2 <- em$sigma2
values$loglik <- em$loglik
values$bic <- -2 * em$loglik + q_df * log(length(rows))
values$n_imputed <- n_imputed
show <- min(k, 5L)
tables <- list(
  list(key = "variance", title = "Explained variance",
       columns = list(list(key = "component", label = "Component", type = "integer"),
                      list(key = "eigenvalue", label = "Eigenvalue", type = "number"),
                      list(key = "proportion", label = "Proportion", type = "percent"),
                      list(key = "cumulative", label = "Cumulative", type = "percent")),
       rows = lapply(seq_len(k_max), function(j) list(component = j, eigenvalue = eig[j], proportion = prop[j], cumulative = cumulative[j]))),
  list(key = "loadings", title = "Loadings",
       columns = c(list(list(key = "variable", label = "Variable")),
                   lapply(seq_len(show), function(j) list(key = paste0("pc", j), label = paste0("PC", j), type = "number"))),
       rows = lapply(seq_along(FEATURES), function(i) {
         r <- list(variable = FEATURES[i])
         for (j in seq_len(show)) r[[paste0("pc", j)]] <- unname(loadings[i, j])
         r
       }))
)
if (!is.null(ppca_table)) tables[[length(tables) + 1L]] <- ppca_table
charts <- list(cs_chart("scree", "scree-plot", "Scree plot", list(
  component = cs_col("Component", seq_len(k_max), "numeric"),
  variance = cs_col("Proportion of variance", prop, "numeric"),
  cumulative = cs_col("Cumulative", cumulative, "numeric")
)))
if (k_max >= 2) {
  pick <- chart_rows(length(rows))
  lab <- if (!is.null(LABEL)) as.character(df[[LABEL]][rows[pick] + 1L]) else rep("", length(pick))
  lab[is.na(lab)] <- ""
  reach <- max(abs(scores[pick, 1:2])) / max(max(abs(loadings[, 1:2])), 1e-12) * 0.8
  charts[[2]] <- cs_chart("biplot", "biplot", "Biplot (PC1 × PC2)", list(
    x = cs_col("PC1", c(scores[pick, 1], loadings[, 1] * reach), "numeric"),
    y = cs_col("PC2", c(scores[pick, 2], loadings[, 2] * reach), "numeric"),
    kind = cs_col("Kind", c(rep("point", length(pick)), rep("loading", length(FEATURES))), "categorical"),
    label = cs_col(if (is.null(LABEL)) "Label" else LABEL, c(lab, FEATURES), "categorical")
  ), note = "Loading arrows are rescaled to the score range.")
}
cs_publish(list(
  title = "Principal component analysis",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = length(rows),
  summary = sprintf("PCA of %d variables: the first component explains %.1f%% of the variance.", length(FEATURES), 100 * prop[1]),
  statistics = list(list(key = "prop1", label = "PC1 variance", value = prop[1], format = "percent"),
                    list(key = "cum2", label = "PC1 + PC2", value = values$cum2, format = "percent")),
  tables = tables,
  charts = charts,
  values = values,
  warnings = warnings,
  artifacts = list(list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"))
))
Python

PCA of 4 variables: the first component explains 68.8% of the variance.

PC1 variance
68.8%
PC1 + PC2
88.2%

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

Explained variance

ComponentEigenvalueProportionCumulative
12.75468.8%68.8%
20.772519.3%88.2%
30.36529.1%97.3%
40.10852.7%100.0%

Loadings

VariablePC1PC2PC3
bill_len0.45530.59700.6443
bill_dep−0.40030.7978−0.4184
flipper_len0.57600.0023−0.2321
body_mass0.54840.0844−0.5966
  • 2 of 344 rows were left out because every value was missing.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Principal component analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.pca 1.2.0 · spec 51813be1d103d27b
# Dataset: ml_penguins (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
from sklearn.decomposition import PCA

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import embed as csembed
from codesplash.ml import rep_linear as rl

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 = ["bill_len", "bill_dep", "flipper_len", "body_mass"]
LABEL = None
df = pd.read_parquet("tests/parity/fixtures/ml_penguins.parquet", columns=list(dict.fromkeys(FEATURES + ([LABEL] if LABEL else []))))
n_input = len(df)
warnings = []
cs.check_finite_columns(df, FEATURES)
# PPCA-EM: keep rows with at least one value; each missing cell gets its conditional mean under a
# probabilistic PCA with LATENT dimensions, fitted by EM on the observed cells (Ilin & Raiko 2010).
X_all = df[FEATURES].apply(pd.to_numeric, errors="coerce").to_numpy(dtype=np.float64)
rows = np.flatnonzero(~np.all(np.isnan(X_all), axis=1))
if len(rows) < n_input:
    warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because every value was missing.")
cs.check_rows(len(rows), 3, "Probabilistic PCA")
X_obs = X_all[rows]
for j, c in enumerate(FEATURES):
    if np.all(np.isnan(X_obs[:, j])):
        cs.cs_error("CS_E_ALL_MISSING", column=c)
center_o = np.nanmean(X_obs, axis=0)
spread_o = np.ones(len(FEATURES))
if True:
    with np.errstate(all="ignore"):
        spread_o = np.array([np.std(X_obs[~np.isnan(X_obs[:, j]), j], ddof=1) if np.sum(~np.isnan(X_obs[:, j])) > 1 else np.nan for j in range(len(FEATURES))])
    spread_o[~(spread_o > 0)] = 1.0
n_imputed = int(np.sum(np.isnan(X_obs)))
LATENT = min(int(2), len(FEATURES) - 1)
em = rl.ppca_em((X_obs - center_o) / spread_o, LATENT)
if not em["converged"]:
    warnings.append("PPCA-EM stopped after 1,000 iterations before its tolerance; the filled values are approximate.")
X = em["completed"] * spread_o + center_o

# %% Principal components
SCALE = True
Z = csembed.standardize(X, ddof=1) if SCALE else X - X.mean(axis=0)  # SD with n − 1, like R's scale()
k_max = min(len(rows) - 1, len(FEATURES))
pca = PCA(n_components=k_max, svd_solver="full").fit(Z)
eig = pca.explained_variance_  # divisor n − 1 (= prcomp sdev²)
prop = eig / eig.sum()
cumulative = np.cumsum(prop)
signs = rl.canonical_signs(pca.components_.T)  # largest |loading| positive (near-ties: the first)
loadings = pca.components_.T * signs
scores = pca.transform(Z) * signs
k = k_max if 3 is None else min(int(3), k_max)

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-95359/discover.pca/penguins_ppca_em/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64)})
for j in range(k):
    emb[f"dim_{j + 1}"] = scores[:, j]
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)

# %% Result
values = {
    "n": len(rows),
    "n_variables": len(FEATURES),
    "n_components": k,
    "cum2": float(cumulative[1]) if k_max >= 2 else float("nan"),
}
if SCALE:  # Kaiser's "eigenvalue above 1" only means something on the correlation scale
    values["kaiser"] = int(np.sum(eig > 1))
for j in range(k_max):
    values[f"eigen[{j + 1}]"] = float(eig[j])
    values[f"prop[{j + 1}]"] = float(prop[j])
    values[f"cumulative[{j + 1}]"] = float(cumulative[j])
for j in range(k):
    values[f"score_check[{j + 1}]"] = csembed.checksum(scores[:, j], rows)
    for i, f in enumerate(FEATURES):
        values[f"loading[{j + 1}:{f}]"] = float(loadings[i, j])
ppca_table = None
# Probabilistic PCA fitted by EM: noise variance and the observed-data log-likelihood (scaled units)
q_df = len(FEATURES) * LATENT - LATENT * (LATENT - 1) / 2 + 1 + len(FEATURES)
values["latent"] = LATENT
values["sigma2"] = float(em["sigma2"])
values["loglik"] = float(em["loglik"])
values["bic"] = float(-2 * em["loglik"] + q_df * np.log(len(rows)))
values["n_imputed"] = n_imputed
show = min(k, 5)
tables = [
    {
        "key": "variance",
        "title": "Explained variance",
        "columns": [
            {"key": "component", "label": "Component", "type": "integer"},
            {"key": "eigenvalue", "label": "Eigenvalue", "type": "number"},
            {"key": "proportion", "label": "Proportion", "type": "percent"},
            {"key": "cumulative", "label": "Cumulative", "type": "percent"},
        ],
        "rows": [{"component": j + 1, "eigenvalue": eig[j], "proportion": prop[j], "cumulative": cumulative[j]} for j in range(k_max)],
    },
    {
        "key": "loadings",
        "title": "Loadings",
        "columns": [{"key": "variable", "label": "Variable"}] + [{"key": f"pc{j + 1}", "label": f"PC{j + 1}", "type": "number"} for j in range(show)],
        "rows": [dict({"variable": f}, **{f"pc{j + 1}": loadings[i, j] for j in range(show)}) for i, f in enumerate(FEATURES)],
    },
]
if ppca_table is not None:
    tables.append(ppca_table)
charts = [
    cs.chart(
        "scree",
        "scree-plot",
        "Scree plot",
        {
            "component": cs.col("Component", list(range(1, k_max + 1)), "numeric"),
            "variance": cs.col("Proportion of variance", prop, "numeric"),
            "cumulative": cs.col("Cumulative", cumulative, "numeric"),
        },
    )
]
if k_max >= 2:
    pick = chart_rows(len(rows))
    lab = ["" if LABEL is None else str(v) for v in df.iloc[rows[pick]][LABEL]] if LABEL else [""] * len(pick)
    reach = np.max(np.abs(scores[pick, :2])) / max(np.max(np.abs(loadings[:, :2])), 1e-12) * 0.8
    charts.append(
        cs.chart(
            "biplot",
            "biplot",
            "Biplot (PC1 × PC2)",
            {
                "x": cs.col("PC1", np.concatenate([scores[pick, 0], loadings[:, 0] * reach]), "numeric"),
                "y": cs.col("PC2", np.concatenate([scores[pick, 1], loadings[:, 1] * reach]), "numeric"),
                "kind": cs.col("Kind", ["point"] * len(pick) + ["loading"] * len(FEATURES), "categorical"),
                "label": cs.col(LABEL or "Label", lab + FEATURES, "categorical"),
            },
            note="Loading arrows are rescaled to the score range.",
        )
    )
cs.publish(
    {
        "title": "Principal component analysis",
        "engine": cs.engine_info("scikit-learn", "numpy", "pandas"),
        "n": len(rows),
        "summary": f"PCA of {len(FEATURES)} variables: the first component explains {prop[0]:.1%} of the variance.",
        "statistics": [
            {"key": "prop1", "label": "PC1 variance", "value": float(prop[0]), "format": "percent"},
            {"key": "cum2", "label": "PC1 + PC2", "value": values["cum2"], "format": "percent"},
        ],
        "tables": tables,
        "charts": charts,
        "values": values,
        "warnings": warnings,
        "artifacts": [{"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"}],
    }
)

0 cells were filled, and every row with at least one value is kept.

06

Check your understanding

Checkpoint

Check yourself

How do archetypes differ from k-means centers?

Show the answer

Answer: b

k-means centers sit in the middle of their segments. Archetypes sit at the extremes, and rows are described as convex mixtures of them.

Check yourself

An archetype sits exactly on one row that is far from all the others. What should you do first?

Show the answer

Answer: a

Archetypes are drawn to the edge of the data, so outliers can become archetypes. Look at the closest real row before naming the pure type.

Check yourself

What does probabilistic PCA add that ordinary PCA lacks?

Show the answer

Answer: b

The components are the same. The model adds σ², a log-likelihood and BIC by rank, and it can fill missing values by EM.

07

Do it on your own data

In the app

Find Archetypal analysis in Discover under Find segments. Probabilistic PCA and PPCA-EM are settings of Principal component analysis under Map the data.

08

Recap

Recap
  • Archetypes are pure types on the data's edge, and rows are mixes of them. Check each archetype's closest real row.
  • Probabilistic PCA gives PCA a likelihood: σ², BIC by rank, and PPCA-EM for missing values.

Concepts in this lesson