Skip to content

CDiscover · discover.kmodes

k-modes and k-prototypes

Which groups of similar rows are there when the columns are categories?

k-modes (Huang) clusters categorical data without turning categories into numbers: each cluster is summarized by its mode (the most common category in every column) and rows are compared by how many columns differ. k-prototypes adds numeric columns, weighing squared distance on the (standardized) numbers against γ × the number of mismatched categories. Starts come from Cao's deterministic density rule, so both engines take the same steps.

Verified in Python and R Python and R agree to 10 decimals Also called k-modes, kmodes, k-prototypes…

A real result

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

k-modes and k-prototypesRecorded · Python and R agreeRecorded 2026-11-25 · 26 values compared · largest relative difference 4.3e-14
R

k-modes with k = 3: 1140 mismatched categories in all (0.52 per row).

Clusters
3
Mean silhouette
0.5838

Clusters

ClusterSizeShareClassSexAge
11,69076.8%Crew (52%)Male (99%)Adult (100%)
244720.3%3rd (44%)Female (100%)Adult (90%)
3642.9%3rd (75%)Male (100%)Child (100%)
Python

k-modes with k = 3: 1140 mismatched categories in all (0.52 per row).

Clusters
3
Mean silhouette
0.5838

Clusters

ClusterSizeShareClassSexAge
11,69076.8%Crew (52%)Male (99%)Adult (100%)
244720.3%3rd (44%)Female (100%)Adult (90%)
3642.9%3rd (75%)Male (100%)Child (100%)

Shortened for the Academy: 2 chart(s) dropped to stay under 100 KB; 2 chart(s) dropped to stay under 100 KB.

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

  • Titanic kmodesml_titanic · features: Class, Sex, Age · label: Survived
  • Penguins kprototypesml_penguins · features: island, sex, bill_len, flipper_len · label: species
  • Penguins gamma imputeml_penguins · features: island, sex, bill_dep, body_mass · label: species
  • Penguins kmodes onlyml_penguins · features: island, sex, bill_len · label: species
  • Degenerate n3ml_titanic · features: Class, Sex, Age · label: Survived

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

Featurescategorical / boolean / numeric · 1–200 columns
Variables that define similarity; at least one must be a category. Numbers are used by k-prototypes.
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

Clusters (k)default 3

Number of clusters (modes).

Algorithmdefault auto

k-modes uses only the categories; k-prototypes also uses the numbers.

  • Automatic (k-prototypes when there are numbers)(default) — k-modes when every feature is a category, k-prototypes when some are numbers; the usual choice.
  • k-modes (categories only) — Counts mismatched categories only; numeric features are left out with a note.
  • k-prototypes (categories and numbers) — Squared distance on the standardized numbers plus γ × the mismatched categories.
Category weight (γ)default —

How much one mismatched category counts against squared distance on the numbers (Huang's γ); larger favors the categories.

Advanced

Maximum iterationsdefault 100

Upper limit on assign-and-update rounds; the clusters usually settle within a few.

preprocess

Scale numbersdefault standard

Standardize numbers so each counts equally against the categories; turn off only when numbers already share one unit.

  • Standardize (population SD)(default) — Rescales each number to mean 0 and SD 1, so γ = 0.5 weighs one mismatch like half a standard deviation squared.
  • No scaling — Keeps raw values, so wide-ranging numbers dominate; pick it only when numbers share one unit.
Missing valuesdefault drop

Rows with missing values are left out, or kept: numbers get the column median and a missing category becomes its own category.

  • Leave the row out(default) — Leaves out rows with a missing value; the clean choice when few are missing.
  • Keep the row (median; missing as a category) — Fills numeric gaps with the median and treats a missing category as one more category; keeps every row.

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.
cost
k-means for categories: clusters are summarized by their most common category per column and rows by how many columns differ.
iterations
k-means for categories: clusters are summarized by their most common category per column and rows by how many columns differ.
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>], mode[<cluster>,<feature>], mean[<cluster>,<feature>], start_row[<cluster>], gamma, ari, ami, nmi

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-9). Python uses numpy; R uses codesplashr.

Default traps between the two languages

  • Both engines run codesplash's written-out k-modes from Cao's deterministic start with batch updates (assign every row, then recompute modes and means); ties go to the lowest cluster and the earliest category level. The kmodes Python package and klaR::kmodes update modes row by row or start at random, so their clusters can differ on tied data.
Python

