Fuzzy Clustering and Data Analysis in PythonThe fuzzyclust toolbox

Chapter 4
Cluster validity and the number of clusters

The algorithms of the previous chapter return a partition for whatever number of clusters they are given, and they return it with the same confidence whether or not the data contain that many groups. This chapter is about judging a partition and choosing the number of clusters. It distinguishes three routes—scanning c with validity indices, merging compatible clusters, and asking which partition is stable under resampling—and describes every index in fuzzyclust.validity: partition-based indices that look only at the memberships, compactness and separation indices that relate the within-cluster scatter to the distances between prototypes, crisp indices evaluated on the hardened partition, and the volume and density indices of Gath and Geva. Compatible cluster merging is given as an algorithm with a geometric and a similarity criterion, and the fuzzy Rand and adjusted Rand indices, which compare two fuzzy partitions, are the basis of stability selection. The practical part runs the three routes on the same data and shows how to combine indices and how evaluating new data with predict_proba is itself a form of validation; visual validation is the subject of chapter 5.

4.1 Problem and idea

Cluster validity is the question of whether a given partition fits the data at all. A clustering algorithm finds the best fit for a fixed number of clusters and a fixed family of cluster shapes, but the best fit need not be meaningful: the number of clusters may be wrong, the assumed shape may not correspond to the groups in the data, or the data may have no group structure. Since clustering is unsupervised, there are no labels to compare with; the quality of a partition must be read from the partition and the data themselves. There are three routes to the number of clusters; the first two are sketched in fig. 4.1.

The scan is general and simple but costs cmax ⁡ −1 complete runs, and its outcome rests on the index. Merging exploits the geometry of the prototypes and is natural when the clusters stand for local models, as in chapters 8 and 9, or when they are nodes of a tree, as in chapter 7; it needs a compatibility criterion with thresholds. Stability selection makes no assumption about what a good cluster looks like beyond the algorithm’s own, but it is the most expensive route, with two fits per resample and per c.

Figure 4.1

Figure 4.1. Two routes to the number of clusters. Left: the algorithm is run for every candidate c, and validity indices computed from the data, the partition, and the prototypes select the best one. Right: a deliberately large number of clusters is reduced by merging pairs that are compatible—parallel principal axes, close centers, similar memberships—and re-clustering after every merge. The toolbox implements the scan in fuzzyclust.validity and merging in fuzzyclust.cluster.CompatibleClusterMerging; merging also appears in the graph-based methods of chapter 7 and the time-series segmentation of chapter 9. A third route, stability selection, is described in section 4.2.9.

Figure 4.2 shows the two quantities from which almost every geometric index is built. Compactness is the scatter of the samples about their prototypes, ∑ ⁡ kμikm ‖xk −vi‖ 2 summed over clusters; it is small when the clusters are tight. Separation is the distance between the prototypes, ‖vi −vj‖ 2, aggregated in some way (the minimum over pairs, the sum, or the distance to the grand mean); it is large when the clusters are far apart. A good partition has small compactness and large separation, so most indices are a ratio or a difference of the two. The partition-based indices use only the memberships and ask how fuzzy the partition is, on the grounds that a wrong number of clusters shows up as ambiguous memberships; the volume-based indices of Gath and Geva measure the volume of the clusters through their covariance matrices. No index is perfect, which is why the toolbox implements sixteen and the recommended practice is to look at several.

Figure 4.2

Figure 4.2. The two ingredients of the geometric validity indices: compactness, the membership-weighted scatter of the samples about their prototypes (thin lines), and separation, the distance between the prototypes (arrow).

4.2 Theory

Throughout, U ∈ ℝc×N is the partition, V the prototypes, m the exponent the algorithm used, Ni = ∑ ⁡ kμik the fuzzy cardinality of cluster i, and x¯ the grand mean of the data. Apart from the volume indices, which use the fuzzy covariance matrices, all distances in the indices are Euclidean. This is the convention of the validity literature and makes the indices comparable across algorithms: the norm of the algorithm is not used, so GK and GG partitions are judged in the same geometry as FCM partitions. We present the indices in four families (sections 4.2.1 to 4.2.4), add two further compactness and separation indices (section 4.2.5), and summarize them in section 4.2.6. The scan and merging procedures (section 4.2.7), the comparison of two fuzzy partitions (section 4.2.8), and the stability-based selection of the number of clusters (section 4.2.9) follow.

4.2.1 Partition-based indices

The partition coefficient of Bezdek [3],

PC = 1 N∑ i=1c ∑ k=1Nμ ik2,1 c ≤PC ≤1,
(4.1)

measures the amount of overlap between the clusters: it is one for a hard partition and 1∕c for the fuzziest one, and a larger value is better. The classification entropy

CE = − 1 N∑ i=1c ∑ k=1Nμ ik log ⁡ μik,0 ≤CE ≤log ⁡ c,
(4.2)

measures the same fuzziness with Shannon’s entropy: it is zero for a hard partition and log ⁡ c for the fuzziest one; lower is better. Both need nothing but U, which is their appeal and their weakness: they have no direct connection to the geometry of the data, and they tend to change monotonically with c—PC decreases and CE increases even for data with clear groups, because more clusters mean more borders and more ambiguous samples. On well-separated data they still have a genuine extremum at the right c (section 4.4.1); on overlapping data the knee of the curve, not its extremum, is the informative point, which is how the MATLAB toolbox manual read its motorcycle scan. They also depend strongly on m, so they cannot compare partitions obtained with different exponents, and they are useless for hard partitions (PC = 1, CE = 0 always). Davé’s modified partition coefficient [29],

