Mixtures for counts, directions, answers and outliers
A Gaussian mixture assumes bell-shaped, continuous groups. Learn the mixtures that fit counts, directions, categorical answers, heavy tails and wide data, and how ICL tells a good density from a good clustering.
What runs in CodeSplash
- Count and direction mixtures Verified in Python and R
- Latent class analysis Verified in Python and R
- Gaussian mixture model Verified in Python and R
You will be able to
- Pick a Poisson, von Mises–Fisher or latent class mixture from the kind of data
- Explain why Student-t components resist outliers and what their degrees of freedom say
- Use factor-analyzer covariances for wide data
- Compare k with BIC and ICL, and read entropy R²
Read first
One idea, many shapes
ReadA Gaussian mixtureGaussian mixtureA model in which each row comes from one of k normal distributions, giving every row a probability for each group. says every row came from one of groups, each a normal distribution. The idea doesn't need the normal part. Swap in a distribution that fits your data and EM works the same way: work out how likely each row is under each group, then refit each group with those probabilities as weights.
Choose from what a row is:
| Each row holds | Mixture | Method |
|---|---|---|
| Measurements on a continuous scale | Gaussian | Gaussian mixture |
| The same, with outliers | Student-t | Gaussian mixture, Component shape: Student-t |
| Many correlated measurements | Factor analyzers | Gaussian mixture, Covariance: factor analyzers |
| Counts (visits, calls, defects) | Poisson | Count and direction mixtures |
| A direction or a mix (only proportions matter) | von Mises–Fisher | Count and direction mixtures |
| Answers to categorical questions | Latent classes | Latent class analysis |
Counts: Poisson mixtures
ReadA Poisson mixturePoisson mixtureGroups of count data, each with its own rate per count column (optionally per unit of exposure). gives each group its own rate for every count column. If customers were watched for different lengths of time, an exposure column turns the rates into rates per month, so a long-time customer with many visits isn't mistaken for a heavy user.
3-component Poisson mixture: log-likelihood -1803.2, BIC 3669.2, ICL 3748.1.
- Clusters
- 3
- Mean silhouette
- 0.3488
Plots
View data
| Center | Cluster | PC1 (59%) | PC2 (37%) |
|---|---|---|---|
| false | 2 | −1.378 | −0.8974 |
| false | 3 | 25.486 | −11.589 |
| false | 2 | 1.122 | 4.124 |
| false | 3 | 10.461 | −9.142 |
| false | 2 | 8.854 | 12.406 |
| false | 1 | −5.218 | −2.550 |
| false | 2 | 2.929 | 2.485 |
| false | 2 | −2.743 | 1.134 |
| false | 1 | −4.905 | 0.5651 |
| false | 2 | 10.006 | 14.911 |
| false | 2 | −0.4460 | 2.563 |
| false | 1 | −5.261 | −1.642 |
| false | 3 | 11.300 | −9.751 |
| false | 1 | −3.693 | −0.0816 |
| false | 1 | −3.888 | 2.211 |
| false | 1 | −5.770 | −2.465 |
| false | 1 | −4.244 | 0.0030 |
| false | 1 | −4.710 | −1.727 |
| false | 3 | 0.6495 | −3.491 |
| false | 1 | −2.370 | −1.206 |
| false | 1 | −6.431 | −1.903 |
| false | 3 | 7.968 | −10.581 |
| false | 2 | −3.803 | 0.3959 |
| false | 2 | 5.717 | 9.284 |
| false | 1 | −5.108 | −3.027 |
| false | 1 | −5.261 | −1.642 |
| false | 2 | 5.870 | 7.899 |
| false | 1 | −4.397 | 1.388 |
| false | 3 | 3.626 | −4.869 |
| false | 3 | 3.228 | −6.169 |
| false | 1 | −5.770 | −2.465 |
| false | 3 | −4.116 | −2.719 |
| false | 1 | −2.921 | −1.121 |
| false | 2 | 3.683 | 5.993 |
| false | 1 | 0.3009 | 0.1861 |
| false | 1 | −2.523 | 0.1792 |
| false | 2 | 5.625 | 5.214 |
| false | 1 | −3.387 | −2.851 |
| false | 1 | −6.431 | −1.903 |
| false | 1 | −2.260 | −1.683 |
| false | 2 | 5.827 | 8.807 |
| false | 1 | −4.091 | −1.382 |
| false | 2 | 5.870 | 7.899 |
| false | 2 | 2.495 | 7.977 |
| false | 1 | −2.523 | 0.1792 |
| false | 1 | −5.414 | −0.2577 |
| false | 1 | −0.3358 | 2.085 |
| false | 1 | −6.431 | −1.903 |
| false | 3 | 16.244 | −8.268 |
| false | 2 | 0.6138 | 3.301 |
| false | 2 | 3.658 | 4.656 |
| false | 1 | −4.244 | 0.0030 |
| false | 2 | 3.089 | 6.985 |
| false | 1 | −5.923 | −1.080 |
| false | 3 | 18.178 | −14.931 |
| false | 1 | −5.414 | −0.2577 |
| false | 2 | 1.894 | 3.084 |
| false | 1 | −3.583 | −0.5590 |
| false | 2 | −4.354 | 0.4805 |
| false | 1 | −3.693 | −0.0816 |
First 60 of 303 rows.
View data
| Cluster | Silhouette width |
|---|---|
| 1 | 0.7831 |
| 1 | 0.7831 |
| 1 | 0.7831 |
| 1 | 0.7831 |
| 1 | 0.7831 |
| 1 | 0.7831 |
| 1 | 0.7831 |
| 1 | 0.7831 |
| 1 | 0.7831 |
| 1 | 0.7831 |
| 1 | 0.7766 |
| 1 | 0.7766 |
| 1 | 0.7766 |
| 1 | 0.7766 |
| 1 | 0.7766 |
| 1 | 0.7666 |
| 1 | 0.7666 |
| 1 | 0.7666 |
| 1 | 0.7666 |
| 1 | 0.7666 |
| 1 | 0.7650 |
| 1 | 0.7650 |
| 1 | 0.7650 |
| 1 | 0.7650 |
| 1 | 0.7650 |
| 1 | 0.7650 |
| 1 | 0.7650 |
| 1 | 0.7650 |
| 1 | 0.7650 |
| 1 | 0.7605 |
| 1 | 0.7605 |
| 1 | 0.7605 |
| 1 | 0.7605 |
| 1 | 0.7597 |
| 1 | 0.7582 |
| 1 | 0.7582 |
| 1 | 0.7582 |
| 1 | 0.7556 |
| 1 | 0.7556 |
| 1 | 0.7556 |
| 1 | 0.7556 |
| 1 | 0.7556 |
| 1 | 0.7556 |
| 1 | 0.7556 |
| 1 | 0.7546 |
| 1 | 0.7546 |
| 1 | 0.7546 |
| 1 | 0.7546 |
| 1 | 0.7546 |
| 1 | 0.7546 |
| 1 | 0.7546 |
| 1 | 0.7480 |
| 1 | 0.7455 |
| 1 | 0.7430 |
| 1 | 0.7430 |
| 1 | 0.7430 |
| 1 | 0.7430 |
| 1 | 0.7430 |
| 1 | 0.7430 |
| 1 | 0.7430 |
First 60 of 300 rows.
Clusters
| Cluster | Size | Share | visits | calls | purchases |
|---|---|---|---|---|---|
| 1 | 149 | 49.7% | 2.235 | 1.215 | 0.5168 |
| 2 | 95 | 31.7% | 10.074 | 1.989 | 4.263 |
| 3 | 56 | 18.7% | 3.464 | 11.607 | 7.589 |
Components (rate per unit exposure)
| Cluster | Weight | Rate: visits | Rate: calls | Rate: purchases |
|---|---|---|---|---|
| 1 | 48.3% | 0.3706 | 0.2017 | 0.0856 |
| 2 | 33.0% | 1.455 | 0.2934 | 0.6202 |
| 3 | 18.7% | 0.5559 | 1.847 | 1.206 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Count and direction mixtures
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.mixture 1.0.0 · spec 65ea2cb05f43e4d3
# Dataset: w5_counts (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("visits", "calls", "purchases")
LABEL <- "segment" # known groups (external validation only)
ROW_ID <- NULL # row labels for charts
SEED <- 42
KINDS <- list(
visits = "numeric",
calls = "numeric",
purchases = "numeric"
)
LEVELS <- list(
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/w5_counts.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.mixture/counts_exposure/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
FAMILY <- "poisson"
EXPOSURE <- "months"
cs_check_finite_columns(df, FEATURES) # ±Inf stops the run
if (K >= length(rows)) cs_error("CS_E_TOO_FEW_ROWS", what = sprintf("A %d-component mixture", K), min = K + 1L, n = length(rows))
rng <- cs_rng(SEED) # shared stream: identical starting responsibilities in Python and R
if (FAMILY == "poisson") {
for (c_ in seq_len(ncol(X))) {
bad_ <- sum(X[, c_] < 0 | X[, c_] != floor(X[, c_]))
if (bad_) cs_error("CS_E_INVALID_VALUES", column = names_[c_], requirement = "a whole-number count of at least 0", count = bad_)
}
exposure <- NULL
if (!is.null(EXPOSURE)) {
ex_ <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/w5_counts.parquet", col_select = EXPOSURE))[[EXPOSURE]]
exposure <- suppressWarnings(as.numeric(as.character(ex_)))[rows + 1L]
bad_ <- sum(!(exposure > 0) | is.na(exposure))
if (bad_) cs_error("CS_E_INVALID_VALUES", column = EXPOSURE, requirement = "a positive exposure", count = bad_)
}
best <- cs_mx_poisson_fit(X, K, rng, exposure = exposure, n_init = 3, tol = 1e-8, max_iter = 500)
centers <- best$params$rates
} else {
if (ncol(X) < 2) cs_error("CS_E_INVALID_OPTION", option = "Features", allowed = "at least two numeric columns for directions", value = ncol(X))
ur_ <- cs_mx_unit_rows(X)
bad_ <- sum(ur_$norms == 0)
if (bad_) cs_error("CS_E_INVALID_VALUES", column = "Each row", requirement = "a direction (not all zeros)", count = bad_)
X <- ur_$U # directions: validation and the map use the unit-length rows
best <- cs_mx_vmf_fit(X, K, rng, n_init = 3, tol = 1e-8, max_iter = 500)
centers <- best$params$mu
}
if (!best$converged) warnings <- c(warnings, "EM stopped at the iteration limit before converging.")
resp <- best$resp
raw <- best$labels
canon <- cs_ml_canonical(raw)
comp_rows <- list()
for (j in seq_len(K)) {
members <- which(raw == j - 1L)
if (!length(members)) next
c_ <- canon[members[1]]
w_ <- best$params$weights[j]
values[[sprintf("weight[%d]", c_)]] <- w_
extra[[sprintf("membership_%d", c_)]] <- resp[, j]
row_ <- list(cluster = c_, weight = w_)
if (FAMILY == "poisson") {
for (i in seq_along(names_)) row_[[names_[i]]] <- best$params$rates[j, i]
} else {
values[[sprintf("kappa[%d]", c_)]] <- best$params$kappa[j]
row_$kappa <- best$params$kappa[j]
}
comp_rows[[length(comp_rows) + 1L]] <- row_
}
comp_rows <- comp_rows[order(vapply(comp_rows, function(r) r$cluster, numeric(1)))]
crit <- cs_mx_criteria(best$loglik, best$n_par, length(rows), resp)
values$loglik <- best$loglik
values <- c(values, crit)
values$family <- if (FAMILY == "poisson") "Poisson" else "von Mises–Fisher"
extra$probability <- apply(resp, 1, max)
tables[[length(tables) + 1L]] <- list(
key = "components",
title = paste0("Components", if (FAMILY == "poisson" && !is.null(EXPOSURE)) " (rate per unit exposure)" else ""),
columns = c(list(list(key = "cluster", label = "Cluster", type = "integer"), list(key = "weight", label = "Weight", type = "percent")),
if (FAMILY == "poisson") lapply(names_, function(n) list(key = n, label = paste("Rate:", n), type = "number"))
else list(list(key = "kappa", label = "Concentration κ", type = "number"))),
rows = comp_rows
)
summary <- sprintf("%d-component %s mixture: log-likelihood %.1f, BIC %.1f, ICL %.1f.", K, values$family, values$loglik, values$bic, values$icl)
# %% 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 = "Count and direction mixtures",
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(
family = "poisson",
k = 3,
n_init = 3,
max_iter = 500,
tol = 1e-8,
scale = "none",
missing = "drop"
))
))
3-component Poisson mixture: log-likelihood -1803.2, BIC 3669.2, ICL 3748.1.
- Clusters
- 3
- Mean silhouette
- 0.3488
To keep this page light, the plots are shown once, under the R tab.
Clusters
| Cluster | Size | Share | visits | calls | purchases |
|---|---|---|---|---|---|
| 1 | 149 | 49.7% | 2.235 | 1.215 | 0.5168 |
| 2 | 95 | 31.7% | 10.074 | 1.989 | 4.263 |
| 3 | 56 | 18.7% | 3.464 | 11.607 | 7.589 |
Components (rate per unit exposure)
| Cluster | Weight | Rate: visits | Rate: calls | Rate: purchases |
|---|---|---|---|---|
| 1 | 48.3% | 0.3706 | 0.2017 | 0.0856 |
| 2 | 33.0% | 1.455 | 0.2934 | 0.6202 |
| 3 | 18.7% | 0.5559 | 1.847 | 1.206 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Count and direction mixtures
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.mixture 1.0.0 · spec 65ea2cb05f43e4d3
# Dataset: w5_counts (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.errors import check_finite_columns, cs_error
from codesplash.ml import mixture_ext as csmx
# %% Data
FEATURES = ["visits", "calls", "purchases"]
LABEL = "segment" # known groups (external validation only)
ROW_ID = None # row labels for charts
SEED = 42
KINDS = {
"visits": "numeric",
"calls": "numeric",
"purchases": "numeric",
}
LEVELS = {
}
df = pd.read_parquet("tests/parity/fixtures/w5_counts.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.mixture/counts_exposure/out-python")
values = {"n_used": len(rows)}
centers = None
center_ids = None
D = None
extra = {}
tables = []
charts = []
summary = None
# %% Clustering
K = 3
FAMILY = "poisson"
EXPOSURE = "months"
check_finite_columns(df, FEATURES) # ±Inf stops the run
if K >= len(rows):
cs_error("CS_E_TOO_FEW_ROWS", what=f"A {K}-component mixture", min=K + 1, n=len(rows))
rng = Rng(SEED) # shared stream: identical starting responsibilities in Python and R
if FAMILY == "poisson":
for _c, _name in enumerate(names):
_bad = int(np.sum((X[:, _c] < 0) | (X[:, _c] != np.floor(X[:, _c]))))
if _bad:
cs_error("CS_E_INVALID_VALUES", column=_name, requirement="a whole-number count of at least 0", count=_bad)
exposure = None
if EXPOSURE:
exposure = pd.to_numeric(pd.read_parquet("tests/parity/fixtures/w5_counts.parquet", columns=[EXPOSURE])[EXPOSURE], errors="coerce").to_numpy(dtype=np.float64)[rows]
_bad = int(np.sum(~(exposure > 0)))
if _bad:
cs_error("CS_E_INVALID_VALUES", column=EXPOSURE, requirement="a positive exposure", count=_bad)
best = csmx.poisson_fit(X, K, rng, exposure=exposure, n_init=3, tol=1e-8, max_iter=500)
centers = best["params"]["rates"]
else:
if X.shape[1] < 2:
cs_error("CS_E_INVALID_OPTION", option="Features", allowed="at least two numeric columns for directions", value=X.shape[1])
U, _norms = csmx.unit_rows(X)
_bad = int(np.sum(_norms == 0))
if _bad:
cs_error("CS_E_INVALID_VALUES", column="Each row", requirement="a direction (not all zeros)", count=_bad)
X = U # directions: validation and the map use the unit-length rows
best = csmx.vmf_fit(X, K, rng, n_init=3, tol=1e-8, max_iter=500)
centers = best["params"]["mu"]
if not best["converged"]:
warnings.append("EM stopped at the iteration limit before converging.")
resp = best["resp"]
raw = best["labels"]
canon = csc.canonical(raw)
comp_rows = []
for j in range(K):
members = np.flatnonzero(raw == j)
if not len(members):
continue
c = int(canon[members[0]])
values[f"weight[{c}]"] = float(best["params"]["weights"][j])
extra[f"membership_{c}"] = resp[:, j]
row = {"cluster": c, "weight": float(best["params"]["weights"][j])}
if FAMILY == "poisson":
for name, v in zip(names, best["params"]["rates"][j]):
row[name] = float(v)
else:
values[f"kappa[{c}]"] = float(best["params"]["kappa"][j])
row["kappa"] = float(best["params"]["kappa"][j])
comp_rows.append(row)
comp_rows.sort(key=lambda r: r["cluster"])
crit = csmx.criteria(best["loglik"], best["n_par"], len(rows), resp)
values["loglik"] = best["loglik"]
values.update(crit)
values["family"] = {"poisson": "Poisson", "vmf": "von Mises–Fisher"}[FAMILY]
extra["probability"] = resp.max(axis=1)
tables.append({
"key": "components",
"title": "Components" + (" (rate per unit exposure)" if FAMILY == "poisson" and EXPOSURE else ""),
"columns": [{"key": "cluster", "label": "Cluster", "type": "integer"}, {"key": "weight", "label": "Weight", "type": "percent"}]
+ ([{"key": n, "label": f"Rate: {n}", "type": "number"} for n in names] if FAMILY == "poisson" else [{"key": "kappa", "label": "Concentration κ", "type": "number"}]),
"rows": comp_rows,
})
summary = (
f"{K}-component {values['family']} mixture: log-likelihood {values['loglik']:.1f}, "
f"BIC {values['bic']:.1f}, ICL {values['icl']:.1f}."
)
# %% 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": "Count and direction mixtures",
"engine": cs.engine_info("numpy", "scipy", "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": {
"family": "poisson",
"k": 3,
"n_init": 3,
"max_iter": 500,
"tol": 1e-8,
"scale": "none",
"missing": "drop",
}},
})
The components table lists each group's rate per month for every count. Compare them with the groups that made the simulated data: browsers, buyers and callers.
Directions: von Mises–Fisher mixtures
ReadSometimes only the direction of a row matters: a spending profile where only the mix counts, a normalized text embedding, a wind direction. A von Mises–Fisher mixturevon Mises–Fisher mixtureGroups of directions: each row is scaled to length 1 and each component has a mean direction and a concentration κ. scales every row to length 1 and clusters the directions. Each group has a mean direction and a concentration κ: the larger κ, the tighter the group.
3-component von Mises–Fisher mixture: log-likelihood -287.4, BIC 635.1, ICL 649.2.
- Clusters
- 3
- Mean silhouette
- 0.5872
Plots
View data
| Center | Cluster | PC1 (51%) | PC2 (41%) |
|---|---|---|---|
| false | 2 | −0.0332 | 0.6376 |
| false | 2 | −0.1356 | 0.7432 |
| false | 2 | −0.0231 | 0.7484 |
| false | 2 | −0.1504 | 0.7311 |
| false | 2 | −0.3566 | 0.4749 |
| false | 2 | −0.2190 | 0.5233 |
| false | 2 | −0.3639 | 0.4602 |
| false | 2 | −0.2162 | 0.5388 |
| false | 2 | −0.2586 | 0.6734 |
| false | 2 | 0.1262 | 0.7230 |
| false | 2 | −0.0068 | 0.6737 |
| false | 2 | −0.0731 | 0.4503 |
| false | 2 | 0.1318 | 0.7883 |
| false | 2 | 0.1249 | 0.6955 |
| false | 2 | 0.0151 | 0.7214 |
| false | 2 | −0.0458 | 0.6176 |
| false | 2 | −0.0983 | 0.7006 |
| false | 2 | −0.2882 | 0.6902 |
| false | 2 | −0.0237 | 0.6958 |
| false | 2 | −0.1338 | 0.6780 |
| false | 2 | −0.1490 | 0.6898 |
| false | 2 | −0.2017 | 0.5991 |
| false | 2 | 0.2052 | 0.6090 |
| false | 2 | 0.0311 | 0.7517 |
| false | 2 | −0.1505 | 0.7634 |
| false | 2 | −0.1581 | 0.5773 |
| false | 2 | −0.2226 | 0.6875 |
| false | 2 | −0.0937 | 0.6794 |
| false | 2 | −0.1741 | 0.7303 |
| false | 2 | −0.0844 | 0.5625 |
| false | 2 | −0.1040 | 0.6316 |
| false | 2 | −0.0532 | 0.7884 |
| false | 2 | −0.1525 | 0.7911 |
| false | 2 | −0.2185 | 0.5612 |
| false | 2 | −0.1098 | 0.6741 |
| false | 2 | 0.0736 | 0.5114 |
| false | 2 | −0.2826 | 0.5937 |
| false | 2 | 0.0863 | 0.5990 |
| false | 2 | −0.0900 | 0.7153 |
| false | 2 | −0.3111 | 0.6877 |
| false | 2 | −0.0970 | 0.7655 |
| false | 2 | −0.1062 | 0.6208 |
| false | 2 | −0.0507 | 0.6887 |
| false | 2 | −0.1257 | 0.7037 |
| false | 2 | 0.1233 | 0.4747 |
| false | 2 | −0.1527 | 0.6700 |
| false | 2 | −0.0368 | 0.6888 |
| false | 2 | −0.0799 | 0.6216 |
| false | 2 | 0.0179 | 0.6143 |
| false | 2 | 0.1259 | 0.6741 |
| false | 2 | −0.1037 | 0.7764 |
| false | 2 | 0.2617 | 0.6183 |
| false | 2 | 0.0015 | 0.4486 |
| false | 2 | −0.4624 | 0.5829 |
| false | 2 | −0.0583 | 0.6978 |
| false | 2 | −0.1580 | 0.5734 |
| false | 2 | −0.0077 | 0.7085 |
| false | 2 | −0.2767 | 0.6616 |
| false | 2 | 0.0970 | 0.6613 |
| false | 2 | 0.1453 | 0.5535 |
First 60 of 243 rows.
View data
| Cluster | Silhouette width |
|---|---|
| 1 | 0.7219 |
| 1 | 0.7196 |
| 1 | 0.7182 |
| 1 | 0.7146 |
| 1 | 0.7119 |
| 1 | 0.7102 |
| 1 | 0.7100 |
| 1 | 0.7072 |
| 1 | 0.7058 |
| 1 | 0.7046 |
| 1 | 0.7042 |
| 1 | 0.7035 |
| 1 | 0.7010 |
| 1 | 0.6998 |
| 1 | 0.6989 |
| 1 | 0.6983 |
| 1 | 0.6980 |
| 1 | 0.6979 |
| 1 | 0.6957 |
| 1 | 0.6941 |
| 1 | 0.6935 |
| 1 | 0.6931 |
| 1 | 0.6928 |
| 1 | 0.6927 |
| 1 | 0.6850 |
| 1 | 0.6845 |
| 1 | 0.6820 |
| 1 | 0.6803 |
| 1 | 0.6787 |
| 1 | 0.6763 |
| 1 | 0.6686 |
| 1 | 0.6685 |
| 1 | 0.6684 |
| 1 | 0.6589 |
| 1 | 0.6515 |
| 1 | 0.6496 |
| 1 | 0.6453 |
| 1 | 0.6429 |
| 1 | 0.6410 |
| 1 | 0.6269 |
| 1 | 0.6193 |
| 1 | 0.6142 |
| 1 | 0.6001 |
| 1 | 0.5998 |
| 1 | 0.5995 |
| 1 | 0.5964 |
| 1 | 0.5957 |
| 1 | 0.5918 |
| 1 | 0.5906 |
| 1 | 0.5889 |
| 1 | 0.5859 |
| 1 | 0.5838 |
| 1 | 0.5801 |
| 1 | 0.5775 |
| 1 | 0.5748 |
| 1 | 0.5692 |
| 1 | 0.5675 |
| 1 | 0.5558 |
| 1 | 0.5547 |
| 1 | 0.5542 |
First 60 of 240 rows.
Clusters
| Cluster | Size | Share | x | y | z |
|---|---|---|---|---|---|
| 1 | 82 | 34.2% | 0.0039 | 1.583 | 0.3055 |
| 2 | 79 | 32.9% | 1.672 | 0.3247 | 0.1167 |
| 3 | 79 | 32.9% | 0.2918 | 0.0317 | −1.410 |
Components
| Cluster | Weight | Concentration κ |
|---|---|---|
| 1 | 34.0% | 13.056 |
| 2 | 32.8% | 39.976 |
| 3 | 33.1% | 7.190 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Count and direction mixtures
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.mixture 1.0.0 · spec 1d865e43e89d5049
# Dataset: w5_directions (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("x", "y", "z")
LABEL <- "source" # known groups (external validation only)
ROW_ID <- NULL # row labels for charts
SEED <- 42
KINDS <- list(
x = "numeric",
y = "numeric",
z = "numeric"
)
LEVELS <- list(
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/w5_directions.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.mixture/directions_vmf/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
FAMILY <- "vmf"
EXPOSURE <- NULL
cs_check_finite_columns(df, FEATURES) # ±Inf stops the run
if (K >= length(rows)) cs_error("CS_E_TOO_FEW_ROWS", what = sprintf("A %d-component mixture", K), min = K + 1L, n = length(rows))
rng <- cs_rng(SEED) # shared stream: identical starting responsibilities in Python and R
if (FAMILY == "poisson") {
for (c_ in seq_len(ncol(X))) {
bad_ <- sum(X[, c_] < 0 | X[, c_] != floor(X[, c_]))
if (bad_) cs_error("CS_E_INVALID_VALUES", column = names_[c_], requirement = "a whole-number count of at least 0", count = bad_)
}
exposure <- NULL
if (!is.null(EXPOSURE)) {
ex_ <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/w5_directions.parquet", col_select = EXPOSURE))[[EXPOSURE]]
exposure <- suppressWarnings(as.numeric(as.character(ex_)))[rows + 1L]
bad_ <- sum(!(exposure > 0) | is.na(exposure))
if (bad_) cs_error("CS_E_INVALID_VALUES", column = EXPOSURE, requirement = "a positive exposure", count = bad_)
}
best <- cs_mx_poisson_fit(X, K, rng, exposure = exposure, n_init = 5, tol = 1e-8, max_iter = 500)
centers <- best$params$rates
} else {
if (ncol(X) < 2) cs_error("CS_E_INVALID_OPTION", option = "Features", allowed = "at least two numeric columns for directions", value = ncol(X))
ur_ <- cs_mx_unit_rows(X)
bad_ <- sum(ur_$norms == 0)
if (bad_) cs_error("CS_E_INVALID_VALUES", column = "Each row", requirement = "a direction (not all zeros)", count = bad_)
X <- ur_$U # directions: validation and the map use the unit-length rows
best <- cs_mx_vmf_fit(X, K, rng, n_init = 5, tol = 1e-8, max_iter = 500)
centers <- best$params$mu
}
if (!best$converged) warnings <- c(warnings, "EM stopped at the iteration limit before converging.")
resp <- best$resp
raw <- best$labels
canon <- cs_ml_canonical(raw)
comp_rows <- list()
for (j in seq_len(K)) {
members <- which(raw == j - 1L)
if (!length(members)) next
c_ <- canon[members[1]]
w_ <- best$params$weights[j]
values[[sprintf("weight[%d]", c_)]] <- w_
extra[[sprintf("membership_%d", c_)]] <- resp[, j]
row_ <- list(cluster = c_, weight = w_)
if (FAMILY == "poisson") {
for (i in seq_along(names_)) row_[[names_[i]]] <- best$params$rates[j, i]
} else {
values[[sprintf("kappa[%d]", c_)]] <- best$params$kappa[j]
row_$kappa <- best$params$kappa[j]
}
comp_rows[[length(comp_rows) + 1L]] <- row_
}
comp_rows <- comp_rows[order(vapply(comp_rows, function(r) r$cluster, numeric(1)))]
crit <- cs_mx_criteria(best$loglik, best$n_par, length(rows), resp)
values$loglik <- best$loglik
values <- c(values, crit)
values$family <- if (FAMILY == "poisson") "Poisson" else "von Mises–Fisher"
extra$probability <- apply(resp, 1, max)
tables[[length(tables) + 1L]] <- list(
key = "components",
title = paste0("Components", if (FAMILY == "poisson" && !is.null(EXPOSURE)) " (rate per unit exposure)" else ""),
columns = c(list(list(key = "cluster", label = "Cluster", type = "integer"), list(key = "weight", label = "Weight", type = "percent")),
if (FAMILY == "poisson") lapply(names_, function(n) list(key = n, label = paste("Rate:", n), type = "number"))
else list(list(key = "kappa", label = "Concentration κ", type = "number"))),
rows = comp_rows
)
summary <- sprintf("%d-component %s mixture: log-likelihood %.1f, BIC %.1f, ICL %.1f.", K, values$family, values$loglik, values$bic, values$icl)
# %% 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 = "Count and direction mixtures",
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(
family = "vmf",
k = 3,
n_init = 5,
max_iter = 500,
tol = 1e-8,
scale = "none",
missing = "drop"
))
))
3-component von Mises–Fisher mixture: log-likelihood -287.4, BIC 635.1, ICL 649.2.
- Clusters
- 3
- Mean silhouette
- 0.5872
To keep this page light, the plots are shown once, under the R tab.
Clusters
| Cluster | Size | Share | x | y | z |
|---|---|---|---|---|---|
| 1 | 82 | 34.2% | 0.0039 | 1.583 | 0.3055 |
| 2 | 79 | 32.9% | 1.672 | 0.3247 | 0.1167 |
| 3 | 79 | 32.9% | 0.2918 | 0.0317 | −1.410 |
Components
| Cluster | Weight | Concentration κ |
|---|---|---|
| 1 | 34.0% | 13.056 |
| 2 | 32.8% | 39.976 |
| 3 | 33.1% | 7.190 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Count and direction mixtures
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.mixture 1.0.0 · spec 1d865e43e89d5049
# Dataset: w5_directions (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.errors import check_finite_columns, cs_error
from codesplash.ml import mixture_ext as csmx
# %% Data
FEATURES = ["x", "y", "z"]
LABEL = "source" # known groups (external validation only)
ROW_ID = None # row labels for charts
SEED = 42
KINDS = {
"x": "numeric",
"y": "numeric",
"z": "numeric",
}
LEVELS = {
}
df = pd.read_parquet("tests/parity/fixtures/w5_directions.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.mixture/directions_vmf/out-python")
values = {"n_used": len(rows)}
centers = None
center_ids = None
D = None
extra = {}
tables = []
charts = []
summary = None
# %% Clustering
K = 3
FAMILY = "vmf"
EXPOSURE = None
check_finite_columns(df, FEATURES) # ±Inf stops the run
if K >= len(rows):
cs_error("CS_E_TOO_FEW_ROWS", what=f"A {K}-component mixture", min=K + 1, n=len(rows))
rng = Rng(SEED) # shared stream: identical starting responsibilities in Python and R
if FAMILY == "poisson":
for _c, _name in enumerate(names):
_bad = int(np.sum((X[:, _c] < 0) | (X[:, _c] != np.floor(X[:, _c]))))
if _bad:
cs_error("CS_E_INVALID_VALUES", column=_name, requirement="a whole-number count of at least 0", count=_bad)
exposure = None
if EXPOSURE:
exposure = pd.to_numeric(pd.read_parquet("tests/parity/fixtures/w5_directions.parquet", columns=[EXPOSURE])[EXPOSURE], errors="coerce").to_numpy(dtype=np.float64)[rows]
_bad = int(np.sum(~(exposure > 0)))
if _bad:
cs_error("CS_E_INVALID_VALUES", column=EXPOSURE, requirement="a positive exposure", count=_bad)
best = csmx.poisson_fit(X, K, rng, exposure=exposure, n_init=5, tol=1e-8, max_iter=500)
centers = best["params"]["rates"]
else:
if X.shape[1] < 2:
cs_error("CS_E_INVALID_OPTION", option="Features", allowed="at least two numeric columns for directions", value=X.shape[1])
U, _norms = csmx.unit_rows(X)
_bad = int(np.sum(_norms == 0))
if _bad:
cs_error("CS_E_INVALID_VALUES", column="Each row", requirement="a direction (not all zeros)", count=_bad)
X = U # directions: validation and the map use the unit-length rows
best = csmx.vmf_fit(X, K, rng, n_init=5, tol=1e-8, max_iter=500)
centers = best["params"]["mu"]
if not best["converged"]:
warnings.append("EM stopped at the iteration limit before converging.")
resp = best["resp"]
raw = best["labels"]
canon = csc.canonical(raw)
comp_rows = []
for j in range(K):
members = np.flatnonzero(raw == j)
if not len(members):
continue
c = int(canon[members[0]])
values[f"weight[{c}]"] = float(best["params"]["weights"][j])
extra[f"membership_{c}"] = resp[:, j]
row = {"cluster": c, "weight": float(best["params"]["weights"][j])}
if FAMILY == "poisson":
for name, v in zip(names, best["params"]["rates"][j]):
row[name] = float(v)
else:
values[f"kappa[{c}]"] = float(best["params"]["kappa"][j])
row["kappa"] = float(best["params"]["kappa"][j])
comp_rows.append(row)
comp_rows.sort(key=lambda r: r["cluster"])
crit = csmx.criteria(best["loglik"], best["n_par"], len(rows), resp)
values["loglik"] = best["loglik"]
values.update(crit)
values["family"] = {"poisson": "Poisson", "vmf": "von Mises–Fisher"}[FAMILY]
extra["probability"] = resp.max(axis=1)
tables.append({
"key": "components",
"title": "Components" + (" (rate per unit exposure)" if FAMILY == "poisson" and EXPOSURE else ""),
"columns": [{"key": "cluster", "label": "Cluster", "type": "integer"}, {"key": "weight", "label": "Weight", "type": "percent"}]
+ ([{"key": n, "label": f"Rate: {n}", "type": "number"} for n in names] if FAMILY == "poisson" else [{"key": "kappa", "label": "Concentration κ", "type": "number"}]),
"rows": comp_rows,
})
summary = (
f"{K}-component {values['family']} mixture: log-likelihood {values['loglik']:.1f}, "
f"BIC {values['bic']:.1f}, ICL {values['icl']:.1f}."
)
# %% 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": "Count and direction mixtures",
"engine": cs.engine_info("numpy", "scipy", "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": {
"family": "vmf",
"k": 3,
"n_init": 5,
"max_iter": 500,
"tol": 1e-8,
"scale": "none",
"missing": "drop",
}},
})
Answers: latent class analysis
ReadLatent class analysisLatent class analysisA mixture for categorical items: each hidden class has its own answer probabilities, and items are independent within a class. is a mixture for categorical items. Each hidden class has its own probability for every answer, and within a class the items are independent. The heat map of item-response probabilities is the result to read: name each class by what it tends to answer.
3-class model on 5 items and 350 rows: log-likelihood -1354.2, BIC 2843.1, entropy R² 0.55.
- Classes
- 3
- BIC
- 2843.08
- Entropy R²
- 0.5523
Plots
View data
| Class | Answer | Probability |
|---|---|---|
| 1 | trust_news: low | 0.7448 |
| 2 | trust_news: low | 0.3781 |
| 3 | trust_news: low | 0.0737 |
| 1 | trust_news: medium | 0.1702 |
| 2 | trust_news: medium | 0.4062 |
| 3 | trust_news: medium | 0.2985 |
| 1 | trust_news: high | 0.0850 |
| 2 | trust_news: high | 0.2158 |
| 3 | trust_news: high | 0.6278 |
| 1 | votes: never | 0.6579 |
| 2 | votes: never | 0.3522 |
| 3 | votes: never | 0.0710 |
| 1 | votes: sometimes | 0.2243 |
| 2 | votes: sometimes | 0.4399 |
| 3 | votes: sometimes | 0.1593 |
| 1 | votes: always | 0.1177 |
| 2 | votes: always | 0.2078 |
| 3 | votes: always | 0.7696 |
| 1 | volunteers: no | 0.9074 |
| 2 | volunteers: no | 0.7851 |
| 3 | volunteers: no | 0.2489 |
| 1 | volunteers: yes | 0.0926 |
| 2 | volunteers: yes | 0.2149 |
| 3 | volunteers: yes | 0.7511 |
| 1 | donates: no | 1.0000 |
| 2 | donates: no | 0.5189 |
| 3 | donates: no | 0.2944 |
| 1 | donates: yes | 1.922e-6 |
| 2 | donates: yes | 0.4811 |
| 3 | donates: yes | 0.7056 |
| 1 | reads_local: no | 0.6968 |
| 2 | reads_local: no | 0.4231 |
| 3 | reads_local: no | 0.1737 |
| 1 | reads_local: yes | 0.3032 |
| 2 | reads_local: yes | 0.5769 |
| 3 | reads_local: yes | 0.8263 |
View data
| Center | Class | PC1 (34%) | PC2 (14%) |
|---|---|---|---|
| false | 2 | −0.3023 | −0.7591 |
| false | 1 | −0.2578 | 0.7053 |
| false | 1 | −1.068 | −0.1659 |
| false | 3 | 0.6470 | 0.4327 |
| false | 1 | −1.217 | −0.3262 |
| false | 1 | −0.2578 | 0.7053 |
| false | 1 | −1.432 | −0.3006 |
| false | 3 | 0.3887 | −0.9873 |
| false | 2 | −0.5028 | −0.3857 |
| false | 3 | 0.9973 | 0.2385 |
| false | 3 | 1.013 | −0.0278 |
| false | 2 | −0.4595 | 1.060 |
| false | 2 | −0.3772 | −0.3941 |
| false | 1 | −1.217 | −0.3262 |
| false | 1 | −1.432 | −0.3006 |
| false | 1 | −0.6081 | 0.8996 |
| false | 3 | 0.9973 | 0.2385 |
| false | 1 | −0.2578 | 0.7053 |
| false | 2 | 0.0987 | 0.4051 |
| false | 3 | 1.704 | −0.2560 |
| false | 3 | 0.1881 | −0.6140 |
| false | 3 | 1.704 | −0.2560 |
| false | 3 | 1.704 | −0.2560 |
| false | 1 | −1.432 | −0.3006 |
| false | 1 | −1.432 | −0.3006 |
| false | 3 | 1.140 | −0.0174 |
| false | 1 | −0.8231 | 0.9252 |
| false | 1 | −0.8676 | −0.5392 |
| false | 1 | −1.432 | −0.3006 |
| false | 1 | −0.6081 | 0.8996 |
| false | 2 | −0.1609 | −1.034 |
| false | 2 | 0.6628 | 0.1664 |
| false | 2 | −0.1164 | 0.4307 |
| false | 1 | −1.217 | −0.3262 |
| false | 2 | 0.1058 | 0.8401 |
| false | 2 | −0.4595 | 1.060 |
| false | 1 | −1.432 | −0.3006 |
| false | 1 | −1.217 | −0.3262 |
| false | 3 | 0.6470 | 0.4327 |
| false | 1 | −0.8231 | 0.9252 |
| false | 3 | 1.704 | −0.2560 |
| false | 1 | −1.432 | −0.3006 |
| false | 2 | −0.3614 | −0.6604 |
| false | 3 | 0.5313 | −1.243 |
| false | 1 | −0.1322 | 0.6969 |
| false | 1 | −1.217 | −0.3262 |
| false | 1 | −0.8664 | −0.5205 |
| false | 1 | −1.068 | −0.1659 |
| false | 2 | 0.0541 | −1.059 |
| false | 1 | −0.6081 | 0.8996 |
| false | 3 | 1.503 | 0.1173 |
| false | 2 | 0.4477 | 0.1921 |
| false | 2 | −0.1164 | 0.4307 |
| false | 3 | 1.013 | −0.0278 |
| false | 3 | 0.7968 | 0.6118 |
| false | 3 | 1.704 | −0.2560 |
| false | 2 | 0.2472 | 0.5654 |
| false | 1 | −1.217 | −0.3262 |
| false | 2 | −0.1609 | −1.034 |
| false | 3 | 1.354 | −0.0618 |
First 60 of 353 rows.
Classes
| Class | Size | Share (by membership) |
|---|---|---|
| 1 | 124 | 31.1% |
| 2 | 114 | 35.8% |
| 3 | 112 | 33.1% |
Item-response probabilities
| Item | Answer | Class 1 | Class 2 | Class 3 |
|---|---|---|---|---|
| trust_news | low | 74.5% | 37.8% | 7.4% |
| trust_news | medium | 17.0% | 40.6% | 29.8% |
| trust_news | high | 8.5% | 21.6% | 62.8% |
| votes | never | 65.8% | 35.2% | 7.1% |
| votes | sometimes | 22.4% | 44.0% | 15.9% |
| votes | always | 11.8% | 20.8% | 77.0% |
| volunteers | no | 90.7% | 78.5% | 24.9% |
| volunteers | yes | 9.3% | 21.5% | 75.1% |
| donates | no | 100.0% | 51.9% | 29.4% |
| donates | yes | 0.0% | 48.1% | 70.6% |
| reads_local | no | 69.7% | 42.3% | 17.4% |
| reads_local | yes | 30.3% | 57.7% | 82.6% |
- 50 of 400 rows were left out because an item was missing.
The exact R script · R R version 4.5.1 (2025-06-13)
# Latent class analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.lca 1.0.0 · spec 90b3dbce383d12e1
# Dataset: w5_lca (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
ITEMS <- c("trust_news", "votes", "volunteers", "donates", "reads_local")
LABEL <- "profile" # known groups (external validation only)
ROW_ID <- NULL # row labels for charts
SEED <- 42
K <- 3
KINDS <- list(
trust_news = "categorical",
votes = "categorical",
volunteers = "categorical",
donates = "categorical",
reads_local = "categorical"
)
LEVELS <- list(
trust_news = c("low", "medium", "high"),
votes = c("never", "sometimes", "always"),
volunteers = c("no", "yes"),
donates = c("no", "yes"),
reads_local = c("no", "yes")
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/w5_lca.parquet", col_select = unique(c(ITEMS, LABEL, ROW_ID))))
n_input <- nrow(df)
enc_all <- cs_lca_encode(df, ITEMS, KINDS, LEVELS)
answered <- rowSums(enc_all$codes >= 0)
MISSING <- "drop"
keep <- if (MISSING == "drop") answered == length(ITEMS) else answered > 0
rows <- which(keep) - 1L
frame <- df[rows + 1L, , drop = FALSE]
warnings <- list()
if (length(rows) < n_input) {
why <- if (MISSING == "drop") "an item was missing" else "every item was missing"
warnings <- c(warnings, sprintf("%d of %d rows were left out because %s.", n_input - length(rows), n_input, why))
}
cs_check_rows(length(rows), K + 1L, sprintf("A %d-class model", K))
enc <- cs_lca_encode(frame, ITEMS, KINDS, LEVELS)
codes <- enc$codes
level_names <- enc$levels
cs_lca_check_items(codes, level_names, ITEMS)
L <- vapply(level_names, length, integer(1))
truth <- if (!is.null(LABEL)) as.character(frame[[LABEL]]) else NULL
out <- cs_ml_out_dir("target/academy-parity/run-52084/discover.lca/survey_three_classes/out-r")
# %% Latent classes
rng <- cs_rng(SEED) # shared stream: identical starting responsibilities in Python and R
best <- cs_lca_fit(codes, L, K, rng, n_init = 10, tol = 1e-8, max_iter = 1000)
if (!best$converged) warnings <- c(warnings, "EM stopped at the iteration limit before converging.")
resp <- best$resp
raw <- best$labels
labels <- cs_ml_canonical(raw)
ids <- sort(unique(labels))
comp <- integer(0)
for (j in seq_len(K)) if (any(raw == j - 1L)) comp[as.character(labels[which(raw == j - 1L)[1]])] <- j
values <- list(n_used = length(rows), k = length(ids), n_noise = 0L, n_par = as.integer(best$n_par))
values$loglik <- best$loglik
values <- c(values, cs_mx_criteria(best$loglik, best$n_par, length(rows), resp))
if (MISSING == "drop") {
values <- c(values, cs_lca_goodness_of_fit(codes, best$params, L))
} else {
values["gsq"] <- list(NULL); values["chisq"] <- list(NULL); values["resid_df"] <- list(NULL)
}
extra <- list()
for (c in ids) {
j <- comp[[as.character(c)]]
values[[sprintf("weight[%d]", c)]] <- best$params$weights[j]
extra[[sprintf("membership_%d", c)]] <- resp[, j]
}
extra$probability <- apply(resp, 1, max)
sz <- cs_ml_cluster_sizes(labels)
for (c in names(sz)) values[[sprintf("size[%s]", c)]] <- sz[[c]]
# %% Item-response probabilities, validation on the answer indicators
names_ <- unlist(lapply(seq_along(ITEMS), function(j) paste0(ITEMS[j], ": ", level_names[[j]])))
X <- matrix(0, length(rows), length(names_))
pos <- 0L
for (j in seq_along(level_names)) for (r in seq_along(level_names[[j]])) {
pos <- pos + 1L
X[, pos] <- as.numeric(codes[, j] == r - 1L)
}
centers <- t(vapply(ids, function(c) unlist(lapply(seq_along(ITEMS), function(j) best$params$probs[[j]][comp[[as.character(c)]], ])), numeric(length(names_))))
if (length(ids) == 1L) centers <- matrix(centers, nrow = 1L)
prob_rows <- list()
pos <- 0L
for (j in seq_along(ITEMS)) for (r in seq_along(level_names[[j]])) {
pos <- pos + 1L
row_ <- list(item = ITEMS[j], answer = level_names[[j]][r])
for (i in seq_along(ids)) {
v <- centers[i, pos]
values[[sprintf("prob[%d,%s: %s]", ids[i], ITEMS[j], level_names[[j]][r])]] <- v
row_[[sprintf("class_%d", ids[i])]] <- v
}
prob_rows[[length(prob_rows) + 1L]] <- row_
}
check <- cs_ml_cluster_validation(X, labels, truth, cap = 3000, seed = SEED)
check$.widths <- NULL
values <- c(values, check)
tables <- list(
list(key = "classes", title = "Classes",
columns = list(list(key = "cluster", label = "Class", type = "integer"), list(key = "size", label = "Size", type = "integer"),
list(key = "share", label = "Share (by membership)", type = "percent")),
rows = lapply(ids, function(c) list(cluster = c, size = sum(labels == c), share = best$params$weights[comp[[as.character(c)]]]))),
list(key = "item_probabilities", title = "Item-response probabilities",
columns = c(list(list(key = "item", label = "Item"), list(key = "answer", label = "Answer")),
lapply(ids, function(c) list(key = sprintf("class_%d", c), label = sprintf("Class %d", c), type = "percent"))),
rows = prob_rows)
)
# %% Labels file and charts
path <- do.call(cs_ml_write_labels, c(list(out, rows, labels), extra))
charts <- list(cs_chart(
"item_probabilities", "matrix-heatmap", "Probability of each answer by class",
list(row = cs_col("Answer", rep(names_, each = length(ids)), "categorical", names_),
col = cs_col("Class", rep(as.character(ids), times = length(names_)), "categorical", as.character(ids)),
value = cs_col("Probability", as.numeric(centers), "numeric")),
controls = list(scale = "sequential")
))
pr <- cs_ml_project2(X, centers, names_)
show <- cs_ml_even_sample(length(rows))
xs <- c(pr$P[show + 1L, 1], pr$C[, 1]); ys <- c(pr$P[show + 1L, 2], pr$C[, 2])
cl <- c(as.character(labels[show + 1L]), as.character(ids))
cent <- c(rep(FALSE, length(show)), rep(TRUE, length(ids)))
lab <- if (!is.null(ROW_ID)) c(as.character(frame[[ROW_ID]])[show + 1L], sprintf("center %d", ids)) else NULL
charts[[length(charts) + 1L]] <- cs_chart(
"clusters", "cluster-scatter", "Classes on the answer indicators",
list(x = cs_col(pr$labels[1], xs, "numeric"), y = cs_col(pr$labels[2], ys, "numeric"),
cluster = cs_col("Class", cl, "categorical", levels = as.character(ids)),
centroid = 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 = ","))
)
# %% Result
summary <- sprintf("%d-class model on %d items and %s rows: log-likelihood %.1f, BIC %.1f, entropy R² %.2f.",
length(ids), length(ITEMS), format(length(rows), big.mark = ","), values$loglik, values$bic, values$entropy_r2)
cs_publish(list(
title = "Latent class analysis",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = length(rows),
summary = summary,
statistics = list(list(key = "k", label = "Classes", value = length(ids), format = "integer"),
list(key = "bic", label = "BIC", value = values$bic),
list(key = "entropy_r2", label = "Entropy R²", value = values$entropy_r2)),
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,
n_init = 10,
max_iter = 1000,
tol = 1e-8,
missing = "drop"
))
))
3-class model on 5 items and 350 rows: log-likelihood -1354.2, BIC 2843.1, entropy R² 0.55.
- Classes
- 3
- BIC
- 2843.08
- Entropy R²
- 0.5523
To keep this page light, the plots are shown once, under the R tab.
Classes
| Class | Size | Share (by membership) |
|---|---|---|
| 1 | 124 | 31.1% |
| 2 | 114 | 35.8% |
| 3 | 112 | 33.1% |
Item-response probabilities
| Item | Answer | Class 1 | Class 2 | Class 3 |
|---|---|---|---|---|
| trust_news | low | 74.5% | 37.8% | 7.4% |
| trust_news | medium | 17.0% | 40.6% | 29.8% |
| trust_news | high | 8.5% | 21.6% | 62.8% |
| votes | never | 65.8% | 35.2% | 7.1% |
| votes | sometimes | 22.4% | 44.0% | 15.9% |
| votes | always | 11.8% | 20.8% | 77.0% |
| volunteers | no | 90.7% | 78.5% | 24.9% |
| volunteers | yes | 9.3% | 21.5% | 75.1% |
| donates | no | 100.0% | 51.9% | 29.4% |
| donates | yes | 0.0% | 48.1% | 70.6% |
| reads_local | no | 69.7% | 42.3% | 17.4% |
| reads_local | yes | 30.3% | 57.7% | 82.6% |
- 50 of 400 rows were left out because an item was missing.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Latent class analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.lca 1.0.0 · spec 90b3dbce383d12e1
# Dataset: w5_lca (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.errors import check_rows
from codesplash.ml import cluster as csc
from codesplash.ml import lca as cslca
from codesplash.stats.rng import Rng
# %% Data
ITEMS = ["trust_news", "votes", "volunteers", "donates", "reads_local"]
LABEL = "profile" # known groups (external validation only)
ROW_ID = None # row labels for charts
SEED = 42
K = 3
KINDS = {
"trust_news": "categorical",
"votes": "categorical",
"volunteers": "categorical",
"donates": "categorical",
"reads_local": "categorical",
}
LEVELS = {
"trust_news": ["low", "medium", "high"],
"votes": ["never", "sometimes", "always"],
"volunteers": ["no", "yes"],
"donates": ["no", "yes"],
"reads_local": ["no", "yes"],
}
df = pd.read_parquet("tests/parity/fixtures/w5_lca.parquet", columns=list(dict.fromkeys(ITEMS + [c for c in (LABEL, ROW_ID) if c])))
n_input = len(df)
codes_all, _ = cslca.encode(df, ITEMS, KINDS, LEVELS)
answered = (codes_all >= 0).sum(axis=1)
MISSING = "drop"
keep = answered == len(ITEMS) if MISSING == "drop" else answered > 0
rows = np.flatnonzero(keep)
frame = df.iloc[rows]
warnings = []
if len(rows) < n_input:
why = "an item was missing" if MISSING == "drop" else "every item was missing"
warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because {why}.")
check_rows(len(rows), K + 1, f"A {K}-class model")
codes, level_names = cslca.encode(frame, ITEMS, KINDS, LEVELS)
cslca.check_items(codes, level_names, ITEMS)
L = [len(v) for v in level_names]
truth = frame[LABEL].astype("object").to_numpy() if LABEL else None
out = csml.out_dir("target/academy-parity/run-52084/discover.lca/survey_three_classes/out-python")
# %% Latent classes
rng = Rng(SEED) # shared stream: identical starting responsibilities in Python and R
best = cslca.fit(codes, L, K, rng, n_init=10, tol=1e-8, max_iter=1000)
if not best["converged"]:
warnings.append("EM stopped at the iteration limit before converging.")
resp = best["resp"]
raw = best["labels"]
labels = csc.canonical(raw)
ids = [int(c) for c in sorted(set(labels.tolist()))]
comp = {int(labels[np.flatnonzero(raw == j)[0]]): j for j in range(K) if np.any(raw == j)}
values = {"n_used": len(rows), "k": len(ids), "n_noise": 0, "n_par": int(best["n_par"])}
values["loglik"] = best["loglik"]
values.update(cslca.criteria(best["loglik"], best["n_par"], len(rows), resp))
if MISSING == "drop":
values.update(cslca.goodness_of_fit(codes, best["params"], L))
else:
values.update({"gsq": None, "chisq": None, "resid_df": None})
extra = {}
for c in ids:
j = comp[c]
values[f"weight[{c}]"] = float(best["params"]["weights"][j])
extra[f"membership_{c}"] = resp[:, j]
extra["probability"] = resp.max(axis=1)
for c, m in csc.sizes(labels).items():
values[f"size[{c}]"] = m
# %% Item-response probabilities, validation on the answer indicators
names = [f"{f}: {lv}" for f, lvs in zip(ITEMS, level_names) for lv in lvs]
X = np.zeros((len(rows), len(names)))
pos = 0
for j, lvs in enumerate(level_names):
for r in range(len(lvs)):
X[:, pos] = (codes[:, j] == r).astype(np.float64)
pos += 1
centers = np.array([np.concatenate([best["params"]["probs"][j][comp[c]] for j in range(len(ITEMS))]) for c in ids])
prob_rows = []
pos = 0
for j, (f, lvs) in enumerate(zip(ITEMS, level_names)):
for r, lv in enumerate(lvs):
row = {"item": f, "answer": lv}
for i, c in enumerate(ids):
v = float(centers[i, pos])
values[f"prob[{c},{f}: {lv}]"] = v
row[f"class_{c}"] = v
prob_rows.append(row)
pos += 1
check = csc.validation(X, labels, truth, cap=3000, seed=SEED)
widths, picked = check.pop("_widths")
values.update(check)
tables = [
{
"key": "classes",
"title": "Classes",
"columns": [{"key": "cluster", "label": "Class", "type": "integer"}, {"key": "size", "label": "Size", "type": "integer"},
{"key": "share", "label": "Share (by membership)", "type": "percent"}],
"rows": [{"cluster": c, "size": int(np.sum(labels == c)), "share": float(best["params"]["weights"][comp[c]])} for c in ids],
},
{
"key": "item_probabilities",
"title": "Item-response probabilities",
"columns": [{"key": "item", "label": "Item"}, {"key": "answer", "label": "Answer"}]
+ [{"key": f"class_{c}", "label": f"Class {c}", "type": "percent"} for c in ids],
"rows": prob_rows,
},
]
# %% Labels file and charts
path = csc.write_labels(out, rows, labels, **extra)
charts = [cs.chart(
"item_probabilities", "matrix-heatmap", "Probability of each answer by class",
{
"row": cs.col("Answer", [n for n in names for _ in ids], "categorical", names),
"col": cs.col("Class", [str(c) for _ in names for c in ids], "categorical", [str(c) for c in ids]),
"value": cs.col("Probability", [float(centers[i, p]) for p in range(len(names)) for i in range(len(ids))], "numeric"),
},
controls={"scale": "sequential"},
)]
P, C, axes = csc.project2(X, centers, names)
show = csc.even_sample(len(rows))
xs, ys = list(P[show, 0]) + list(C[:, 0]), list(P[show, 1]) + list(C[:, 1])
cl = [str(c) for c in labels[show]] + [str(c) for c in ids]
cent = [False] * len(show) + [True] * len(ids)
lab = None
if ROW_ID:
lab = [str(v) for v in frame[ROW_ID].astype("object").to_numpy()[show]] + [f"center {c}" for c in ids]
charts.append(cs.chart(
"clusters", "cluster-scatter", "Classes on the answer indicators",
{
"x": cs.col(axes[0], xs, "numeric"),
"y": cs.col(axes[1], ys, "numeric"),
"cluster": cs.col("Class", cl, "categorical", levels=[str(c) for c in ids]),
"centroid": cs.col("Center", cent, "boolean"),
"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.",
))
# %% Result
summary = (
f"{len(ids)}-class model on {len(ITEMS)} items and {len(rows):,} rows: log-likelihood {values['loglik']:.1f}, "
f"BIC {values['bic']:.1f}, entropy R² {values['entropy_r2']:.2f}."
)
cs.publish({
"title": "Latent class analysis",
"engine": cs.engine_info("numpy", "pandas"),
"n": len(rows),
"summary": summary,
"statistics": [
{"key": "k", "label": "Classes", "value": len(ids), "format": "integer"},
{"key": "bic", "label": "BIC", "value": values["bic"]},
{"key": "entropy_r2", "label": "Entropy R²", "value": values["entropy_r2"]},
],
"tables": tables,
"values": values,
"charts": charts,
"warnings": warnings,
"artifacts": [{"key": "labels", "path": path, "format": "parquet"}],
"model": {"kind": "clusterer", "features": names, "params": {
"k": 3,
"n_init": 10,
"max_iter": 1000,
"tol": 1e-8,
"missing": "drop",
}},
})
With complete rows, the card also reports G² against the observed answer patterns. With many items most patterns are rare, so compare numbers of classes with BIC rather than G²'s p-value.
Outliers: Student-t components
ReadA normal component has thin tails, so a few far-away rows either drag a mean toward them or claim a component of their own. A Student-t mixtureStudent-t mixture modelA mixture whose components are multivariate t distributions; outlying rows get small weights instead of distorting the fit. has heavier tails. Each row gets a weight in the fit, and rows far from every component get small weights instead of moving the means. The degrees of freedom ν say how heavy the tails had to be: under about 10 means much heavier tails than a normal distribution.
2-component Student-t mixture (full): log-likelihood -294.6, BIC 661.4, AIC 615.1.
- Clusters
- 2
- Mean silhouette
- 0.5156
Plots
View data
| Center | Cluster | u | v |
|---|---|---|---|
| false | 2 | −0.6422 | −0.3679 |
| false | 2 | −0.5110 | −0.4271 |
| false | 2 | −0.4782 | −0.2422 |
| false | 2 | −0.6735 | −0.4616 |
| false | 2 | −1.335 | −0.6992 |
| false | 2 | −0.4137 | −0.2482 |
| false | 2 | −0.5636 | −0.3828 |
| false | 2 | −0.1024 | −0.6490 |
| false | 2 | −0.4661 | −0.2010 |
| false | 2 | −0.1556 | −0.0182 |
| false | 2 | −0.6889 | −0.2894 |
| false | 2 | −0.5007 | −0.3335 |
| false | 2 | −0.6785 | 0.3768 |
| false | 2 | −0.5339 | 0.0731 |
| false | 1 | 0.1927 | −0.4478 |
| false | 1 | 0.9041 | −0.2342 |
| false | 2 | −0.7989 | −0.3282 |
| false | 2 | −0.5721 | −0.5115 |
| false | 2 | −0.7537 | −0.2531 |
| false | 2 | −0.9074 | 0.2575 |
| false | 2 | −0.4309 | −0.3312 |
| false | 2 | −0.6433 | −0.0612 |
| false | 2 | −0.3969 | −0.2429 |
| false | 2 | −0.3978 | −0.4151 |
| false | 2 | −0.7797 | −0.4662 |
| false | 2 | −0.6129 | −0.4159 |
| false | 2 | −0.5571 | −0.3818 |
| false | 2 | −0.5438 | −0.2266 |
| false | 2 | −0.2558 | −0.3365 |
| false | 2 | −0.5845 | −0.3535 |
| false | 2 | −0.5573 | −0.4136 |
| false | 2 | −0.8343 | −0.2339 |
| false | 2 | −0.7649 | −0.4463 |
| false | 1 | 0.4322 | −0.1062 |
| false | 2 | −0.4576 | −0.1665 |
| false | 2 | −0.7455 | −0.3800 |
| false | 2 | −0.8628 | −0.1167 |
| false | 2 | −0.7588 | −0.5780 |
| false | 2 | −0.9183 | −0.0567 |
| false | 2 | −0.8805 | −0.2118 |
| false | 2 | −0.4351 | −0.0499 |
| false | 2 | −0.7052 | 0.0029 |
| false | 2 | −0.4846 | −0.3264 |
| false | 2 | −0.3901 | −0.1404 |
| false | 2 | 0.0977 | −0.2917 |
| false | 2 | −0.4890 | −0.5098 |
| false | 2 | −0.6001 | −0.2822 |
| false | 2 | −0.3912 | −0.1535 |
| false | 2 | −0.3405 | −0.2278 |
| false | 2 | −0.7837 | −0.0515 |
| false | 2 | −0.7093 | −0.4189 |
| false | 2 | −0.9029 | −0.1973 |
| false | 2 | −0.5381 | −0.4126 |
| false | 1 | 0.3672 | −0.2922 |
| false | 2 | −0.6020 | −0.0676 |
| false | 2 | −0.6998 | −0.3037 |
| false | 2 | −0.6549 | −0.2004 |
| false | 2 | −0.6006 | −0.3947 |
| false | 2 | −0.3307 | −0.3065 |
| false | 2 | 0.1048 | −0.2451 |
First 60 of 262 rows.
View data
| Cluster | Silhouette width |
|---|---|
| 1 | 0.4552 |
| 1 | 0.4537 |
| 1 | 0.4536 |
| 1 | 0.4521 |
| 1 | 0.4520 |
| 1 | 0.4509 |
| 1 | 0.4497 |
| 1 | 0.4487 |
| 1 | 0.4483 |
| 1 | 0.4474 |
| 1 | 0.4453 |
| 1 | 0.4447 |
| 1 | 0.4432 |
| 1 | 0.4405 |
| 1 | 0.4393 |
| 1 | 0.4388 |
| 1 | 0.4386 |
| 1 | 0.4377 |
| 1 | 0.4365 |
| 1 | 0.4356 |
| 1 | 0.4317 |
| 1 | 0.4312 |
| 1 | 0.4309 |
| 1 | 0.4281 |
| 1 | 0.4258 |
| 1 | 0.4234 |
| 1 | 0.4228 |
| 1 | 0.4210 |
| 1 | 0.4186 |
| 1 | 0.4185 |
| 1 | 0.4165 |
| 1 | 0.4152 |
| 1 | 0.4121 |
| 1 | 0.4116 |
| 1 | 0.4110 |
| 1 | 0.4087 |
| 1 | 0.4050 |
| 1 | 0.4046 |
| 1 | 0.4042 |
| 1 | 0.4020 |
| 1 | 0.4000 |
| 1 | 0.3971 |
| 1 | 0.3967 |
| 1 | 0.3964 |
| 1 | 0.3962 |
| 1 | 0.3942 |
| 1 | 0.3932 |
| 1 | 0.3919 |
| 1 | 0.3904 |
| 1 | 0.3900 |
| 1 | 0.3884 |
| 1 | 0.3869 |
| 1 | 0.3831 |
| 1 | 0.3830 |
| 1 | 0.3817 |
| 1 | 0.3802 |
| 1 | 0.3785 |
| 1 | 0.3769 |
| 1 | 0.3755 |
| 1 | 0.3743 |
First 60 of 260 rows.
Clusters
| Cluster | Size | Share | u | v |
|---|---|---|---|---|
| 1 | 133 | 51.2% | 6.002 | 2.719 |
| 2 | 127 | 48.8% | 0.1778 | 0.0775 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Gaussian mixture model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.gmm 1.1.0 · spec 9b03a06bfb13fce0
# Dataset: w5_heavy (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("u", "v")
LABEL <- "group" # known groups (external validation only)
ROW_ID <- NULL # row labels for charts
SEED <- 42
KINDS <- list(
u = "numeric",
v = "numeric"
)
LEVELS <- list(
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/w5_heavy.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.gmm/heavy_student_t_full/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 <- 2
COV <- "full"
COMPONENT <- "student_t"
if (K >= length(rows)) cs_error("CS_E_TOO_FEW_ROWS", what = sprintf("A %d-component mixture", K), min = K + 1L, n = length(rows))
rng <- cs_rng(SEED) # shared stream: identical starting responsibilities in Python and R
if (COMPONENT == "gaussian" && COV != "factor") {
best <- NULL
for (start in seq_len(3)) {
# EM with scikit-learn's updates (reg_covar = 1e-6; lower bound from the E-step before each M-step)
fit <- cs_ml_gmm_em(X, cs_ml_gmm_start(X, K, COV, rng), COV, tol = 1e-8, max_iter = 500)
if (is.null(best) || fit$lower_bound > best$lower_bound) best <- fit
}
if (!best$converged) warnings <- c(warnings, "EM stopped at the iteration limit before converging.")
resp <- best$resp
raw <- best$labels
centers <- best$params$means
canon <- cs_ml_canonical(raw)
for (j in seq_len(K)) {
members <- which(raw == j - 1L)
if (length(members)) values[[sprintf("weight[%d]", canon[members[1]])]] <- best$params$weights[j]
}
n_par_ <- cs_ml_gmm_n_parameters(K, ncol(X), COV)
values$loglik <- best$loglik_mean * length(rows)
values$bic <- -2 * values$loglik + n_par_ * log(length(rows))
values$aic <- -2 * values$loglik + 2 * n_par_
values$covariance <- switch(COV, full = "full", diag = "diagonal", tied = "tied", spherical = "spherical")
summary <- sprintf("%d-component Gaussian mixture (%s covariances): log-likelihood %.1f, BIC %.1f, AIC %.1f.",
K, COV, values$loglik, values$bic, values$aic)
} else {
Q <- 2
if (COV == "factor" && COMPONENT != "gaussian") {
cs_error("CS_E_INVALID_OPTION", option = "Covariance", allowed = "full, diagonal, tied or spherical for Student-t components", value = "factor analyzers")
}
if (COV == "factor" && Q >= ncol(X)) {
cs_error("CS_E_INVALID_OPTION", option = "Factors", allowed = sprintf("fewer than the %d design columns", ncol(X)), value = Q)
}
fit <- cs_mx_gmm_ext_fit(X, K, rng, COMPONENT, COV, df0 = 4, estimate_df = TRUE,
factors = Q, n_init = 3, tol = 1e-8, max_iter = 500)
if (!fit$converged) warnings <- c(warnings, "EM stopped at the iteration limit before converging.")
resp <- fit$resp
raw <- fit$labels
centers <- fit$params$means
canon <- cs_ml_canonical(raw)
for (j in seq_len(K)) {
members <- which(raw == j - 1L)
if (length(members)) {
c_ <- canon[members[1]]
values[[sprintf("weight[%d]", c_)]] <- fit$params$weights[j]
if (COMPONENT == "student_t") values[[sprintf("df[%d]", c_)]] <- fit$params$df[j]
}
}
crit_ <- cs_mx_criteria(fit$loglik, fit$n_par, length(rows), resp)
values$loglik <- fit$loglik
values$bic <- crit_$bic
values$aic <- crit_$aic
values$covariance <- if (COV == "factor") sprintf("factor analyzers (q = %d)", Q) else switch(COV, full = "full", diag = "diagonal", tied = "tied", spherical = "spherical")
n_par_ <- fit$n_par
kind_ <- if (COMPONENT == "student_t") "Student-t mixture" else "mixture of factor analyzers"
summary <- sprintf("%d-component %s (%s): log-likelihood %.1f, BIC %.1f, AIC %.1f.", K, kind_, values$covariance, values$loglik, values$bic, values$aic)
if (COMPONENT == "student_t") extra$t_weight <- fit$u[cbind(seq_along(raw), raw + 1L)] # small = down-weighted as an outlier
}
for (j in seq_len(K)) {
members <- which(raw == j - 1L)
if (length(members)) extra[[sprintf("membership_%d", canon[members[1]])]] <- resp[, j]
}
values$component <- if (COMPONENT == "gaussian") "Gaussian" else "Student-t"
values$n_par <- as.integer(n_par_)
crit_ <- cs_mx_criteria(values$loglik, n_par_, length(rows), resp)
values$icl <- crit_$icl
values$entropy_r2 <- crit_$entropy_r2
extra$probability <- apply(resp, 1, max)
# %% 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 = "Gaussian mixture model",
engine = cs_engine_info("stats", "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 = 2,
covariance = "full",
factors = 2,
component = "student_t",
df_rule = "estimate",
df = 4,
n_init = 3,
max_iter = 500,
tol = 1e-8,
scale = "standard",
missing = "drop"
))
))
2-component Student-t mixture (full): log-likelihood -294.6, BIC 661.4, AIC 615.1.
- Clusters
- 2
- Mean silhouette
- 0.5156
To keep this page light, the plots are shown once, under the R tab.
Clusters
| Cluster | Size | Share | u | v |
|---|---|---|---|---|
| 1 | 133 | 51.2% | 6.002 | 2.719 |
| 2 | 127 | 48.8% | 0.1778 | 0.0775 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Gaussian mixture model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.gmm 1.1.0 · spec 9b03a06bfb13fce0
# Dataset: w5_heavy (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 sklearn.mixture import GaussianMixture
from codesplash.errors import cs_error
from codesplash.ml import mixture_ext as csmx
# %% Data
FEATURES = ["u", "v"]
LABEL = "group" # known groups (external validation only)
ROW_ID = None # row labels for charts
SEED = 42
KINDS = {
"u": "numeric",
"v": "numeric",
}
LEVELS = {
}
df = pd.read_parquet("tests/parity/fixtures/w5_heavy.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.gmm/heavy_student_t_full/out-python")
values = {"n_used": len(rows)}
centers = None
center_ids = None
D = None
extra = {}
tables = []
charts = []
summary = None
# %% Clustering
K = 2
COV = "full"
COMPONENT = "student_t"
if K >= len(rows):
cs_error("CS_E_TOO_FEW_ROWS", what=f"A {K}-component mixture", min=K + 1, n=len(rows))
rng = Rng(SEED) # shared stream: identical starting responsibilities in Python and R
if COMPONENT == "gaussian" and COV != "factor":
best = None
for start in range(3):
w0, m0, p0 = csc.gmm_start(X, K, COV, rng)
gm = GaussianMixture(
n_components=K, covariance_type=COV, tol=1e-8, reg_covar=1e-6, max_iter=500,
weights_init=w0, means_init=m0, precisions_init=p0, init_params="random", random_state=SEED,
).fit(X)
if best is None or gm.lower_bound_ > best.lower_bound_:
best = gm
if not best.converged_:
warnings.append("EM stopped at the iteration limit before converging.")
resp = best.predict_proba(X)
raw = resp.argmax(axis=1).astype(np.int64)
centers = best.means_
canon = csc.canonical(raw)
for j in range(K):
members = np.flatnonzero(raw == j)
if len(members):
values[f"weight[{int(canon[members[0]])}]"] = float(best.weights_[j])
values["loglik"] = float(best.score(X)) * len(rows)
values["bic"] = float(best.bic(X))
values["aic"] = float(best.aic(X))
values["covariance"] = {"full": "full", "diag": "diagonal", "tied": "tied", "spherical": "spherical"}[COV]
_n_par = csc.gmm_n_parameters(K, X.shape[1], COV)
summary = (
f"{K}-component Gaussian mixture ({COV} covariances): log-likelihood {values['loglik']:.1f}, "
f"BIC {values['bic']:.1f}, AIC {values['aic']:.1f}."
)
else:
Q = 2
if COV == "factor" and COMPONENT != "gaussian":
cs_error("CS_E_INVALID_OPTION", option="Covariance", allowed="full, diagonal, tied or spherical for Student-t components", value="factor analyzers")
if COV == "factor" and Q >= X.shape[1]:
cs_error("CS_E_INVALID_OPTION", option="Factors", allowed=f"fewer than the {X.shape[1]} design columns", value=Q)
fit = csmx.gmm_ext_fit(
X, K, rng, COMPONENT, COV, df0=4, estimate_df=True, factors=Q,
n_init=3, tol=1e-8, max_iter=500,
)
if not fit["converged"]:
warnings.append("EM stopped at the iteration limit before converging.")
resp = fit["resp"]
raw = fit["labels"]
centers = fit["params"]["means"]
canon = csc.canonical(raw)
for j in range(K):
members = np.flatnonzero(raw == j)
if len(members):
c = int(canon[members[0]])
values[f"weight[{c}]"] = float(fit["params"]["weights"][j])
if COMPONENT == "student_t":
values[f"df[{c}]"] = float(fit["params"]["df"][j])
_crit = csmx.criteria(fit["loglik"], fit["n_par"], len(rows), resp)
values["loglik"] = fit["loglik"]
values["bic"] = _crit["bic"]
values["aic"] = _crit["aic"]
values["covariance"] = f"factor analyzers (q = {Q})" if COV == "factor" else {"full": "full", "diag": "diagonal", "tied": "tied", "spherical": "spherical"}[COV]
_n_par = fit["n_par"]
_kind = "Student-t mixture" if COMPONENT == "student_t" else "mixture of factor analyzers"
summary = (
f"{K}-component {_kind} ({values['covariance']}): log-likelihood {values['loglik']:.1f}, "
f"BIC {values['bic']:.1f}, AIC {values['aic']:.1f}."
)
if COMPONENT == "student_t":
extra["t_weight"] = fit["u"][np.arange(len(rows)), raw] # small = down-weighted as an outlier
for j in range(K):
members = np.flatnonzero(raw == j)
if len(members):
extra[f"membership_{int(canon[members[0]])}"] = resp[:, j]
values["component"] = {"gaussian": "Gaussian", "student_t": "Student-t"}[COMPONENT]
values["n_par"] = int(_n_par)
_crit = csmx.criteria(values["loglik"], int(_n_par), len(rows), resp)
values["icl"] = _crit["icl"]
values["entropy_r2"] = _crit["entropy_r2"]
extra["probability"] = resp.max(axis=1)
# %% 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": "Gaussian mixture model",
"engine": cs.engine_info("scikit-learn", "scipy", "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": 2,
"covariance": "full",
"factors": 2,
"component": "student_t",
"df_rule": "estimate",
"df": 4,
"n_init": 3,
"max_iter": 500,
"tol": 1e-8,
"scale": "standard",
"missing": "drop",
}},
})
Wide data: factor analyzers
ReadA full covariance has numbers per component, which is too many when there are many columns. A mixture of factor analyzersMixture of factor analyzersA Gaussian mixture whose covariances are q loadings plus one shared diagonal, so wide data need far fewer parameters. explains each component's covariance with loadings plus one shared diagonal, the way factor analysis explains correlated measurements with a few factors.
3-component mixture of factor analyzers (factor analyzers (q = 1)): log-likelihood -428.3, BIC 1006.9, AIC 916.6.
- Clusters
- 3
- Mean silhouette
- 0.1315
Plots
View data
| Center | Cluster | PC1 (73%) | PC2 (23%) |
|---|---|---|---|
| false | 2 | −2.265 | 0.4800 |
| false | 2 | −2.081 | −0.6741 |
| false | 2 | −2.364 | −0.3419 |
| false | 2 | −2.299 | −0.5974 |
| false | 3 | −2.390 | 0.6468 |
| false | 3 | −2.076 | 1.489 |
| false | 2 | −2.444 | 0.0476 |
| false | 2 | −2.233 | 0.2231 |
| false | 2 | −2.335 | −1.115 |
| false | 2 | −2.184 | −0.4690 |
| false | 3 | −2.166 | 1.044 |
| false | 2 | −2.326 | 0.1331 |
| false | 2 | −2.218 | −0.7287 |
| false | 2 | −2.633 | −0.9615 |
| false | 3 | −2.199 | 1.860 |
| false | 3 | −2.262 | 2.686 |
| false | 3 | −2.208 | 1.484 |
| false | 3 | −2.190 | 0.4888 |
| false | 3 | −1.899 | 1.405 |
| false | 3 | −2.343 | 1.128 |
| false | 3 | −1.914 | 0.4089 |
| false | 3 | −2.207 | 0.9241 |
| false | 2 | −2.774 | 0.4583 |
| false | 2 | −1.819 | 0.0856 |
| false | 2 | −2.227 | 0.1373 |
| false | 2 | −1.952 | −0.6256 |
| false | 2 | −2.051 | 0.2422 |
| false | 3 | −2.169 | 0.5271 |
| false | 2 | −2.140 | 0.3132 |
| false | 2 | −2.265 | −0.3377 |
| false | 2 | −2.140 | −0.5045 |
| false | 3 | −1.832 | 0.4237 |
| false | 3 | −2.615 | 1.794 |
| false | 3 | −2.446 | 2.151 |
| false | 2 | −2.110 | −0.4602 |
| false | 2 | −2.208 | −0.2061 |
| false | 3 | −2.045 | 0.6616 |
| false | 2 | −2.527 | 0.5923 |
| false | 2 | −2.430 | −0.9042 |
| false | 2 | −2.170 | 0.2689 |
| false | 2 | −2.286 | 0.4417 |
| false | 2 | −1.858 | −2.337 |
| false | 2 | −2.554 | −0.4791 |
| false | 2 | −1.964 | 0.4723 |
| false | 3 | −2.137 | 1.142 |
| false | 2 | −2.070 | −0.7111 |
| false | 3 | −2.385 | 1.120 |
| false | 2 | −2.394 | −0.3862 |
| false | 3 | −2.229 | 0.9980 |
| false | 2 | −2.204 | 0.0092 |
| false | 3 | 1.102 | 0.8630 |
| false | 3 | 0.7313 | 0.5946 |
| false | 3 | 1.241 | 0.6163 |
| false | 1 | 0.4075 | −1.754 |
| false | 1 | 1.075 | −0.2084 |
| false | 1 | 0.3887 | −0.5933 |
| false | 1 | 0.7465 | 0.7730 |
| false | 1 | −0.4873 | −1.852 |
| false | 3 | 0.9279 | 0.0322 |
| false | 1 | 0.0114 | −1.034 |
First 60 of 153 rows.
View data
| Cluster | Silhouette width |
|---|---|
| 1 | 0.5459 |
| 1 | 0.5355 |
| 1 | 0.5354 |
| 1 | 0.5330 |
| 1 | 0.5314 |
| 1 | 0.5278 |
| 1 | 0.5268 |
| 1 | 0.5221 |
| 1 | 0.5199 |
| 1 | 0.5199 |
| 1 | 0.5192 |
| 1 | 0.4982 |
| 1 | 0.4970 |
| 1 | 0.4880 |
| 1 | 0.4863 |
| 1 | 0.4762 |
| 1 | 0.4645 |
| 1 | 0.4590 |
| 1 | 0.4588 |
| 1 | 0.4580 |
| 1 | 0.4516 |
| 1 | 0.4503 |
| 1 | 0.4471 |
| 1 | 0.4350 |
| 1 | 0.4332 |
| 1 | 0.4327 |
| 1 | 0.4301 |
| 1 | 0.4057 |
| 1 | 0.4003 |
| 1 | 0.3917 |
| 1 | 0.3882 |
| 1 | 0.3842 |
| 1 | 0.3815 |
| 1 | 0.3770 |
| 1 | 0.3713 |
| 1 | 0.3671 |
| 1 | 0.3662 |
| 1 | 0.3620 |
| 1 | 0.3511 |
| 1 | 0.3277 |
| 1 | 0.3263 |
| 1 | 0.3186 |
| 1 | 0.3102 |
| 1 | 0.3043 |
| 1 | 0.2994 |
| 1 | 0.2809 |
| 1 | 0.2610 |
| 1 | 0.2595 |
| 1 | 0.2550 |
| 1 | 0.2492 |
| 1 | 0.2448 |
| 1 | 0.2156 |
| 1 | 0.1973 |
| 1 | 0.1833 |
| 1 | 0.1788 |
| 1 | 0.1482 |
| 1 | 0.0997 |
| 1 | 0.0136 |
| 1 | −0.0286 |
| 1 | −0.0622 |
First 60 of 150 rows.
Clusters
| Cluster | Size | Share | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 60 | 40.0% | 6.045 | 2.875 | 4.822 | 1.762 |
| 2 | 50 | 33.3% | 5.262 | 3.004 | 2.600 | 0.6500 |
| 3 | 40 | 26.7% | 6.268 | 3.397 | 3.610 | 1.042 |
- EM stopped at the iteration limit before converging.
The exact R script · R R version 4.5.1 (2025-06-13)
# Gaussian mixture model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.gmm 1.1.0 · spec c1c14f00bef0e724
# Dataset: ml_iris (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("sepal_length", "sepal_width", "petal_length", "petal_width")
LABEL <- "species" # known groups (external validation only)
ROW_ID <- NULL # row labels for charts
SEED <- 42
KINDS <- list(
sepal_length = "numeric",
sepal_width = "numeric",
petal_length = "numeric",
petal_width = "numeric"
)
LEVELS <- list(
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.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.gmm/iris_factor_q1/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
COV <- "factor"
COMPONENT <- "gaussian"
if (K >= length(rows)) cs_error("CS_E_TOO_FEW_ROWS", what = sprintf("A %d-component mixture", K), min = K + 1L, n = length(rows))
rng <- cs_rng(SEED) # shared stream: identical starting responsibilities in Python and R
if (COMPONENT == "gaussian" && COV != "factor") {
best <- NULL
for (start in seq_len(2)) {
# EM with scikit-learn's updates (reg_covar = 1e-6; lower bound from the E-step before each M-step)
fit <- cs_ml_gmm_em(X, cs_ml_gmm_start(X, K, COV, rng), COV, tol = 1e-8, max_iter = 4000)
if (is.null(best) || fit$lower_bound > best$lower_bound) best <- fit
}
if (!best$converged) warnings <- c(warnings, "EM stopped at the iteration limit before converging.")
resp <- best$resp
raw <- best$labels
centers <- best$params$means
canon <- cs_ml_canonical(raw)
for (j in seq_len(K)) {
members <- which(raw == j - 1L)
if (length(members)) values[[sprintf("weight[%d]", canon[members[1]])]] <- best$params$weights[j]
}
n_par_ <- cs_ml_gmm_n_parameters(K, ncol(X), COV)
values$loglik <- best$loglik_mean * length(rows)
values$bic <- -2 * values$loglik + n_par_ * log(length(rows))
values$aic <- -2 * values$loglik + 2 * n_par_
values$covariance <- switch(COV, full = "full", diag = "diagonal", tied = "tied", spherical = "spherical")
summary <- sprintf("%d-component Gaussian mixture (%s covariances): log-likelihood %.1f, BIC %.1f, AIC %.1f.",
K, COV, values$loglik, values$bic, values$aic)
} else {
Q <- 1
if (COV == "factor" && COMPONENT != "gaussian") {
cs_error("CS_E_INVALID_OPTION", option = "Covariance", allowed = "full, diagonal, tied or spherical for Student-t components", value = "factor analyzers")
}
if (COV == "factor" && Q >= ncol(X)) {
cs_error("CS_E_INVALID_OPTION", option = "Factors", allowed = sprintf("fewer than the %d design columns", ncol(X)), value = Q)
}
fit <- cs_mx_gmm_ext_fit(X, K, rng, COMPONENT, COV, df0 = 4, estimate_df = TRUE,
factors = Q, n_init = 2, tol = 1e-8, max_iter = 4000)
if (!fit$converged) warnings <- c(warnings, "EM stopped at the iteration limit before converging.")
resp <- fit$resp
raw <- fit$labels
centers <- fit$params$means
canon <- cs_ml_canonical(raw)
for (j in seq_len(K)) {
members <- which(raw == j - 1L)
if (length(members)) {
c_ <- canon[members[1]]
values[[sprintf("weight[%d]", c_)]] <- fit$params$weights[j]
if (COMPONENT == "student_t") values[[sprintf("df[%d]", c_)]] <- fit$params$df[j]
}
}
crit_ <- cs_mx_criteria(fit$loglik, fit$n_par, length(rows), resp)
values$loglik <- fit$loglik
values$bic <- crit_$bic
values$aic <- crit_$aic
values$covariance <- if (COV == "factor") sprintf("factor analyzers (q = %d)", Q) else switch(COV, full = "full", diag = "diagonal", tied = "tied", spherical = "spherical")
n_par_ <- fit$n_par
kind_ <- if (COMPONENT == "student_t") "Student-t mixture" else "mixture of factor analyzers"
summary <- sprintf("%d-component %s (%s): log-likelihood %.1f, BIC %.1f, AIC %.1f.", K, kind_, values$covariance, values$loglik, values$bic, values$aic)
if (COMPONENT == "student_t") extra$t_weight <- fit$u[cbind(seq_along(raw), raw + 1L)] # small = down-weighted as an outlier
}
for (j in seq_len(K)) {
members <- which(raw == j - 1L)
if (length(members)) extra[[sprintf("membership_%d", canon[members[1]])]] <- resp[, j]
}
values$component <- if (COMPONENT == "gaussian") "Gaussian" else "Student-t"
values$n_par <- as.integer(n_par_)
crit_ <- cs_mx_criteria(values$loglik, n_par_, length(rows), resp)
values$icl <- crit_$icl
values$entropy_r2 <- crit_$entropy_r2
extra$probability <- apply(resp, 1, max)
# %% 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 = "Gaussian mixture model",
engine = cs_engine_info("stats", "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,
covariance = "factor",
factors = 1,
component = "gaussian",
df_rule = "estimate",
df = 4,
n_init = 2,
max_iter = 4000,
tol = 1e-8,
scale = "standard",
missing = "drop"
))
))
3-component mixture of factor analyzers (factor analyzers (q = 1)): log-likelihood -428.3, BIC 1006.9, AIC 916.6.
- Clusters
- 3
- Mean silhouette
- 0.1315
To keep this page light, the plots are shown once, under the R tab.
Clusters
| Cluster | Size | Share | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 60 | 40.0% | 6.045 | 2.875 | 4.822 | 1.762 |
| 2 | 50 | 33.3% | 5.262 | 3.004 | 2.600 | 0.6500 |
| 3 | 40 | 26.7% | 6.268 | 3.397 | 3.610 | 1.042 |
- EM stopped at the iteration limit before converging.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Gaussian mixture model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.gmm 1.1.0 · spec c1c14f00bef0e724
# Dataset: ml_iris (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 sklearn.mixture import GaussianMixture
from codesplash.errors import cs_error
from codesplash.ml import mixture_ext as csmx
# %% Data
FEATURES = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
LABEL = "species" # known groups (external validation only)
ROW_ID = None # row labels for charts
SEED = 42
KINDS = {
"sepal_length": "numeric",
"sepal_width": "numeric",
"petal_length": "numeric",
"petal_width": "numeric",
}
LEVELS = {
}
df = pd.read_parquet("tests/parity/fixtures/ml_iris.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.gmm/iris_factor_q1/out-python")
values = {"n_used": len(rows)}
centers = None
center_ids = None
D = None
extra = {}
tables = []
charts = []
summary = None
# %% Clustering
K = 3
COV = "factor"
COMPONENT = "gaussian"
if K >= len(rows):
cs_error("CS_E_TOO_FEW_ROWS", what=f"A {K}-component mixture", min=K + 1, n=len(rows))
rng = Rng(SEED) # shared stream: identical starting responsibilities in Python and R
if COMPONENT == "gaussian" and COV != "factor":
best = None
for start in range(2):
w0, m0, p0 = csc.gmm_start(X, K, COV, rng)
gm = GaussianMixture(
n_components=K, covariance_type=COV, tol=1e-8, reg_covar=1e-6, max_iter=4000,
weights_init=w0, means_init=m0, precisions_init=p0, init_params="random", random_state=SEED,
).fit(X)
if best is None or gm.lower_bound_ > best.lower_bound_:
best = gm
if not best.converged_:
warnings.append("EM stopped at the iteration limit before converging.")
resp = best.predict_proba(X)
raw = resp.argmax(axis=1).astype(np.int64)
centers = best.means_
canon = csc.canonical(raw)
for j in range(K):
members = np.flatnonzero(raw == j)
if len(members):
values[f"weight[{int(canon[members[0]])}]"] = float(best.weights_[j])
values["loglik"] = float(best.score(X)) * len(rows)
values["bic"] = float(best.bic(X))
values["aic"] = float(best.aic(X))
values["covariance"] = {"full": "full", "diag": "diagonal", "tied": "tied", "spherical": "spherical"}[COV]
_n_par = csc.gmm_n_parameters(K, X.shape[1], COV)
summary = (
f"{K}-component Gaussian mixture ({COV} covariances): log-likelihood {values['loglik']:.1f}, "
f"BIC {values['bic']:.1f}, AIC {values['aic']:.1f}."
)
else:
Q = 1
if COV == "factor" and COMPONENT != "gaussian":
cs_error("CS_E_INVALID_OPTION", option="Covariance", allowed="full, diagonal, tied or spherical for Student-t components", value="factor analyzers")
if COV == "factor" and Q >= X.shape[1]:
cs_error("CS_E_INVALID_OPTION", option="Factors", allowed=f"fewer than the {X.shape[1]} design columns", value=Q)
fit = csmx.gmm_ext_fit(
X, K, rng, COMPONENT, COV, df0=4, estimate_df=True, factors=Q,
n_init=2, tol=1e-8, max_iter=4000,
)
if not fit["converged"]:
warnings.append("EM stopped at the iteration limit before converging.")
resp = fit["resp"]
raw = fit["labels"]
centers = fit["params"]["means"]
canon = csc.canonical(raw)
for j in range(K):
members = np.flatnonzero(raw == j)
if len(members):
c = int(canon[members[0]])
values[f"weight[{c}]"] = float(fit["params"]["weights"][j])
if COMPONENT == "student_t":
values[f"df[{c}]"] = float(fit["params"]["df"][j])
_crit = csmx.criteria(fit["loglik"], fit["n_par"], len(rows), resp)
values["loglik"] = fit["loglik"]
values["bic"] = _crit["bic"]
values["aic"] = _crit["aic"]
values["covariance"] = f"factor analyzers (q = {Q})" if COV == "factor" else {"full": "full", "diag": "diagonal", "tied": "tied", "spherical": "spherical"}[COV]
_n_par = fit["n_par"]
_kind = "Student-t mixture" if COMPONENT == "student_t" else "mixture of factor analyzers"
summary = (
f"{K}-component {_kind} ({values['covariance']}): log-likelihood {values['loglik']:.1f}, "
f"BIC {values['bic']:.1f}, AIC {values['aic']:.1f}."
)
if COMPONENT == "student_t":
extra["t_weight"] = fit["u"][np.arange(len(rows)), raw] # small = down-weighted as an outlier
for j in range(K):
members = np.flatnonzero(raw == j)
if len(members):
extra[f"membership_{int(canon[members[0]])}"] = resp[:, j]
values["component"] = {"gaussian": "Gaussian", "student_t": "Student-t"}[COMPONENT]
values["n_par"] = int(_n_par)
_crit = csmx.criteria(values["loglik"], int(_n_par), len(rows), resp)
values["icl"] = _crit["icl"]
values["entropy_r2"] = _crit["entropy_r2"]
extra["probability"] = resp.max(axis=1)
# %% 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": "Gaussian mixture model",
"engine": cs.engine_info("scikit-learn", "scipy", "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,
"covariance": "factor",
"factors": 1,
"component": "gaussian",
"df_rule": "estimate",
"df": 4,
"n_init": 2,
"max_iter": 4000,
"tol": 1e-8,
"scale": "standard",
"missing": "drop",
}},
})
BIC chooses a density, ICL a clustering
ReadBICBICLike AIC but with a stronger penalty for parameters as n grows; favors simpler models. rewards the model that describes the data best, even when two components overlap heavily. ICLIntegrated completed likelihoodBIC plus a penalty for fuzzy assignments; lower is better, and it prefers components that form well-separated clusters. adds a penalty for uncertain assignments, so it prefers components that are well apart. When BIC and ICL pick different , some components overlap: they help the density, but they aren't separate segments.
Entropy R²Entropy R² (classification certainty)1 minus the responsibilities' entropy over its maximum: 1 means every row belongs to one component with near certainty, 0 means coin flips. puts the same idea on a 0 to 1 scale: 1 means every row belongs to one component with near certainty.
Check your understanding
CheckpointCheck yourself
Each row is a store with its count of returns last quarter and its number of weeks open. Which mixture fits?
Show the answer
Answer: b
Counts call for a Poisson model, and exposure turns each group's rate into returns per week, so stores open longer aren't mistaken for stores with more returns.
Check yourself
Two customers spend 1,000 in exactly the same proportions across categories. How does a von Mises–Fisher mixture treat them?
Show the answer
Answer: a
Scaling to length 1 keeps only the direction (the mix) and drops the size.
Check yourself
In a latent class model, class 2 has probability 0.85 of "always" for votes and 0.80 of "yes" for donates. What's the best reading?
Show the answer
Answer: b
Item-response probabilities describe each class. Within a class the items are modeled as independent, so they say nothing about causes.
Check yourself
A 4-class model has entropy R² of 0.45. What does it warn you about?
Show the answer
Answer: b
Low entropy R² means assignments are fuzzy. The classes can still describe the data, but treat each row's class label with care.
Check yourself
A Student-t mixture estimates ν = 1.4 for one component and ν = 45 for the other. What does that say?
Show the answer
Answer: a
Small ν means heavy tails, and large ν approaches a normal distribution. Each component gets its own ν when it is estimated.
Check yourself
BIC is lowest at = 4 and ICL is lowest at = 3. Which is the best reading?
Show the answer
Answer: b
ICL penalizes uncertain assignments, so it prefers well-separated components. When the two disagree, report both and look at the overlap.
Concepts in this lesson