Skip to content

CDiscover · discover.fuzzy

Fuzzy c-means

Which groups are there, and how strongly does each row belong to each one?

Fuzzy c-means (Bezdek): every row gets a membership in every cluster (memberships sum to 1), so rows between clusters show up as mixed instead of being forced into one. The fuzzifier m sets how soft the split is. The possibilistic variant (Krishnapuram & Keller) turns memberships into typicalities that need not sum to 1, so outlying rows get low typicality everywhere. Both engines run the same written-out updates from the same k-means++ starts.

Verified in Python and R Python and R agree to 6 decimals Also called FCM, fuzzy k-means, soft clustering…

A real result

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

Fuzzy c-meansRecorded · Python and R agreeRecorded 2026-11-25 · 42 values compared
R

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

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

First 60 of 153 rows.

Fuzzy membershipsWhich rows belong firmly to one cluster, and which sit between clusters?
View data
ClusterRowMembership
1row 10.0053
2row 10.9916
3row 10.0031
1row 20.1192
2row 20.8290
3row 20.0518
1row 30.0473
2row 30.9294
3row 30.0233
1row 40.0892
2row 40.8695
3row 40.0413
1row 50.0160
2row 50.9739
3row 50.0100
1row 60.1020
2row 60.8188
3row 60.0792
1row 70.0263
2row 70.9593
3row 70.0144
1row 80.0011
2row 80.9983
3row 80.0006
1row 90.1806
2row 90.7403
3row 90.0791
1row 100.0744
2row 100.8912
3row 100.0344
1row 110.0541
2row 110.9087
3row 110.0373
1row 120.0089
2row 120.9863
3row 120.0048
1row 130.1176
2row 130.8299
3row 130.0525
1row 140.1421
2row 140.7900
3row 140.0679
1row 150.1385
2row 150.7448
3row 150.1167
1row 160.1868
2row 160.6333
3row 160.1799
1row 170.0971
2row 170.8280
3row 170.0750
1row 180.0052
2row 180.9917
3row 180.0031
1row 190.1099
2row 190.8055
3row 190.0846
1row 200.0583
2row 200.9007
3row 200.0410

First 60 of 450 rows.

Silhouette widthsHow well does each row fit its cluster compared with the next-nearest cluster?
View data
ClusterSilhouette width
10.5892
10.5878
10.5875
10.5875
10.5853
10.5741
10.5708
10.5618
10.5615
10.5569
10.5559
10.5459
10.5445
10.5423
10.5040
10.4984
10.4738
10.4660
10.4643
10.4446
10.4432
10.4393
10.4351
10.4327
10.4290
10.4216
10.4160
10.4157
10.4042
10.4030
10.3914
10.3875
10.3760
10.3682
10.3677
10.3463
10.3458
10.3421
10.3360
10.3303
10.3303
10.3011
10.2459
10.2277
10.2222
10.1980
10.1709
10.1666
10.1383
10.0869
10.0768
10.0492
20.7329
20.7321
20.7294
20.7275
20.7273
20.7232
20.7232
20.7204

First 60 of 150 rows.

Clusters

ClusterSizeSharesepal_lengthsepal_widthpetal_lengthpetal_width
15234.7%5.8022.6714.3561.394
25033.3%5.0063.4281.4620.2460
34832.0%6.7603.0905.5021.981
Python

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

ClusterSizeSharesepal_lengthsepal_widthpetal_lengthpetal_width
15234.7%5.8022.6714.3561.394
25033.3%5.0063.4281.4620.2460
34832.0%6.7603.0905.5021.981

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

Worked examples in the app

  • Iris fcmml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
  • Iris pcmml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
  • Usarrests softml_usarrests · features: Murder, Assault, UrbanPop, Rape · id: state
  • Penguins mixed imputeml_penguins · features: bill_len, bill_dep, flipper_len, body_mass, island · label: species
  • Degenerate n3ml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species

In the guides

Where it sits in the decision guides

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

What you need