MPC = 1 − c c −1(1 −PC),0 ≤MPC ≤1,
(4.3)

rescales PC from its range [1∕c,1] to [0,1] and thereby reduces the monotone trend; higher is better.

4.2.2 Compactness and separation indices

The partition index of Bensaid et al. [30],

SC = ∑ i=1c ∑ k=1Nμikm ‖xk −vi‖ 2 Ni ∑ j=1c ‖vj −vi‖ 2 ,
(4.4)

is a sum of cluster-wise validities, the compactness of cluster i over its separation from all other prototypes, each normalized by the fuzzy cardinality Ni so that a small cluster is not favored merely for being small. Lower is better. Its authors designed it for comparing different partitions with the same number of clusters, e.g. from different algorithms or initializations; across c it tends to decrease. The separation index, which the MATLAB manual attributes to the same paper, is the Xie–Beni index in its original form [31], with squared memberships,

S = ∑ i=1c ∑ k=1Nμik2 ‖xk −vi‖ 2 Nmin ⁡ i≠j ‖vi −vj‖ 2 .
(4.5)

It uses the minimum distance between prototypes as separation, which makes it sensitive to any two prototypes that come close; lower is better. The Xie–Beni index of the toolbox weights the scatter with the exponent m of the algorithm instead of the square, the form analyzed by Pal and Bezdek [32],

XB = ∑ i=1c ∑ k=1Nμikm ‖xk −vi‖ 2 Nmin ⁡ i≠j ‖vi −vj‖ 2 .
(4.6)

It is the compactness (J∕N for Euclidean FCM) over the minimal separation; for m = 2 it coincides with S, and SC, S, and XB differ mainly in how the separation is aggregated. XB is the most widely used fuzzy validity index. Lower is better, and it is usually inspected for the first pronounced minimum, because it decreases again for large c, when the minimal center distance shrinks only slowly while the compactness keeps improving. Pal and Bezdek showed that the index is reliable for m between about 1.5 and 2.5. The Fukuyama–Sugeno index [33],

FS = ∑ i=1c ∑ k=1Nμ ikm( ‖x k −vi‖ 2 − ‖v i −x¯‖2),
(4.7)

is compactness minus separation, where the separation of cluster i is its distance from the grand mean weighted by its fuzzy mass; lower (more negative) is better. Because it is a difference rather than a ratio, its value depends on the scale of the data, and it tends to prefer small c on data with one dominant group. The PBM-F index of Pakhira, Bandyopadhyay, and Maulik [34],

PBMF =(1 c ⋅ E1 Jm ⋅Dc)2, (4.8) withE1 = ∑ k=1N ‖x k −x¯‖,Jm = ∑ i,kμikm ‖x k −vi‖ ,Dc = max ⁡ i,j ‖vi −vj‖ ,

combines the ratio of the scatter about the grand mean to the fuzzy within-cluster scatter (both with unsquared distances) with the maximal distance between prototypes and penalizes c explicitly by the factor 1∕c; higher is better. The maximal separation makes it insensitive to one pair of close prototypes but also lets it reward a single far-away cluster.

4.2.3 Crisp indices on the hardened partition

Three indices were designed for hard partitions and are evaluated on the hardened partition argmax ⁡ iμik. Dunn’s index [35],

DI = min ⁡ i min ⁡ j≠i { min ⁡ x∈Ci,y∈Cjd(x,y) max ⁡ l max ⁡ x,y∈Cld(x,y) },
(4.9)

is the smallest distance between two clusters (single linkage) over the largest cluster diameter; higher is better. The index was proposed to identify “compact and well separated” clusters. Its drawbacks are the cost—all N(N −1)∕2 pairwise distances are needed, so it is O(N2)—and its sensitivity: a single pair of close samples from different clusters or a single outlier that inflates a diameter changes the value completely, and for overlapping clusters the hardened partition has no meaningful inter-cluster distance at all. The alternative Dunn index of the MATLAB toolbox bounds the inter-cluster distance from below by the triangle inequality, d(x,y) ≥ |d(y,vj) −d(x,vj)|, which needs only the distances of the samples to the prototypes:

ADI = min ⁡ i min ⁡ j≠i { min ⁡ x∈Ci,y∈Cj |d(y,vj) −d(x,vj)| max ⁡ l max ⁡ x,y∈Cld(x,y) }.
(4.10)

Higher is better; the bound is loose (two samples at the same distance from vj but on opposite sides give zero), so ADI is often tiny, and the MATLAB manual itself noted that it “is not tested enough to know how reliable its results are”. The silhouette of Rousseeuw [36] compares, for every sample, its mean distance ak to the members of its own cluster with the smallest mean distance bk to the members of another cluster,

SIL = 1 N∑ k=1N bk −ak max ⁡ (ak,bk) ∈[−1,1],
(4.11)

higher is better. It is the least sensitive of the three crisp indices because it averages over all samples, but it is also O(N2) and, like all crisp indices, ignores the memberships. The toolbox computes it with sklearn.metrics.silhouette_score.

4.2.4 Volume and density indices

Gath and Geva [21] introduced three measures that use the fuzzy covariance matrices Fi of (3.10) and therefore fit the ellipsoidal clusters of GK and GG. The fuzzy hypervolume

FHV = ∑ i=1cdet ⁡ F i
(4.12)

is the total volume of the clusters; compact clusters give small values, and lower is better. It is the natural companion of the GG algorithm and serves as the splitting criterion of the MST clustering in chapter 7. The partition density

