Fuzzy Clustering and Data Analysis in PythonThe fuzzyclust toolbox

Chapter 7
Graph-based fuzzy clustering

Every algorithm so far described a cluster by a prototype (a point, an ellipsoid, a shell, a linear variety) and measured the distance of the samples to it. This chapter starts instead from a graph over the samples and presents two methods of the Abonyi group that find clusters of arbitrary shape and return to a prototype description where one is useful. The first builds the minimal spanning tree of the data, removes inconsistent edges by Zahn’s criteria, splits the subtrees further as long as the total fuzzy hypervolume decreases, and hands the crisp partition to Gath–Geva clustering, which turns it into a mixture of Gaussians with memberships, covariances and a similarity structure among the clusters. The second keeps the c-means functional but replaces the Euclidean distance by the geodesic distance along a nearest-neighbor graph and the centers by medoids, so that the clusters follow the manifold the data lie on. Both are in fuzzyclust.graph, need only SciPy’s sparse-graph routines, and reuse the Gath–Geva clusterer and the volume-based validity indices of earlier chapters.

7.1 Problem and idea

Prototype-based clustering answers the question “which prototype is this sample closest to?” and therefore inherits the geometry of the prototype: fuzzy c-means finds spheres, Gustafson–Kessel and Gath–Geva find ellipsoids, and the shell and variety algorithms find shells and subspaces. When the groups have none of these shapes (a chain of points, a bent arm, two interleaved spirals, rings), the prototypes can only tile the groups into pieces, and the pieces are not the clusters a human sees. Hierarchical and graph-theoretic clustering take the opposite view: a cluster is a set of samples that are connected to each other through short steps and separated from the rest by long ones, whatever the shape of the set. Zahn’s classical formulation [81] uses the minimal spanning tree (MST) of the data: the tree connects all N samples with N −1 edges of minimal total length, so that removing k edges leaves k + 1 subtrees that are candidate clusters (fig. 7.1, top). The tree keeps only N −1 of the N(N −1)∕2 pairwise distances, which makes the method cheap, and single-linkage clustering amounts to removing its edges in decreasing order of length [82].

Two problems arise. The first is deciding which edges are “inconsistent”. The longest edges separate clusters only when all clusters have the same density: a global threshold either leaves tight groups merged or shatters diffuse ones, and the local comparison with neighboring edges that Zahn proposed requires the user to choose a factor and a neighborhood depth. The second is that no length criterion can detect a chain: a thin sequence of points between two groups keeps every edge short, so the groups remain connected (fig. 7.1, bottom); this is the chaining effect of single linkage. Vathy-Fogarassy, Feil and Abonyi [83] solve both problems by combining the tree with fuzzy clustering. The tree is first cut by Zahn’s criteria; the subtrees are then split further at the edge that minimizes the total fuzzy hypervolume of the resulting clusters, which is Gath and Geva’s validity measure [21] used as a splitting criterion. A union of two compact groups, with or without a chain between them, has a far larger volume than its parts, whereas halving a Gaussian group increases the summed volume, so chains and bends are cut and Gaussian groups are left alone. Finally, the crisp tree partition initializes Gath–Geva clustering, which is too sensitive to its start to be run from a random partition on such data but turns a good start into a fuzzy, parametric description: centers, covariance matrices, memberships, and a similarity among the clusters that organizes them into a dendrogram.

Figure 7.1

Figure 7.1. Clustering with the minimal spanning tree. Top: the tree of two groups; the long edge eab between them is inconsistent because it is much longer than the edges in its tree neighborhood (Zahn’s local criterion), which also works when the groups have different densities. Bottom: a chain of points between two groups keeps every edge short and defeats all length criteria; the hybrid algorithm cuts the edge whose removal minimizes the summed fuzzy hypervolume of the two parts, because two compact groups have a much smaller volume than their elongated union.

The second method addresses a different failure of the prototype. Even where the groups are clear, the distance may be wrong: when the data lie on a curved low-dimensional manifold, such as a spiral arm (fig. 7.2) or an S-shaped sheet (fig. 7.18), two samples that are close in the Euclidean sense may be far apart along the manifold, and a center that is the mean of samples on both sides of a fold lies in empty space. Feil and Abonyi [84] replace the Euclidean distance by the geodesic distance: the length of the shortest path in a graph that links every sample with its k nearest neighbors, with the edges weighted by their Euclidean lengths. This is the distance Isomap [85] uses to unfold manifolds, and it converges to the true geodesic as the sampling becomes dense [86]. Because geodesic distances exist only between samples, the prototypes are restricted to samples, which makes the algorithm a fuzzy c-medoid method in the spirit of Kaufman and Rousseeuw [5] and places the medoids on the manifold automatically. The only structural parameter is k: if it is too small, the manifold falls apart into several graph components; if it is too large, edges “short-circuit” arms that come close to each other.

Figure 7.2

