Skip to content

Mixture families: heavy tails, factors, infinite K, classes, counts and directions

Every mixture says the data came from K component distributions. Which component suits Gaussian, heavy-tailed, wide, categorical, count and directional data, what a Dirichlet-process prior changes, and how to choose K honestly.

Advanced ~15 min9 steps

What runs in CodeSplash

You will be able to

  • Write a finite mixture and the EM responsibilities
  • Match the component family to the data type (t, factor, latent class, Poisson, von Mises–Fisher)
  • Explain what a Dirichlet-process prior does and what its occupied count isn't
  • Choose K with held-out likelihood or a penalty, and check local independence

Read first

01

One template, many components

Read

A mixture says each row came from one of KK components, picked with probabilities πk\pi_k:

p(x)=∑k=1Kπk f(x;θk).p(x)=\sum_{k=1}^{K}\pi_k\,f(x;\theta_k).

EM alternates responsibilities rik∝πkf(xi;θk)r_{ik}\propto\pi_k f(x_i;\theta_k), how much each component owns each row, with weighted updates of πk\pi_k and θk\theta_k. Only the component family ff changes from method to method, and it should match the data: numbers, heavy tails, many columns, categories, counts or directions.

A component is a statistical device. It needn't be a real population.

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?

3
How sure?
3
0
3.0
300
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

02

Gaussian mixtures

Read

The Gaussian mixtureGaussian mixtureA model in which each row comes from one of k normal distributions, giving every row a probability for each group. uses f=N(μk,Σk)f=\mathcal N(\mu_k,\Sigma_k). Its covariance shape sets how many parameters you pay for: full ellipses for every component, one tied ellipse, axis-aligned, or circles.

Gaussian mixture modelRecorded · Python and R agreeRecorded 2026-11-25 · 47 values compared
R

3-component Gaussian mixture (full covariances): log-likelihood -296.9, BIC 814.3, AIC 681.8.

Clusters
3
Mean silhouette
0.3230

Plots

ClustersWhich rows group together, and how well separated are the groups?
View data
CenterClusterPC1 (73%)PC2 (23%)
false2−2.2650.4800
false2−2.081−0.6741
false2−2.364−0.3419
false2−2.299−0.5974
false2−2.3900.6468
false2−2.0761.489
false2−2.4440.0476
false2−2.2330.2231
false2−2.335−1.115
false2−2.184−0.4690
false2−2.1661.044
false2−2.3260.1331
false2−2.218−0.7287
false2−2.633−0.9615
false2−2.1991.860
false2−2.2622.686
false2−2.2081.484
false2−2.1900.4888
false2−1.8991.405
false2−2.3431.128
false2−1.9140.4089
false2−2.2070.9241
false2−2.7740.4583
false2−1.8190.0856
false2−2.2270.1373
false2−1.952−0.6256
false2−2.0510.2422
false2−2.1690.5271
false2−2.1400.3132
false2−2.265−0.3377
false2−2.140−0.5045
false2−1.8320.4237
false2−2.6151.794
false2−2.4462.151
false2−2.110−0.4602
false2−2.208−0.2061
false2−2.0450.6616
false2−2.5270.5923
false2−2.430−0.9042
false2−2.1700.2689
false2−2.2860.4417
false2−1.858−2.337
false2−2.554−0.4791
false2−1.9640.4723
false2−2.1371.142
false2−2.070−0.7111
false2−2.3851.120
false2−2.394−0.3862
false2−2.2290.9980
false2−2.2040.0092
false11.1020.8630
false10.73130.5946
false11.2410.6163
false10.4075−1.754
false11.075−0.2084
false10.3887−0.5933
false10.74650.7730
false1−0.4873−1.852
false10.92790.0322
false10.0114−1.034

First 60 of 153 rows.