PD = ∑ i=1cSi FHV ,Si = ∑ k:(xk−vi)TFi−1(xk−vi)<1μik,
(4.13)

is the membership mass inside the unit Mahalanobis ellipsoids of the clusters per unit of volume—how densely the “central” members fill the clusters; higher is better. The average partition density

APD = 1 c∑ i=1c Si det ⁡ F i
(4.14)

averages the density cluster by cluster, so that every cluster counts equally whatever its size; higher is better. A single small and very dense cluster can therefore dominate APD, whereas PD is dominated by the large clusters. The three indices reward tight, well-filled ellipsoids irrespective of their orientation, which the Euclidean compactness indices cannot do. Their weak point is the determinant, which collapses for nearly singular covariance matrices (a cluster of few points, a collinear cluster) and then makes FHV tiny and PD huge for a degenerate partition. They are computed from the fuzzy (not the hardened) partition, with Fi weighted by μikm, whatever algorithm produced U.

4.2.5 Two further compactness and separation indices

The Xie–Beni index decreases again for large c because its separation, the minimal distance between prototypes, shrinks more slowly than the compactness improves. Kwon [37] removed this tendency with a punishing term in the numerator,

KWON = ∑ i=1c ∑ k=1Nμik2 ‖xk −vi‖ 2 + 1 c ∑ i=1c ‖vi −x¯‖2 min ⁡ i≠j ‖vi −vj‖ 2 ,
(4.15)

the mean squared distance of the prototypes from the grand mean, which grows as prototypes are added toward the periphery of the data; lower is better. Since the numerator is not divided by N, the index equals N ⋅S plus the punishing term divided by the minimal separation; it inherits the reaction of XB and S to a close pair of prototypes but not their decrease at large c. Wu and Yang [38] combined a cluster-wise partition coefficient with an exponential separation in the partition coefficient and exponential separation index,

PCAES = ∑ i=1c ∑ k=1Nμik2 μM −∑ i=1c exp ⁡ ( − min ⁡ j≠i ‖vi −vj‖ 2 βT ), (4.16) withμM = min ⁡ 1≤i≤c ∑ k=1Nμ ik2,β T = 1 c∑ i=1c ‖v i −x¯‖2;

higher is better. The first sum rates the compactness of every cluster relative to the least compact one; the second charges every cluster up to one unit for a neighbor closer than the typical spread βT of the prototypes. The index thus judges clusters individually rather than through one global ratio. Since the first sum is at least c and the penalty at most c, the index is nonnegative. Its weak point is the normalization by the smallest cluster mass μM: a spurious cluster with very few members inflates every ratio of the first sum, and the index then favors a large c (section 4.4.2), so its curve should be read, not only its maximum.

4.2.6 Summary of the indices

Table 4.1 collects the sixteen indices. Three practical observations help in reading a scan. First, PC, CE, and MPC answer a different question from the geometric indices: they ask whether the partition is confident, the others whether it is good; a wrong number of clusters usually spoils both, but a crisp partition of a bad c is possible (small m) and so is a fuzzy partition of the right one (overlapping groups). Second, the ratio indices XB and S react to the closest pair of prototypes, so they jump when a scan first places two prototypes into one group; this is what makes their first pronounced minimum informative and their behavior at large c erratic. Third, the crisp indices are the ones to trust least on overlapping data, and the volume indices the ones to trust most on well-separated ellipsoidal clusters.

Table 4.1. Validity indices of fuzzyclust.validity. “Opt.” is the direction of the optimum; the last column names the main weakness. The function names are listed in section 4.3.
Index Opt.

Measures

Weakness

PC max

fuzziness of U only, eq. (4.1)

monotone in c, no link to the data, depends on m

CE min

entropy of U, eq. (4.2)

same as PC

MPC max

PC rescaled to [0,1], eq. (4.3)

no link to the data

SC min

compactness / summed separation per cluster, eq. (4.4)

decreases with c; meant for equal c

S min

compactness (μ2) / minimal separation, eq. (4.5)

sensitive to one close pair of prototypes

XB min

compactness (μm) / minimal separation, eq. (4.6)

decreases again for large c; use the first minimum

FS min

compactness − separation from the grand mean, eq. (4.7)

scale-dependent; favors small c

DI max

min inter-cluster distance / max diameter (crisp), eq. (4.9)

O(N2); unreliable for overlapping clusters, outliers

ADI max

DI with a triangle-inequality bound, eq. (4.10)

loose bound, often near zero

SIL max

mean silhouette of the hardened partition, eq. (4.11)

O(N2); ignores memberships

FHV min

total cluster volume ∑ ⁡ idet ⁡ F i, eq. (4.12)

collapses for degenerate covariances

PD max

central membership mass per volume, eq. (4.13)

same as FHV

APD max

mean density per cluster, eq. (4.14)

same as FHV

PBMF max

scatter ratio × maximal separation ∕c, eq. (4.8)

rewards one far-away cluster

KWON min

XB-type ratio with a prototype-spread penalty, eq. (4.15)

sensitive to one close pair of prototypes

PCAES max

cluster-wise PC − exponential separation, eq. (4.16)

a tiny spurious cluster inflates it

4.2.7 Scanning the number of clusters and merging clusters