The exact script CodeSplash ran for example “Titanic kmodes” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# k-modes and k-prototypes
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.kmodes 1.0.0 · spec 52b9b7a570b0523a
# Dataset: ml_titanic (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import cluster as csc
from codesplash.stats.rng import Rng
from codesplash.ml import cluster_partitional as cpart

# %% Data
FEATURES = ["Class", "Sex", "Age"]
LABEL = "Survived"  # known groups (external validation only)
ROW_ID = None  # row labels for charts
SEED = 42
KINDS = {
    "Class": "categorical",
    "Sex": "categorical",
    "Age": "categorical",
}
LEVELS = {
    "Class": ["1st", "2nd", "3rd", "Crew"],
    "Sex": ["Male", "Female"],
    "Age": ["Child", "Adult"],
}
df = pd.read_parquet("tests/parity/fixtures/ml_titanic.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.kmodes/titanic_kmodes/out-python")
values = {"n_used": len(rows)}
centers = None
center_ids = None
D = None
extra = {}
tables = []
charts = []
summary = None

# %% Clustering
cs.check_finite_columns(frame, [f for f in FEATURES if KINDS[f] == "numeric"])  # ±Inf stops with CS_E_NOT_FINITE in both engines
K = 3
ALGO = "auto"
GAMMA = None
SCALE = "standard"
CAT = [f for f in FEATURES if KINDS[f] != "numeric"]
NUM = [f for f in FEATURES if KINDS[f] == "numeric"]
if not CAT:
    cs.cs_error("CS_E_INVALID_OPTION", option="Features", allowed="at least one category (use k-means for numbers only)", value="numbers only")
if ALGO == "auto":
    ALGO = "kprototypes" if NUM else "kmodes"
if ALGO == "kmodes" and NUM:
    warnings.append(f"k-modes uses only the categories; {', '.join(NUM)} {'was' if len(NUM) == 1 else 'were'} left out (choose k-prototypes to use numbers).")
if K >= len(rows):
    cs.cs_error("CS_E_TOO_FEW_ROWS", what=f"k-modes with k = {K}", min=K + 1, n=len(rows))
# Categories → integer codes in the stored level order (booleans false, true; a missing value is its own last category).
codes, LEVS = [], []
for f in CAT:
    v = frame[f].astype("object").to_numpy()
    miss = frame[f].isna().to_numpy()
    if KINDS[f] == "boolean":
        s = np.array(["" if m else ("true" if bool(t) else "false") for t, m in zip(v, miss)], dtype=object)
        levs = ["false", "true"]
    else:
        s = np.array(["" if m else str(t) for t, m in zip(v, miss)], dtype=object)
        levs = [str(x) for x in LEVELS.get(f, [])]
        levs += sorted(set(s[~miss].tolist()) - set(levs))
    if miss.any():
        levs = levs + ["(missing)"]
        s[miss] = "(missing)"
    pos = {lv: i for i, lv in enumerate(levs)}
    codes.append(np.array([pos[t] for t in s], dtype=np.int64))
    LEVS.append(levs)
Z = np.column_stack(codes)
N = None
if ALGO == "kprototypes" and NUM:
    cols = []
    for f in NUM:
        x = pd.to_numeric(frame[f], errors="coerce").to_numpy(dtype=np.float64)
        if np.isnan(x).any():
            x = np.where(np.isnan(x), float(np.nanmedian(x)), x)
        if SCALE == "standard":
            mu = float(np.mean(x))
            sd = float(np.sqrt(np.mean((x - mu) ** 2)))
            x = (x - mu) / sd if sd > 0 else x - mu
        cols.append(x)
    N = np.column_stack(cols)
if N is None:
    G = 1.0  # k-modes: the cost is the number of mismatched categories
else:
    G = float(GAMMA) if GAMMA is not None else 0.5 * float(np.mean(np.sqrt(np.mean((N - N.mean(axis=0)) ** 2, axis=0))))
    values["gamma"] = G
fit = cpart.kmodes(Z, N, [len(lv) for lv in LEVS], K, G, max_iter=100)
if "too_few_distinct" in fit:
    cs.cs_error("CS_E_UNDEFINED", what=f"k-modes with k = {K}", reason=f"only {fit['too_few_distinct']} distinct rows can start a cluster")
if not fit["converged"]:
    warnings.append("The assign-and-update rounds stopped at the iteration limit before the clusters settled.")
raw = fit["labels"]
values["cost"] = fit["cost"]
values["iterations"] = fit["iterations"]
canon = csc.canonical(raw)
for j in range(K):
    members = np.flatnonzero(raw == j)
    if not len(members):
        continue
    c = int(canon[members[0]])
    values[f"start_row[{c}]"] = int(rows[fit["start"][j]])
    for a, f in enumerate(CAT):
        values[f"mode[{c},{f}]"] = LEVS[a][int(fit["Zm"][j, a])]
