Skip to content

CDiscover · discover.mixture

Count and direction mixtures

Which groups could have generated these counts — or these directions?

A finite mixture for data a Gaussian mixture fits badly. Poisson: each component has its own rate for every count column (independent within a component), optionally per unit of an exposure column such as months active. von Mises–Fisher: each row is treated as a direction (scaled to length 1) and each component has a mean direction and a concentration κ (Banerjee et al.'s closed-form update). Both are fitted by EM from host-drawn starting responsibilities; every row gets its most probable component and the probability of each one. BIC, AIC and ICL compare choices of k.

Verified in Python and R Python and R agree to 6 decimals

A real result

Example “Counts poisson”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Count and direction mixturesRecorded · Python and R agreeRecorded 2026-11-25 · 39 values compared
R

3-component Poisson mixture: log-likelihood -2069.2, BIC 4201.2, ICL 4238.5.

Clusters
3
Mean silhouette
0.5348

Plots

ClustersWhich rows group together, and how well separated are the groups?
View data
CenterClusterPC1 (59%)PC2 (37%)
false1−1.378−0.8974
false325.486−11.589
false21.1224.124
false310.461−9.142
false28.85412.406
false1−5.218−2.550
false22.9292.485
false1−2.7431.134
false1−4.9050.5651
false210.00614.911
false2−0.44602.563
false1−5.261−1.642
false311.300−9.751
false1−3.693−0.0816
false1−3.8882.211
false1−5.770−2.465
false1−4.2440.0030
false1−4.710−1.727
false30.6495−3.491
false1−2.370−1.206
false1−6.431−1.903
false37.968−10.581
false1−3.8030.3959
false25.7179.284
false1−5.108−3.027
false1−5.261−1.642
false25.8707.899
false1−4.3971.388
false33.626−4.869
false33.228−6.169
false1−5.770−2.465
false1−4.116−2.719
false1−2.921−1.121
false23.6835.993
false20.30090.1861
false1−2.5230.1792
false25.6255.214
false1−3.387−2.851
false1−6.431−1.903
false1−2.260−1.683
false25.8278.807
false1−4.091−1.382
false25.8707.899
false22.4957.977
false1−2.5230.1792
false1−5.414−0.2577
false1−0.33582.085
false1−6.431−1.903
false316.244−8.268
false20.61383.301
false23.6584.656
false1−4.2440.0030
false23.0896.985
false1−5.923−1.080
false318.178−14.931
false1−5.414−0.2577
false21.8943.084
false1−3.583−0.5590
false1−4.3540.4805
false1−3.693−0.0816

First 60 of 303 rows.

Silhouette widthsHow well does each row fit its cluster compared with the next-nearest cluster?
View data
ClusterSilhouette width
10.8030
10.8030
10.8030
10.8030
10.8030
10.8030
10.8030
10.8030
10.8030
10.8030
10.8014
10.8014
10.8014
10.8014
10.8014
10.7974
10.7974
10.7974
10.7974
10.7974
10.7960
10.7886
10.7886
10.7886
10.7886
10.7886
10.7886
10.7886
10.7886
10.7886
10.7857
10.7857
10.7857
10.7857
10.7857
10.7857
10.7857
10.7853
10.7853
10.7853
10.7853
10.7853
10.7853
10.7853
10.7853
10.7823
10.7823
10.7811
10.7801
10.7801
10.7801
10.7801
10.7801
10.7783
10.7783
10.7783
10.7783
10.7783
10.7783
10.7783

First 60 of 300 rows.

Clusters

ClusterSizeSharevisitscallspurchases
118461.3%2.2281.3040.7609
27525.0%122.5475.160
34113.7%4.24414.3669.268

Components

ClusterWeightRate: visitsRate: callsRate: purchases
162.0%2.2631.3310.7931
224.9%11.9742.5945.176
313.2%4.31314.6599.458
Python

3-component Poisson mixture: log-likelihood -2069.2, BIC 4201.2, ICL 4238.5.

Clusters
3
Mean silhouette
0.5348

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

Clusters

ClusterSizeSharevisitscallspurchases
118461.3%2.2281.3040.7609
27525.0%122.5475.160
34113.7%4.24414.3669.268

Components

ClusterWeightRate: visitsRate: callsRate: purchases
162.0%2.2631.3310.7931
224.9%11.9742.5945.176
313.2%4.31314.6599.458

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Counts poissonw5_counts · features: visits, calls, purchases · label: segment
  • Counts exposurew5_counts · exposure: months · features: visits, calls, purchases · label: segment
  • Claims one countml_claims · exposure: exposure · features: claims
  • Directions vmfw5_directions · features: x, y, z · label: source
  • Iris vmf standardizedml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
  • Degenerate n3w5_counts · features: visits, calls, purchases · label: segment
  • Degenerate infw5_counts · features: visits, calls, purchases · label: segment

In the guides

Where it sits in the decision guides

  • Clustering (k-means, hierarchical) · DS & ML Decision Guide · Discover — find structure without labels

What you need

Featuresnumeric · 1–100 columns
Count columns (Poisson: whole numbers ≥ 0) or the coordinates of each direction (von Mises–Fisher).
Exposurenumeric · 0–1 column
Optional (Poisson) — time or size each row was observed for; rates are then per unit of exposure.
Known groupscategorical / boolean · 0–1 column
Optional — compared with the clusters (adjusted Rand index, AMI, NMI); never used to fit.
Row labelscategorical / numeric · 0–1 column
Optional names shown on the chart points.

Choices you make

model

Kind of datadefault poisson

What each row holds: counts, or a direction in space.

  • Counts (Poisson)(default) — Each component has a rate per count column; the right mixture for visits, calls, defects or claims.
  • Directions (von Mises–Fisher) — Each row is scaled to length 1 and clustered by angle; the right mixture for normalized profiles, embeddings or compass-like data.
Components (k)default 3

Number of mixture components (clusters).

Startsdefault 5

Independent EM runs; the one with the highest log-likelihood wins.

Advanced

Maximum iterationsdefault 500

Upper limit on EM iterations. Raise it if the fit warns that it did not converge.

Convergence tolerancedefault 1e-8

Stop when the mean log-likelihood changes by less than this.

preprocess

Scale numbersdefault none

Directions: standardize the columns before each row is scaled to length 1, or use them as they are.

  • No scaling(default) — Uses the coordinates as they are; the usual choice for directions and normalized profiles.
  • Standardize (population SD) — Gives every column mean 0 and SD 1 first, so no column dominates the angles.
Missing valuesdefault drop

Rows with missing values are left out, or filled with the column median.

  • Leave the row out(default) — Leaves out rows with a missing value; the clean choice when few are missing.
  • Fill with the median — Fills gaps with the column median; keeps every row, at some cost to the fit.

What it reports

k
How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
n_used
How many independent units the analysis used; it sets precision and power.
n_noise
How many independent units the analysis used; it sets precision and power.
loglik
The logarithm of the likelihood; higher (less negative) means the model fits the data better.
bic
Like AIC but with a stronger penalty for parameters as n grows; favors simpler models.
aic
A model score balancing fit against complexity; lower is better, and only differences matter.
icl
BIC plus a penalty for fuzzy assignments; lower is better, and it prefers components that form well-separated clusters.
entropy_r2
1 minus the responsibilities' entropy over its maximum: 1 means every row belongs to one component with near certainty, 0 means coin flips.
family
Groups of count data, each with its own rate per count column (optionally per unit of exposure).
silhouette
How well each point sits in its cluster compared with the nearest other cluster, from −1 to 1.
calinski_harabasz
Between-cluster spread over within-cluster spread. Higher means tighter, better-separated clusters.
davies_bouldin
How much each cluster overlaps its most similar neighbor, on average. Lower is better; 0 is the floor.

Per group, level or term: size[<cluster>], weight[<cluster>], kappa[<cluster>], center[<cluster>,<design column>], mean[<cluster>,<feature>], ari, ami, nmi

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses numpy, scipy; R uses codesplashr.

Default traps between the two languages

  • Both engines run the mixture twin (codesplash.ml.mixture_ext ↔ codesplashr::cs_mx_*) from the same host-drawn responsibilities, with the same EM updates and stopping rule. The von Mises–Fisher normalizer uses scipy.special.ive and R's besselI(expon.scaled = TRUE), which agree to about 1e-14.
Python

The exact script CodeSplash ran for example “Counts poisson” · 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 216b8ae6ee56ccf8
# Dataset: w5_counts (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import cluster as csc
from codesplash.stats.rng import Rng
from codesplash.errors import check_finite_columns, cs_error
from codesplash.ml import mixture_ext as csmx

# %% Data
FEATURES = ["visits", "calls", "purchases"]
LABEL = "segment"  # known groups (external validation only)
ROW_ID = None  # row labels for charts
SEED = 42
KINDS = {
    "visits": "numeric",
    "calls": "numeric",
    "purchases": "numeric",
}
LEVELS = {
}
df = pd.read_parquet("tests/parity/fixtures/w5_counts.parquet", columns=list(dict.fromkeys(FEATURES + [c for c in (LABEL, ROW_ID) if c])))
n_input = len(df)
X, rows, names, frame = csc.prepare(df, FEATURES, KINDS, LEVELS, missing="drop", scale="none")
warnings = []
if len(rows) < n_input:
    warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a feature was missing.")
if len(rows) < 3:
    raise ValueError("Clustering needs at least three rows with every feature present.")
truth = frame[LABEL].astype("object").to_numpy() if LABEL else None
out = csml.out_dir("target/academy-parity/run-8142/discover.mixture/counts_poisson/out-python")
values = {"n_used": len(rows)}
centers = None
center_ids = None
D = None
extra = {}
tables = []
charts = []
summary = None

# %% Clustering
K = 3
FAMILY = "poisson"
EXPOSURE = 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_counts.parquet", columns=[EXPOSURE])[EXPOSURE], errors="coerce").to_numpy(dtype=np.float64)[rows]
        _bad = int(np.sum(~(exposure > 0)))
        if _bad:
            cs_error("CS_E_INVALID_VALUES", column=EXPOSURE, requirement="a positive exposure", count=_bad)
    best = csmx.poisson_fit(X, K, rng, exposure=exposure, n_init=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": "poisson",
        "k": 3,
        "n_init": 5,
        "max_iter": 500,
        "tol": 1e-8,
        "scale": "none",
        "missing": "drop",
    }},
})
R