The scan is straightforward (algorithm 4.1): clone the estimator, set c, fit, evaluate the indices, and tabulate. Two details matter. First, the algorithm should be run with the same settings for every c—same m, same tolerance, same initialization strategy—and with enough restarts that a poor local optimum at one c does not masquerade as a bad c. Second, the suggested optimum of every index should be read together with its curve: an index that decreases monotonically has its extremum at cmax ⁡ but may point elsewhere with its knee, and an index whose curve is flat over a range of c says that the data do not decide. The plotting helper plot_validity_scan min–max scales every index to [0,1] so that all curves fit one axis and their agreement is visible at a glance.

Algorithm

Compatible cluster merging turns the second route of fig. 4.1 into an algorithm (algorithm 4.2). It was introduced by Krishnapuram and Freg [39] for fitting an unknown number of lines and planes and adapted to fuzzy modeling by Kaymak and Babuška [40]. The partition with cmax ⁡ clusters is computed, every pair of clusters is judged by a compatibility criterion, the most compatible pair is merged, and the algorithm is re-run from the merged partition with one cluster fewer, until no pair passes the thresholds. Merging adds the two membership columns, μ(ij) = μi + μj; the first iteration of the refit then computes the membership-weighted center and covariance of the union, which is what Kelly’s merging formulas [41] give in closed form. Two families of criteria are implemented.

Merging needs at most cmax ⁡ −c∗ refits, each started close to its solution, against cmax ⁡ −1 refits from scratch for a scan, and the clusters it ends with are interpretable as local models. This is why it is also the route taken in the fuzzy segmentation of time series (section 9.2.1), with a similarity of local PCA models as criterion, and in the analysis of the MST clustering (section 7.2.3), where the membership similarity of the refined clusters shows which of them may be merged; the volume-prototype clustering of chapter 6 merges by (4.17) within a single run, each time the partition has converged, without refitting from scratch.

Algorithm

In a nutshell: Compatible cluster merging

  • Starts with too many clusters and merges the most compatible pair, refitting after every merge, until no compatible pair remains: the number of clusters is a result, not an input.
  • Geometric criterion (parallel normals, common hyperplane, close centers) for thin clusters and local linear models; membership similarity Sij for clusters of any shape.
  • Cheaper than a scan (cmax ⁡ −c∗ warm-started refits) and insensitive to cmax ⁡ as long as it is large enough.
  • The thresholds are the parameters; for the similarity criterion γS = 0.2 separates “one group” (S ≈0.3–0.35) from “two groups”.
  • Parameters: base_estimator, start_n_clusters, min_n_clusters, criterion, parallel_threshold, hyperplane_threshold, distance_threshold, thin_threshold, similarity_threshold; attributes merge_history_, estimator_.

4.2.8 Comparing fuzzy partitions

The indices so far judge a partition against the data. A different question is how similar two partitions are, for example those of two algorithms, of two numbers of clusters, or of two runs on resampled data, or a partition and a known reference. For hard partitions the Rand index answers it by counting the pairs of samples on which the partitions agree—together in both or apart in both—and the adjusted Rand index of Hubert and Arabie [44] removes the agreement expected by chance. Both have fuzzy generalizations, and both reduce to the classical indices when the partitions are hard.

Hüllermeier, Rifqi, Henzgen, and Senge [45] read a fuzzy partition as a fuzzy equivalence relation, the degree to which samples k and l are in the same cluster,

EU(k,l) = 1 −1 2 ∑ i=1c |μ ik −μil| ,
(4.18)

one for identical membership vectors and zero for disjoint ones, and define the fuzzy Rand index as one minus the mean distance between the relations of two partitions U1 and U2 (possibly with different numbers of clusters),

R(U1,U2) = 1 − ∑ k<l |E1(k,l) −E2(k,l)| N(N −1)∕2 .
(4.19)

The paper defines no adjusted index. For a chance-corrected comparison the toolbox therefore builds fuzzy pair counts from the two relations with the Łukasiewicz t-norm ⊤ ⁡(a,b) = max ⁡ (a + b −1,0); this construction is the book’s own (the Jaccard-type measures of Hüllermeier et al. split the pairs differently, with the product t-norm). The degrees to which a pair is together in both partitions, together only in the first, only in the second, and apart in both are n11 = ∑ ⁡ k<l⊤ ⁡(E1,E2), n10 = ∑ ⁡ k<l⊤ ⁡(E1,1 −E2), n01 = ∑ ⁡ k<l⊤ ⁡(1 −E1,E2) and n00 = ∑ ⁡ k<l⊤ ⁡(1 −E1,1 −E2), and they give a count-based Rand index (n11 + n00)∕np with np = n11 + n10 + n01 + n00. For hard partitions np = N(N −1)∕2 and the count-based form equals (4.19); for soft partitions it does not, because the four degrees of a pair need not sum to one (n11 + n00 per pair is |E1 + E2 −1|, n10 + n01 is |E1 −E2|), so the toolbox uses the distance form (4.19), the definition of [45], as the fuzzy Rand index. With Hubert and Arabie’s correction the counts give the fuzzy adjusted Rand index

ARI = n11 −e 1 2((n11 + n10) + (n11 + n01)) −e,e = (n11 + n10)(n11 + n01) np ,
(4.20)

where e is the agreement expected by chance, and the fuzzy Jaccard index n11∕(n11 + n10 + n01). Campello [46] builds the counts differently, from the degrees that a pair is in the same cluster, V kl = ∑ ⁡ i⊤ ⁡(μik,μil), and in different clusters, Xkl = ∑ ⁡ i≠j⊤ ⁡(μik,μjl), combined with a t-norm across the two partitions (n11 = ∑ ⁡ k<l⊤ ⁡(V kl(1),V kl(2)), n10 = ∑ ⁡ k<l⊤ ⁡(V kl(1),Xkl(2)), and so on). With the product t-norm, Campello’s index is not reflexive for fuzzy partitions: a partition compared with itself scores below one, the more so the fuzzier it is. It is useful for ranking partitions against a reference, whereas the index of Hüllermeier et al. is a proper metric-based similarity.