if len(set(raw.tolist())) < K:
    warnings.append(f"{K - len(set(raw.tolist()))} cluster(s) ended with no rows.")
cost_m = cpart.mixed_cost(Z, N, fit["Zm"], fit["Nm"], G)
extra["distance"] = cost_m[np.arange(len(raw)), raw]
if len(rows) <= 3000:
    D = cpart.mixed_matrix(Z, N, G)  # silhouette in the method's own dissimilarity
else:
    warnings.append("The silhouette uses distances on 0/1 indicator columns (more than 3,000 rows).")
if N is None:
    summary = f"k-modes with k = {K}: {values['cost']:.0f} mismatched categories in all ({values['cost'] / len(rows):.2f} per row)."
else:
    summary = f"k-prototypes with k = {K} (γ = {G:.3g}): total dissimilarity to the prototypes {values['cost']:.4g}."

# %% 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": "k-modes and k-prototypes",
    "engine": cs.engine_info("numpy", "numpy", "pandas"),
    "n": len(rows),
    "summary": summary,
    "statistics": [
        {"key": "k", "label": "Clusters", "value": k, "format": "integer"},
        {"key": "silhouette", "label": "Mean silhouette", "value": values["silhouette"]},
    ],
    "tables": tables,
    "values": values,
    "charts": charts,
    "warnings": warnings,
    "artifacts": [{"key": "labels", "path": path, "format": "parquet"}],
    "model": {"kind": "clusterer", "features": names, "params": {
        "k": 3,
        "algorithm": "auto",
        "gamma": None,
        "max_iter": 100,
        "scale": "standard",
        "missing": "drop",
    }},
})
R

The exact script CodeSplash ran for example “Titanic kmodes” · R version 4.5.1 (2025-06-13)