The exact script CodeSplash ran for example “Counts poisson” · 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 216b8ae6ee56ccf8
# Dataset: w5_counts (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
FEATURES <- c("visits", "calls", "purchases")
LABEL <- "segment"  # known groups (external validation only)
ROW_ID <- NULL  # row labels for charts
SEED <- 42
KINDS <- list(
  visits = "numeric",
  calls = "numeric",
  purchases = "numeric"
)
LEVELS <- list(
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/w5_counts.parquet", col_select = unique(c(FEATURES, LABEL, ROW_ID))))
n_input <- nrow(df)
prep <- cs_ml_cluster_prepare(df, FEATURES, KINDS, LEVELS, missing = "drop", scale = "none")
X <- prep$X; rows <- prep$rows; names_ <- prep$names; frame <- prep$frame
warnings <- list()
if (length(rows) < n_input) {
  warnings <- c(warnings, sprintf("%d of %d rows were left out because a feature was missing.", n_input - length(rows), n_input))
}
if (length(rows) < 3) stop("Clustering needs at least three rows with every feature present.")
truth <- if (!is.null(LABEL)) as.character(frame[[LABEL]]) else NULL
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.mixture/counts_poisson/out-r")
values <- list(n_used = length(rows))
centers <- NULL
center_ids <- NULL
D <- NULL
extra <- list()
tables <- list()
charts <- list()
summary <- NULL

# %% Clustering
K <- 3
FAMILY <- "poisson"
EXPOSURE <- 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_counts.parquet", col_select = EXPOSURE))[[EXPOSURE]]
    exposure <- suppressWarnings(as.numeric(as.character(ex_)))[rows + 1L]
    bad_ <- sum(!(exposure > 0) | is.na(exposure))
    if (bad_) cs_error("CS_E_INVALID_VALUES", column = EXPOSURE, requirement = "a positive exposure", count = bad_)
  }
  best <- cs_mx_poisson_fit(X, K, rng, exposure = exposure, n_init = 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 = "poisson",
    k = 3,
    n_init = 5,
    max_iter = 500,
    tol = 1e-8,
    scale = "none",
    missing = "drop"
  ))
))

Sources

  • McLachlan G, Peel D (2000). Finite mixture models. Wiley (Poisson mixtures, ch. 1, 4).
  • Banerjee A, Dhillon IS, Ghosh J, Sra S (2005). Clustering on the unit hypersphere using von Mises–Fisher distributions. JMLR 6:1345–1382.
  • Biernacki C, Celeux G, Govaert G (2000). Assessing a mixture model for clustering with the integrated completed likelihood. IEEE TPAMI 22:719–725.

From the CodeSplash method registry · discover.mixture v1.0.0.