The raw fuzzy Rand index is dominated by the pairs that are apart in both partitions, of which there are many when c is large, so it is close to one for almost any pair of reasonable partitions; the adjusted index is the one to read. A fuzzy partition and the hard partition obtained by hardening it do not reach an adjusted index of one: the index measures the agreement of the relations, and memberships below one are a genuine difference.

In a nutshell: Comparing fuzzy partitions

  • Fuzzy Rand, adjusted Rand, and Jaccard indices compare two partitions of the same samples, with any numbers of clusters, any algorithms, hard or fuzzy.
  • Hüllermeier et al.: distance between the fuzzy equivalence relations EU(k,l); reflexive, reduces to the classical indices for hard partitions.
  • Campello: t-norm-based counts of “same cluster” and “different clusters”; not reflexive for fuzzy partitions with the product t-norm.
  • Read the adjusted index (zero for chance agreement); the raw index is near one for large c.
  • Uses: comparing algorithms and numbers of clusters, comparing with a reference partition, and the stability selection below.

4.2.9 Stability-based selection of the number of clusters

A third route to the number of clusters asks for reproducibility instead of geometry: if the data contain c∗ groups, a partition into c∗ clusters should be nearly the same on different samples of the data, whereas a partition into too many clusters splits a group at a place that depends on the sample and a partition into too few merges groups in a sample-dependent way. Ben-Hur, Elisseeff, and Guyon [47] cluster two random sub-samples of a fraction f of the data and compare the two partitions on the samples they share; Lange, Roth, Braun, and Buhmann [48] split the data into two halves, cluster both, let the model of the first half predict the second half, and compare the prediction with the second half’s own partition. For a fuzzy clusterer the prediction is predict_proba, and the comparison is the fuzzy adjusted Rand index (4.20), which is zero for chance agreement and therefore needs no further normalization across c (the raw Rand index increases with c). Repeating the procedure gives a distribution of agreements for every c; a stable number of clusters has a mean near one and a small spread (algorithm 4.3). The sub-sample fraction must leave room for variation: with f close to one the sub-samples are nearly identical and every c looks stable.

Algorithm

In a nutshell: Stability selection

  • Chooses the c whose partitions are reproducible across resamples: sub-sample pairs (Ben-Hur et al.) or split-half prediction (Lange et al.).
  • Needs no assumption about cluster shape beyond the clusterer’s own; compares partitions with the fuzzy adjusted Rand index.
  • Read mean and spread per c; a large spread at a c means that the partition depends on the sample.
  • Costs 2B fits per c (the most expensive route); the sub-sample fraction should lie between about 0.5 and 0.8.
  • Parameters: n_clusters_range, n_splits, method, subsample, index, random_state.

In a nutshell: Validity indices

  • Sixteen indices in four families: fuzziness of U (PC, CE, MPC), compactness/separation (SC, S, XB, FS, PBMF, KWON, PCAES), crisp (DI, ADI, SIL), and volume and density (FHV, PD, APD); all with Euclidean distances.
  • Direction of the optimum is in INDEX_DIRECTION; PC and CE are monotone in c on overlapping data (read the knee); XB and S jump when two prototypes first share a group (read the first minimum).
  • Scan c with identical settings and enough restarts; prefer the c on which the geometric indices agree; confirm visually.
  • Compatible cluster merging (section 4.2.7) is the alternative when clusters are local models, ordered segments, or nodes of a tree (chapters 7 to 9), stability selection (section 4.2.9) when reproducibility is the criterion.
  • An index extremum is a hint, not a proof: indices measure geometric separation, not agreement with any external labels.

4.3 Using it in fuzzyclust

fuzzyclust.validity.<index>(X, U, V, m=2.0)

Every index is a function with the same signature: X (N,n), U the membership matrix (N,c) as stored by the estimators (i.e. UT), V the prototypes (c,n) and m the exponent the algorithm used. PC, CE, and MPC ignore X and V; DI, ADI, and SIL harden U first; FHV, PD, and APD compute the fuzzy covariances from X, U, V, and m. The functions are partition_coefficient (PC), classification_entropy (CE), modified_partition_coefficient (MPC), partition_index (SC), separation_index (S), xie_beni (XB), fukuyama_sugeno (FS), dunn_index (DI), alternative_dunn_index (ADI), silhouette (SIL), fuzzy_hypervolume (FHV), partition_density (PD), average_partition_density (APD), pbmf_index (PBMF), kwon_index (KWON), and pcaes_index (PCAES); the indices that need a separation between prototypes (SC, S, XB, KWON, PCAES) return nan for a single cluster. validity_indices(X, U, V, m=2.0, indices=None) evaluates a subset or all of them and returns a dict. INDEX_DIRECTION maps every short name to "max" or "min".

fuzzyclust.validity.scan_n_clusters(estimator, X, n_clusters_range=range( 2, 11), indices=None)

Clones the estimator (any fuzzyclust clusterer, fitted or not), sets n_clusters to every value of the range, fits, and returns a pandas.DataFrame indexed by n_clusters with one column per index. The exponent is taken from the estimator’s m. suggest_n_clusters(table) returns a Series with the arg-max or arg-min of every column according to INDEX_DIRECTION; for PC and CE the knee is often the better reading, so the raw suggestion is reported for completeness only.