Silhouette widthsHow well does each row fit its cluster compared with the next-nearest cluster?
View data
ClusterSilhouette width
10.3288
10.3273
10.3195
10.3152
10.3129
10.3098
10.3040
10.2876
10.2822
10.2784
10.2708
10.2705
10.2594
10.2566
10.2548
10.2466
10.2437
10.2407
10.2389
10.2366
10.2208
10.2204
10.2202
10.2196
10.2193
10.2035
10.1964
10.1735
10.1730
10.1589
10.1317
10.1280
10.1175
10.1039
10.1012
10.0976
10.0951
10.0903
10.0873
10.0588
10.0495
10.0487
10.0236
10.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

ClusterSizeSharesepal_lengthsepal_widthpetal_lengthpetal_width
16543.3%6.1982.8054.6741.443
25033.3%5.0063.4281.4620.2460
33523.3%6.3802.9975.3372.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"
  ))
))
Python

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

ClusterSizeSharesepal_lengthsepal_widthpetal_lengthpetal_width
16543.3%6.1982.8054.6741.443
25033.3%5.0063.4281.4620.2460
33523.3%6.3802.9975.3372.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",
    }},
})

With full covariances on iris the model uses 44 parameters. An unconstrained likelihood can run to infinity when one component shrinks onto a single point, so fits need regularization, several starts and enough rows per component. Check the smallest covariance eigenvalues.

03

Heavy tails and wide data

Read

The Student-t mixtureStudent-t mixture modelA mixture whose components are multivariate t distributions; outlying rows get small weights instead of distorting the fit. swaps in multivariate tt components with degrees of freedom νk\nu_k. In EM, a row far from its center (large Mahalanobis distance δik\delta_{ik}) gets weight uik=(νk+d)/(νk+δik)u_{ik}=(\nu_k+d)/(\nu_k+\delta_{ik}), so outliers stop dragging the means. Heavy tails can also swallow a real small group. On penguins the extra tail parameters didn't pay: BIC 2,528 against 2,516 for Gaussian (lower is better).

Mixtures of factor analyzersMixture of factor analyzersA Gaussian mixture whose covariances are q loadings plus one shared diagonal, so wide data need far fewer parameters. write each covariance as ΛkΛk⊤+Ψk\Lambda_k\Lambda_k^\top+\Psi_k: qq loadings plus noise. With qq = 1 on iris that's 30 parameters. Loadings can be rotated freely, so a good density doesn't make the factors unique.

04

Let the data pick K?

Read

A Dirichlet-process mixture puts a prior on infinitely many components: G∼DP(α,G0)G\sim DP(\alpha,G_0), each row's parameters drawn from GG. In the Chinese-restaurant picture, a new row joins an existing component in proportion to its size, or opens a new one in proportion to α\alpha.

It's tempting to read the number of occupied components as "the number of groups". It isn't: that count grows with the data and depends on α\alpha. Variational fits also cap the components at a truncation level; if every slot is used, raise the cap. Check predictive density and sensitivity to α\alpha.

05

Categories, counts and directions

Read
  • Latent class analysisLatent class analysisA mixture for categorical items: each hidden class has its own answer probabilities, and items are independent within a class. models categorical answers: within a class, each item's answer has its own probabilities, and items are independent given the class (local independence).
  • A Poisson mixturePoisson mixtureGroups of count data, each with its own rate per count column (optionally per unit of exposure). models counts with rates λk\lambda_k; each component forces mean = variance, and known exposure (time at risk) scales the rate.
  • 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 κ. models unit vectors with mean directions μk\mu_k and concentrations κk\kappa_k; vector length is thrown away.
Count and direction mixturesRecorded · Python and R agreeRecorded 2026-11-25 · 42 values compared
R

3-component von Mises–Fisher mixture: log-likelihood -287.4, BIC 635.1, ICL 649.2.

Clusters
3
Mean silhouette
0.5872

Plots