Figure 7.2. Geodesic distance on a neighborhood graph. Left: two spiral arms sampled by 22 points each, linked to their two nearest neighbors. The samples xk and xl are 3.6 apart in the plane but 8.0 along the arm; a Euclidean prototype between them would sit in empty space, whereas a medoid with geodesic distances stays on the arm. Right: with k = 2 the arms are separate components of the graph. They are bridged through their closest pair of points with a penalty equal to the largest within-component distance, so that all distances are finite but the two arms remain geodesically far apart.

7.2 Theory

The notation is that of the rest of the book: X ∈ ℝN×n with rows xk, memberships μik in the matrix U ∈ ℝc×N (stored transposed in the code), prototypes vi with index i (or j), samples with index k. We treat the hybrid MST–GG algorithm first (sections 7.2.1 to 7.2.3), then the geodesic distance (section 7.2.4) and the two clustering algorithms built on it (sections 7.2.5 and 7.2.6).

7.2.1 The minimal spanning tree and Zahn’s cutting criteria

Let G = (V,E) be the complete weighted graph on the samples, with edge weights w(ekl) = d(xk,xl) (Euclidean here; any metric would do). A spanning tree is a connected subgraph without cycles that reaches every vertex; the minimal spanning tree T = (V,ET ) is the one with the smallest total weight,

∑ e∈ETw(e) = min ⁡ ,|ET |= N −1,
(7.1)

computable by Prim’s algorithm in O(N2) time or by Kruskal’s in O(N2 log ⁡ N) [87, 88] (fuzzyclust uses SciPy’s implementation on the dense distance matrix). Removing k edges from T leaves k + 1 subtrees, and the sets of their vertices are the clusters; if δ is the length of a removed edge, no point on one side of it is closer than δ to a point on the other side. Clustering with the MST is therefore divisive hierarchical clustering, and the whole question is which edges to remove.

Criterion 1 (global threshold). Remove every edge longer than a multiple of the mean edge length,

w(e) > δ = λ 1 N −1∑ e′∈ETw(e′),
(7.2)

or remove the longest edges one by one until the desired number of clusters is reached. Both forms presuppose a single density: the mean is dominated by the largest group, and a tight pair of groups sits below the threshold while the tails of a diffuse group are cut off (fig. 7.7).

Criterion 2 (local inconsistency). Zahn [81] compares an edge with its surroundings instead. Let Nk(eab) be the set of tree edges within k steps of either endpoint a or b of the edge (not counting eab itself), with mean length w¯ and standard deviation σw. The edge is inconsistent when

w(eab) ≥fw¯(ratio form)orw(eab) > w¯ + sσw(deviation form),
(7.3)

with a factor f (typically 2–3) or a number of standard deviations s. The hybrid algorithm uses the ratio form; the deviation form, Zahn’s second proposal, needs a deeper neighborhood, because the standard deviation of a handful of edges is a poor reference. The reference length adapts to the surroundings of every edge, so groups of widely different density are separated (fig. 7.1, top), at the price of two parameters that interact: the deeper the neighborhood, the more stable the reference and the wider the range of factors that works. Both criteria cut edges in one pass; fuzzyclust applies the flagged cuts longest first and refuses a cut that would create a component smaller than min_cluster_size, which keeps single outliers from becoming clusters.

7.2.2 Criterion 3: splitting by the fuzzy hypervolume

Length criteria compare distances and are blind to chains. The hybrid algorithm therefore judges a candidate partition by the quality of the clusters it produces, using a validity measure as the splitting criterion. Varma and Simon [89] used the Fukuyama–Sugeno measure [33] in this role; Vathy-Fogarassy, Feil and Abonyi take the fuzzy hypervolume of Gath and Geva [21], because the clusters will be refined by Gath–Geva clustering, to which the hypervolume belongs. For a partition U with centers vj, the fuzzy covariance matrix, the hypervolume of cluster j and the total hypervolume are

Fj = ∑ k=1Nμjkm(xk −vj)(xk −vj)T ∑ k=1Nμjkm ,V j = det ⁡ F j,FHV = ∑ j=1cV j,
(7.4)

evaluated during the tree phase with the crisp memberships of the tree partition. The alternative criterion of Varma and Simon, in its crisp form,

FS = ∑ j=1c ∑ xk∈Sj ( ‖xk −vj‖ 2 − ‖v j −v¯‖2 ),
(7.5)

with v¯ the global mean, rewards compact clusters with distant centers and is available as criterion="fukuyama_sugeno".

The splitting starts with the subcluster of largest volume V i. Each of its Ni −1 tree edges is removed in turn, which produces a binary split into a and b and a candidate partition with total volume FHV −V i + V a + V b; the cut with the smallest total volume is the best split of this subcluster. fuzzyclust accepts the best split when its relative gain,

V i −V a −V b V i > min_gain,
(7.6)

