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.
What runs in CodeSplash
- Archetypal analysis Verified in Python and R
- Principal component analysis Verified in Python and R
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
Segments at the edges, not the centers
Readk-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".
Archetypes of US arrests
ReadArchetypal 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 |
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"
))
))
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 |
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.
Segments and memberships
ReadEach 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.
View data
| variable | with | r |
|---|---|---|
| age | age | 1 |
| age | BMI | 0.1207 |
| age | systolic BP | 0.1471 |
| age | cholesterol | 0.1467 |
| age | glucose | 0.1912 |
| age | activity | −0.1247 |
| BMI | age | 0.1207 |
| BMI | BMI | 1 |
| BMI | systolic BP | 0.3132 |
| BMI | cholesterol | 0.3194 |
| BMI | glucose | 0.3629 |
| BMI | activity | −0.1770 |
| systolic BP | age | 0.1471 |
| systolic BP | BMI | 0.3132 |
| systolic BP | systolic BP | 1 |
| systolic BP | cholesterol | 0.4537 |
| systolic BP | glucose | 0.5647 |
| systolic BP | activity | −0.3672 |
| cholesterol | age | 0.1467 |
| cholesterol | BMI | 0.3194 |
| cholesterol | systolic BP | 0.4537 |
| cholesterol | cholesterol | 1 |
| cholesterol | glucose | 0.6006 |
| cholesterol | activity | −0.3861 |
| glucose | age | 0.1912 |
| glucose | BMI | 0.3629 |
| glucose | systolic BP | 0.5647 |
| glucose | cholesterol | 0.6006 |
| glucose | glucose | 1 |
| glucose | activity | −0.4105 |
| activity | age | −0.1247 |
| activity | BMI | −0.1770 |
| activity | systolic BP | −0.3672 |
| activity | cholesterol | −0.3861 |
| activity | glucose | −0.4105 |
| activity | activity | 1 |
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 analysis with k = 3: the archetypes explain 100% of the variation; each row is a mix of them (membership columns).
- Clusters
- 3
- Mean silhouette
- 0.4189
Plots
View data
| Center | Cluster | PC1 (62%) | PC2 (38%) |
|---|---|---|---|
| false | 3 | 6.956 | −3.062 |
| false | 1 | −6.497 | −3.218 |
| false | 2 | 0.5277 | 6.355 |
| false | 2 | 0.0714 | 0.7195 |
| false | 3 | 3.527 | −0.3142 |
| false | 2 | −2.592 | 2.099 |
| false | 2 | −0.0076 | 5.624 |
| false | 2 | −1.689 | 1.970 |
| false | 1 | −3.916 | −1.437 |
| false | 1 | −2.075 | 1.140 |
| false | 2 | −1.093 | 2.732 |
| false | 1 | −4.352 | −1.785 |
| false | 1 | −2.714 | 1.009 |
| false | 3 | 3.883 | −0.2344 |
| false | 1 | −0.9144 | −2.935 |
| false | 2 | 0.5248 | 3.814 |
| false | 2 | 2.486 | 1.886 |
| false | 1 | −2.499 | 1.005 |
| false | 1 | 0.1331 | −0.6407 |
| false | 2 | −0.6333 | 4.127 |
| false | 3 | 3.918 | 0.1091 |
| false | 3 | 3.591 | −1.956 |
| false | 1 | −4.854 | −1.827 |
| false | 3 | 1.458 | −2.462 |
| false | 2 | 1.659 | 4.434 |
| false | 2 | −1.871 | 2.735 |
| false | 1 | −4.907 | −1.280 |
| false | 3 | 0.5422 | −0.5398 |
| false | 1 | −1.862 | −2.048 |
| false | 2 | 3.046 | 2.174 |
| false | 3 | 6.097 | −2.737 |
| false | 1 | −2.397 | −2.098 |
| false | 1 | −2.279 | −3.159 |
| false | 1 | −2.393 | −0.7996 |
| false | 1 | −1.930 | −2.747 |
| false | 2 | −0.4309 | 4.763 |
| false | 3 | 2.209 | 0.1479 |
| false | 1 | −4.610 | −2.434 |
| false | 1 | −0.7122 | −2.162 |
| false | 1 | −0.8692 | −0.7999 |
| false | 1 | −2.152 | −2.543 |
| false | 3 | 2.360 | −0.2768 |
| false | 2 | −1.906 | 1.139 |
| false | 3 | 3.236 | −2.369 |
| false | 3 | 4.429 | −0.9506 |
| false | 1 | −2.039 | −0.8721 |
| false | 3 | 1.159 | −0.8047 |
| false | 2 | 1.108 | 1.403 |
| false | 2 | −1.101 | 0.9592 |
| false | 3 | 6.157 | −2.112 |
| false | 2 | −0.8316 | 1.548 |
| false | 3 | 4.029 | 0.6832 |
| false | 2 | −1.759 | 1.132 |
| false | 1 | −3.673 | 0.0259 |
| false | 2 | 1.957 | 1.445 |
| false | 1 | −1.510 | −2.546 |
| false | 3 | 5.822 | −1.546 |
| false | 3 | 2.114 | −1.107 |
| false | 2 | −1.383 | 2.896 |
| false | 3 | 1.451 | −2.273 |
First 60 of 63 rows.
View data
| Variable | Value | Archetype | Scaled value |
|---|---|---|---|
| a | 8 | Archetype 1 | 8 |
| b | 1 | Archetype 1 | 1 |
| c | 0 | Archetype 1 | 0 |
| d | 6 | Archetype 1 | 6 |
| a | 3 | Archetype 2 | 3 |
| b | 9 | Archetype 2 | 9 |
| c | 4 | Archetype 2 | 4 |
| d | 0 | Archetype 2 | 0 |
| a | 0 | Archetype 3 | 0 |
| b | 0 | Archetype 3 | 0 |
| c | 10 | Archetype 3 | 10 |
| d | 2 | Archetype 3 | 2 |
View data
| Cluster | Silhouette width |
|---|---|
| 1 | 0.6351 |
| 1 | 0.6306 |
| 1 | 0.6081 |
| 1 | 0.6072 |
| 1 | 0.6021 |
| 1 | 0.6021 |
| 1 | 0.6002 |
| 1 | 0.5932 |
| 1 | 0.5757 |
| 1 | 0.5654 |
| 1 | 0.5462 |
| 1 | 0.5248 |
| 1 | 0.5084 |
| 1 | 0.4768 |
| 1 | 0.4257 |
| 1 | 0.4251 |
| 1 | 0.4049 |
| 1 | 0.3279 |
| 1 | 0.0836 |
| 1 | 0.0504 |
| 1 | 0.0413 |
| 1 | −0.1228 |
| 2 | 0.5794 |
| 2 | 0.5756 |
| 2 | 0.5704 |
| 2 | 0.5427 |
| 2 | 0.5302 |
| 2 | 0.5149 |
| 2 | 0.4909 |
| 2 | 0.4622 |
| 2 | 0.4423 |
| 2 | 0.3897 |
| 2 | 0.3665 |
| 2 | 0.2698 |
| 2 | 0.2582 |
| 2 | 0.2163 |
| 2 | 0.1883 |
| 2 | 0.1185 |
| 2 | 0.0834 |
| 2 | 0.0671 |
| 2 | 0.0547 |
| 2 | −0.0124 |
| 3 | 0.6439 |
| 3 | 0.6336 |
| 3 | 0.6085 |
| 3 | 0.6024 |
| 3 | 0.5932 |
| 3 | 0.5879 |
| 3 | 0.5867 |
| 3 | 0.5818 |
| 3 | 0.5432 |
| 3 | 0.5403 |
| 3 | 0.5172 |
| 3 | 0.4570 |
| 3 | 0.4460 |
| 3 | 0.3418 |
| 3 | 0.3400 |
| 3 | 0.3273 |
| 3 | 0.3033 |
| 3 | 0.0578 |
Clusters
| Cluster | Size | Share | a | b | c | d |
|---|---|---|---|---|---|---|
| 1 | 22 | 36.7% | 5.583 | 2.254 | 2.615 | 4.160 |
| 2 | 20 | 33.3% | 3.746 | 5.777 | 3.932 | 1.719 |
| 3 | 18 | 30.0% | 1.893 | 1.954 | 7.185 | 2.250 |
Archetypes (in the original units) and the closest real row
| Archetype | Closest row | Mean membership | a | b | c | d |
|---|---|---|---|---|---|---|
| 1 | 2 | 35.9% | 8 | 1 | 0 | 6 |
| 2 | 3 | 33.1% | 3 | 9 | 4 | 0 |
| 3 | 1 | 31.0% | 0 | 0 | 10 | 2 |
- Archetype 1 sits on row 2, which is extreme in at least one variable; outliers pull archetypes outward.
- Archetype 2 sits on row 3, which is extreme in at least one variable; outliers pull archetypes outward.
- Archetype 3 sits on row 1, which is extreme in at least one variable; outliers pull archetypes outward.
The exact R script · R R version 4.5.1 (2025-06-13)
# Archetypal analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.archetypes 1.0.0 · spec 380f335c032ed4a4
# Dataset: rep1_simplex (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
FEATURES <- c("a", "b", "c", "d")
LABEL <- NULL # known groups (external validation only)
ROW_ID <- NULL # row labels for charts
SEED <- 42
KINDS <- list(
a = "numeric",
b = "numeric",
c = "numeric",
d = "numeric"
)
LEVELS <- list(
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/rep1_simplex.parquet", col_select = unique(c(FEATURES, LABEL, ROW_ID))))
n_input <- nrow(df)
prep <- cs_ml_cluster_prepare(df, FEATURES, KINDS, LEVELS, missing = "drop", scale = "none")
X <- prep$X; rows <- prep$rows; names_ <- prep$names; frame <- prep$frame
warnings <- list()
if (length(rows) < n_input) {
warnings <- c(warnings, sprintf("%d of %d rows were left out because a feature was missing.", n_input - length(rows), n_input))
}
if (length(rows) < 3) stop("Clustering needs at least three rows with every feature present.")
truth <- if (!is.null(LABEL)) as.character(frame[[LABEL]]) else NULL
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.archetypes/simplex_corners/out-r")
values <- list(n_used = length(rows))
centers <- NULL
center_ids <- NULL
D <- NULL
extra <- list()
tables <- list()
charts <- list()
summary <- NULL
# %% Clustering
K <- 3
if (!all(is.finite(X))) stop("Archetypal analysis needs finite values; remove or recode infinite values first.")
if (K >= length(rows)) cs_error("CS_E_TOO_FEW_ROWS", what = sprintf("Archetypal analysis with k = %d", K), min = K + 1, n = length(rows))
# Projected gradient on both simplex factors from a furthest-sum start (no random draws).
fit <- cs_rep_archetypes(X, K, max_iter = 500)
if (!fit$converged) warnings <- c(warnings, sprintf("Archetypal analysis stopped after %d iterations before its tolerance; raise the iteration limit.", fit$iterations))
o <- cs_rep_archetype_order(fit$A) # the clustering driver's canonical order, so cluster c is archetype c
A <- fit$A[, o, drop = FALSE]
Cw <- fit$C[o, , drop = FALSE]
Zc <- Cw %*% X
raw <- max.col(A, ties.method = "first") - 1L
centers <- Zc
for (j in seq_len(K)) extra[[sprintf("membership_%d", j)]] <- A[, j]
sst <- sum(sweep(X, 2, colMeans(X))^2)
values$n_archetypes <- K
values$rss <- fit$sse
values$var_explained <- if (sst > 0) 1 - fit$sse / sst else NaN
X_raw <- as.matrix(as.data.frame(lapply(frame[, FEATURES, drop = FALSE], function(x) as.numeric(as.character(x)))))
for (j in seq_len(ncol(X_raw))) { # filled cells take the column median, as the design did
gap <- is.na(X_raw[, j])
if (any(gap)) X_raw[gap, j] <- stats::median(X_raw[, j], na.rm = TRUE)
}
Z_raw <- Cw %*% X_raw # archetypes as mixtures of real rows, in the original units
arch_rows <- list()
for (j in seq_len(K)) {
d <- sqrt(rowSums(sweep(X, 2, Zc[j, ])^2))
near <- which.min(d)
values[[sprintf("nearest_row[%d]", j)]] <- rows[near] + 1L
values[[sprintf("nearest_distance[%d]", j)]] <- d[near]
values[[sprintf("mean_membership[%d]", j)]] <- mean(A[, j])
r <- list(archetype = j, nearest = rows[near] + 1L, membership = mean(A[, j]))
for (i in seq_along(FEATURES)) {
values[[sprintf("archetype[%d,%s]", j, FEATURES[i])]] <- Z_raw[j, i]
r[[FEATURES[i]]] <- Z_raw[j, i]
}
arch_rows[[j]] <- r
top <- which.max(Cw[j, ])
if (Cw[j, top] >= 0.9 && max(abs(X[top, ])) > 4) {
warnings <- c(warnings, sprintf("Archetype %d sits on row %d, which is extreme in at least one variable; outliers pull archetypes outward.", j, rows[top] + 1L))
}
}
tables[[length(tables) + 1L]] <- list(
key = "archetypes", title = "Archetypes (in the original units) and the closest real row",
columns = c(list(list(key = "archetype", label = "Archetype", type = "integer"),
list(key = "nearest", label = "Closest row", type = "integer"),
list(key = "membership", label = "Mean membership", type = "percent")),
lapply(FEATURES, function(f) list(key = f, label = f, type = "number"))),
rows = arch_rows
)
names_a <- paste("Archetype", seq_len(K))
charts[[length(charts) + 1L]] <- cs_chart("profiles", "matrix-heatmap", "Archetype profiles (scaled; cell text in the original units)", list(
row = cs_col("Archetype", rep(names_a, each = length(FEATURES)), "categorical", levels = names_a),
col = cs_col("Variable", rep(FEATURES, times = K), "categorical", levels = FEATURES),
value = cs_col("Scaled value", as.vector(t(Zc)), "numeric"),
label = cs_col("Value", formatC(as.vector(t(Z_raw)), digits = 3, format = "g"), "categorical")
))
summary <- sprintf("Archetypal analysis with k = %d: the archetypes explain %.0f%% of the variation; each row is a mix of them (membership columns).",
K, 100 * values$var_explained)
# %% Canonical labels and validation
labels <- cs_ml_canonical(raw)
ids <- sort(unique(labels[labels != -1]))
k <- length(ids)
values$k <- k
values$n_noise <- sum(labels == -1)
if (!is.null(centers)) {
cid <- if (is.null(center_ids)) seq_len(nrow(centers)) - 1L else center_ids
raw_of <- vapply(ids, function(c) raw[which(labels == c)[1]], numeric(1))
centers <- centers[match(raw_of, cid), , drop = FALSE]
for (i in seq_along(ids)) for (j in seq_along(names_)) {
values[[sprintf("center[%d,%s]", ids[i], names_[j])]] <- centers[i, j]
}
}
sz <- cs_ml_cluster_sizes(labels)
for (c in names(sz)) values[[sprintf("size[%s]", c)]] <- sz[[c]]
check <- cs_ml_cluster_validation(X, labels, truth, D = D, cap = 3000, seed = SEED)
widths <- check$.widths
check$.widths <- NULL
values <- c(values, check)
profile_rows <- list()
for (c in ids) {
member <- labels == c
row <- list(cluster = c, size = sum(member), share = mean(member))
for (f in FEATURES) {
if (identical(KINDS[[f]], "numeric")) {
m <- mean(suppressWarnings(as.numeric(frame[[f]]))[member], na.rm = TRUE)
row[[f]] <- m
values[[sprintf("mean[%d,%s]", c, f)]] <- m
} else {
v <- as.character(frame[[f]])[member]
v <- v[!is.na(v)]
top <- if (length(v)) sort(table(v), decreasing = TRUE) else NULL
row[[f]] <- if (length(top)) sprintf("%s (%.0f%%)", names(top)[1], 100 * top[[1]] / sum(member)) else ""
}
}
profile_rows[[length(profile_rows) + 1L]] <- row
}
tables <- c(list(list(
key = "clusters", title = "Clusters",
columns = c(list(list(key = "cluster", label = "Cluster", type = "integer"),
list(key = "size", label = "Size", type = "integer"),
list(key = "share", label = "Share", type = "percent")),
lapply(FEATURES, function(f) list(key = f, label = f, type = if (identical(KINDS[[f]], "numeric")) "number" else "string"))),
rows = profile_rows
)), tables)
# %% Labels file and charts
path <- do.call(cs_ml_write_labels, c(list(out, rows, labels), extra))
name_of <- function(c) as.character(c) # noise stays "-1" (drawn gray, listed last)
pr <- cs_ml_project2(X, centers, names_)
show <- cs_ml_even_sample(length(rows))
xs <- pr$P[show + 1L, 1]; ys <- pr$P[show + 1L, 2]
cl <- name_of(labels[show + 1L])
cent <- rep(FALSE, length(show))
lab <- if (!is.null(ROW_ID)) as.character(frame[[ROW_ID]])[show + 1L] else NULL
if (!is.null(pr$C)) {
xs <- c(xs, pr$C[, 1]); ys <- c(ys, pr$C[, 2])
cl <- c(cl, name_of(ids)); cent <- c(cent, rep(TRUE, length(ids)))
if (!is.null(lab)) lab <- c(lab, sprintf("center %d", ids))
}
level_names <- c(as.character(ids), if (values$n_noise > 0) "-1")
charts <- c(list(cs_chart(
"clusters", "cluster-scatter", "Clusters",
list(x = cs_col(pr$labels[1], xs, "numeric"), y = cs_col(pr$labels[2], ys, "numeric"),
cluster = cs_col("Cluster", cl, "categorical", levels = level_names),
centroid = if (!is.null(pr$C)) cs_col("Center", cent, "boolean"),
label = if (!is.null(lab)) cs_col("Row", lab, "categorical")),
note = if (length(show) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(show), big.mark = ","), format(length(rows), big.mark = ","))
)), charts)
if (!is.nan(values$silhouette)) {
wl <- labels[widths$pick + 1L]
o <- order(wl, -widths$width)
charts[[length(charts) + 1L]] <- cs_chart(
"silhouette", "silhouette-plot", "Silhouette widths",
list(cluster = cs_col("Cluster", as.character(wl[o]), "categorical", levels = as.character(ids)),
width = cs_col("Silhouette width", widths$width[o], "numeric")),
note = if (length(widths$pick) == sum(labels != -1)) NULL else sprintf("%s rows sampled for the silhouette.", format(length(widths$pick), big.mark = ","))
)
}
# %% Result
if (is.null(summary)) {
summary <- sprintf("%d cluster%s in %s rows", k, if (k != 1) "s" else "", format(length(rows), big.mark = ","))
if (values$n_noise > 0) summary <- paste0(summary, sprintf(" (%s noise points)", format(values$n_noise, big.mark = ",")))
if (!is.nan(values$silhouette)) summary <- paste0(summary, sprintf("; mean silhouette %.2f", values$silhouette))
summary <- paste0(summary, ".")
}
cs_publish(list(
title = "Archetypal analysis",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = length(rows),
summary = summary,
statistics = list(list(key = "k", label = "Clusters", value = k, format = "integer"),
list(key = "silhouette", label = "Mean silhouette", value = values$silhouette)),
tables = tables,
values = values,
charts = charts,
warnings = warnings,
artifacts = list(list(key = "labels", path = path, format = "parquet")),
model = list(kind = "clusterer", features = I(names_), params = list(
k = 3,
max_iter = 500,
scale = "none",
missing = "drop"
))
))
Archetypal analysis with k = 3: the archetypes explain 100% of the variation; each row is a mix of them (membership columns).
- Clusters
- 3
- Mean silhouette
- 0.4189
To keep this page light, the plots are shown once, under the R tab.
Clusters
| Cluster | Size | Share | a | b | c | d |
|---|---|---|---|---|---|---|
| 1 | 22 | 36.7% | 5.583 | 2.254 | 2.615 | 4.160 |
| 2 | 20 | 33.3% | 3.746 | 5.777 | 3.932 | 1.719 |
| 3 | 18 | 30.0% | 1.893 | 1.954 | 7.185 | 2.250 |
Archetypes (in the original units) and the closest real row
| Archetype | Closest row | Mean membership | a | b | c | d |
|---|---|---|---|---|---|---|
| 1 | 2 | 35.9% | 8 | 1 | 0 | 6 |
| 2 | 3 | 33.1% | 3 | 9 | 4 | 0 |
| 3 | 1 | 31.0% | 0 | 0 | 10 | 2 |
- Archetype 1 sits on row 2, which is extreme in at least one variable; outliers pull archetypes outward.
- Archetype 2 sits on row 3, which is extreme in at least one variable; outliers pull archetypes outward.
- Archetype 3 sits on row 1, which is extreme in at least one variable; outliers pull archetypes outward.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Archetypal analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.archetypes 1.0.0 · spec 380f335c032ed4a4
# Dataset: rep1_simplex (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import cluster as csc
from codesplash.stats.rng import Rng
from codesplash.ml import rep_linear as rl
# %% Data
FEATURES = ["a", "b", "c", "d"]
LABEL = None # known groups (external validation only)
ROW_ID = None # row labels for charts
SEED = 42
KINDS = {
"a": "numeric",
"b": "numeric",
"c": "numeric",
"d": "numeric",
}
LEVELS = {
}
df = pd.read_parquet("tests/parity/fixtures/rep1_simplex.parquet", columns=list(dict.fromkeys(FEATURES + [c for c in (LABEL, ROW_ID) if c])))
n_input = len(df)
X, rows, names, frame = csc.prepare(df, FEATURES, KINDS, LEVELS, missing="drop", scale="none")
warnings = []
if len(rows) < n_input:
warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a feature was missing.")
if len(rows) < 3:
raise ValueError("Clustering needs at least three rows with every feature present.")
truth = frame[LABEL].astype("object").to_numpy() if LABEL else None
out = csml.out_dir("target/academy-parity/run-8142/discover.archetypes/simplex_corners/out-python")
values = {"n_used": len(rows)}
centers = None
center_ids = None
D = None
extra = {}
tables = []
charts = []
summary = None
# %% Clustering
K = 3
if not np.all(np.isfinite(X)): # the R driver stops in its scaling step on infinite values; stop here too
raise ValueError("Archetypal analysis needs finite values; remove or recode infinite values first.")
if K >= len(rows):
cs.cs_error("CS_E_TOO_FEW_ROWS", what=f"Archetypal analysis with k = {K}", min=K + 1, n=len(rows))
# Projected gradient on both simplex factors from a furthest-sum start (no random draws).
A, Cw, sse, iterations, converged, start = rl.archetypes(X, K, max_iter=500)
if not converged:
warnings.append(f"Archetypal analysis stopped after {iterations} iterations before its tolerance; raise the iteration limit.")
o = rl.archetype_order(A) # the clustering driver's canonical order, so cluster c is archetype c
A = A[:, o]
Cw = Cw[o]
Zc = Cw @ X
raw = np.argmax(A, axis=1).astype(np.int64)
centers = Zc
for j in range(K):
extra[f"membership_{j + 1}"] = A[:, j]
sst = float(np.sum((X - X.mean(axis=0)) ** 2))
values["n_archetypes"] = K
values["rss"] = float(sse)
values["var_explained"] = 1.0 - float(sse) / sst if sst > 0 else float("nan")
X_raw = frame[FEATURES].apply(pd.to_numeric, errors="coerce").to_numpy(dtype=np.float64, copy=True)
for j in range(X_raw.shape[1]): # filled cells take the column median, as the design did
gap = np.isnan(X_raw[:, j])
if gap.any():
X_raw[gap, j] = np.nanmedian(X_raw[:, j])
Z_raw = Cw @ X_raw # archetypes as mixtures of real rows, in the original units
arch_rows = []
for j in range(K):
d = np.sqrt(np.sum((X - Zc[j]) ** 2, axis=1))
near = int(np.argmin(d))
values[f"nearest_row[{j + 1}]"] = int(rows[near]) + 1
values[f"nearest_distance[{j + 1}]"] = float(d[near])
values[f"mean_membership[{j + 1}]"] = float(A[:, j].mean())
row = {"archetype": j + 1, "nearest": int(rows[near]) + 1, "membership": float(A[:, j].mean())}
for i, f in enumerate(FEATURES):
values[f"archetype[{j + 1},{f}]"] = float(Z_raw[j, i])
row[f] = float(Z_raw[j, i])
arch_rows.append(row)
top = int(np.argmax(Cw[j]))
if Cw[j, top] >= 0.9 and float(np.max(np.abs(X[top]))) > 4:
warnings.append(f"Archetype {j + 1} sits on row {int(rows[top]) + 1}, which is extreme in at least one variable; outliers pull archetypes outward.")
tables.append({
"key": "archetypes",
"title": "Archetypes (in the original units) and the closest real row",
"columns": [
{"key": "archetype", "label": "Archetype", "type": "integer"},
{"key": "nearest", "label": "Closest row", "type": "integer"},
{"key": "membership", "label": "Mean membership", "type": "percent"},
]
+ [{"key": f, "label": f, "type": "number"} for f in FEATURES],
"rows": arch_rows,
})
names_a = [f"Archetype {j + 1}" for j in range(K)]
charts.append(cs.chart(
"profiles",
"matrix-heatmap",
"Archetype profiles (scaled; cell text in the original units)",
{
"row": cs.col("Archetype", [a for a in names_a for _ in FEATURES], "categorical", levels=names_a),
"col": cs.col("Variable", [f for _ in names_a for f in FEATURES], "categorical", levels=FEATURES),
"value": cs.col("Scaled value", [float(Zc[j, i]) for j in range(K) for i in range(len(FEATURES))], "numeric"),
"label": cs.col("Value", [f"{Z_raw[j, i]:.3g}" for j in range(K) for i in range(len(FEATURES))], "categorical"),
},
))
summary = (
f"Archetypal analysis with k = {K}: the archetypes explain {values['var_explained']:.0%} of the variation; "
"each row is a mix of them (membership columns)."
)
# %% Canonical labels and validation
labels = csc.canonical(raw)
ids = [int(c) for c in sorted(set(labels.tolist())) if c != -1]
k = len(ids)
values["k"] = k
values["n_noise"] = int(np.sum(labels == -1))
if centers is not None:
# reorder centers to canonical ids: the raw id of each canonical cluster
raw_of = {c: raw[np.flatnonzero(labels == c)[0]] for c in ids}
pos = {int(r): i for i, r in enumerate(center_ids if center_ids is not None else range(len(centers)))}
centers = np.array([centers[pos[int(raw_of[c])]] for c in ids])
for c, row in zip(ids, centers):
for name, v in zip(names, row):
values[f"center[{c},{name}]"] = float(v)
for c, m in csc.sizes(labels).items():
values[f"size[{c}]"] = m
check = csc.validation(X, labels, truth, D=D, cap=3000, seed=SEED)
widths, picked = check.pop("_widths")
values.update(check)
# per-cluster means of numeric features in their own units (interpretation)
profile_rows = []
for c in ids:
member = labels == c
row = {"cluster": c, "size": int(member.sum()), "share": float(member.mean())}
for f in FEATURES:
if KINDS[f] == "numeric":
m = float(np.nanmean(pd.to_numeric(frame[f], errors="coerce").to_numpy(dtype=np.float64)[member]))
row[f] = m
values[f"mean[{c},{f}]"] = m
else:
top = pd.Series(frame[f].astype("object").to_numpy()[member]).dropna().astype(str).value_counts()
row[f] = f"{top.index[0]} ({top.iloc[0] / member.sum():.0%})" if len(top) else ""
profile_rows.append(row)
tables.insert(0, {
"key": "clusters",
"title": "Clusters",
"columns": [
{"key": "cluster", "label": "Cluster", "type": "integer"},
{"key": "size", "label": "Size", "type": "integer"},
{"key": "share", "label": "Share", "type": "percent"},
]
+ [{"key": f, "label": f, "type": "number" if KINDS[f] == "numeric" else "string"} for f in FEATURES],
"rows": profile_rows,
})
# %% Labels file and charts
path = csc.write_labels(out, rows, labels, **extra)
name_of = lambda c: str(c) # noqa: E731 — noise stays "-1" (drawn gray, listed last)
P, C, axes = csc.project2(X, centers, names)
show = csc.even_sample(len(rows))
point_labels = [str(v) for v in frame[ROW_ID].astype("object").to_numpy()[show]] if ROW_ID else None
xs, ys = list(P[show, 0]), list(P[show, 1])
cl = [name_of(c) for c in labels[show]]
cent = [False] * len(show)
lab = point_labels
if C is not None:
xs += list(C[:, 0])
ys += list(C[:, 1])
cl += [name_of(c) for c in ids]
cent += [True] * len(ids)
lab = None if lab is None else lab + [f"center {c}" for c in ids]
level_names = [str(c) for c in ids] + (["-1"] if values["n_noise"] else [])
charts.insert(0, cs.chart(
"clusters", "cluster-scatter", "Clusters",
{
"x": cs.col(axes[0], xs, "numeric"),
"y": cs.col(axes[1], ys, "numeric"),
"cluster": cs.col("Cluster", cl, "categorical", levels=level_names),
"centroid": cs.col("Center", cent, "boolean") if C is not None else None,
"label": cs.col("Row", lab, "categorical") if lab is not None else None,
},
note=None if len(show) == len(rows) else f"{len(show):,} of {len(rows):,} rows shown.",
))
if not np.isnan(values["silhouette"]):
wl = labels[picked]
order = np.lexsort((-widths, wl))
charts.append(cs.chart(
"silhouette", "silhouette-plot", "Silhouette widths",
{"cluster": cs.col("Cluster", [str(c) for c in wl[order]], "categorical", levels=[str(c) for c in ids]),
"width": cs.col("Silhouette width", list(widths[order]), "numeric")},
note=None if len(picked) == int(np.sum(labels != -1)) else f"{len(picked):,} rows sampled for the silhouette.",
))
# %% Result
if summary is None:
summary = f"{k} cluster{'s' if k != 1 else ''} in {len(rows):,} rows"
if values["n_noise"]:
summary += f" ({values['n_noise']:,} noise points)"
if not np.isnan(values["silhouette"]):
summary += f"; mean silhouette {values['silhouette']:.2f}"
summary += "."
cs.publish({
"title": "Archetypal analysis",
"engine": cs.engine_info("numpy", "numpy", "pandas"),
"n": len(rows),
"summary": summary,
"statistics": [
{"key": "k", "label": "Clusters", "value": k, "format": "integer"},
{"key": "silhouette", "label": "Mean silhouette", "value": values["silhouette"]},
],
"tables": tables,
"values": values,
"charts": charts,
"warnings": warnings,
"artifacts": [{"key": "labels", "path": path, "format": "parquet"}],
"model": {"kind": "clusterer", "features": names, "params": {
"k": 3,
"max_iter": 500,
"scale": "none",
"missing": "drop",
}},
})
A PCA with a likelihood
ReadOrdinary 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:
PCA of 4 variables: the first component explains 62.0% of the variance.
- PC1 variance
- 62.0%
- PC1 + PC2
- 86.8%
Plots
View data
| Component | Cumulative | Proportion of variance |
|---|---|---|
| 1 | 0.6201 | 0.6201 |
| 2 | 0.8675 | 0.2474 |
| 3 | 0.9566 | 0.0891 |
| 4 | 1 | 0.0434 |
Loading arrows are rescaled to the score range.
View data
| Kind | Label | PC1 | PC2 |
|---|---|---|---|
| point | 0.9757 | −1.122 | |
| point | 1.931 | −1.062 | |
| point | 1.745 | 0.7385 | |
| point | −0.1400 | −1.109 | |
| point | 2.499 | 1.527 | |
| point | 1.499 | 0.9776 | |
| point | −1.345 | 1.078 | |
| point | 0.0472 | 0.3221 | |
| point | 2.983 | −0.0388 | |
| point | 1.623 | −1.266 | |
| point | −0.9035 | 1.555 | |
| point | −1.623 | −0.2089 | |
| point | 1.365 | 0.6750 | |
| point | −0.5004 | 0.1500 | |
| point | −2.231 | 0.1030 | |
| point | −0.7889 | 0.2674 | |
| point | −0.7433 | −0.9488 | |
| point | 1.549 | −0.8623 | |
| point | −2.373 | −0.3726 | |
| point | 1.746 | −0.4234 | |
| point | −0.4813 | 1.460 | |
| point | 2.087 | 0.1538 | |
| point | −1.676 | 0.6259 | |
| point | 0.9865 | −2.370 | |
| point | 0.6898 | 0.2607 | |
| point | −1.174 | −0.5315 | |
| point | −1.253 | 0.1920 | |
| point | 2.846 | 0.7678 | |
| point | −2.360 | 0.0179 | |
| point | 0.1797 | 1.435 | |
| point | 1.960 | −0.1414 | |
| point | 1.666 | 0.8149 | |
| point | 1.112 | −2.206 | |
| point | −2.962 | −0.5931 | |
| point | −0.2237 | 0.7348 | |
| point | −0.3086 | 0.2850 | |
| point | 0.0585 | 0.5360 | |
| point | −0.8795 | 0.5654 | |
| point | −0.8551 | 1.477 | |
| point | 1.307 | −1.914 | |
| point | −1.968 | −0.8151 | |
| point | 0.9897 | −0.8516 | |
| point | 1.342 | 0.4083 | |
| point | −0.5450 | 1.457 | |
| point | −2.773 | −1.388 | |
| point | −0.0954 | −0.1977 | |
| point | −0.2147 | 0.9604 | |
| point | −2.087 | −1.411 | |
| point | −2.059 | 0.6051 | |
| point | −0.6231 | −0.3178 | |
| loading | Murder | 1.465 | −1.143 |
| loading | Assault | 1.594 | −0.5139 |
| loading | UrbanPop | 0.7606 | 2.386 |
| loading | Rape | 1.486 | 0.4574 |
Explained variance
| Component | Eigenvalue | Proportion | Cumulative |
|---|---|---|---|
| 1 | 2.480 | 62.0% | 62.0% |
| 2 | 0.9898 | 24.7% | 86.8% |
| 3 | 0.3566 | 8.9% | 95.7% |
| 4 | 0.1734 | 4.3% | 100.0% |
Loadings
| Variable | PC1 | PC2 | PC3 | PC4 |
|---|---|---|---|---|
| Murder | 0.5359 | −0.4182 | −0.3412 | −0.6492 |
| Assault | 0.5832 | −0.1880 | −0.2681 | 0.7434 |
| UrbanPop | 0.2782 | 0.8728 | −0.3780 | −0.1339 |
| Rape | 0.5434 | 0.1673 | 0.8178 | −0.0890 |
Probabilistic PCA by rank (σ² = noise variance; lowest BIC is the best rank)
| Rank | σ² | Log-likelihood | Parameters | BIC |
|---|---|---|---|---|
| 1 | 0.4965 | −253.47 | 9 | 542.15 |
| 2 | 0.2597 | −237.82 | 12 | 522.58 |
| 3 | 0.1700 | −234.64 | 14 | 524.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"))
))
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
| Component | Eigenvalue | Proportion | Cumulative |
|---|---|---|---|
| 1 | 2.480 | 62.0% | 62.0% |
| 2 | 0.9898 | 24.7% | 86.8% |
| 3 | 0.3566 | 8.9% | 95.7% |
| 4 | 0.1734 | 4.3% | 100.0% |
Loadings
| Variable | PC1 | PC2 | PC3 | PC4 |
|---|---|---|---|---|
| Murder | 0.5359 | −0.4182 | −0.3412 | −0.6492 |
| Assault | 0.5832 | −0.1880 | −0.2681 | 0.7434 |
| UrbanPop | 0.2782 | 0.8728 | −0.3780 | −0.1339 |
| Rape | 0.5434 | 0.1673 | 0.8178 | −0.0890 |
Probabilistic PCA by rank (σ² = noise variance; lowest BIC is the best rank)
| Rank | σ² | Log-likelihood | Parameters | BIC |
|---|---|---|---|---|
| 1 | 0.4965 | −253.47 | 9 | 542.15 |
| 2 | 0.2597 | −237.82 | 12 | 522.58 |
| 3 | 0.1700 | −234.64 | 14 | 524.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.
Filling gaps with PPCA-EM
ReadThe 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.
PCA of 4 variables: the first component explains 68.8% of the variance.
- PC1 variance
- 68.8%
- PC1 + PC2
- 88.2%
Plots
View data
| Component | Cumulative | Proportion of variance |
|---|---|---|
| 1 | 0.6884 | 0.6884 |
| 2 | 0.8816 | 0.1931 |
| 3 | 0.9729 | 0.0913 |
| 4 | 1 | 0.0271 |
Loading arrows are rescaled to the score range.
View data
| Kind | Label | PC1 | PC2 |
|---|---|---|---|
| point | −1.841 | 0.0476 | |
| point | −1.305 | −0.4277 | |
| point | −1.367 | −0.1543 | |
| point | −1.876 | −0.0020 | |
| point | −1.909 | 0.8280 | |
| point | −1.760 | −0.3510 | |
| point | −0.8089 | 0.5217 | |
| point | −1.833 | −0.7685 | |
| point | −1.192 | 1.025 | |
| point | −1.728 | −0.7874 | |
| point | −1.740 | −0.6655 | |
| point | −1.786 | −0.2357 | |
| point | −1.945 | 1.010 | |
| point | −1.562 | 0.5962 | |
| point | −1.737 | −0.5939 | |
| point | −1.567 | 0.0958 | |
| point | −0.7944 | 1.309 | |
| point | −2.340 | −0.6317 | |
| point | −0.9928 | 1.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.750 | 0.1506 | |
| point | −1.692 | −0.1793 | |
| point | −2.699 | −0.1886 | |
| point | −1.669 | 0.3024 | |
| point | −1.867 | −0.7697 | |
| point | −1.898 | −0.3872 | |
| point | −1.646 | −0.3184 | |
| point | −1.506 | 0.3415 | |
| point | −1.438 | −0.9768 | |
| point | −1.431 | 1.073 | |
| point | −1.624 | 0.5625 | |
| point | −1.719 | 0.2846 | |
| point | −2.395 | 0.0786 | |
| point | −1.125 | 0.3809 | |
| point | −2.285 | −0.5824 | |
| point | −0.9621 | 0.1304 | |
| point | −2.298 | −0.4397 | |
| point | −0.5676 | 1.069 | |
| point | −2.000 | −0.9874 | |
| point | −0.8695 | 0.2336 | |
| point | −1.916 | 0.3535 | |
| point | −2.627 | −0.1284 | |
| point | −1.774 | −0.6446 | |
| point | −1.398 | 1.451 | |
| point | −1.562 | −0.3272 | |
| point | −1.135 | 0.2968 | |
| point | −1.857 | −0.7540 | |
| point | −0.7777 | 0.7226 | |
| point | −2.438 | −0.7862 | |
| point | −1.253 | 0.2551 | |
| point | −1.538 | −0.4683 | |
| point | −1.210 | 0.2593 | |
| point | −2.247 | −1.180 | |
| point | −1.514 | 0.0473 | |
| point | −2.006 | −1.114 |
First 60 of 346 rows.
Explained variance
| Component | Eigenvalue | Proportion | Cumulative |
|---|---|---|---|
| 1 | 2.754 | 68.8% | 68.8% |
| 2 | 0.7725 | 19.3% | 88.2% |
| 3 | 0.3652 | 9.1% | 97.3% |
| 4 | 0.1085 | 2.7% | 100.0% |
Loadings
| Variable | PC1 | PC2 | PC3 |
|---|---|---|---|
| bill_len | 0.4553 | 0.5970 | 0.6443 |
| bill_dep | −0.4003 | 0.7978 | −0.4184 |
| flipper_len | 0.5760 | 0.0023 | −0.2321 |
| body_mass | 0.5484 | 0.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"))
))
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
| Component | Eigenvalue | Proportion | Cumulative |
|---|---|---|---|
| 1 | 2.754 | 68.8% | 68.8% |
| 2 | 0.7725 | 19.3% | 88.2% |
| 3 | 0.3652 | 9.1% | 97.3% |
| 4 | 0.1085 | 2.7% | 100.0% |
Loadings
| Variable | PC1 | PC2 | PC3 |
|---|---|---|---|
| bill_len | 0.4553 | 0.5970 | 0.6443 |
| bill_dep | −0.4003 | 0.7978 | −0.4184 |
| flipper_len | 0.5760 | 0.0023 | −0.2321 |
| body_mass | 0.5484 | 0.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.
Check your understanding
CheckpointCheck 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.
Do it on your own data
In the appFind Archetypal analysis in Discover under Find segments. Probabilistic PCA and PPCA-EM are settings of Principal component analysis under Map the data.
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