Why computation: latent variables and the EM engine
Most useful models hide variables you never observe. Meet the three questions every computation must answer, then the first engine for hidden variables: expectation–maximization.
What runs in CodeSplash
- INF001Expectation–maximization (EM) Runs in CodeSplash
- Gaussian mixture model Verified in Python and R
You will be able to
- Separate three questions: is the computation right, is the model useful, would the checks notice a failure
- Describe the E-step and M-step of EM and what each one optimizes
- Explain why a rising likelihood doesn't prove a global optimum or honest uncertainty
- Say where EM runs in CodeSplash
Three questions, kept apart
ReadA Bayesian model is a recipe: a prior, a likelihood, maybe hidden variables. The posterior it implies is almost never a formula you can write down, so a computation stands between the model and every number you report. This track is about those computations, and it keeps three questions apart:
- Is the algorithm computing the posterior the model defines?
- Is that model a useful description of the data?
- Would the checks you ran notice if 1 or 2 failed?
A perfect sampler can faithfully compute the posterior of a bad model. A good model can be ruined by a sampler that never explored. And a check that can't fail tells you nothing.
Hidden variables
ReadMany models include variables you never see: which mixture component produced a row, which topic produced a word, what an annotator's true label was. Writing them as , the likelihood of what you did see averages over them:
That sum is what makes fitting hard. If you knew , fitting would be easy: count, average, done. Expectation–maximizationEM algorithmAlternates between estimating which group each row belongs to and refitting each group, raising the likelihood every round. (EM) exploits that. It doesn't guess once; it keeps a probability for every possible value and fits as if those probabilities were partial counts.
Reference · INF001 · Runs in CodeSplashExpectation–maximization (EM)Fits maximum-likelihood or MAP parameters when introducing latent or missing variables makes complete-data optimization simpler. EM is the fitting engine behind many mixtures, factor models, and hidden-state models;The two steps
ReadEM alternates:
- E-step. With the current parameters , compute each row's probability of each hidden value (in a mixture, its responsibilities).
- M-step. Choose new parameters that maximize the expected complete-data log-likelihood under those probabilities:
Each full round can't lower the observed-data likelihood. For a fixed-variance two-component normal mixture, one round moves the log-likelihood from −10.339 to −10.159. Add the log prior in the M-step and EM finds a posterior mode (MAP) instead.
Predict: what does "converged" promise?
PredictPredict first
EM stops when the log-likelihood barely changes. What has it actually shown?
Reveal
Only that the likelihood stopped rising from this start. EM climbs; it can stop on a lower peak or a saddle, crawl slowly where components overlap, or run off toward an infinite likelihood when a component shrinks onto one point. Several starts, and a held-out score, are the checks.
EM in CodeSplash
ReadGaussian mixture model in Discover fits by EM. On iris with three full-covariance components, it ends at a log-likelihood of −296.9, and its clusters match the species with an adjusted Rand index of 0.72.
3-component Gaussian mixture (full covariances): log-likelihood -296.9, BIC 814.3, AIC 681.8.
- Clusters
- 3
- Mean silhouette
- 0.3230
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 | 2 | −2.390 | 0.6468 |
| false | 2 | −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 | 2 | −2.166 | 1.044 |
| false | 2 | −2.326 | 0.1331 |
| false | 2 | −2.218 | −0.7287 |
| false | 2 | −2.633 | −0.9615 |
| false | 2 | −2.199 | 1.860 |
| false | 2 | −2.262 | 2.686 |
| false | 2 | −2.208 | 1.484 |
| false | 2 | −2.190 | 0.4888 |
| false | 2 | −1.899 | 1.405 |
| false | 2 | −2.343 | 1.128 |
| false | 2 | −1.914 | 0.4089 |
| false | 2 | −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 | 2 | −2.169 | 0.5271 |
| false | 2 | −2.140 | 0.3132 |
| false | 2 | −2.265 | −0.3377 |
| false | 2 | −2.140 | −0.5045 |
| false | 2 | −1.832 | 0.4237 |
| false | 2 | −2.615 | 1.794 |
| false | 2 | −2.446 | 2.151 |
| false | 2 | −2.110 | −0.4602 |
| false | 2 | −2.208 | −0.2061 |
| false | 2 | −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 | 2 | −2.137 | 1.142 |
| false | 2 | −2.070 | −0.7111 |
| false | 2 | −2.385 | 1.120 |
| false | 2 | −2.394 | −0.3862 |
| false | 2 | −2.229 | 0.9980 |
| false | 2 | −2.204 | 0.0092 |
| false | 1 | 1.102 | 0.8630 |
| false | 1 | 0.7313 | 0.5946 |
| false | 1 | 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 | 1 | 0.9279 | 0.0322 |
| false | 1 | 0.0114 | −1.034 |
First 60 of 153 rows.
View data
| Cluster | Silhouette width |
|---|---|
| 1 | 0.3288 |
| 1 | 0.3273 |
| 1 | 0.3195 |
| 1 | 0.3152 |
| 1 | 0.3129 |
| 1 | 0.3098 |
| 1 | 0.3040 |
| 1 | 0.2876 |
| 1 | 0.2822 |
| 1 | 0.2784 |
| 1 | 0.2708 |
| 1 | 0.2705 |
| 1 | 0.2594 |
| 1 | 0.2566 |
| 1 | 0.2548 |
| 1 | 0.2466 |
| 1 | 0.2437 |
| 1 | 0.2407 |
| 1 | 0.2389 |
| 1 | 0.2366 |
| 1 | 0.2208 |
| 1 | 0.2204 |
| 1 | 0.2202 |
| 1 | 0.2196 |
| 1 | 0.2193 |
| 1 | 0.2035 |
| 1 | 0.1964 |
| 1 | 0.1735 |
| 1 | 0.1730 |
| 1 | 0.1589 |
| 1 | 0.1317 |
| 1 | 0.1280 |
| 1 | 0.1175 |
| 1 | 0.1039 |
| 1 | 0.1012 |
| 1 | 0.0976 |
| 1 | 0.0951 |
| 1 | 0.0903 |
| 1 | 0.0873 |
| 1 | 0.0588 |
| 1 | 0.0495 |
| 1 | 0.0487 |
| 1 | 0.0236 |
| 1 | 0.0202 |
| 1 | −0.0060 |
| 1 | −0.0826 |
| 1 | −0.0881 |
| 1 | −0.0915 |
| 1 | −0.1113 |
| 1 | −0.1212 |
| 1 | −0.1368 |
| 1 | −0.1726 |
| 1 | −0.1906 |
| 1 | −0.1999 |
| 1 | −0.2038 |
| 1 | −0.2055 |
| 1 | −0.2193 |
| 1 | −0.2246 |
| 1 | −0.2315 |
| 1 | −0.2361 |
First 60 of 150 rows.
Clusters
| Cluster | Size | Share | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 65 | 43.3% | 6.198 | 2.805 | 4.674 | 1.443 |
| 2 | 50 | 33.3% | 5.006 | 3.428 | 1.462 | 0.2460 |
| 3 | 35 | 23.3% | 6.380 | 2.997 | 5.337 | 2.109 |
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 f7cd92c6c3cba233
# 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_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 <- 3
COV <- "full"
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(5)) {
# 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 = 5, 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 = 3,
covariance = "full",
factors = 2,
component = "gaussian",
df_rule = "estimate",
df = 4,
n_init = 5,
max_iter = 500,
tol = 1e-8,
scale = "standard",
missing = "drop"
))
))
3-component Gaussian mixture (full covariances): log-likelihood -296.9, BIC 814.3, AIC 681.8.
- Clusters
- 3
- Mean silhouette
- 0.3230
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 | 65 | 43.3% | 6.198 | 2.805 | 4.674 | 1.443 |
| 2 | 50 | 33.3% | 5.006 | 3.428 | 1.462 | 0.2460 |
| 3 | 35 | 23.3% | 6.380 | 2.997 | 5.337 | 2.109 |
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 f7cd92c6c3cba233
# 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_full/out-python")
values = {"n_used": len(rows)}
centers = None
center_ids = None
D = None
extra = {}
tables = []
charts = []
summary = None
# %% Clustering
K = 3
COV = "full"
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(5):
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=5, 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": 3,
"covariance": "full",
"factors": 2,
"component": "gaussian",
"df_rule": "estimate",
"df": 4,
"n_init": 5,
"max_iter": 500,
"tol": 1e-8,
"scale": "standard",
"missing": "drop",
}},
})
The Starts setting (n_init) reruns EM from several initializations and keeps the best; the two-component run below uses three. The responsibilities are the E-step's output: a row with probability 0.5 for two components is genuinely ambiguous, and reporting it as one cluster hides that.
2-component Gaussian mixture (diag covariances): log-likelihood -496.5, BIC 1078.2, AIC 1027.1.
- Clusters
- 2
- Mean silhouette
- 0.5818
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 | 2 | −2.390 | 0.6468 |
| false | 2 | −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 | 2 | −2.166 | 1.044 |
| false | 2 | −2.326 | 0.1331 |
| false | 2 | −2.218 | −0.7287 |
| false | 2 | −2.633 | −0.9615 |
| false | 2 | −2.199 | 1.860 |
| false | 2 | −2.262 | 2.686 |
| false | 2 | −2.208 | 1.484 |
| false | 2 | −2.190 | 0.4888 |
| false | 2 | −1.899 | 1.405 |
| false | 2 | −2.343 | 1.128 |
| false | 2 | −1.914 | 0.4089 |
| false | 2 | −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 | 2 | −2.169 | 0.5271 |
| false | 2 | −2.140 | 0.3132 |
| false | 2 | −2.265 | −0.3377 |
| false | 2 | −2.140 | −0.5045 |
| false | 2 | −1.832 | 0.4237 |
| false | 2 | −2.615 | 1.794 |
| false | 2 | −2.446 | 2.151 |
| false | 2 | −2.110 | −0.4602 |
| false | 2 | −2.208 | −0.2061 |
| false | 2 | −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 | 2 | −2.137 | 1.142 |
| false | 2 | −2.070 | −0.7111 |
| false | 2 | −2.385 | 1.120 |
| false | 2 | −2.394 | −0.3862 |
| false | 2 | −2.229 | 0.9980 |
| false | 2 | −2.204 | 0.0092 |
| false | 1 | 1.102 | 0.8630 |
| false | 1 | 0.7313 | 0.5946 |
| false | 1 | 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 | 1 | 0.9279 | 0.0322 |
| false | 1 | 0.0114 | −1.034 |
First 60 of 152 rows.
View data
| Cluster | Silhouette width |
|---|---|
| 1 | 0.6662 |
| 1 | 0.6658 |
| 1 | 0.6646 |
| 1 | 0.6605 |
| 1 | 0.6604 |
| 1 | 0.6595 |
| 1 | 0.6580 |
| 1 | 0.6576 |
| 1 | 0.6502 |
| 1 | 0.6491 |
| 1 | 0.6487 |
| 1 | 0.6438 |
| 1 | 0.6386 |
| 1 | 0.6385 |
| 1 | 0.6347 |
| 1 | 0.6337 |
| 1 | 0.6326 |
| 1 | 0.6292 |
| 1 | 0.6289 |
| 1 | 0.6248 |
| 1 | 0.6245 |
| 1 | 0.6202 |
| 1 | 0.6189 |
| 1 | 0.6189 |
| 1 | 0.6176 |
| 1 | 0.6131 |
| 1 | 0.6118 |
| 1 | 0.6114 |
| 1 | 0.6107 |
| 1 | 0.6094 |
| 1 | 0.6084 |
| 1 | 0.6047 |
| 1 | 0.6017 |
| 1 | 0.6016 |
| 1 | 0.6013 |
| 1 | 0.6013 |
| 1 | 0.5981 |
| 1 | 0.5980 |
| 1 | 0.5948 |
| 1 | 0.5897 |
| 1 | 0.5879 |
| 1 | 0.5878 |
| 1 | 0.5870 |
| 1 | 0.5852 |
| 1 | 0.5796 |
| 1 | 0.5772 |
| 1 | 0.5766 |
| 1 | 0.5765 |
| 1 | 0.5729 |
| 1 | 0.5699 |
| 1 | 0.5681 |
| 1 | 0.5665 |
| 1 | 0.5637 |
| 1 | 0.5605 |
| 1 | 0.5578 |
| 1 | 0.5561 |
| 1 | 0.5556 |
| 1 | 0.5504 |
| 1 | 0.5448 |
| 1 | 0.5360 |
First 60 of 150 rows.
Clusters
| Cluster | Size | Share | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 100 | 66.7% | 6.262 | 2.872 | 4.906 | 1.676 |
| 2 | 50 | 33.3% | 5.006 | 3.428 | 1.462 | 0.2460 |
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 d36b539742c5abbb
# 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 <- NULL # 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_diag/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 <- "diag"
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(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 = "diag",
factors = 2,
component = "gaussian",
df_rule = "estimate",
df = 4,
n_init = 3,
max_iter = 500,
tol = 1e-8,
scale = "standard",
missing = "drop"
))
))
2-component Gaussian mixture (diag covariances): log-likelihood -496.5, BIC 1078.2, AIC 1027.1.
- Clusters
- 2
- Mean silhouette
- 0.5818
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 | 100 | 66.7% | 6.262 | 2.872 | 4.906 | 1.676 |
| 2 | 50 | 33.3% | 5.006 | 3.428 | 1.462 | 0.2460 |
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 d36b539742c5abbb
# 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 = None # 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_diag/out-python")
values = {"n_used": len(rows)}
centers = None
center_ids = None
D = None
extra = {}
tables = []
charts = []
summary = None
# %% Clustering
K = 2
COV = "diag"
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(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": "diag",
"factors": 2,
"component": "gaussian",
"df_rule": "estimate",
"df": 4,
"n_init": 3,
"max_iter": 500,
"tol": 1e-8,
"scale": "standard",
"missing": "drop",
}},
})
Pitfalls that look like success
Read- A rising likelihood is an optimization fact. It isn't a significance test, and it doesn't make the responsibilities calibrated.
- Label switchingLabel switchingMixture and annotator models give the same likelihood when their component or class labels are permuted, so labels can swap.. Swap the names of two components and the likelihood is identical. Across restarts or bootstrap runs, "component 1" can mean different things; match components before averaging them.
- Collapse. An unconstrained normal component can shrink onto one row and send the likelihood to infinity. A covariance floor prevents that, but it changes the model; say you used one.
- EM gives a point. It returns a mode, not a posterior. Uncertainty needs more: the curvature at the mode, a sampler, or a bootstrap.
AExplorable · Gaussian mixtures by EM
How can you recover overlapping groups you never saw labeled?
The data come from three groups, this far apart. How many components will BIC choose?
Commit your prediction above to see the result
Make your prediction to see the result.
Check your understanding
CheckpointCheck yourself
What does EM's E-step produce in a two-component mixture?
Show the answer
Answer: b
The E-step averages over the hidden assignment instead of fixing it. Hard labels throw away exactly the uncertainty EM is built to keep.
Check yourself
Your EM run's log-likelihood rose every iteration and then flattened. A colleague says this proves the fit is the global maximum and the clusters are real. What's wrong?
Show the answer
Answer: b
Run several starts, compare held-out log scores, and check cluster validity separately. Convergence answers "did the climb stop?", not "is this the right answer?"
Check yourself
You refit a three-component mixture on 50 bootstrap samples and average "component 1's mean" across them. The average lands between two clusters. Why?
Show the answer
Answer: b
Permuting labels leaves the likelihood unchanged, so nothing ties a label to a cluster across fits. Match components (for example by their means) before averaging.
Check yourself
A sampler reproduces a model's known analytic posterior perfectly, but the model assumes normal noise and the data have one wild outlier. Which question is still open?
Show the answer
Answer: b
Accurate computation and a useful model are different questions. Posterior predictive checks target the second one.
Recap
Recap- Keep three questions apart: right computation, useful model, sensitive checks.
- EM alternates expected hidden values (E) and a fit to them (M); the likelihood can't fall.
- Convergence means the climb stopped, not that the answer is global or the uncertainty honest.
- Label switching and collapsing components are the usual traps.
- Runs in CodeSplash: EM fits Gaussian mixture model in Discover (and the mixture synthesizer).
Concepts in this lesson