exceeds a threshold (0.15 by default) and each part has at least min_cluster_size samples; otherwise the next largest subcluster is tried, and the procedure stops when no subcluster can be improved or max_clusters is reached. The threshold is the toolbox’s reading of the paper’s “special parameters that control the generalization level of the hierarchical clustering tree”: cutting a few tail points off a compact group always lowers the volume a little, and the relative gain separates such cosmetic cuts from real structure. The criterion spares Gaussian groups and breaks chains. Halving a Gaussian group along its principal axis reduces the variance along that axis to (1 −2∕π)σ2 ≈0.36σ2, so each half keeps about 0.6 of the volume and the two halves together have 1.2 times the volume of the whole; the split brings no gain. For two compact groups joined by a chain, the determinant of the union is inflated by the distance between the groups, and the parts are much smaller (fig. 7.1, bottom). A curved group is split into arcs for the same reason, and this is intended: every final cluster is then well approximated by one Gaussian, which is the representation the refinement needs. Evaluating all Ni −1 cuts is cheap: with the subtree rooted at any vertex, the count, the sum of xk and the sum of xkxkT below every vertex are accumulated in one pass from the leaves to the root, and the statistics of both sides of any edge follow by subtraction, so the statistics of all candidate cuts cost O(Nin2), plus two n ×n determinants (one for each side) per cut.

When the number of clusters is given (n_clusters=c), the same machinery is steered toward it: coarse cuts of Criteria 1–2 beyond c are undone shortest first, and the volume splitting continues with the best available cut, gain or no gain, until c clusters exist. This makes the estimator usable in the validity scans of the toolbox; the scan of the volume indices over c shows a knee at the number where the automatic rule stops (fig. 7.10).

7.2.3 Gath–Geva refinement and the analysis of the result

The tree partition is crisp and carries no model. In Step 4 of the algorithm it initializes Gath–Geva clustering with as many clusters as the tree partition has: the crisp membership matrix is the starting U, and the GG iterations (prior αi, center vi, fuzzy covariance Fi, exponential distance, membership update) run to convergence as in section 3.2.5. GG is a maximum-likelihood estimator of a Gaussian mixture and is notoriously sensitive to its initialization: started from FCM or at random on a chained or curved data set, it merges a group with a chain or splits a group. Here, however, it only has to polish the tree partition, and it does so without leaving it (fig. 7.5). The result is a fuzzy partition with centers, covariance matrices and priors: a compact parametric description of clusters whose shapes the tree found, and the basis of the membership contours and covariance ellipses in the figures. (FCM as refinement, refine="fcm", is pulled off the tree partition by the chain points; refine=None keeps the crisp partition with the covariances of the tree clusters.)

Two measures evaluate the result. The adequacy of a cut eab that produced clusters Ca ∋a and Cb ∋b is read off the refined memberships,

CP(eab) = ∑ k∈{a,b} |μik −μjk| ,i = cluster of a,j = cluster of b,
(7.7)

which is 2 when the two endpoints belong firmly to different clusters and 0 when the refinement has re-united them (cut_quality_). The clusters themselves are compared as fuzzy sets over the samples by the ratio of fuzzy intersection and union,

Sij = ∑ k=1N min ⁡ (μik,μjk) ∑ k=1N max ⁡ (μik,μjk) = |Ai ∩Aj| |Ai ∪Aj|,
(7.8)

a symmetric matrix with unit diagonal (cluster_similarity_). Used as the distance 1 −Sij in single-linkage clustering, it yields a dendrogram of the clusters: pieces of one nonconvex group share samples with intermediate memberships and join at a low level, while pieces of different groups do not, so the dendrogram shows which clusters may be merged and how they are related in the original space (fig. 7.12). GG memberships are nearly crisp, so the similarities are small (the dendrogram in the paper also spans only the range from 0.96 to 1), but their order carries the structure.

Algorithm

In a nutshell: Hybrid MST–GG clustering

  • Divisive clustering on the minimal spanning tree: Zahn’s global and local length criteria separate distinct groups (also of different density); the fuzzy hypervolume criterion cuts chains and bends that length criteria cannot see and spares Gaussian groups.
  • The tree partition initializes Gath–Geva clustering, which turns it into a mixture of Gaussians with memberships and covariances without destroying it; nonconvex groups come out as Gaussian pieces.
  • Parameters: factor f and depth k of the local criterion (f = 3–4 with k ≥3 in the examples), or a global λ; min_gain and min_cluster_size for the splitting; n_clusters to steer toward a given number.
  • Analysis: cut adequacy CP(e), similarity Sij of the fuzzy clusters and its dendrogram for merging and visualization; O(N2) memory for the distance matrix.

7.2.4 Geodesic distances on a neighborhood graph