# k-modes and k-prototypes
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.kmodes 1.0.0 · spec 52b9b7a570b0523a
# Dataset: ml_titanic (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("Class", "Sex", "Age")
LABEL <- "Survived"  # known groups (external validation only)
ROW_ID <- NULL  # row labels for charts
SEED <- 42
KINDS <- list(
  Class = "categorical",
  Sex = "categorical",
  Age = "categorical"
)
LEVELS <- list(
  Class = c("1st", "2nd", "3rd", "Crew"),
  Sex = c("Male", "Female"),
  Age = c("Child", "Adult")
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_titanic.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.kmodes/titanic_kmodes/out-r")
values <- list(n_used = length(rows))
centers <- NULL
center_ids <- NULL
D <- NULL
extra <- list()
tables <- list()
charts <- list()
summary <- NULL

# %% Clustering
cs_check_finite_columns(frame, FEATURES[vapply(FEATURES, function(f) identical(KINDS[[f]], "numeric"), logical(1))])  # ±Inf stops with CS_E_NOT_FINITE in both engines
K <- 3
ALGO <- "auto"
GAMMA <- NULL
SCALE <- "standard"
CAT <- FEATURES[vapply(FEATURES, function(f) !identical(KINDS[[f]], "numeric"), logical(1))]
NUM <- FEATURES[vapply(FEATURES, function(f) identical(KINDS[[f]], "numeric"), logical(1))]
if (!length(CAT)) cs_error("CS_E_INVALID_OPTION", option = "Features", allowed = "at least one category (use k-means for numbers only)", value = "numbers only")
if (ALGO == "auto") ALGO <- if (length(NUM)) "kprototypes" else "kmodes"
if (ALGO == "kmodes" && length(NUM)) {
  warnings <- c(warnings, sprintf("k-modes uses only the categories; %s %s left out (choose k-prototypes to use numbers).",
                                  paste(NUM, collapse = ", "), if (length(NUM) == 1) "was" else "were"))
}
if (K >= length(rows)) cs_error("CS_E_TOO_FEW_ROWS", what = sprintf("k-modes with k = %d", K), min = K + 1, n = length(rows))
# Categories -> integer codes in the stored level order (booleans false, true; a missing value is its own last category).
LEVS <- list()
Z <- matrix(0L, length(rows), length(CAT))
for (a in seq_along(CAT)) {
  f <- CAT[a]
  v <- frame[[f]]
  miss <- is.na(v)
  if (identical(KINDS[[f]], "boolean")) {
    s <- ifelse(miss, "", ifelse(as.logical(v), "true", "false"))
    levs <- c("false", "true")
  } else {
    s <- ifelse(miss, "", as.character(v))
    levs <- as.character(unlist(LEVELS[[f]]))
    levs <- c(levs, sort(setdiff(unique(s[!miss]), levs), method = "radix"))
  }
  if (any(miss)) {
    levs <- c(levs, "(missing)")
    s[miss] <- "(missing)"
  }
  Z[, a] <- match(s, levs) - 1L
  LEVS[[a]] <- levs
}
N <- NULL
if (ALGO == "kprototypes" && length(NUM)) {
  N <- matrix(0, length(rows), length(NUM))
  for (cc in seq_along(NUM)) {
    x <- suppressWarnings(as.numeric(frame[[NUM[cc]]]))
    if (any(is.na(x))) x <- ifelse(is.na(x), stats::median(x, na.rm = TRUE), x)
    if (SCALE == "standard") {
      mu <- mean(x)
      sd <- sqrt(mean((x - mu)^2))
      x <- if (sd > 0) (x - mu) / sd else x - mu
    }
    N[, cc] <- x
  }
}
if (is.null(N)) {
  G <- 1  # k-modes: the cost is the number of mismatched categories
} else {
  G <- if (!is.null(GAMMA)) as.numeric(GAMMA) else 0.5 * mean(apply(N, 2, function(x) sqrt(mean((x - mean(x))^2))))
  values$gamma <- G
}
fit <- cs_ml_kmodes(Z, N, vapply(LEVS, length, integer(1)), K, G, max_iter = 100)
if (!is.null(fit$too_few_distinct)) cs_error("CS_E_UNDEFINED", what = sprintf("k-modes with k = %d", K), reason = sprintf("only %d distinct rows can start a cluster", fit$too_few_distinct))
if (!fit$converged) warnings <- c(warnings, "The assign-and-update rounds stopped at the iteration limit before the clusters settled.")
raw <- fit$labels
values$cost <- fit$cost
values$iterations <- fit$iterations
canon <- cs_ml_canonical(raw)
for (j in seq_len(K)) {
  members <- which(raw == j - 1L)
  if (!length(members)) next
  cl <- canon[members[1]]
  values[[sprintf("start_row[%d]", cl)]] <- rows[fit$start[j] + 1L]
  for (a in seq_along(CAT)) values[[sprintf("mode[%d,%s]", cl, CAT[a])]] <- LEVS[[a]][fit$Zm[j, a] + 1L]
}
if (length(unique(raw)) < K) warnings <- c(warnings, sprintf("%d cluster(s) ended with no rows.", K - length(unique(raw))))
cm <- cs_ml_mixed_cost(Z, N, fit$Zm, fit$Nm, G)
extra$distance <- cm[cbind(seq_along(raw), raw + 1L)]
if (length(rows) <= 3000) {
  D <- cs_ml_mixed_matrix(Z, N, G)  # silhouette in the method's own dissimilarity
} else {
  warnings <- c(warnings, "The silhouette uses distances on 0/1 indicator columns (more than 3,000 rows).")
}
summary <- if (is.null(N)) {
  sprintf("k-modes with k = %d: %.0f mismatched categories in all (%.2f per row).", K, values$cost, values$cost / length(rows))
} else {
  sprintf("k-prototypes with k = %d (γ = %s): total dissimilarity to the prototypes %s.", K, formatC(G, digits = 3, format = "g"), formatC(values$cost, digits = 4, format = "g"))
}

# %% 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 = "k-modes and k-prototypes",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(rows),
  summary = summary,
  statistics = list(list(key = "k", label = "Clusters", value = k, format = "integer"),
                    list(key = "silhouette", label = "Mean silhouette", value = values$silhouette)),
  tables = tables,
  values = values,
  charts = charts,
  warnings = warnings,
  artifacts = list(list(key = "labels", path = path, format = "parquet")),
  model = list(kind = "clusterer", features = I(names_), params = list(
    k = 3,
    algorithm = "auto",
    gamma = NULL,
    max_iter = 100,
    scale = "standard",
    missing = "drop"
  ))
))

Sources

  • Huang Z (1998). Extensions to the k-means algorithm for clustering large data sets with categorical values. Data Mining and Knowledge Discovery 2:283–304.
  • Huang Z (1997). Clustering large data sets with mixed numeric and categorical values. Proc. 1st PAKDD, 21–34.
  • Cao F, Liang J, Bai L (2009). A new initialization method for categorical data clustering. Expert Systems with Applications 36(7):10223–10228.

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