fuzzyclust.plotting.plot_validity_scan(table, ax=None, normalize=True)

Plots every column of a scan table against c, min–max scaled to [0,1] by default so that all indices share one axis; the legend states the direction of each optimum. Pass a column subset, e.g. table[["XB", "S", "SIL"]], to compare families separately.

fuzzyclust.validity.fuzzy_rand_index(U1, U2, method="huellermeier",  tnorm=None)

Fuzzy Rand index (4.19) of two membership matrices of the same samples, (N,c1) and (N,c2); hard partitions are passed as one-hot matrices, which fuzzyclust._utils.labels_to_membership builds from labels. method="campello" uses Campello’s counts; tnorm is "product", "minimum", or "lukasiewicz" (None: the distance form (4.19) for Hüllermeier, product for Campello; a t-norm selects the count-based form). fuzzy_adjusted_rand_index (4.20) and fuzzy_jaccard_index take the same arguments. The pairwise relations need O(N2c) memory, so compare sub-samples of a few thousand samples at most.

fuzzyclust.validity.stability_selection(estimator, X,  n_clusters_range=range(2, 11), n_splits=20, method="subsample",  subsample=0.8, index="fuzzy_ari", random_state=None)

Stability selection as in section 4.2.9; method is "subsample" (Ben-Hur et al.) or "split" (Lange et al.); index one of "fuzzy_ari", "fuzzy_rand", "fuzzy_jaccard". Returns a DataFrame indexed by n_clusters with one column per repetition; table.mean(axis=1).idxmax() is the most stable c, and table.T can be passed to a box plot.

fuzzyclust.cluster.CompatibleClusterMerging

base_estimator=None, start_n_clusters=8, min_n_clusters=1, criterion="geometric", parallel_threshold=0.95, hyperplane_threshold=0.5, distance_threshold=2.0, thin_threshold=0.2, similarity_threshold=0.2. base_estimator=None means GK(random_state=0); any fuzzyclust clusterer is accepted; its n_clusters and init are overridden. The four geometric thresholds are γ1,…,γ4, similarity_threshold is γS. Attributes: n_clusters_, estimator_ (the final fitted model), merge_history_ (one dict per merge with n_clusters, pair, compatibility), compatibility_, and cluster_centers_, membership_, labels_, distances_ of the final model; predict, predict_proba, and transform delegate to it. The helper functions cluster_similarity(U) and geometric_compatibility(V, F, ...) compute the two criteria.

The three routes in a few lines:

ccm = CompatibleClusterMerging(FCM(random_state=0), start_n_clusters=10, criterion="similarity", 
                               similarity_threshold=0.2).fit(X) 
for step in ccm.merge_history_: 
    print(f"c = {step[’n_clusters’]:2d}: merge clusters {step[’pair’]} (similarity {step[’compatibility’]:.2f})") 
print(f"final number of clusters: {ccm.n_clusters_}")
   
table = scan_n_clusters(FCM(random_state=0, n_init=3), X, range(2, 10), 
                        indices=["XB", "KWON", "PCAES", "PBMF", "SIL"]) 
print(suggest_n_clusters(table).to_dict()) 
stab = stability_selection(FCM(random_state=0), X, range(2, 10), n_splits=20, method="subsample", 
                           random_state=0) 
stab_split = stability_selection(FCM(random_state=0), X, range(2, 10), n_splits=20, method="split", 
                                 random_state=0) 
print("most stable c (subsample, split):", stab.mean(axis=1).idxmax(), stab_split.mean(axis=1).idxmax())
                                                                     

                                                                     
   

and the comparison of partitions obtained in different ways:

partitions = { 
    "truth": labels_to_membership(y, 5), 
    "FCM c=5": FCM(n_clusters=5, random_state=0).fit(X).membership_, 
    "GK c=5": GK(n_clusters=5, random_state=0).fit(X).membership_, 
    "merging": ccm.membership_, 
    "FCM c=4": FCM(n_clusters=4, random_state=0).fit(X).membership_, 
    "FCM c=8": FCM(n_clusters=8, random_state=0).fit(X).membership_, 
} 
names = list(partitions) 
ari = np.array([[fuzzy_adjusted_rand_index(partitions[a], partitions[b]) for b in names] for a in names])
   

A complete scan with all indices and its plot:

from fuzzyclust.validity import scan_n_clusters, suggest_n_clusters 
from fuzzyclust.plotting import plot_validity_scan 
 
table = scan_n_clusters(FCM(m=2.0, random_state=0, n_init=5), X, range(2, 10)) 
print(suggest_n_clusters(table)) 
plot_validity_scan(table[["SC", "S", "XB", "DI", "ADI", "SIL"]])

Because every index is a plain function of (X, U, V, m), it can also score held-out data through predict_proba, which is how the grid search of section 2.4.4 selects c and m with the Xie–Beni index:

def neg_xie_beni(estimator, X):            # scikit-learn scorer: higher is better 
    U = estimator.predict_proba(X) 
    return -validity_indices(X, U, estimator.cluster_centers_, m=estimator.m, indices=["XB"])["XB"]

4.4 Examples

4.4.1 A validity scan on five clusters