ClustersWhich rows group together, and how well separated are the groups?
View data
CenterClusterPC1 (51%)PC2 (41%)
false2−0.03320.6376
false2−0.13560.7432
false2−0.02310.7484
false2−0.15040.7311
false2−0.35660.4749
false2−0.21900.5233
false2−0.36390.4602
false2−0.21620.5388
false2−0.25860.6734
false20.12620.7230
false2−0.00680.6737
false2−0.07310.4503
false20.13180.7883
false20.12490.6955
false20.01510.7214
false2−0.04580.6176
false2−0.09830.7006
false2−0.28820.6902
false2−0.02370.6958
false2−0.13380.6780
false2−0.14900.6898
false2−0.20170.5991
false20.20520.6090
false20.03110.7517
false2−0.15050.7634
false2−0.15810.5773
false2−0.22260.6875
false2−0.09370.6794
false2−0.17410.7303
false2−0.08440.5625
false2−0.10400.6316
false2−0.05320.7884
false2−0.15250.7911
false2−0.21850.5612
false2−0.10980.6741
false20.07360.5114
false2−0.28260.5937
false20.08630.5990
false2−0.09000.7153
false2−0.31110.6877
false2−0.09700.7655
false2−0.10620.6208
false2−0.05070.6887
false2−0.12570.7037
false20.12330.4747
false2−0.15270.6700
false2−0.03680.6888
false2−0.07990.6216
false20.01790.6143
false20.12590.6741
false2−0.10370.7764
false20.26170.6183
false20.00150.4486
false2−0.46240.5829
false2−0.05830.6978
false2−0.15800.5734
false2−0.00770.7085
false2−0.27670.6616
false20.09700.6613
false20.14530.5535

First 60 of 243 rows.

Silhouette widthsHow well does each row fit its cluster compared with the next-nearest cluster?
View data
ClusterSilhouette width
10.7219
10.7196
10.7182
10.7146
10.7119
10.7102
10.7100
10.7072
10.7058
10.7046
10.7042
10.7035
10.7010
10.6998
10.6989
10.6983
10.6980
10.6979
10.6957
10.6941
10.6935
10.6931
10.6928
10.6927
10.6850
10.6845
10.6820
10.6803
10.6787
10.6763
10.6686
10.6685
10.6684
10.6589
10.6515
10.6496
10.6453
10.6429
10.6410
10.6269
10.6193
10.6142
10.6001
10.5998
10.5995
10.5964
10.5957
10.5918
10.5906
10.5889
10.5859
10.5838
10.5801
10.5775
10.5748
10.5692
10.5675
10.5558
10.5547
10.5542

First 60 of 240 rows.

Clusters

ClusterSizeSharexyz
18234.2%0.00391.5830.3055
27932.9%1.6720.32470.1167
37932.9%0.29180.0317−1.410

Components

ClusterWeightConcentration κ
134.0%13.056
232.8%39.976
333.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"
  ))
))
Python

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

ClusterSizeSharexyz
18234.2%0.00391.5830.3055
27932.9%1.6720.32470.1167
37932.9%0.29180.0317−1.410

Components

ClusterWeightConcentration κ
134.0%13.056
232.8%39.976
333.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",
    }},
})
06

Two classes or three?

Predict

Predict first

A survey's latent class model with three classes has a higher likelihood than with two, but a worse BIC. What do you report?

Three: the likelihood is higherTwo: the penalized criterion is lowerCan't tell without checking local independence
Reveal

Check before you choose. BIC favored two classes (2,808 against 2,843). But if two items stay associated within classes, local independence fails, and an extra class may only be soaking up that leftover association. Look at residual item-pair associations and class profiles, not only the smallest BIC.

07

Where each idea stands in CodeSplash

