Note
Go to the end to download the full example code or to run this example in your browser via Binder.
Choosing the number of clusters with validity indices#
A clustering algorithm always delivers a partition for the requested
\(c\), whether or not it is meaningful. Cluster validity indices
quantify how well a partition fits the data; running the algorithm for
\(c = 2,\dots,c_{\max}\) and locating the extremum of the indices is the
classical recipe for selecting the number of clusters. No single index is
reliable on its own, so fuzzyclust.validity offers a family of them:
Index |
Name |
Measures |
Optimum |
|---|---|---|---|
PC |
partition coefficient |
fuzziness only |
max |
CE |
classification entropy |
fuzziness only |
min |
MPC |
modified partition coefficient |
fuzziness, rescaled |
max |
SC |
partition index |
compactness/separation |
min |
S |
separation index |
compactness/separation |
min |
XB |
Xie–Beni |
compactness/separation |
min |
FS |
Fukuyama–Sugeno |
compactness − separation |
min |
DI |
Dunn’s index |
crisp, O(N²) |
max |
ADI |
alternative Dunn index |
crisp, cheap bound |
max |
SIL |
silhouette |
crisp |
max |
import matplotlib.pyplot as plt
from fuzzyclust import FCM, GK
from fuzzyclust.datasets import make_fuzzy_blobs
from fuzzyclust.plotting import plot_clusters, plot_validity_scan
from fuzzyclust.validity import scan_n_clusters, suggest_n_clusters
X, y_true = make_fuzzy_blobs(n_clusters=5, n_samples_per_cluster=80, spread=0.55, box=12.0, random_state=2)
plot_clusters(X, y_true).set_title("data generated from 5 components")

Text(0.5, 1.0, 'data generated from 5 components')
scan_n_clusters refits the estimator for every \(c\) and returns a
DataFrame of index values; suggest_n_clusters reads off the optimum
of every column, taking into account whether the index is maximized or
minimized.
table = scan_n_clusters(FCM(m=2.0, random_state=0), X, n_clusters_range=range(2, 10))
print(table.round(3))
print("\nsuggested number of clusters per index:")
print(suggest_n_clusters(table))
PC CE MPC SC ... APD PBMF KWON PCAES
n_clusters ...
2 0.733 0.416 0.466 0.507 ... 28.877 22.696 101.960 2.205
3 0.746 0.470 0.618 0.083 ... 45.518 51.945 26.732 3.300
4 0.774 0.460 0.699 0.048 ... 74.468 85.947 28.153 3.199
5 0.834 0.383 0.793 0.021 ... 105.545 98.421 20.831 3.444
6 0.767 0.516 0.720 0.021 ... 95.523 90.538 262.672 9.802
7 0.709 0.623 0.661 0.017 ... 86.572 85.417 238.840 7.808
8 0.665 0.711 0.617 0.014 ... 84.908 87.551 240.588 6.326
9 0.626 0.780 0.579 0.011 ... 82.645 98.130 207.053 4.858
[8 rows x 16 columns]
suggested number of clusters per index:
PC 5
CE 5
MPC 5
SC 9
S 5
XB 5
FS 5
DI 5
ADI 5
SIL 5
FHV 5
PD 5
APD 5
PBMF 5
KWON 5
PCAES 6
Name: suggested_n_clusters, dtype: int64
Plotting the (min–max normalized) indices against \(c\) shows the consensus: the separation-based indices (XB, S, DI, ADI, and SIL) agree on \(c=5\). PC and CE measure fuzziness only and drift with \(c\) and \(m\); here they peak at \(c=5\), but the table below shows that for \(m\ge2.5\) they point to \(c=2\).
fig, axes = plt.subplots(1, 2, figsize=(12, 4.5))
plot_validity_scan(table[["PC", "CE", "MPC"]], ax=axes[0])
axes[0].set_title("partition-based indices")
plot_validity_scan(table[["SC", "S", "XB", "DI", "ADI", "SIL"]], ax=axes[1])
axes[1].set_title("geometry-based indices")
plt.tight_layout()