The script plot_05_validity_scan.py generates five compact Gaussian clusters and scans FCM for c = 2,…,9. Table 4.2 lists the index values; thirteen of the fourteen indices place their optimum at c = 5, and only SC, which is designed for comparing partitions with equal c and decreases with c, suggests cmax ⁡ . The two indices of section 4.2.5, which the script computes as well, disagree: KWON has its minimum at five (20.8, against 26.7 at c = 3 and above 200 for c ≥6), PCAES its maximum at six (9.8 against 3.4 at five), a jump caused by a small sixth cluster whose mass μM divides the first sum of (4.16). On these well-separated data even PC and CE have a genuine extremum at five, whereas on the overlapping motorcycle data of the MATLAB manual they were monotone and only their knee was informative. Figure 4.3 shows the normalized curves. The ratio indices XB and S fall steeply from c = 2 to c = 3, reach their minimum at c = 5, and jump to a much larger value at c = 6, when a prototype is first placed inside an existing group and the minimal center distance collapses. DI has a sharp peak because five is the only c at which every pair of hardened clusters is separated by a clear gap; at every other c some pair nearly touches. The script also scans GK on the same data: with adaptive shapes its XB and SIL values are close to those of FCM, and the two algorithms agree on c = 5. Finally, it repeats the FCM scan for m from 1.3 to 3. XB, DI, SIL, and MPC select five clusters for every exponent, and S, FS, and ADI deviate only at the ends of the range, whereas PC and CE select c = 5 for m ≤2 and c = 2 for m ≥2.5: a softer partition makes fewer clusters look less fuzzy, which is the dependence on m noted in section 4.2.1.

Table 4.2. Validity scan of FCM (m = 2) on five Gaussian clusters, c = 2,…,9 (script plot_05_validity_scan.py). Bold: optimum of each index. S (not shown) equals XB because m = 2; ADI (not shown) is 0.006 at c = 5 and below 0.0005 elsewhere.
c PC CE MPC SC XB FS DI SIL FHV PD APD PBMF
2 0.733 0.416 0.466 0.507 0.254 643 0.020 0.449 5.55 28.8 28.9 22.7
3 0.746 0.470 0.618 0.083 0.066 − 2962 0.004 0.588 3.42 43.9 45.5 51.9
4 0.774 0.460 0.699 0.048 0.068 −3735 0.012 0.619 2.33 69.5 74.5 85.9
5 0.834 0.383 0.793 0.021 0.049 −4335 0.155 0.715 1.52 105.3 105.5 98.4
6 0.767 0.516 0.720 0.021 0.617 −4150 0.019 0.623 1.75 94.0 95.5 90.5
7 0.709 0.623 0.661 0.017 0.553 −3838 0.022 0.537 1.90 85.0 86.6 85.4
8 0.665 0.711 0.617 0.014 0.549 −3587 0.019 0.459 1.93 83.4 84.9 87.6
9 0.626 0.780 0.579 0.011 0.463 −3342 0.019 0.375 1.94 81.0 82.6 98.1

Figure 4.3

Figure 4.3. Validity scan of FCM on five Gaussian clusters, indices min–max scaled to [0,1]. Left: the partition-based indices have their extremum at c = 5 because the clusters are well separated. Right: apart from SC, which decreases with c, the geometric indices agree on c = 5; XB and S (identical for m = 2, so only the XB curve is visible) jump when a sixth prototype enters an existing group, and DI and ADI peak sharply.

Open in ColabExample plot_05_validity_scan.py in the gallery

4.4.2 Three routes on the same data

The script plot_14_merging_stability.py runs merging, the validity scan, and stability selection on five Gaussian groups of different sizes and spreads. Compatible cluster merging with the similarity criterion starts from ten FCM clusters (fig. 4.4, left), in which three of the groups are covered by two or three prototypes each. The five merges join clusters with similarities between 0.36 and 0.30—each time two clusters on one group—and after the fifth merge the largest similarity left is 0.10, well below the threshold 0.2: the procedure stops at five clusters, whose partition coincides with that of FCM run directly with c = 5 (fuzzy adjusted Rand index 1.00).

Figure 4.4

Figure 4.4. Compatible cluster merging with the similarity criterion on five groups. Left: FCM with cmax ⁡ = 10. Middle: the largest similarity Sij before every merge; it falls below the threshold (dashed) after the partition has reached five clusters. Right: the final partition.

Open in ColabExample plot_14_merging_stability.py in the gallery

The validity scan and the stability selection are shown in fig. 4.5. XB, the Kwon index, and the silhouette select five clusters, PBMF six, and PCAES has its maximum at nine, where FCM creates a cluster of a few samples whose small mass inflates the first sum of (4.16); up to c = 6 its curve rises steadily, so it does not reject five either. The stability profile gives the clearest answer: for c = 5 the twenty sub-sample pairs agree with a mean fuzzy adjusted Rand index of 0.97 and a standard deviation of 0.008, while for c = 4 the mean is 0.88 and the spread twenty times larger, because which two groups are merged depends on the sub-sample; the split-half protocol peaks at five as well (0.92).

Figure 4.5

Figure 4.5. Validity scan (left) and stability selection (right) on the same five groups. The box plots show the fuzzy adjusted Rand index of twenty pairs of 80 % sub-samples for every c, the squares the mean of the split-half protocol; both peak at c = 5, where the box is also the narrowest.

Figure 4.6 compares six partitions of the data: the generating labels as a one-hot matrix, FCM and GK with five clusters, the merged partition, and FCM with four and eight clusters. The raw fuzzy Rand index (left) is above 0.8 for every pair and hardly discriminates; the adjusted index (middle) does: FCM, GK, and the merged partition agree with each other (0.95 to 1.00) and with the truth (0.70, the memberships below one keep the value below one), whereas FCM with four or eight clusters reaches only 0.58 and 0.56 against the truth. Campello’s index with the product t-norm (right) ranks the partitions against the truth in the same order but is not reflexive: every fuzzy partition compared with itself scores only 0.42 to 0.54.