Let the samples lie on (or near) a smooth manifold M ⊂ ℝn of lower dimension. The intrinsic distance between two samples is the length of the shortest curve on M connecting them, the geodesic distance dM, which can differ arbitrarily from the Euclidean chord (fig. 7.2, left). Isomap [85] approximates it in two steps. A neighborhood graph links each sample with its k nearest neighbors (k-Isomap) or with all samples within a radius 𝜀 (𝜀-Isomap), every edge weighted by its Euclidean length; the graph distance dg(xk,xl), the length of the shortest path found by Dijkstra’s or Floyd’s algorithm [90, 91], then stands in for dM. Bernstein et al. [86] prove that dg →dM as the sampling density grows: short edges follow the manifold, and the shortest path cannot cut through empty space because there are no edges there. The approximation is good when k (or 𝜀) is large enough for the graph to be connected along the manifold and small enough that no edge jumps across a gap between folds or arms (a “short-circuit”). The scale-free k is easier to set than 𝜀, and the number of connected components of the graph is the first diagnostic.

Components are the practical difficulty: if the graph is disconnected, the geodesic distance between components is undefined (infinite). The paper treats the components of the spiral as distinct manifolds that the clustering should keep apart. fuzzyclust follows this and makes it operational: components are linked through their closest pair of points by a bridge whose length is the Euclidean gap plus a penalty, by default equal to the largest finite geodesic distance of the unbridged graph (fig. 7.2, right). Every distance is then finite, and a path across a bridge is longer than any path inside a component, so clusters do not span components, while a component without a medoid still receives memberships through its bridge instead of being lost. The penalty can be set to zero when the components are known to be fragments of one manifold (k too small), in which case the plain bridge re-joins them at their natural junctions (fig. 7.20).

7.2.5 Algorithm II: geodesic distance based fuzzy c-medoids

The clustering minimizes the c-means functional of Bezdek [3] with geodesic distances and prototypes restricted to samples,

J = ∑ i=1c ∑ k=1Nμ ikmd g(xk,vi)2,v i ∈{x1,…,xN},
(7.9)

under the usual constraints ∑ ⁡ iμik = 1. The restriction is forced by the distance, since dg exists only between samples, and it is welcome: a medoid lies on the manifold by construction, whereas a mean of samples on both sides of a fold does not (fig. 7.18). The alternating optimization has the two familiar steps. For fixed medoids, the Lagrange conditions give the FCM membership formula with dg,

μik = 1 ∑ j=1c (dg(xk,vi)∕dg(xk,vj) )2∕(m−1),
(7.10)

and for fixed memberships every sample is tried as the medoid of every cluster, and the one with the smallest weighted sum of squared geodesic distances is taken,

vi = xj,j = argmin ⁡ l ∑ k=1Nμ ikmd g(xk,xl)2,
(7.11)

which is one matrix product Dg(2)(Um)T of the squared distance matrix with the powered memberships, O(cN2) per iteration. The iterations stop when the medoids no longer change (or max ⁡ |Δμik|< 𝜖). The paper starts from c arbitrary samples. fuzzyclust defaults to a D2-weighted seeding on geodesic distances (init="kmeans++"), because a medoid rarely migrates across a penalized bridge during the iterations: a random start that puts every medoid into one graph component leaves the other components without a prototype. Random starts with restarts are available as well. The dense geodesic distance matrix and the exhaustive medoid search limit the method to a few thousand samples; the paper points to sampling schemes such as CLARA [5] for larger data sets. A new sample has no geodesic distance of its own; fuzzyclust enters the graph at the nearest training sample and adds the Euclidean distance to it, which is exact for training points and adequate close to the manifold.

Algorithm

In a nutshell: Geodesic fuzzy c-medoids

  • The c-means functional with the geodesic (shortest-path) distance of a k-nearest-neighbor graph and medoids as prototypes: clusters follow the manifold, and memberships fade along it, not across it.
  • One structural parameter, k: large enough to keep each manifold connected, small enough not to connect different ones; the component count and the plateau of the result over k show the usable range.
  • Disconnected components are bridged with a penalty (kept apart, all distances finite) or, when they are fragments of one manifold, with plain bridges; m plays its usual role.
  • O(N2) memory and O(cN2) time per iteration, which suits small and medium data sets; new samples enter through their nearest training sample.

7.2.6 Algorithm I: clustering of the Isomap projection

The paper’s first route leaves the manifold entirely to Isomap and clusters its output. Classical multidimensional scaling [92] of the geodesic distance matrix Dg gives coordinates yk ∈ ℝq that reproduce the geodesic distances as well as possible: with H = I −1 N 11T, the matrix B = −1 2HDg(2)H is decomposed, and Y = QqΛq1∕2 is formed from its q largest eigenpairs. The discarded share of the eigenvalue mass is the residual variance, and its decrease with q indicates the intrinsic dimension of the manifold. Fuzzy c-means is run on Y, and each center is “re-projected” into the feature space as the sample whose projection is closest to it, so that the prototypes lie on the manifold here too; the cost (7.9) evaluated with geodesic distances to the re-projected centers compares the two routes. The weakness is the projection: Isomap can only embed a connected graph (hence the bridges), and a projection that folds the manifold spoils the clustering. The paper found Algorithm II slightly better on the S-curve and the spiral; in fuzzyclust the two reach nearly the same geodesic cost (fig. 7.18).