Validity indices are algorithm-agnostic: the same scan works for GK (or any other estimator of the toolbox). Because GK adapts the cluster shapes, its compactness/separation indices are usually slightly better than those of FCM for the same \(c\).
table_gk = scan_n_clusters(GK(random_state=0), X, range(2, 10), indices=["XB", "SIL"])
comparison = table[["XB", "SIL"]].join(table_gk, lsuffix="_FCM", rsuffix="_GK")
print(comparison.round(3))
/home/runner/work/fuzzyclust/fuzzyclust/examples/01_clustering/plot_05_validity_scan.py:68: Pandas4Warning: The 'lsuffix' and 'rsuffix' keywords in DataFrame.join are deprecated and will be removed in a future version. Use the 'suffixes' keyword instead.
comparison = table[["XB", "SIL"]].join(table_gk, lsuffix="_FCM", rsuffix="_GK")
XB_FCM SIL_FCM XB_GK SIL_GK
n_clusters
2 0.254 0.449 0.286 0.450
3 0.066 0.588 0.074 0.610
4 0.068 0.619 0.083 0.641
5 0.049 0.715 0.049 0.715
6 0.617 0.623 0.650 0.627
7 0.553 0.537 0.626 0.549
8 0.549 0.459 0.570 0.460
9 0.463 0.375 0.757 0.441
In practice, compute several indices, prefer the value of \(c\) on
which the geometry-based indices agree, and inspect the resulting partition
visually (e.g., with the projections of fuzzyclust.viz) before
trusting it. An index extremum is a hint, not a proof.
Parameter study: the verdict and the fuzziness exponent#
Every index is evaluated on the partition that FCM delivers, and that partition depends on \(m\). The scan is therefore repeated for several exponents, and the suggested number of clusters is tabulated per index. XB, DI, SIL, and MPC keep pointing at \(c=5\) for every exponent because the prototypes barely move with \(m\); S, FS, and ADI deviate only for the smallest or the largest exponents. The indices that only measure fuzziness (PC, CE) behave differently: for a soft partition (\(m\ge2.5\)) they flip to \(c=2\), since fewer clusters simply means less fuzziness to share. The Xie–Beni curves show that the minimum deepens as \(m\) grows but stays at \(c=5\).
# [snippet:m_scan]
import pandas as pd
m_values = (1.3, 1.6, 2.0, 2.5, 3.0)
tables = {m: scan_n_clusters(FCM(m=m, random_state=0), X, n_clusters_range=range(2, 10)) for m in m_values}
verdict = pd.DataFrame({f"m = {m}": suggest_n_clusters(t) for m, t in tables.items()})
# [/snippet:m_scan]
print("suggested number of clusters per index and exponent:")
print(verdict.loc[["PC", "CE", "MPC", "SC", "S", "XB", "FS", "DI", "ADI", "SIL"]])
fig, ax = plt.subplots(figsize=(6.5, 4))
for m, t in tables.items():
ax.plot(t.index, t["XB"], "o-", label=f"m = {m}")
ax.axvline(5, color="0.5", ls=":")
ax.set_xlabel("number of clusters $c$")
ax.set_ylabel("Xie–Beni index (lower is better)")
ax.set_title("the Xie–Beni minimum stays at $c=5$ for every exponent")
ax.legend(frameon=False, fontsize=8)
ax.grid(True, color="0.9")
plt.tight_layout()

suggested number of clusters per index and exponent:
m = 1.3 m = 1.6 m = 2.0 m = 2.5 m = 3.0
PC 5 5 5 2 2
CE 5 5 5 2 2
MPC 5 5 5 5 5
SC 9 9 9 9 9
S 5 5 5 5 3
XB 5 5 5 5 5
FS 9 5 5 5 4
DI 5 5 5 5 5
ADI 3 3 5 5 5
SIL 5 5 5 5 5
Take-away#
A validity scan turns the choice of \(c\) into a comparison of
partitions, and the indices that combine compactness with separation
(XB, S, DI, SIL, and the volume-based FHV/PD) are the ones to trust: on
these five well-separated groups they agree with each other and with the
GK variant of the scan, and XB, DI, and SIL also across the range of
exponents tested (S drops to three clusters at \(m=3\)). The
fuzziness-only indices PC and CE change their verdict with \(m\)
(\(c=5\) for \(m\le2\), \(c=2\) for larger exponents); SC favors many small
clusters on this data set. No index replaces a look at the partition (the
projections of fuzzyclust.viz are the next step), but a consensus
of the geometry-based indices is a strong hint.
Total running time of the script: (0 minutes 1.047 seconds)