Read
EntryIn CodeSplash
Gaussian mixture (UCL039)Runs in CodeSplash: Gaussian mixture model
Student-t mixture (UCL040)Runs as an option of Gaussian mixture model: Component Student-t (heavy tails)
Mixtures of factor analyzers (UCL041)Runs as an option of Gaussian mixture model: Covariance Factor analyzers
Dirichlet-process mixture (UCL042)Partly runs in CodeSplash: finite mixtures only; the Dirichlet-process prior isn't built
Latent class analysis (UCL043)Runs in CodeSplash: Latent class analysis
Poisson mixture (UCL044)Runs in CodeSplash: Count and direction mixtures, Counts (Poisson)
von Mises–Fisher mixture (UCL045)Runs in CodeSplash: Count and direction mixtures, Directions
Reference · UCL042 · Partly runs in CodeSplashDirichlet-process mixture modelPlace a distribution over mixture complexity rather than fixing a finite number of occupied components in advance. It is useful for flexible density modeling when cluster count is uncertain.
08

Check your understanding

Checkpoint

Check yourself

A Gaussian mixture fit reports an enormous likelihood, and one component holds a single row. What happened?

Show the answer

Answer: a

Unconstrained Gaussian likelihoods are unbounded. Regularize the covariances, try several starts and require enough rows per component.

Check yourself

A mixture fits well with three Gaussian components. Does the data contain three populations?

Show the answer

Answer: b

Components are building blocks for a density. Populations are a claim you check with domain knowledge and new data.

Check yourself

In a Student-t mixture, what happens to a row far from its component's center?

Show the answer

Answer: b

The weight uik=(ν+d)/(ν+δik)u_{ik}=(\nu+d)/(\nu+\delta_{ik}) shrinks as the distance grows. That's what makes the fit robust to moderate outliers.

Check yourself

How do you decide whether heavy tails were worth it?

Show the answer

Answer: b

Tail parameters cost parameters. If the Gaussian model scores as well, the extra flexibility wasn't needed.

Check yourself

Why use mixtures of factor analyzers on wide data?

Show the answer

Answer: a

Σk=ΛkΛk⊤+Ψk\Sigma_k=\Lambda_k\Lambda_k^\top+\Psi_k keeps correlations while cutting parameters. The loadings are only defined up to rotation.

Check yourself

Two runs of a factor-analyzer mixture give the same density but different loadings. Is one wrong?

Show the answer

Answer: b

Only ΛΛ⊤\Lambda\Lambda^\top is identified. Interpret factors only after fixing a rotation convention.

Check yourself

A Dirichlet-process mixture uses 7 components. What does that tell you?

Show the answer

Answer: b

Occupied components reflect the prior and the sample size. Check sensitivity to α and whether every truncation slot was used.

Check yourself

In the Chinese-restaurant picture, what does a larger concentration α do?

Show the answer

Answer: a

A new row opens a component with weight proportional to α and joins an existing one in proportion to its size.

Check yourself

What does latent class analysis assume within a class?

Show the answer

Answer: b

Local independence lets the class explain all association between items. When it fails, extra classes may only absorb leftover dependence.

Check yourself

Some answer patterns are very rare. What can that do to an LCA fit?

Show the answer

Answer: a

Boundary estimates and weak identification come from sparse patterns. Use several starts and look at class uncertainty.

Check yourself

What does each Poisson component force?

Show the answer

Answer: b

A mixture of Poissons can be overdispersed overall, but each component has mean = variance. Zero inflation or dependence may need another model.

Check yourself

Customers were observed for different lengths of time. How should a Poisson mixture handle it?

Show the answer

Answer: b

Without exposure, long-observed customers look like a high-rate group. Rates must be compared on a common scale.

Check yourself

When does a von Mises–Fisher mixture fit?

Show the answer

Answer: a

vMF lives on the unit sphere and discards length. It's the probabilistic cousin of spherical k-means.

Check yourself

Directional clusters are elongated in one direction around their mean. What's the limitation?

Show the answer

Answer: b

Each component has one concentration κ, the same in every direction. Check angular residuals before trusting the fit.

09

Do it on your own data

In the app

Under Find segments, open Gaussian mixture model and switch Component or Covariance; open Latent class analysis for survey answers or baskets; open Count and direction mixtures for counts (with an exposure column) or unit vectors.

Concepts in this lesson