Algorithm

In a nutshell: Clustering of the Isomap projection

  • Isomap unfolds the manifold, FCM clusters the flat picture, and the centers return to the data space as the closest samples.
  • Needs a connected (or bridged) graph and a good projection; the residual variance tells how much of the geodesic geometry q dimensions keep.
  • The graph parameters of Algorithm II (components are always bridged) plus the embedding dimension q; the FCM step inherits init and n_init.

7.3 Using it in fuzzyclust

Everything in this chapter is in fuzzyclust.graph. The three estimators derive from BaseFuzzyClusterer and have the usual methods fit, predict, predict_proba, transform and score. The graph utilities are functions built on the sparse-graph routines of SciPy, so no optional dependency is needed; networkx is accepted only as an alternative backend for the tree.

fuzzyclust.graph.MSTClustering

n_clusters=None, threshold=None, inconsistency=2.5, inconsistency_std=None, n_hops=2, criterion="hypervolume"| "fukuyama_sugeno", min_gain=0.15, min_cluster_size=5, max_clusters=20, refine="gg"|"fcm"|None, m=2.0, gamma=0.0, tol, max_iter, backend="scipy"| "networkx", random_state, verbose.
Attributes n_clusters_, tree_labels_ (crisp tree partition), labels_, membership_, cluster_centers_, covariances_, mst_edges_, mst_weights_, cut_edges_, cut_phases_ (0: length criteria, 1: volume), cut_quality_ (CP), hypervolumes_, cluster_similarity_ (Sij), refiner_ (the fitted GG or FCM). min_gain=1.0 disables the splitting phase (unless n_clusters is given); threshold=None and inconsistency=None, with the default inconsistency_std=None, disable the length criteria.

fuzzyclust.graph.GeodesicFCM

n_clusters=3, n_neighbors=10, radius=None, connect_components=True, bridge_penalty=1.0, m=2.0, tol, max_iter, init="kmeans++"|"random"| index array, n_init=1, random_state, verbose.
Attributes medoid_indices_, cluster_centers_ (the medoids), membership_, labels_, geodesic_distances_, neighbors_graph_, n_components_, component_labels_, bridge_edges_, objective_, objective_history_, n_iter_. New samples enter the graph through their nearest training sample.

fuzzyclust.graph.IsomapFCM

n_clusters=3, n_components=2, n_neighbors=10, radius=None, bridge_penalty=1.0, m, tol, max_iter, init, n_init, random_state, verbose.
Attributes embedding_ (Y), embedded_centers_, medoid_indices_, cluster_centers_ (re-projected), membership_, labels_, geodesic_objective_, residual_variance_, fcm_ and the graph attributes of GeodesicFCM.

graph utilities, data generators and plot helpers

minimum_spanning_tree(X, backend) → edges, lengths; neighbors_graph(X, n_neighbors, radius) → sparse adjacency; geodesic_distances(X, n_neighbors, radius, connect_components, bridge_penalty) → Bunch(distances,  graph, n_components, component_labels, bridges); isomap_embedding(D,  n_components) → coordinates, eigenvalues; fuzzy_cluster_similarity(U) → Sij. Generators make_chained_blobs, make_density_blobs, make_s_curve (with make_rings, make_two_moons, make_curved_manifold of fuzzyclust.datasets). Plots plot_mst(X, model), plot_neighbors_graph(X,  graph_or_model), plot_geodesic_path(X, graph, source, target), plot_similarity_dendrogram(S).

The classical tree clusterer and the hybrid one differ in two parameters:

tree_only = MSTClustering(threshold=None, inconsistency=None, min_gain=1.0, refine=None).fit(X) 
zahn = MSTClustering(inconsistency=2.5, n_hops=2, min_gain=1.0, refine=None).fit(X) 
print("tree only  :", tree_only.n_clusters_, "cluster") 
print("Zahn (f=2.5):", zahn.n_clusters_, "clusters, cut edges:", len(zahn.cut_edges_))
   
mst = MSTClustering(random_state=0).fit(X) 
print("clusters found:", mst.n_clusters_) 
print("cut phases    :", mst.cut_phases_, " (0 = length criteria, 1 = volume criterion)") 
print("hypervolumes  :", mst.hypervolumes_.round(3))
   

The refinement and its adequacy measures are part of the fit, and the number of clusters can be prescribed and scanned with the validity functions of the toolbox:

gg_random = GG(n_clusters=mst.n_clusters_, random_state=0).fit(X) 
ari_tree = adjusted_rand_score(y[blob], mst.tree_labels_[blob]) 
ari_gg = adjusted_rand_score(y[blob], mst.labels_[blob]) 
ari_random = adjusted_rand_score(y[blob], gg_random.labels_[blob]) 
print(f"ARI of the blobs: tree partition {ari_tree:.2f}, MST-GG {ari_gg:.2f}, GG from random start {ari_random:.2f}") 
print("cut adequacy CP(e):", mst.cut_quality_.round(2))
   
