Soft memberships and categories: fuzzy c-means and k-modes
Two ways past k-means' assumptions. Fuzzy c-means gives every row a membership in every cluster; k-modes clusters categories directly, with k-prototypes adding numbers.
What runs in CodeSplash
- Fuzzy c-means Verified in Python and R
- k-modes and k-prototypes Verified in Python and R
You will be able to
- Read fuzzy memberships and the partition coefficient
- Tell fuzzy memberships from possibilistic typicalities
- Cluster categorical and mixed data with k-modes and k-prototypes
When one label per row is too strong
Readk-means puts every row in exactly one cluster, even a row that sits halfway between two. Fuzzy c-meansFuzzy c-meansClustering where every row has a membership in every cluster, the memberships summing to 1. keeps the same idea of centers but gives each row a membership in every cluster. A row's memberships add up to 1, so a row at 0.5 / 0.5 is honestly in between.
The fuzzifier sets how soft the split is. Near 1 it behaves almost like k-means. The usual choice is 2. Larger values blur the clusters together.
Fuzzy c-means with k = 3 (m = 2): partition coefficient 0.71 (1 = crisp, 0.33 = no structure), Xie–Beni 0.222.
- Clusters
- 3
- Mean silhouette
- 0.4584
Plots
View data
| Center | Cluster | PC1 (73%) | PC2 (23%) |
|---|---|---|---|
| false | 2 | −2.265 | 0.4800 |
| false | 2 | −2.081 | −0.6741 |
| false | 2 | −2.364 | −0.3419 |
| false | 2 | −2.299 | −0.5974 |
| false | 2 | −2.390 | 0.6468 |
| false | 2 | −2.076 | 1.489 |
| false | 2 | −2.444 | 0.0476 |
| false | 2 | −2.233 | 0.2231 |
| false | 2 | −2.335 | −1.115 |
| false | 2 | −2.184 | −0.4690 |
| false | 2 | −2.166 | 1.044 |
| false | 2 | −2.326 | 0.1331 |
| false | 2 | −2.218 | −0.7287 |
| false | 2 | −2.633 | −0.9615 |
| false | 2 | −2.199 | 1.860 |
| false | 2 | −2.262 | 2.686 |
| false | 2 | −2.208 | 1.484 |
| false | 2 | −2.190 | 0.4888 |
| false | 2 | −1.899 | 1.405 |
| false | 2 | −2.343 | 1.128 |
| false | 2 | −1.914 | 0.4089 |
| false | 2 | −2.207 | 0.9241 |
| false | 2 | −2.774 | 0.4583 |
| false | 2 | −1.819 | 0.0856 |
| false | 2 | −2.227 | 0.1373 |
| false | 2 | −1.952 | −0.6256 |
| false | 2 | −2.051 | 0.2422 |
| false | 2 | −2.169 | 0.5271 |
| false | 2 | −2.140 | 0.3132 |
| false | 2 | −2.265 | −0.3377 |
| false | 2 | −2.140 | −0.5045 |
| false | 2 | −1.832 | 0.4237 |
| false | 2 | −2.615 | 1.794 |
| false | 2 | −2.446 | 2.151 |
| false | 2 | −2.110 | −0.4602 |
| false | 2 | −2.208 | −0.2061 |
| false | 2 | −2.045 | 0.6616 |
| false | 2 | −2.527 | 0.5923 |
| false | 2 | −2.430 | −0.9042 |
| false | 2 | −2.170 | 0.2689 |
| false | 2 | −2.286 | 0.4417 |
| false | 2 | −1.858 | −2.337 |
| false | 2 | −2.554 | −0.4791 |
| false | 2 | −1.964 | 0.4723 |
| false | 2 | −2.137 | 1.142 |
| false | 2 | −2.070 | −0.7111 |
| false | 2 | −2.385 | 1.120 |
| false | 2 | −2.394 | −0.3862 |
| false | 2 | −2.229 | 0.9980 |
| false | 2 | −2.204 | 0.0092 |
| false | 3 | 1.102 | 0.8630 |
| false | 3 | 0.7313 | 0.5946 |
| false | 3 | 1.241 | 0.6163 |
| false | 1 | 0.4075 | −1.754 |
| false | 1 | 1.075 | −0.2084 |
| false | 1 | 0.3887 | −0.5933 |
| false | 3 | 0.7465 | 0.7730 |
| false | 1 | −0.4873 | −1.852 |
| false | 1 | 0.9279 | 0.0322 |
| false | 1 | 0.0114 | −1.034 |
First 60 of 153 rows.
View data
| Cluster | Row | Membership |
|---|---|---|
| 1 | row 1 | 0.0053 |
| 2 | row 1 | 0.9916 |
| 3 | row 1 | 0.0031 |
| 1 | row 2 | 0.1192 |
| 2 | row 2 | 0.8290 |
| 3 | row 2 | 0.0518 |
| 1 | row 3 | 0.0473 |
| 2 | row 3 | 0.9294 |
| 3 | row 3 | 0.0233 |
| 1 | row 4 | 0.0892 |
| 2 | row 4 | 0.8695 |
| 3 | row 4 | 0.0413 |
| 1 | row 5 | 0.0160 |
| 2 | row 5 | 0.9739 |
| 3 | row 5 | 0.0100 |
| 1 | row 6 | 0.1020 |
| 2 | row 6 | 0.8188 |
| 3 | row 6 | 0.0792 |
| 1 | row 7 | 0.0263 |
| 2 | row 7 | 0.9593 |
| 3 | row 7 | 0.0144 |
| 1 | row 8 | 0.0011 |
| 2 | row 8 | 0.9983 |
| 3 | row 8 | 0.0006 |
| 1 | row 9 | 0.1806 |
| 2 | row 9 | 0.7403 |
| 3 | row 9 | 0.0791 |
| 1 | row 10 | 0.0744 |
| 2 | row 10 | 0.8912 |
| 3 | row 10 | 0.0344 |
| 1 | row 11 | 0.0541 |
| 2 | row 11 | 0.9087 |
| 3 | row 11 | 0.0373 |
| 1 | row 12 | 0.0089 |
| 2 | row 12 | 0.9863 |
| 3 | row 12 | 0.0048 |
| 1 | row 13 | 0.1176 |
| 2 | row 13 | 0.8299 |
| 3 | row 13 | 0.0525 |
| 1 | row 14 | 0.1421 |
| 2 | row 14 | 0.7900 |
| 3 | row 14 | 0.0679 |
| 1 | row 15 | 0.1385 |
| 2 | row 15 | 0.7448 |
| 3 | row 15 | 0.1167 |
| 1 | row 16 | 0.1868 |
| 2 | row 16 | 0.6333 |
| 3 | row 16 | 0.1799 |
| 1 | row 17 | 0.0971 |
| 2 | row 17 | 0.8280 |
| 3 | row 17 | 0.0750 |
| 1 | row 18 | 0.0052 |
| 2 | row 18 | 0.9917 |
| 3 | row 18 | 0.0031 |
| 1 | row 19 | 0.1099 |
| 2 | row 19 | 0.8055 |
| 3 | row 19 | 0.0846 |
| 1 | row 20 | 0.0583 |
| 2 | row 20 | 0.9007 |
| 3 | row 20 | 0.0410 |
First 60 of 450 rows.
View data
| Cluster | Silhouette width |
|---|---|
| 1 | 0.5892 |
| 1 | 0.5878 |
| 1 | 0.5875 |
| 1 | 0.5875 |
| 1 | 0.5853 |
| 1 | 0.5741 |
| 1 | 0.5708 |
| 1 | 0.5618 |
| 1 | 0.5615 |
| 1 | 0.5569 |
| 1 | 0.5559 |
| 1 | 0.5459 |
| 1 | 0.5445 |
| 1 | 0.5423 |
| 1 | 0.5040 |
| 1 | 0.4984 |
| 1 | 0.4738 |
| 1 | 0.4660 |
| 1 | 0.4643 |
| 1 | 0.4446 |
| 1 | 0.4432 |
| 1 | 0.4393 |
| 1 | 0.4351 |
| 1 | 0.4327 |
| 1 | 0.4290 |
| 1 | 0.4216 |
| 1 | 0.4160 |
| 1 | 0.4157 |
| 1 | 0.4042 |
| 1 | 0.4030 |
| 1 | 0.3914 |
| 1 | 0.3875 |
| 1 | 0.3760 |
| 1 | 0.3682 |
| 1 | 0.3677 |
| 1 | 0.3463 |
| 1 | 0.3458 |
| 1 | 0.3421 |
| 1 | 0.3360 |
| 1 | 0.3303 |
| 1 | 0.3303 |
| 1 | 0.3011 |
| 1 | 0.2459 |
| 1 | 0.2277 |
| 1 | 0.2222 |
| 1 | 0.1980 |
| 1 | 0.1709 |
| 1 | 0.1666 |
| 1 | 0.1383 |
| 1 | 0.0869 |
| 1 | 0.0768 |
| 1 | 0.0492 |
| 2 | 0.7329 |
| 2 | 0.7321 |
| 2 | 0.7294 |
| 2 | 0.7275 |
| 2 | 0.7273 |
| 2 | 0.7232 |
| 2 | 0.7232 |
| 2 | 0.7204 |
First 60 of 150 rows.
Clusters
| Cluster | Size | Share | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 52 | 34.7% | 5.802 | 2.671 | 4.356 | 1.394 |
| 2 | 50 | 33.3% | 5.006 | 3.428 | 1.462 | 0.2460 |
| 3 | 48 | 32.0% | 6.760 | 3.090 | 5.502 | 1.981 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Fuzzy c-means
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.fuzzy 1.0.0 · spec 74756e88a823850d
# 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.fuzzy/iris_fcm/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
MODEL <- "fcm"
M <- as.numeric(2)
if (K >= length(rows)) cs_error("CS_E_TOO_FEW_ROWS", what = sprintf("Fuzzy c-means with k = %d", K), min = K + 1, n = length(rows))
if (!any(apply(X, 2, function(v) max(v) - min(v)) > 0)) cs_error("CS_E_CONSTANT", column = paste(FEATURES, collapse = ", "))
# Fuzzy c-means from shared-stream k-means++ centers (the Python twin draws the same starts).
fit <- cs_ml_fcm(X, K, M, cs_rng(SEED), n_init = 5, max_iter = 500)
U <- fit$U
if (MODEL == "pcm") {
# Possibilistic c-means started from the fuzzy solution (eta from the fuzzy memberships).
pf <- cs_ml_pcm(X, fit, M, max_iter = 500)
W <- pf$T; centers <- pf$centers; converged <- pf$converged
values$objective <- pf$objective
values$iterations <- pf$iterations
prefix <- "typicality"
} else {
W <- U; centers <- fit$centers; converged <- fit$converged
values$objective <- fit$objective
values$iterations <- fit$iterations
prefix <- "membership"
}
if (!converged) warnings <- c(warnings, "The updates stopped at the iteration limit before the memberships settled.")
raw <- max.col(W, ties.method = "first") - 1L
values$fuzzifier <- M
values <- c(values, cs_ml_fuzzy_indices(U, cs_ml_sq_dists(X, fit$centers), fit$centers, M))
canon <- cs_ml_canonical(raw)
js <- which(vapply(seq_len(K), function(j) any(raw == j - 1L), logical(1)))
cid <- vapply(js, function(j) canon[which(raw == j - 1L)[1]], numeric(1))
present <- js[order(cid)]
cid <- sort(cid)
for (i in seq_along(present)) extra[[sprintf("%s_%d", prefix, cid[i])]] <- W[, present[i]]
extra[[prefix]] <- apply(W, 1, max)
if (MODEL == "pcm") {
values$typicality_mean <- mean(apply(W, 1, max))
for (i in seq_along(present)) values[[sprintf("eta[%d]", cid[i])]] <- pf$eta[present[i]]
merged <- K - length(present)
values$n_merged <- merged
if (merged > 0) warnings <- c(warnings, sprintf("%d of the %d possibilistic clusters ended on the same center as another (a known trait of the method); %d remain.", merged, K, length(present)))
} else if (length(present) < K) {
warnings <- c(warnings, sprintf("%d cluster(s) are not the strongest membership of any row.", K - length(present)))
}
if (MODEL == "fcm") {
show <- cs_ml_even_sample(length(rows))
ids_shown <- if (!is.null(ROW_ID)) as.character(frame[[ROW_ID]])[show + 1L] else character(0)
if (!length(ids_shown) || anyDuplicated(ids_shown)) ids_shown <- sprintf("row %d", rows[show + 1L] + 1L)
it <- character(0); cl <- character(0); mv <- numeric(0)
for (pos in seq_along(show)) for (q in seq_along(present)) {
it <- c(it, ids_shown[pos]); cl <- c(cl, as.character(cid[q])); mv <- c(mv, W[show[pos] + 1L, present[q]])
}
charts <- c(charts, list(cs_chart(
"memberships", "membership-bars", "Fuzzy memberships",
list(item = cs_col("Row", it, "categorical"), cluster = cs_col("Cluster", cl, "categorical", levels = as.character(cid)),
membership = cs_col("Membership", mv, "numeric")),
note = if (length(show) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(show), big.mark = ","), format(length(rows), big.mark = ","))
)))
}
summary <- sprintf("%s c-means with k = %d (m = %s): partition coefficient %.2f (1 = crisp, %.2f = no structure), Xie–Beni %s.",
if (MODEL == "pcm") "Possibilistic" else "Fuzzy", K, format(M), values$partition_coefficient, 1 / K,
formatC(values$xie_beni, digits = 3, 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 = "Fuzzy c-means",
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,
model = "fcm",
fuzzifier = 2,
n_init = 5,
max_iter = 500,
scale = "standard",
missing = "drop"
))
))
Fuzzy c-means with k = 3 (m = 2): partition coefficient 0.71 (1 = crisp, 0.33 = no structure), Xie–Beni 0.222.
- Clusters
- 3
- Mean silhouette
- 0.4584
To keep this page light, the plots are shown once, under the R tab.
Clusters
| Cluster | Size | Share | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 52 | 34.7% | 5.802 | 2.671 | 4.356 | 1.394 |
| 2 | 50 | 33.3% | 5.006 | 3.428 | 1.462 | 0.2460 |
| 3 | 48 | 32.0% | 6.760 | 3.090 | 5.502 | 1.981 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Fuzzy c-means
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.fuzzy 1.0.0 · spec 74756e88a823850d
# 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 codesplash.ml import cluster_partitional as cpart
# %% 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.fuzzy/iris_fcm/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
MODEL = "fcm"
M = float(2)
if K >= len(rows):
cs.cs_error("CS_E_TOO_FEW_ROWS", what=f"Fuzzy c-means with k = {K}", min=K + 1, n=len(rows))
if not np.any(np.ptp(X, axis=0) > 0):
cs.cs_error("CS_E_CONSTANT", column=", ".join(FEATURES))
# Fuzzy c-means from shared-stream k-means++ centers (the R twin draws the same starts).
fit = cpart.fcm(X, K, M, Rng(SEED), n_init=5, max_iter=500)
U = fit["U"]
if MODEL == "pcm":
# Possibilistic c-means started from the fuzzy solution (η from the fuzzy memberships).
pf = cpart.pcm(X, fit, M, max_iter=500)
W, centers, converged = pf["T"], pf["centers"], pf["converged"]
values["objective"] = pf["objective"]
values["iterations"] = pf["iterations"]
prefix = "typicality"
else:
W, centers, converged = U, fit["centers"], fit["converged"]
values["objective"] = fit["objective"]
values["iterations"] = fit["iterations"]
prefix = "membership"
if not converged:
warnings.append("The updates stopped at the iteration limit before the memberships settled.")
raw = np.argmax(W, axis=1).astype(np.int64)
values["fuzzifier"] = M
values.update(cpart.fuzzy_indices(U, cpart.sq_dists(X, fit["centers"]), fit["centers"], M))
canon = csc.canonical(raw)
present = sorted((int(canon[np.flatnonzero(raw == j)[0]]), j) for j in range(K) if np.any(raw == j))
for c, j in present:
extra[f"{prefix}_{c}"] = W[:, j] # soft memberships (fuzzy) or typicalities (possibilistic) per cluster
extra[prefix] = W.max(axis=1)
if MODEL == "pcm":
values["typicality_mean"] = float(np.mean(W.max(axis=1)))
for c, j in present:
values[f"eta[{c}]"] = float(pf["eta"][j])
merged = K - len(present)
values["n_merged"] = merged
if merged:
warnings.append(f"{merged} of the {K} possibilistic clusters ended on the same center as another (a known trait of the method); {len(present)} remain.")
elif len(present) < K:
warnings.append(f"{K - len(present)} cluster(s) are not the strongest membership of any row.")
if MODEL == "fcm":
show = csc.even_sample(len(rows))
ids_shown = [str(v) for v in frame[ROW_ID].astype("object").to_numpy()[show]] if ROW_ID else []
if not ids_shown or len(set(ids_shown)) < len(ids_shown):
ids_shown = [f"row {int(rows[i]) + 1}" for i in show]
it, cl, mv = [], [], []
for pos, i in enumerate(show):
for c, j in present:
it.append(ids_shown[pos])
cl.append(str(c))
mv.append(float(W[i, j]))
charts.append(cs.chart(
"memberships", "membership-bars", "Fuzzy memberships",
{"item": cs.col("Row", it, "categorical"), "cluster": cs.col("Cluster", cl, "categorical", levels=[str(c) for c, _ in present]),
"membership": cs.col("Membership", mv, "numeric")},
note=None if len(show) == len(rows) else f"{len(show):,} of {len(rows):,} rows shown.",
))
summary = (
f"{'Possibilistic' if MODEL == 'pcm' else 'Fuzzy'} c-means with k = {K} (m = {M:g}): partition coefficient "
f"{values['partition_coefficient']:.2f} (1 = crisp, {1 / K:.2f} = no structure), Xie–Beni {values['xie_beni']:.3g}."
)
# %% 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": "Fuzzy c-means",
"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,
"model": "fcm",
"fuzzifier": 2,
"n_init": 5,
"max_iter": 500,
"scale": "standard",
"missing": "drop",
}},
})
On iris with = 3, the run settles after 50 rounds. The saved columns membership_1 … membership_3 hold each row's memberships, and cluster keeps its strongest one.
How crisp is the split?
ReadThe partition coefficientPartition coefficientMean of the squared memberships: 1 for a crisp split, 1/k when every row belongs equally everywhere. is the mean squared membership. It is 1 when every row belongs wholly to one cluster and when every row belongs equally everywhere.
Here it is 0.707, against for no structure. The two overlapping species keep it well below 1: many of their rows are genuinely mixed.
Typicality instead of membership
ReadFuzzy memberships must sum to 1, so an outlier far from every center still gets a full unit of membership somewhere. Possibilistic c-means drops that rule. Each row gets a typicality per cluster between 0 and 1, and an outlier scores low everywhere.
Possibilistic c-means with k = 3 (m = 2): partition coefficient 0.71 (1 = crisp, 0.33 = no structure), Xie–Beni 0.222.
- Clusters
- 2
- Mean silhouette
- 0.5818
Plots
View data
| Center | Cluster | PC1 (73%) | PC2 (23%) |
|---|---|---|---|
| false | 2 | −2.265 | 0.4800 |
| false | 2 | −2.081 | −0.6741 |
| false | 2 | −2.364 | −0.3419 |
| false | 2 | −2.299 | −0.5974 |
| false | 2 | −2.390 | 0.6468 |
| false | 2 | −2.076 | 1.489 |
| false | 2 | −2.444 | 0.0476 |
| false | 2 | −2.233 | 0.2231 |
| false | 2 | −2.335 | −1.115 |
| false | 2 | −2.184 | −0.4690 |
| false | 2 | −2.166 | 1.044 |
| false | 2 | −2.326 | 0.1331 |
| false | 2 | −2.218 | −0.7287 |
| false | 2 | −2.633 | −0.9615 |
| false | 2 | −2.199 | 1.860 |
| false | 2 | −2.262 | 2.686 |
| false | 2 | −2.208 | 1.484 |
| false | 2 | −2.190 | 0.4888 |
| false | 2 | −1.899 | 1.405 |
| false | 2 | −2.343 | 1.128 |
| false | 2 | −1.914 | 0.4089 |
| false | 2 | −2.207 | 0.9241 |
| false | 2 | −2.774 | 0.4583 |
| false | 2 | −1.819 | 0.0856 |
| false | 2 | −2.227 | 0.1373 |
| false | 2 | −1.952 | −0.6256 |
| false | 2 | −2.051 | 0.2422 |
| false | 2 | −2.169 | 0.5271 |
| false | 2 | −2.140 | 0.3132 |
| false | 2 | −2.265 | −0.3377 |
| false | 2 | −2.140 | −0.5045 |
| false | 2 | −1.832 | 0.4237 |
| false | 2 | −2.615 | 1.794 |
| false | 2 | −2.446 | 2.151 |
| false | 2 | −2.110 | −0.4602 |
| false | 2 | −2.208 | −0.2061 |
| false | 2 | −2.045 | 0.6616 |
| false | 2 | −2.527 | 0.5923 |
| false | 2 | −2.430 | −0.9042 |
| false | 2 | −2.170 | 0.2689 |
| false | 2 | −2.286 | 0.4417 |
| false | 2 | −1.858 | −2.337 |
| false | 2 | −2.554 | −0.4791 |
| false | 2 | −1.964 | 0.4723 |
| false | 2 | −2.137 | 1.142 |
| false | 2 | −2.070 | −0.7111 |
| false | 2 | −2.385 | 1.120 |
| false | 2 | −2.394 | −0.3862 |
| false | 2 | −2.229 | 0.9980 |
| false | 2 | −2.204 | 0.0092 |
| false | 1 | 1.102 | 0.8630 |
| false | 1 | 0.7313 | 0.5946 |
| false | 1 | 1.241 | 0.6163 |
| false | 1 | 0.4075 | −1.754 |
| false | 1 | 1.075 | −0.2084 |
| false | 1 | 0.3887 | −0.5933 |
| false | 1 | 0.7465 | 0.7730 |
| false | 1 | −0.4873 | −1.852 |
| false | 1 | 0.9279 | 0.0322 |
| false | 1 | 0.0114 | −1.034 |
First 60 of 152 rows.
View data
| Cluster | Silhouette width |
|---|---|
| 1 | 0.6662 |
| 1 | 0.6658 |
| 1 | 0.6646 |
| 1 | 0.6605 |
| 1 | 0.6604 |
| 1 | 0.6595 |
| 1 | 0.6580 |
| 1 | 0.6576 |
| 1 | 0.6502 |
| 1 | 0.6491 |
| 1 | 0.6487 |
| 1 | 0.6438 |
| 1 | 0.6386 |
| 1 | 0.6385 |
| 1 | 0.6347 |
| 1 | 0.6337 |
| 1 | 0.6326 |
| 1 | 0.6292 |
| 1 | 0.6289 |
| 1 | 0.6248 |
| 1 | 0.6245 |
| 1 | 0.6202 |
| 1 | 0.6189 |
| 1 | 0.6189 |
| 1 | 0.6176 |
| 1 | 0.6131 |
| 1 | 0.6118 |
| 1 | 0.6114 |
| 1 | 0.6107 |
| 1 | 0.6094 |
| 1 | 0.6084 |
| 1 | 0.6047 |
| 1 | 0.6017 |
| 1 | 0.6016 |
| 1 | 0.6013 |
| 1 | 0.6013 |
| 1 | 0.5981 |
| 1 | 0.5980 |
| 1 | 0.5948 |
| 1 | 0.5897 |
| 1 | 0.5879 |
| 1 | 0.5878 |
| 1 | 0.5870 |
| 1 | 0.5852 |
| 1 | 0.5796 |
| 1 | 0.5772 |
| 1 | 0.5766 |
| 1 | 0.5765 |
| 1 | 0.5729 |
| 1 | 0.5699 |
| 1 | 0.5681 |
| 1 | 0.5665 |
| 1 | 0.5637 |
| 1 | 0.5605 |
| 1 | 0.5578 |
| 1 | 0.5561 |
| 1 | 0.5556 |
| 1 | 0.5504 |
| 1 | 0.5448 |
| 1 | 0.5360 |
First 60 of 150 rows.
Clusters
| Cluster | Size | Share | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 100 | 66.7% | 6.262 | 2.872 | 4.906 | 1.676 |
| 2 | 50 | 33.3% | 5.006 | 3.428 | 1.462 | 0.2460 |
- 1 of the 3 possibilistic clusters ended on the same center as another (a known trait of the method); 2 remain.
The exact R script · R R version 4.5.1 (2025-06-13)
# Fuzzy c-means
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.fuzzy 1.0.0 · spec e3f663b3627dc78a
# 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.fuzzy/iris_pcm/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
MODEL <- "pcm"
M <- as.numeric(2)
if (K >= length(rows)) cs_error("CS_E_TOO_FEW_ROWS", what = sprintf("Fuzzy c-means with k = %d", K), min = K + 1, n = length(rows))
if (!any(apply(X, 2, function(v) max(v) - min(v)) > 0)) cs_error("CS_E_CONSTANT", column = paste(FEATURES, collapse = ", "))
# Fuzzy c-means from shared-stream k-means++ centers (the Python twin draws the same starts).
fit <- cs_ml_fcm(X, K, M, cs_rng(SEED), n_init = 5, max_iter = 500)
U <- fit$U
if (MODEL == "pcm") {
# Possibilistic c-means started from the fuzzy solution (eta from the fuzzy memberships).
pf <- cs_ml_pcm(X, fit, M, max_iter = 500)
W <- pf$T; centers <- pf$centers; converged <- pf$converged
values$objective <- pf$objective
values$iterations <- pf$iterations
prefix <- "typicality"
} else {
W <- U; centers <- fit$centers; converged <- fit$converged
values$objective <- fit$objective
values$iterations <- fit$iterations
prefix <- "membership"
}
if (!converged) warnings <- c(warnings, "The updates stopped at the iteration limit before the memberships settled.")
raw <- max.col(W, ties.method = "first") - 1L
values$fuzzifier <- M
values <- c(values, cs_ml_fuzzy_indices(U, cs_ml_sq_dists(X, fit$centers), fit$centers, M))
canon <- cs_ml_canonical(raw)
js <- which(vapply(seq_len(K), function(j) any(raw == j - 1L), logical(1)))
cid <- vapply(js, function(j) canon[which(raw == j - 1L)[1]], numeric(1))
present <- js[order(cid)]
cid <- sort(cid)
for (i in seq_along(present)) extra[[sprintf("%s_%d", prefix, cid[i])]] <- W[, present[i]]
extra[[prefix]] <- apply(W, 1, max)
if (MODEL == "pcm") {
values$typicality_mean <- mean(apply(W, 1, max))
for (i in seq_along(present)) values[[sprintf("eta[%d]", cid[i])]] <- pf$eta[present[i]]
merged <- K - length(present)
values$n_merged <- merged
if (merged > 0) warnings <- c(warnings, sprintf("%d of the %d possibilistic clusters ended on the same center as another (a known trait of the method); %d remain.", merged, K, length(present)))
} else if (length(present) < K) {
warnings <- c(warnings, sprintf("%d cluster(s) are not the strongest membership of any row.", K - length(present)))
}
if (MODEL == "fcm") {
show <- cs_ml_even_sample(length(rows))
ids_shown <- if (!is.null(ROW_ID)) as.character(frame[[ROW_ID]])[show + 1L] else character(0)
if (!length(ids_shown) || anyDuplicated(ids_shown)) ids_shown <- sprintf("row %d", rows[show + 1L] + 1L)
it <- character(0); cl <- character(0); mv <- numeric(0)
for (pos in seq_along(show)) for (q in seq_along(present)) {
it <- c(it, ids_shown[pos]); cl <- c(cl, as.character(cid[q])); mv <- c(mv, W[show[pos] + 1L, present[q]])
}
charts <- c(charts, list(cs_chart(
"memberships", "membership-bars", "Fuzzy memberships",
list(item = cs_col("Row", it, "categorical"), cluster = cs_col("Cluster", cl, "categorical", levels = as.character(cid)),
membership = cs_col("Membership", mv, "numeric")),
note = if (length(show) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(show), big.mark = ","), format(length(rows), big.mark = ","))
)))
}
summary <- sprintf("%s c-means with k = %d (m = %s): partition coefficient %.2f (1 = crisp, %.2f = no structure), Xie–Beni %s.",
if (MODEL == "pcm") "Possibilistic" else "Fuzzy", K, format(M), values$partition_coefficient, 1 / K,
formatC(values$xie_beni, digits = 3, 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 = "Fuzzy c-means",
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,
model = "pcm",
fuzzifier = 2,
n_init = 5,
max_iter = 500,
scale = "standard",
missing = "drop"
))
))
Possibilistic c-means with k = 3 (m = 2): partition coefficient 0.71 (1 = crisp, 0.33 = no structure), Xie–Beni 0.222.
- Clusters
- 2
- Mean silhouette
- 0.5818
To keep this page light, the plots are shown once, under the R tab.
Clusters
| Cluster | Size | Share | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 100 | 66.7% | 6.262 | 2.872 | 4.906 | 1.676 |
| 2 | 50 | 33.3% | 5.006 | 3.428 | 1.462 | 0.2460 |
- 1 of the 3 possibilistic clusters ended on the same center as another (a known trait of the method); 2 remain.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Fuzzy c-means
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.fuzzy 1.0.0 · spec e3f663b3627dc78a
# 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 codesplash.ml import cluster_partitional as cpart
# %% 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.fuzzy/iris_pcm/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
MODEL = "pcm"
M = float(2)
if K >= len(rows):
cs.cs_error("CS_E_TOO_FEW_ROWS", what=f"Fuzzy c-means with k = {K}", min=K + 1, n=len(rows))
if not np.any(np.ptp(X, axis=0) > 0):
cs.cs_error("CS_E_CONSTANT", column=", ".join(FEATURES))
# Fuzzy c-means from shared-stream k-means++ centers (the R twin draws the same starts).
fit = cpart.fcm(X, K, M, Rng(SEED), n_init=5, max_iter=500)
U = fit["U"]
if MODEL == "pcm":
# Possibilistic c-means started from the fuzzy solution (η from the fuzzy memberships).
pf = cpart.pcm(X, fit, M, max_iter=500)
W, centers, converged = pf["T"], pf["centers"], pf["converged"]
values["objective"] = pf["objective"]
values["iterations"] = pf["iterations"]
prefix = "typicality"
else:
W, centers, converged = U, fit["centers"], fit["converged"]
values["objective"] = fit["objective"]
values["iterations"] = fit["iterations"]
prefix = "membership"
if not converged:
warnings.append("The updates stopped at the iteration limit before the memberships settled.")
raw = np.argmax(W, axis=1).astype(np.int64)
values["fuzzifier"] = M
values.update(cpart.fuzzy_indices(U, cpart.sq_dists(X, fit["centers"]), fit["centers"], M))
canon = csc.canonical(raw)
present = sorted((int(canon[np.flatnonzero(raw == j)[0]]), j) for j in range(K) if np.any(raw == j))
for c, j in present:
extra[f"{prefix}_{c}"] = W[:, j] # soft memberships (fuzzy) or typicalities (possibilistic) per cluster
extra[prefix] = W.max(axis=1)
if MODEL == "pcm":
values["typicality_mean"] = float(np.mean(W.max(axis=1)))
for c, j in present:
values[f"eta[{c}]"] = float(pf["eta"][j])
merged = K - len(present)
values["n_merged"] = merged
if merged:
warnings.append(f"{merged} of the {K} possibilistic clusters ended on the same center as another (a known trait of the method); {len(present)} remain.")
elif len(present) < K:
warnings.append(f"{K - len(present)} cluster(s) are not the strongest membership of any row.")
if MODEL == "fcm":
show = csc.even_sample(len(rows))
ids_shown = [str(v) for v in frame[ROW_ID].astype("object").to_numpy()[show]] if ROW_ID else []
if not ids_shown or len(set(ids_shown)) < len(ids_shown):
ids_shown = [f"row {int(rows[i]) + 1}" for i in show]
it, cl, mv = [], [], []
for pos, i in enumerate(show):
for c, j in present:
it.append(ids_shown[pos])
cl.append(str(c))
mv.append(float(W[i, j]))
charts.append(cs.chart(
"memberships", "membership-bars", "Fuzzy memberships",
{"item": cs.col("Row", it, "categorical"), "cluster": cs.col("Cluster", cl, "categorical", levels=[str(c) for c, _ in present]),
"membership": cs.col("Membership", mv, "numeric")},
note=None if len(show) == len(rows) else f"{len(show):,} of {len(rows):,} rows shown.",
))
summary = (
f"{'Possibilistic' if MODEL == 'pcm' else 'Fuzzy'} c-means with k = {K} (m = {M:g}): partition coefficient "
f"{values['partition_coefficient']:.2f} (1 = crisp, {1 / K:.2f} = no structure), Xie–Beni {values['xie_beni']:.3g}."
)
# %% 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": "Fuzzy c-means",
"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,
"model": "pcm",
"fuzzifier": 2,
"n_init": 5,
"max_iter": 500,
"scale": "standard",
"missing": "drop",
}},
})
The mean of each row's highest typicality is 0.527. Possibilistic clusters can also merge: close clusters may slide onto the same center, so you can get fewer than . Here 1 of the three ended on another cluster's center.
Clustering categories with k-modes
Readk-means needs numbers. Turning categories into 0/1 columns works, but the "center" of a set of 0/1 columns is a list of shares that matches no real row. k-modesk-modesk-means for categories: clusters are summarized by their most common category per column and rows by how many columns differ. works on the categories themselves:
- the distance between two rows is the number of columns where they differ;
- each cluster is summarized by its mode, the most common category in every column.
k-modes with k = 3: 1140 mismatched categories in all (0.52 per row).
- Clusters
- 3
- Mean silhouette
- 0.5838
Clusters
| Cluster | Size | Share | Class | Sex | Age |
|---|---|---|---|---|---|
| 1 | 1,690 | 76.8% | Crew (52%) | Male (99%) | Adult (100%) |
| 2 | 447 | 20.3% | 3rd (44%) | Female (100%) | Adult (90%) |
| 3 | 64 | 2.9% | 3rd (75%) | Male (100%) | Child (100%) |
The exact R script · R 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"
))
))
k-modes with k = 3: 1140 mismatched categories in all (0.52 per row).
- Clusters
- 3
- Mean silhouette
- 0.5838
Clusters
| Cluster | Size | Share | Class | Sex | Age |
|---|---|---|---|---|---|
| 1 | 1,690 | 76.8% | Crew (52%) | Male (99%) | Adult (100%) |
| 2 | 447 | 20.3% | 3rd (44%) | Female (100%) | Adult (90%) |
| 3 | 64 | 2.9% | 3rd (75%) | Male (100%) | Child (100%) |
The exact Python script · Python 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",
}},
})
Shortened for the Academy: 2 chart(s) dropped to stay under 100 KB; 2 chart(s) dropped to stay under 100 KB.
On the Titanic passengers (class, sex and age), three clusters leave 1,140 mismatched categories in all. Read each cluster by its modes in the cluster table. Then check the known groups row: survival was never used to fit, yet the clusters line up with it partly.
Mixed data with k-prototypes
Readk-prototypes adds numbers. Its distance is the squared distance on the standardized numbers plus × the number of mismatched categories, so sets how much one mismatch counts.
k-prototypes with k = 3 (γ = 0.5): total dissimilarity to the prototypes 279.1.
- Clusters
- 3
- Mean silhouette
- 0.6334
Plots
View data
| Cluster | PC1 (58%) | PC2 (19%) |
|---|---|---|
| 1 | −1.549 | 0.4655 |
| 1 | −1.562 | −0.2686 |
| 1 | −1.027 | −0.4587 |
| 1 | −1.556 | −0.7135 |
| 1 | −1.085 | 0.2233 |
| 1 | −1.878 | −0.1765 |
| 1 | −0.8527 | 0.0705 |
| 1 | −1.566 | −0.0144 |
| 1 | −1.120 | 0.1337 |
| 1 | −1.258 | −0.4153 |
| 1 | −1.959 | −0.4914 |
| 1 | −1.218 | −0.5975 |
| 3 | −0.3593 | 0.2992 |
| 1 | −2.271 | −0.6536 |
| 3 | −0.0863 | 0.6895 |
| 1 | −2.064 | −0.4677 |
| 1 | −1.477 | −0.0248 |
| 1 | −1.559 | −1.065 |
| 1 | −1.173 | −0.1256 |
| 1 | −1.345 | 0.0707 |
| 1 | −1.729 | −1.060 |
| 1 | −0.9827 | 0.1404 |
| 1 | −1.105 | −0.6082 |
| 1 | −2.150 | −0.4014 |
| 1 | −1.141 | 0.2182 |
| 1 | −1.962 | 0.4758 |
| 1 | −1.932 | 0.9008 |
| 1 | −1.473 | 0.1874 |
| 1 | −1.195 | 1.049 |
| 1 | −1.503 | −0.2835 |
| 1 | −0.8124 | 0.5553 |
| 1 | −1.153 | 0.6936 |
| 1 | −1.540 | 0.6525 |
| 1 | −2.043 | 0.2244 |
| 1 | −1.327 | 0.9534 |
| 1 | −2.126 | 0.1000 |
| 1 | −0.6694 | 0.7230 |
| 1 | −1.990 | −0.0587 |
| 3 | −0.2248 | 0.9806 |
| 1 | −1.919 | 0.0569 |
| 1 | −1.058 | 0.7630 |
| 1 | −1.269 | 1.124 |
| 1 | −1.795 | −0.1740 |
| 1 | −0.6849 | 0.9685 |
| 1 | −1.262 | −0.6575 |
| 1 | −0.7984 | −0.0472 |
| 1 | −1.618 | −1.172 |
| 1 | 0.0157 | −0.2283 |
| 1 | −1.824 | −1.129 |
| 1 | −0.4960 | −0.0209 |
| 1 | −1.334 | −0.7096 |
| 1 | −0.4942 | −0.1480 |
| 1 | −1.878 | −0.7824 |
| 1 | −0.8050 | −0.4372 |
| 1 | −1.778 | −0.9672 |
| 1 | −0.3125 | −0.1449 |
| 1 | −1.550 | −0.8023 |
| 1 | −0.4831 | −0.0757 |
| 1 | −1.743 | −0.8776 |
| 1 | −0.4231 | −0.0323 |
First 60 of 333 rows.
View data
| Cluster | Silhouette width |
|---|---|
| 1 | 0.8239 |
| 1 | 0.8238 |
| 1 | 0.8238 |
| 1 | 0.8236 |
| 1 | 0.8233 |
| 1 | 0.8227 |
| 1 | 0.8224 |
| 1 | 0.8220 |
| 1 | 0.8212 |
| 1 | 0.8209 |
| 1 | 0.8207 |
| 1 | 0.8201 |
| 1 | 0.8190 |
| 1 | 0.8185 |
| 1 | 0.8181 |
| 1 | 0.8168 |
| 1 | 0.8159 |
| 1 | 0.8159 |
| 1 | 0.8158 |
| 1 | 0.8157 |
| 1 | 0.8153 |
| 1 | 0.8130 |
| 1 | 0.8130 |
| 1 | 0.8125 |
| 1 | 0.8123 |
| 1 | 0.8122 |
| 1 | 0.8090 |
| 1 | 0.8088 |
| 1 | 0.8071 |
| 1 | 0.8071 |
| 1 | 0.8069 |
| 1 | 0.8046 |
| 1 | 0.8038 |
| 1 | 0.8032 |
| 1 | 0.8007 |
| 1 | 0.8002 |
| 1 | 0.7999 |
| 1 | 0.7983 |
| 1 | 0.7981 |
| 1 | 0.7974 |
| 1 | 0.7961 |
| 1 | 0.7961 |
| 1 | 0.7960 |
| 1 | 0.7934 |
| 1 | 0.7930 |
| 1 | 0.7925 |
| 1 | 0.7898 |
| 1 | 0.7894 |
| 1 | 0.7887 |
| 1 | 0.7877 |
| 1 | 0.7847 |
| 1 | 0.7833 |
| 1 | 0.7820 |
| 1 | 0.7817 |
| 1 | 0.7786 |
| 1 | 0.7772 |
| 1 | 0.7749 |
| 1 | 0.7743 |
| 1 | 0.7741 |
| 1 | 0.7729 |
First 60 of 333 rows.
Clusters
| Cluster | Size | Share | island | sex | bill_len | flipper_len |
|---|---|---|---|---|---|---|
| 1 | 139 | 41.7% | Dream (42%) | female (56%) | 38.517 | 189.40 |
| 2 | 123 | 36.9% | Biscoe (96%) | male (54%) | 47.619 | 217.07 |
| 3 | 71 | 21.3% | Dream (86%) | male (58%) | 48.432 | 195.72 |
- 11 of 344 rows were left out because a feature was missing.
The exact R script · R 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 be3f0b1044e505a9
# Dataset: ml_penguins (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("island", "sex", "bill_len", "flipper_len")
LABEL <- "species" # known groups (external validation only)
ROW_ID <- NULL # row labels for charts
SEED <- 42
KINDS <- list(
island = "categorical",
sex = "categorical",
bill_len = "numeric",
flipper_len = "numeric"
)
LEVELS <- list(
island = c("Biscoe", "Dream", "Torgersen"),
sex = c("female", "male")
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_penguins.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/penguins_kprototypes/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"
))
))
k-prototypes with k = 3 (γ = 0.5): total dissimilarity to the prototypes 279.1.
- Clusters
- 3
- Mean silhouette
- 0.6334
To keep this page light, the plots are shown once, under the R tab.
Clusters
| Cluster | Size | Share | island | sex | bill_len | flipper_len |
|---|---|---|---|---|---|---|
| 1 | 139 | 41.7% | Dream (42%) | female (56%) | 38.517 | 189.40 |
| 2 | 123 | 36.9% | Biscoe (96%) | male (54%) | 47.619 | 217.07 |
| 3 | 71 | 21.3% | Dream (86%) | male (58%) | 48.432 | 195.72 |
- 11 of 344 rows were left out because a feature was missing.
The exact Python script · Python 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 be3f0b1044e505a9
# Dataset: ml_penguins (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 = ["island", "sex", "bill_len", "flipper_len"]
LABEL = "species" # known groups (external validation only)
ROW_ID = None # row labels for charts
SEED = 42
KINDS = {
"island": "categorical",
"sex": "categorical",
"bill_len": "numeric",
"flipper_len": "numeric",
}
LEVELS = {
"island": ["Biscoe", "Dream", "Torgersen"],
"sex": ["female", "male"],
}
df = pd.read_parquet("tests/parity/fixtures/ml_penguins.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/penguins_kprototypes/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",
}},
})
With island and sex plus bill length and flipper length, the default is 0.500. Raise it and the clusters follow the categories more; lower it and the numbers dominate.
Check your understanding
CheckpointCheck yourself
A row's fuzzy memberships are 0.45, 0.40 and 0.15. What's the honest reading?
Show the answer
Answer: b
Memberships are graded. The cluster column keeps the strongest one, but 0.45 against 0.40 means the row is mixed.
Check yourself
With = 4, the partition coefficient is 0.30. What does that say?
Show the answer
Answer: b
The coefficient runs from (no structure) to 1 (crisp). At 0.30 with four clusters, the memberships are nearly flat.
Check yourself
Why can possibilistic c-means flag an outlier when fuzzy c-means can't?
Show the answer
Answer: b
Fuzzy memberships always add up to 1, so an outlier is forced to belong somewhere. Typicalities have no such rule.
Check yourself
How does k-modes measure the distance between two rows?
Show the answer
Answer: b
Matching dissimilarity counts mismatches. Category codes have no order, so subtracting them would be meaningless.
Check yourself
In k-prototypes you raise from 0.5 to 5. What changes?
Show the answer
Answer: a
weighs one mismatched category against squared distance on the standardized numbers. Larger favors the categories.
Do it on your own data
In the appUnder Find segments, pick Fuzzy c-means for numeric data where groups overlap, or k-modes and k-prototypes when your columns are categories.
Recap
Recap- Fuzzy c-means gives graded memberships that sum to 1; the partition coefficient runs from to 1.
- Possibilistic typicalities don't sum to 1, so outliers score low everywhere.
- k-modes counts mismatched categories and describes clusters by their modes; k-prototypes adds numbers, weighed by .
Concepts in this lesson