Featuresnumeric / categorical / boolean · 1–200 columns
Variables that define similarity. Categories enter as 0/1 indicator columns.
Known groupscategorical / boolean · 0–1 column
Optional — compared with the clusters (adjusted Rand index, AMI, NMI); never used to fit.
Row labelscategorical / numeric · 0–1 column
Optional names shown on the chart points.

Choices you make

model

Clusters (k)default 3

Number of clusters.

Membershipsdefault fcm

Fuzzy memberships sum to 1 across clusters; possibilistic typicalities don't, so outliers belong weakly everywhere.

  • Fuzzy (memberships sum to 1)(default) — Fuzzy c-means: each row's memberships add up to 1; the standard soft clustering.
  • Possibilistic (typicalities) — Possibilistic c-means, started from the fuzzy solution: typicalities don't sum to 1, so outlying rows score low in every cluster. Close clusters can merge.
Fuzzifier (m)default 2

How soft the split is: near 1 is almost k-means; 2 is the usual choice; larger values blur the clusters together.

Advanced

Startsdefault 5

Runs from different k-means++ starts; the run with the lowest objective is kept.

Maximum iterationsdefault 500

Upper limit on update rounds per start; memberships usually settle well before it.

preprocess

Scale numbersdefault standard

Standardize numbers so each counts equally in distances; turn off only when columns already share one unit.

  • Standardize (population SD)(default) — Rescales each number to mean 0 and SD 1 so every column counts equally in distances; the safe choice.
  • No scaling — Keeps raw values, so wide-ranging columns dominate distances; pick it only when columns share one unit.
Missing valuesdefault drop

Rows with missing values are left out, or filled with the column median (categories get none).

  • Leave the row out(default) — Leaves out rows with a missing value; the clean choice when few are missing.
  • Fill with the median (categories → none) — Fills numeric gaps with the median and leaves category gaps as no category; keeps every row, at some cost to the shape.

What it reports

k
How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
n_used
How many independent units the analysis used; it sets precision and power.
n_noise
How many independent units the analysis used; it sets precision and power.
objective
Clustering where every row has a membership in every cluster, the memberships summing to 1.
iterations
Clustering where every row has a membership in every cluster, the memberships summing to 1.
fuzzifier
The exponent that sets how soft a fuzzy clustering is: near 1 is almost k-means, 2 is usual, larger blurs clusters.
partition_coefficient
Mean of the squared memberships: 1 for a crisp split, 1/k when every row belongs equally everywhere.
partition_entropy
Mean of the squared memberships: 1 for a crisp split, 1/k when every row belongs equally everywhere.
xie_beni
Fuzzy compactness divided by n × the smallest squared distance between centers; lower means tight, well-separated clusters.
silhouette
How well each point sits in its cluster compared with the nearest other cluster, from −1 to 1.
calinski_harabasz
Between-cluster spread over within-cluster spread. Higher means tighter, better-separated clusters.
davies_bouldin
How much each cluster overlaps its most similar neighbor, on average. Lower is better; 0 is the floor.

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

Python and R

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

Default traps between the two languages

  • Both engines run codesplash's written-out c-means updates from the same k-means++ starts (shared Wichmann–Hill stream) until no membership moves by more than 1e-10, so they reach the same fixed point; a later start replaces the kept one only when its objective is lower by more than 1e-10 (relative). e1071::cmeans and scikit-fuzzy start from random memberships instead.
Python

The exact script CodeSplash ran for example “Iris fcm” · 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",
    }},
})
R

The exact script CodeSplash ran for example “Iris fcm” · 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"
  ))
))

Sources

  • Bezdek JC (1981). Pattern Recognition with Fuzzy Objective Function Algorithms. Plenum.
  • Krishnapuram R, Keller JM (1993). A possibilistic approach to clustering. IEEE Transactions on Fuzzy Systems 1(2):98–110.
  • Xie XL, Beni G (1991). A validity measure for fuzzy clustering. IEEE TPAMI 13(8):841–847.

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