Figure 4.6

Figure 4.6. Fuzzy Rand index of Hüllermeier et al., the fuzzy adjusted Rand index from Łukasiewicz pair counts, and Campello’s fuzzy adjusted Rand index between six partitions of the same data. Only the adjusted indices separate the good partitions from those with a wrong number of clusters; Campello’s index is below one on the diagonal for fuzzy partitions.

The geometric criterion is demonstrated on three noisy line segments (fig. 4.7): Gustafson–Kessel with ten clusters cuts every segment into thin pieces, and merging pieces with parallel normals on a common line leaves three clusters (fuzzy adjusted Rand index 0.83 with the truth). The parameter study (fig. 4.8) shows a wide plateau of the similarity threshold: every value from 0.10 to 0.25 ends at five clusters, 0.30 stops one merge early, 0.35 and above hardly merge at all, and 0.05 merges distinct groups down to a single cluster. For the stability selection, sub-samples of 50 % and 80 % both select five clusters, the smaller fraction with lower agreements for every c except four, where the two are equal; with 95 % the sub-samples are nearly identical and four clusters appear almost as stable as five (0.983 against 0.987), which is why the fraction must leave room for variation.

Figure 4.7

Figure 4.7. Compatible cluster merging with the geometric criterion on three line segments: GK with ten clusters (left) and the three clusters left after merging pieces with parallel normals on a common line (right).

Figure 4.8

Figure 4.8. Parameter study: the final number of clusters of the similarity merging against its threshold (left) and the mean stability profile for three sub-sample fractions (right).

4.4.3 Combining indices and reading a scan

The scan above is the easy case. In practice the indices disagree, and the following rules of thumb, distilled from the MATLAB manual’s motorcycle study and from the examples of this book, help in reading them. Prefer the c on which XB, S, and SIL agree, and take the first pronounced minimum of XB rather than its global one. Use SC and PC/CE to compare partitions with the same c and the same m—different algorithms or initializations—rather than across c. Treat DI and ADI as confirmations for well-separated data and ignore them when the clusters overlap. Use FHV , PD, and APD for GK and GG partitions of ellipsoidal clusters, and distrust them whenever a covariance matrix is nearly singular. When the differences between neighboring c are minor, choose the smaller c. And when the indices leave two candidates, let the picture decide. Figure 5.14 in chapter 5 shows FCM partitions of the breast cancer data for c = 2,3,4 projected with the fuzzy Sammon mapping. The indices PC, CE, and XB favor two clusters (SC, which decreases with c, points to four); the pictures show why—the third prototype splits the large benign group, the fourth the malignant one, and the clusters overlap in the projection—and also where the ambiguous cases lie.

4.4.4 New data as validation

A partition that describes structure rather than noise should generalize: samples that were not used for fitting should fall into the same regions with the same confidence as the training samples. The script of section 3.4.7 (plot_06_predict_new_data.py) fits GK on 60 % of three elongated clusters and evaluates the remaining 40 % with predict_proba (fig. 4.9). The test samples fall into the membership regions learned from the training data; their memberships and their distances to the prototypes (transform) have the same distribution as those of the training set. Three uses follow. Held-out validity indices computed from predict_proba are less optimistic than training indices and can drive a grid search over c and m (section 2.4.4). The stability of the partition across random train/test splits or bootstrap samples is itself a validity criterion (section 4.2.9): a c whose prototypes move little between resamples is supported by the data. Finally, a new sample whose maximal membership is low and whose distance to the nearest prototype is large—the far-away point of the script has a maximal membership of 0.52 and a distance of 28, against a training median of 1.2—is a novelty, which is the basis of clustering-based process monitoring.

Figure 4.9

Figure 4.9. Gustafson–Kessel fitted on 60 % of the data and evaluated on the rest: the test samples (open markers, colored by predicted label) fall into the membership regions learned from the training data. Held-out memberships and distances validate the partition and detect novelties.

Open in ColabExample plot_06_predict_new_data.py in the gallery

4.5 Further reading

The partition coefficient and classification entropy are Bezdek’s [3], the modified partition coefficient Davé’s [29]; the partition index is from Bensaid et al. [30], the Xie–Beni index, whose original form is the separation index S, from [31], with the analysis of its dependence on m by Pal and Bezdek [32], and the Fukuyama–Sugeno index from [33]. Dunn’s index is in [35], the silhouette in Rousseeuw [36], and the PBM-F index in Pakhira, Bandyopadhyay, and Maulik [34]; the alternative Dunn index is from the MATLAB toolbox manual [12]. The fuzzy hypervolume and the partition densities are from Gath and Geva [21]. Compatible cluster merging goes back to Krishnapuram and Freg [39] and was brought to fuzzy modeling by Kaymak and Babuška [40], with Kelly’s merging formulas [41]; adaptive merging by membership similarity is from Kaymak and Setnes [43], and the Jaccard similarity used by the toolbox from Setnes et al. [42]. The Kwon index is in [37], the PCAES index in Wu and Yang [38], who also compare it with many of the indices above. The fuzzy Rand indices are from Hüllermeier et al. [45] and Campello [46], the adjustment for chance from Hubert and Arabie [44]; stability-based validation is developed by Ben-Hur, Elisseeff, and Guyon [47] and Lange et al. [48]. Babuška [7] discusses validity scans and cluster merging in the context of fuzzy modeling, and Höppner et al. [6] survey validity measures for the whole objective-function family.