cs = range(2, 9) 
rows = [] 
for c in cs: 
    model = MSTClustering(n_clusters=c, random_state=0).fit(X) 
    U, V = model.membership_, model.cluster_centers_ 
    rows.append(( 
        validity.fuzzy_hypervolume(X, U, V), 
        validity.partition_density(X, U, V), 
        validity.average_partition_density(X, U, V), 
        adjusted_rand_score(y, model.labels_), 
    )) 
rows = np.array(rows) 
auto = MSTClustering(random_state=0).fit(X) 
print("volume criterion alone picks", auto.n_clusters_, "clusters")
   

The geodesic clusterer is a drop-in replacement for FCM, and the geodesic distances and paths are available on their own:

k = 8 
results = {} 
for name, (X, y) in datasets.items(): 
    fcm = FCM(n_clusters=2, random_state=0).fit(X) 
    geo = GeodesicFCM(n_clusters=2, n_neighbors=k, random_state=0).fit(X) 
    results[name] = (fcm, geo) 
    print(f"{name:16s}: FCM ARI = {adjusted_rand_score(y, fcm.labels_):.2f}, " 
          f"geodesic c-medoids ARI = {adjusted_rand_score(y, geo.labels_):.2f} " 
          f"({geo.n_components_} graph component(s), {geo.n_iter_} iterations)")
   
geo = geodesic_distances(X, n_neighbors=8) 
D, G = geo.distances, geo.graph 
# two samples of the first arm, far apart along the arm 
arm = np.flatnonzero(y == 0) 
radius = np.linalg.norm(X[arm], axis=1) 
source, target = arm[radius.argmin()], arm[radius.argmax()] 
print(f"Euclidean distance {np.linalg.norm(X[source] - X[target]):.2f}, geodesic distance {D[source, target]:.2f}")
   
fcm = FCM(n_clusters=8, random_state=0).fit(Xs) 
geo = GeodesicFCM(n_clusters=8, n_neighbors=10, random_state=0).fit(Xs) 
iso = IsomapFCM(n_clusters=8, n_components=2, n_neighbors=10, random_state=0).fit(Xs) 
# geodesic cost of the FCM partition, with the samples closest to its centers as prototypes 
Dg = geo.geodesic_distances_ 
fcm_proxies = np.linalg.norm(Xs[:, None] - fcm.cluster_centers_[None], axis=2).argmin(axis=0) 
J_fcm = float(np.sum(fcm.membership_**2 * Dg[:, fcm_proxies] ** 2)) 
print(f"geodesic cost J: FCM {J_fcm:.0f}, Isomap + FCM {iso.geodesic_objective_:.0f}, " 
      f"geodesic c-medoids {geo.objective_:.0f}") 
print(f"Isomap residual variance with 2 components: {iso.residual_variance_:.3f}")
                                                                     

                                                                     
   

7.4 Examples

7.4.1 Cutting, splitting and refining the tree

Two Gaussian groups of 120 points are joined by a chain of 25 points (fig. 7.3). Without any criterion the tree is one cluster. Zahn’s local criterion with f = 2.5 and k = 2 flags one edge, inside the chain close to the left group, so most of the chain stays attached to the right group: the length criteria cannot separate the groups from the chain. The volume criterion (fig. 7.4) makes two further cuts, one where the chain meets the right group and one in the middle of the chain. The result is four tree clusters, the two groups with hypervolumes 0.29 and 0.25 (the left one with the six chain points left of the length cut) and two chain pieces with 0.02 and 0.05, and the points of the two groups are separated exactly. Started from this partition, Gath–Geva keeps it (agreement 0.98 with the tree partition) and delivers the membership contours and covariance ellipses of fig. 7.5; the same GG started from a random partition with four clusters spends one Gaussian on the whole chain and collapses another onto a few points at the edge of the left group. The cut adequacies are 0 for the cut of the length criterion, whose endpoints the refinement re-united in the neighboring chain piece, and 1.5 and 2.0 for the two volume cuts. The parameter study (fig. 7.6) shows the number of tree clusters falling as the required relative gain rises from 0.05 to 0.6: from twenty to six with min_cluster_size=2, from five to two with the default size of five, and from three to two with sizes of ten and twenty, which remove the small fragments altogether. The printed comparison of the refinements shows FCM pulled off the tree partition (agreement 0.63) while GG stays on it.

Figure 7.3

Figure 7.3. The minimal spanning tree of two groups joined by a chain (left) and the single edge that Zahn’s local criterion removes (right, dashed): the chain stays attached to one group.

Open in ColabExample plot_01_mst_clustering.py in the gallery

Figure 7.4

Figure 7.4. The volume criterion cuts the chain (orange dashed edges) and separates it from the groups; the length-criterion cut is drawn in vermilion.

Figure 7.5

Figure 7.5. Gath–Geva clustering initialized with the tree partition (left) polishes it into a fuzzy partition with covariance ellipses; the same GG from a random start (right) spends one Gaussian on the chain and collapses another onto a few points of the left group.

