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 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.
- Validity scans. The algorithm is run for every , a validity index is computed for every partition, and the at which the index is extremal (or has a knee) is selected. The index may evaluate the whole partition—the usual case, and the one treated here—or the individual clusters, in which case poor clusters are removed and similar ones joined.
- Compatible cluster merging. The algorithm starts with a deliberately large , and the number of clusters is reduced step by step by merging pairs of clusters that are compatible according to some criterion, re-clustering after every merge, until no compatible pair remains.
- Stability selection. The data are resampled, the algorithm is run on every sample for every candidate , and the whose partitions agree best across the samples is selected; agreement is measured by a fuzzy generalization of the Rand index.
The scan is general and simple but costs 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 .
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, summed over clusters; it is small when the clusters are tight. Separation is the distance between the prototypes, , 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.
4.2 Theory
Throughout, is the partition, the prototypes, the exponent the algorithm used, the fuzzy cardinality of cluster , and 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],
|
| (4.1) |
measures the amount of overlap between the clusters: it is one for a hard partition and for the fuzziest one, and a larger value is better. The classification entropy
|
| (4.2) |
measures the same fuzziness with Shannon’s entropy: it is zero for a hard partition and for the fuzziest one; lower is better. Both need nothing but , 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 — decreases and 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 (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 , so they cannot compare partitions obtained with different exponents, and they are useless for hard partitions (, always). Davé’s modified partition coefficient [29],
|
| (4.3) |
rescales from its range to and thereby reduces the monotone trend; higher is better.
4.2.2 Compactness and separation indices
The partition index of Bensaid et al. [30],
|
| (4.4) |
is a sum of cluster-wise validities, the compactness of cluster over its separation from all other prototypes, each normalized by the fuzzy cardinality 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 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,
|
| (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 of the algorithm instead of the square, the form analyzed by Pal and Bezdek [32],
|
| (4.6) |
It is the compactness ( for Euclidean FCM) over the minimal separation; for it coincides with , and , , and differ mainly in how the separation is aggregated. 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 , when the minimal center distance shrinks only slowly while the compactness keeps improving. Pal and Bezdek showed that the index is reliable for between about and . The Fukuyama–Sugeno index [33],
|
| (4.7) |
is compactness minus separation, where the separation of cluster 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 on data with one dominant group. The PBM-F index of Pakhira, Bandyopadhyay, and Maulik [34],
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 explicitly by the factor ; 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 . Dunn’s index [35],
|
| (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 pairwise distances are needed, so it is —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, , which needs only the distances of the samples to the prototypes:
|
| (4.10) |
Higher is better; the bound is loose (two samples at the same distance from but on opposite sides give zero), so 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 to the members of its own cluster with the smallest mean distance to the members of another cluster,
|
| (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 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 of (3.10) and therefore fit the ellipsoidal clusters of GK and GG. The fuzzy hypervolume
|
| (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
|
| (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
|
| (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 , whereas 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 tiny and huge for a degenerate partition. They are computed from the fuzzy (not the hardened) partition, with weighted by , whatever algorithm produced .
4.2.5 Two further compactness and separation indices
The Xie–Beni index decreases again for large 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,
|
| (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 , the index equals plus the punishing term divided by the minimal separation; it inherits the reaction of and to a close pair of prototypes but not their decrease at large . Wu and Yang [38] combined a cluster-wise partition coefficient with an exponential separation in the partition coefficient and exponential separation index,
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 of the prototypes. The index thus judges clusters individually rather than through one global ratio. Since the first sum is at least and the penalty at most , the index is nonnegative. Its weak point is the normalization by the smallest cluster mass : a spurious cluster with very few members inflates every ratio of the first sum, and the index then favors a large (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, , , and 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 is possible (small ) and so is a fuzzy partition of the right one (overlapping groups). Second, the ratio indices and 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 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.
| Index | Opt. | Measures | Weakness |
| PC | max | fuzziness of only, eq. (4.1) | monotone in , no link to the data, depends on |
| CE | min | entropy of , eq. (4.2) | same as PC |
| MPC | max | PC rescaled to , eq. (4.3) | no link to the data |
| SC | min | compactness / summed separation per cluster, eq. (4.4) | decreases with ; meant for equal |
| S | min | compactness () / minimal separation, eq. (4.5) | sensitive to one close pair of prototypes |
| XB | min | compactness () / minimal separation, eq. (4.6) | decreases again for large ; use the first minimum |
| FS | min | compactness separation from the grand mean, eq. (4.7) | scale-dependent; favors small |
| DI | max | min inter-cluster distance / max diameter (crisp), eq. (4.9) | ; 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) | ; ignores memberships |
| FHV | min | total cluster volume , 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 , 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 , fit, evaluate the indices, and tabulate. Two details matter. First, the algorithm should be run with the same settings for every —same , same tolerance, same initialization strategy—and with enough restarts that a poor local optimum at one does not masquerade as a bad . Second, the suggested optimum of every index should be read together with its curve: an index that decreases monotonically has its extremum at but may point elsewhere with its knee, and an index whose curve is flat over a range of says that the data do not decide. The plotting helper plot_validity_scan min–max scales every index to so that all curves fit one axis and their agreement is visible at a glance.
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 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, ; 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.
- The geometric criterion follows Krishnapuram and Freg and suits thin clusters: lines, planes, and local linear models. With the eigenvector of the smallest eigenvalue of (the normal of the cluster) and its extent along the main axis, two thin clusters () are compatible if their normals are parallel, , their centers lie on a common hyperplane, , and the centers are close, .
-
The similarity criterion works for clusters of any shape: two clusters are compatible if their membership functions, seen as fuzzy sets over the samples, are similar. The toolbox measures this with the fuzzy Jaccard similarity of the two columns of [42],
(4.17) with a fixed threshold , evaluated after every converged fit. Kaymak and Setnes [43], who introduced adaptive merging by membership similarity, use a fuzzy inclusion measure instead, with , and merge during the iteration: as soon as the largest similarity has stopped changing and exceeds for the current number of clusters . Two FCM clusters that share one Gaussian group have – for and any , two clusters on separate groups less than ; to make the threshold independent of the exponent, the toolbox evaluates on the partition rescaled to , .
Merging needs at most refits, each started close to its solution, against 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.
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 for clusters of any shape.
- Cheaper than a scan ( warm-started refits) and insensitive to as long as it is large enough.
- The thresholds are the parameters; for the similarity criterion separates “one group” (–) 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 and are in the same cluster,
|
| (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 and (possibly with different numbers of clusters),
|
| (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 ; 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 , , and , and they give a count-based Rand index with . For hard partitions 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 ( per pair is , is ), 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
|
| (4.20) |
where is the agreement expected by chance, and the fuzzy Jaccard index . Campello [46] builds the counts differently, from the degrees that a pair is in the same cluster, , and in different clusters, , combined with a t-norm across the two partitions (, , 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 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 ; 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 .
- 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 groups, a partition into 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 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 (the raw Rand index increases with ). Repeating the procedure gives a distribution of agreements for every ; 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 close to one the sub-samples are nearly identical and every looks stable.
In a nutshell: Stability selection
- Chooses the 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 ; a large spread at a means that the partition depends on the sample.
- Costs fits per (the most expensive route); the sub-sample fraction should lie between about and .
- Parameters: n_clusters_range, n_splits, method, subsample, index, random_state.
In a nutshell: Validity indices
- Sixteen indices in four families: fuzziness of (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 on overlapping data (read the knee); XB and S jump when two prototypes first share a group (read the first minimum).
- Scan with identical settings and enough restarts; prefer the 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 , U the membership matrix as stored by the estimators (i.e. ), V the prototypes 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 , min–max scaled to 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, and ; 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 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 , 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 , similarity_threshold is . 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 and 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 . Table 4.2 lists the index values; thirteen of the fourteen indices place their optimum at , and only , which is designed for comparing partitions with equal and decreases with , suggests . The two indices of section 4.2.5, which the script computes as well, disagree: has its minimum at five (, against at and above for ), its maximum at six ( against at five), a jump caused by a small sixth cluster whose mass divides the first sum of (4.16). On these well-separated data even and 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 and fall steeply from to , reach their minimum at , and jump to a much larger value at , when a prototype is first placed inside an existing group and the minimal center distance collapses. has a sharp peak because five is the only at which every pair of hardened clusters is separated by a clear gap; at every other some pair nearly touches. The script also scans GK on the same data: with adaptive shapes its and values are close to those of FCM, and the two algorithms agree on . Finally, it repeats the FCM scan for from to . , , , and select five clusters for every exponent, and , , and deviate only at the ends of the range, whereas and select for and for : a softer partition makes fewer clusters look less fuzzy, which is the dependence on noted in section 4.2.1.
| 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 | 0.004 | 0.588 | 3.42 | 43.9 | 45.5 | 51.9 | |
| 4 | 0.774 | 0.460 | 0.699 | 0.048 | 0.068 | 0.012 | 0.619 | 2.33 | 69.5 | 74.5 | 85.9 | |
| 5 | 0.834 | 0.383 | 0.793 | 0.021 | 0.049 | 0.155 | 0.715 | 1.52 | 105.3 | 105.5 | 98.4 | |
| 6 | 0.767 | 0.516 | 0.720 | 0.021 | 0.617 | 0.019 | 0.623 | 1.75 | 94.0 | 95.5 | 90.5 | |
| 7 | 0.709 | 0.623 | 0.661 | 0.017 | 0.553 | 0.022 | 0.537 | 1.90 | 85.0 | 86.6 | 85.4 | |
| 8 | 0.665 | 0.711 | 0.617 | 0.014 | 0.549 | 0.019 | 0.459 | 1.93 | 83.4 | 84.9 | 87.6 | |
| 9 | 0.626 | 0.780 | 0.579 | 0.011 | 0.463 | 0.019 | 0.375 | 1.94 | 81.0 | 82.6 | 98.1 |
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 and —each time two clusters on one group—and after the fifth merge the largest similarity left is , well below the threshold : the procedure stops at five clusters, whose partition coincides with that of FCM run directly with (fuzzy adjusted Rand index ).
Open in ColabExample plot_14_merging_stability.py in the gallery
The validity scan and the stability selection are shown in fig. 4.5. , the Kwon index, and the silhouette select five clusters, six, and 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 its curve rises steadily, so it does not reject five either. The stability profile gives the clearest answer: for the twenty sub-sample pairs agree with a mean fuzzy adjusted Rand index of and a standard deviation of , while for the mean is 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 ().
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 for every pair and hardly discriminates; the adjusted index (middle) does: FCM, GK, and the merged partition agree with each other ( to ) and with the truth (, the memberships below one keep the value below one), whereas FCM with four or eight clusters reaches only and 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 to .
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 with the truth). The parameter study (fig. 4.8) shows a wide plateau of the similarity threshold: every value from to ends at five clusters, stops one merge early, and above hardly merge at all, and 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 except four, where the two are equal; with 95 % the sub-samples are nearly identical and four clusters appear almost as stable as five ( against ), which is why the fraction must leave room for variation.
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 on which , , and agree, and take the first pronounced minimum of rather than its global one. Use and / to compare partitions with the same and the same —different algorithms or initializations—rather than across . Treat and as confirmations for well-separated data and ignore them when the clusters overlap. Use , , and for GK and GG partitions of ellipsoidal clusters, and distrust them whenever a covariance matrix is nearly singular. When the differences between neighboring are minor, choose the smaller . 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 projected with the fuzzy Sammon mapping. The indices , , and favor two clusters (, which decreases with , 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 and (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 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 and a distance of , against a training median of —is a novelty, which is the basis of clustering-based process monitoring.
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 , from [31], with the analysis of its dependence on 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.