Figure 7.6

Figure 7.6. Left: the number of tree clusters against the required relative volume gain for several minimum cluster sizes. Right: FCM as refinement is pulled off the tree partition by the chain points.

7.4.2 Which edges are inconsistent?

The data are a diffuse group of 200 points next to two tight groups of 40 points (fig. 7.7). A global threshold of twice the mean edge length cuts eight clusters out of the tree, mostly tails of the diffuse group; four times the mean leaves the two tight groups merged, and the printed scan shows that no threshold in between returns the three groups: the edge between the tight groups is no longer than the longest edges inside the diffuse group (fig. 7.8). The local criterion with f = 2.5 and k = 3 finds the three groups exactly, because each separating edge is far longer than its own neighbors. Figure 7.9 varies the factor and the depth: with k = 1 no factor returns the three groups (f ≤3 fragments the diffuse group, f = 4 already misses a separation), with k = 3 or 5 every f between 2.5 and 4 works (with k = 8 from f = 3 on), and f = 6 misses a separation for every depth; the deviation form needs k ≥5 at three standard deviations and k ≥2 at four. Raising min_cluster_size tames an eager criterion (f = 2, k = 2: from ten clusters at size 5 to four at size 20).

Figure 7.7

Figure 7.7. Length criteria on a diffuse group and two tight groups. A global threshold of twice the mean edge length shatters the diffuse group (left), four times the mean merges the tight groups (middle), and Zahn’s local criterion separates the three groups (right).

Open in ColabExample plot_02_mst_cut_criteria.py in the gallery

Figure 7.8

Figure 7.8. Edge lengths of the tree with the two global thresholds (dashed) and the two edges removed by the local criterion (vermilion): the edge between the tight groups lies among the long edges of the diffuse group.

Figure 7.9

Figure 7.9. Number of clusters found by the ratio form (left) and the deviation form (right) of Criterion 2 as a function of the factor and the neighborhood depth; the dotted line is the true number.

7.4.3 How many clusters?

Four Gaussian groups of different sizes are clustered with n_clusters from 2 to 8, and the volume indices of Gath and Geva are computed from the refined partitions (fig. 7.10). The fuzzy hypervolume falls by 38 % from three to four clusters and by less than 3 % for every further split; the partition density rises steeply up to four and then stays flat; the average partition density peaks at four but is overtaken at eight, where small dense fragments appear. The knee, not the extremum, carries the information, and the relative decrease of FHV drops below the default min_gain of 0.15 exactly where the automatic run stops, at four. Two concentric rings (fig. 7.11) show the limits of the refinement: the tree partition with two clusters separates the rings perfectly, but a Gath–Geva refinement of two clusters fails (ARI 0.09), because one Gaussian cannot describe a hollow ring and the inner ring is absorbed by the broad outer Gaussian. Without a prescribed number, the volume criterion keeps splitting the rings into arcs that are approximately Gaussian until max_clusters is reached; with max_clusters=12 it produces twelve arcs, and the refinement of the arcs is faithful. Their fuzzy similarity matrix (fig. 7.12) has its large entries between neighboring arcs of the same ring, the single-linkage dendrogram of 1 −Sij has two main branches, and cutting it into two groups merges the arcs back into the rings (ARI 1.0). The similarities grow with the exponent m of the refinement (the largest same-ring entry rises from 0.007 at m = 1.5 to 0.05 at m = 4) while the merge stays correct, and the number of arcs follows max_clusters.

Figure 7.10

Figure 7.10. Volume-based validity indices of the MST–GG partitions of four groups against the number of clusters: fuzzy hypervolume, partition density, average partition density and the relative decrease of the hypervolume with the default minimum gain (dashed); the dotted line is the number the automatic run picks.

Open in ColabExample plot_03_mst_validation.py in the gallery

Figure 7.11

Figure 7.11. Two rings: the tree partition with two clusters (left), the failed Gath–Geva refinement of two clusters (middle) and the twelve Gaussian arcs the volume criterion produces (right).

Figure 7.12

Figure 7.12. Fuzzy similarity of the twelve arcs (left) and its single-linkage dendrogram (right): the two branches are the two rings.

7.4.4 Geodesic c-medoids versus fuzzy c-means

The data sets are two spiral arms, two moons and two rings, each with two clusters (fig. 7.13). FCM reaches adjusted Rand indices of only 0.02, 0.24 and 0.00, because its centers cut straight across the manifolds, while the geodesic c-medoids with k = 8 recover all three groupings exactly in three to five iterations. The spiral forms one graph component in which the path between the arms runs through the center; the moons and the rings fall into two components that are bridged with a penalty. The memberships (fig. 7.14) fade along the arm from the medoid toward its ends, while a point of the other arm that is close in the Euclidean sense keeps a membership near zero. The scan over k (fig. 7.15) shows the two failure modes. A small k fragments the sparsely sampled outer parts of the arms into components that have to be bridged, and the result degrades; a large k connects the arms where they come close, and the geodesic distance loses its meaning. On the spiral the plateau spans k = 8 to 15, on the moons 5 to 8. Moons whose gap is narrower than the sample spacing form one component already at k = 3 (fig. 7.15, right) and cannot be separated for any k (fig. 7.16): the graph cannot resolve a gap the sampling does not resolve. The printed study shows the usual effect of m on the softness of the partition. It also shows that on the rings a plain Euclidean bridge (bridge_penalty=0) lets the far side of the outer ring switch to the inner medoid through the bridge (ARI 0.28), whereas both the penalized bridge and infinite distances (connect_components=False) keep the rings apart.

Figure 7.13

Figure 7.13. Fuzzy c-means (top) and geodesic c-medoids with k = 8 (bottom, with the neighborhood graph and the bridge of the two-component cases) on two spiral arms, two moons and two rings: only the geodesic clusters follow the manifolds.

Open in ColabExample plot_04_geodesic_fcm.py in the gallery

Figure 7.14

Figure 7.14. Memberships of the spiral samples in the two geodesic clusters: they fade along the arm, not across it.

Figure 7.15

Figure 7.15. Agreement with the true groups (left) and number of graph components (right) against the number of neighbors k for the four data sets: good results need a k between fragmentation and short-circuits.

Figure 7.16

Figure 7.16. Noisier moons with k = 4 and k = 15: the gap is bridged by the graph itself, and the tips of the moons follow the other medoid.

7.4.5 Geodesic paths, the S-curve and the Isomap route

Figure 7.17 traces shortest paths through the k = 8 graph of the spiral: between the inner and the outer end of one arm the geodesic distance is 32 against a chord of 8.4, and the closest outer pair of samples of different arms, 1.7 apart in the plane, is 38 apart along the graph. On the three-dimensional S-curve with eight clusters (fig. 7.18) the FCM centers float between the layers of the S (up to 0.19 from the nearest sample), while the medoids of Algorithm II and the re-projected centers of Algorithm I lie on the sheet. The geodesic cost of the partitions is 334 for FCM against 269 and 273 for the two geodesic routes, which thus reach nearly the same solution by different means. The Isomap projection unrolls the S into a rectangle that FCM tiles regularly, and the geodesic clusters cover the sheet in the same way (fig. 7.19). The study of Algorithm I on the spiral (fig. 7.20) shows the role of the bridges when the graph is fragmented: with k = 4 the arms break into seven components. The penalized bridges keep every fragment apart in the projection, and two clusters cannot collect them (ARI 0.86 for both algorithms), whereas plain bridges re-join the fragments of an arm at their natural junctions, and both algorithms recover the arms. With k = 10 the graph is connected and the bridges play no role. On the S-curve, two and three Isomap dimensions give nearly the same geodesic cost (269 and 272), whereas a single dimension raises it to 665; the residual variance drops from 0.09 with one component to 0.04 with two.

Figure 7.17

Figure 7.17. Shortest paths in the neighborhood graph of the spiral: along one arm from its inner to its outer end (left) and between the closest outer pair of samples of different arms (right); the dotted lines are the Euclidean chords.

Open in ColabExample plot_05_geodesic_path_isomap.py in the gallery

Figure 7.18

Figure 7.18. Eight clusters on the S-curve: FCM centers float between the layers (left), the re-projected centers of the Isomap route (middle) and the geodesic medoids (right) lie on the sheet.

Figure 7.19

Figure 7.19. The Isomap projection of the S-curve with the FCM centers (left) and the geodesic c-medoid clusters in the same projection (right): both tile the unrolled sheet regularly.

Figure 7.20

Figure 7.20. Isomap projection of the spiral with k = 4, where the arms are fragmented into seven components: penalized bridges keep the fragments apart (left), plain bridges re-join the fragments of each arm (right); colors are the true arms, crosses the FCM centers.

7.5 Further reading

The hybrid MST–GG algorithm was published in [83]; it builds on Zahn’s graph-theoretical clustering [81], on the relation between the minimal spanning tree and single linkage [82], on the tree algorithms of Prim and Kruskal [87, 88], on the hypervolume and density indices of Gath and Geva [21], on the Fukuyama–Sugeno measure [33] as used by Varma and Simon [89], and on compatible cluster merging [40] for the idea of merging similar fuzzy clusters; the Gath–Geva refinement may use the covariance regularization of [19]. Graph-theoretic and hierarchical clustering in general are covered by [4]. The geodesic clustering algorithms are from [84], which rests on Isomap [85] and the convergence of graph distances to geodesics [86], on shortest paths [90, 91], on classical multidimensional scaling [92], on the c-means functional [3] and on the medoid methods of Kaufman and Rousseeuw [5]; locally linear embedding [93] is the other classical manifold method the paper mentions. The fuzzy Sammon mapping of chapter 5 [51] is the natural tool for inspecting the clusters found here when the data have more than two dimensions.