Fuzzy Clustering and Data Analysis in PythonThe fuzzyclust toolbox

Chapter 3
Hard and fuzzy partitioning algorithms

The previous chapter set up the template: a prototype, a distance, the c-means functional, and its alternating optimization. This chapter fills it with the core algorithms of the toolbox, all of which the MATLAB predecessor already offered: the hard reference methods k-means and k-medoids; fuzzy c-means (FCM), derived in full together with the role of the fuzziness exponent; the Gustafson–Kessel algorithm (GK), which gives every cluster its own norm and is presented with the eigenstructure of its covariance matrices and the regularization of Babuška, van der Veen, and Kaymak; and the Gath–Geva algorithm (GG), which replaces the norm by an exponential distance that adapts volume and density and must be started from a good partition. A comparison of the four is followed by two extensions: the mechanisms that make a partition fuzzy (the exponent m, entropy regularization and its interpretation as deterministic annealing, quadratic regularization, and the polynomial fuzzifier of Klawonn and Höppner, which allows exact zero memberships), and the density-based estimation of the number and location of clusters by the mountain method and subtractive clustering, which also initializes the iterative algorithms. Everything that follows builds on this chapter: validity indices judge the partitions these algorithms produce, and the identification, time-series, and graph methods of later chapters use GK and GG as building blocks.

3.1 Problem and idea

Every algorithm of this chapter minimizes the c-means functional J = ∑ ⁡ i ∑ kμikmDik2 of section 2.2.5 by alternating optimization, and all of them have point prototypes. They differ in the distance and in the partition space. Figure 3.1 shows what this means for one set of three prototypes: the level curves of the maximal membership max ⁡ iμi(x) over the plane, the picture that the MATLAB function clusteval drew and plot_membership_contours draws, change shape from algorithm to algorithm. k-means tiles the plane into Voronoi cells with crisp boundaries. FCM, with a fixed Euclidean norm, draws nearly circular contours around every prototype; it can only see spherical clusters of about the same size. GK derives a norm-inducing matrix from the fuzzy covariance of each cluster, so its contours are ellipses with the orientation and elongation of the cluster, but the determinant constraint fixes the volume of every cluster. GG measures distance by the reciprocal of a Gaussian density weighted by a prior probability; its contours are ellipses of different size and density, and the memberships fall off exponentially, so the partition is almost crisp between the clusters. Each step up this ladder buys flexibility at a price: more parameters per cluster, more computation, and greater sensitivity to the initial partition, which is why GG is usually started from FCM or GK.

Figure 3.1

Figure 3.1. Level curves of the maximal membership max ⁡ iμi(x) for one set of prototypes under four algorithms. They are the Voronoi cells of k-means (crisp), circles for fuzzy c-means (one global norm), ellipses of equal volume but individual orientation for Gustafson–Kessel (adaptive norm with determinant constraint), and ellipses of individual size and density with nearly crisp borders for Gath–Geva (exponential distance with priors).

3.2 Theory

We treat the algorithms in the order of fig. 3.1: the hard methods (sections 3.2.1 and 3.2.2), fuzzy c-means with its derivation and the role of m (section 3.2.3 and eq. (3.7)), Gustafson–Kessel (section 3.2.4), and Gath–Geva (section 3.2.5);section 3.2.6 compares them. Section 3.2.7 then examines the mechanism that makes these partitions fuzzy and its alternatives, and section 3.2.8 the estimation of the number and location of clusters before any iteration. The notation is that of table 2.1; in formulas U is c ×N, in code it is stored transposed.

3.2.1 Hard c-means (k-means)

The hard c-means or k-means algorithm [17] partitions the data into c disjoint subsets A1,…,Ac and minimizes the within-cluster sum of squares,

J(X;U,V) = ∑ i=1c ∑ xk∈Ai ‖xk −vi‖ 2 = ∑ i=1c ∑ k=1Nμ ik ‖xk −vi‖ 2,U ∈M hc,
(3.1)

which is the c-means functional (2.9) for m = 1 and a hard partition. For fixed subsets the minimizing prototype is the mean of the members,

vi = 1 Ni ∑ xk∈Aixk,Ni = |Ai| = ∑ k=1Nμ ik,
(3.2)

and for fixed prototypes the minimizing partition assigns every sample to its nearest prototype, μik = 1 if i = argmin ⁡ j ‖xk −vj‖ 2 and 0 otherwise. Alternating the two steps decreases J and terminates after finitely many iterations, because there are finitely many partitions and none is visited twice. The result depends more strongly on the start than that of FCM, because a prototype that loses all its members cannot recover. fuzzyclust keeps the previous prototype of an emptied cluster instead of letting it collapse, and restarts (n_init) are the standard remedy. The MATLAB toolbox manual illustrates the problem with two runs on the same data, one of which splits a cluster and merges two others.

Algorithm

In a nutshell: k-means

  • Minimizes the within-cluster sum of squares; prototypes are cluster means, the partition is crisp (Voronoi cells).
  • Assumes compact, roughly spherical clusters of similar size in the Euclidean norm; needs scaled data.
  • Fast (O(Ncn) per iteration) and converges in finitely many steps, but depends strongly on the start: use n_init or k-means++ seeding.
  • Parameters: n_clusters, init, n_init; it is the m →1 limit of FCM and the hard reference for all fuzzy results.

3.2.2 k-medoids

The mean of a cluster need not be a meaningful object: if the rows of X are discrete states of a system, categorical codes mapped to numbers, or positions on a network, the average of two states is no state. The k-medoids algorithm [5] keeps the nearest-prototype assignment of k-means but requires every prototype to be one of the samples, vi ∈{x1,…,xN}. Two rules choose the prototype of a cluster among its members. The exact rule takes the medoid, the member with the smallest total distance to the other members; it minimizes the sum of distances rather than of squared distances, which is the criterion of the PAM algorithm of Kaufman and Rousseeuw. The MATLAB toolbox took the member closest to the cluster mean, which is cheaper and is the exact minimizer of the within-cluster sum of squares (3.1) among the members, because the total squared distance of a member to all members equals Ni times its squared distance to the mean plus a constant. fuzzyclust offers both (medoid="exact" or "nearest_mean"). Because prototypes are data points, k-medoids is less sensitive to outliers than k-means (an outlier can pull a mean but cannot become a medoid unless it forms a cluster of its own), and the medoids can be reported as representative samples. The row indices of the medoids are kept in medoid_indices_; the geodesic fuzzy c-medoids of chapter 7 build on the same idea with a different distance.

Algorithm

In a nutshell: k-medoids

  • k-means with prototypes restricted to data points; the exact medoid minimizes the total distance to the other members (the PAM criterion), the cheaper nearest-to-mean rule the total squared distance.
  • Use when the mean is not a valid object (discrete states, codes) or when representative samples are wanted; more robust to outliers than k-means.
  • Exact medoids cost O(∑ ⁡ iNi2n) per iteration; same start dependence as k-means.
  • Parameters: n_clusters, medoid, init, n_init; attribute medoid_indices_.

3.2.3 Fuzzy c-means

Fuzzy c-means [2, 3] minimizes the c-means functional over the fuzzy partitioning space,

J(X;U,V) = ∑ i=1c ∑ k=1Nμ ikmD ikA2,D ikA2 = (x k −vi)TA(x k −vi),
(3.3)

where U ∈Mfc, m > 1, and A is a fixed norm-inducing matrix (identity, diagonal, or Mahalanobis, section 2.2.2). The stationary points are found by adjoining the column constraint ∑ ⁡ iμik = 1 with Lagrange multipliers λk,

J¯(X;U,V,λ) = ∑ i=1c ∑ k=1Nμ ikmD ikA2+∑ k=1Nλ k(∑ i=1cμ ik−1),
(3.4)

and setting the partial derivatives to zero. The derivative with respect to a single membership gives

mμikm−1D ikA2 + λ k = 0⟹μik =( −λk m ) 1 m−1 (DikA2)− 1 m−1 ,
(3.5)

and summing (3.5) over i under the column constraint gives

∑ j=1c( −λk m ) 1 m−1 (DjkA2)− 1 m−1 = 1,

so that dividing (3.5) by this sum eliminates the multiplier:

μik = 1 ∑ j=1c(DikA∕DjkA)2∕(m−1),1 ≤i ≤c,1 ≤k ≤N.
(3.6)

The derivative with respect to vi gives −2A∑ ⁡ kμikm(xk −vi) = 0, hence

vi = ∑ k=1Nμikmxk ∑ k=1Nμikm ,1 ≤i ≤c,
(3.7)

independently of A. If DikA2 > 0 for all i,k and m > 1, then (U,V) can minimize (3.3) only if (3.6) and (3.7) hold [3]; the solution automatically satisfies the remaining constraints of Mfc. Equation (3.7) is the mean of the data weighted by the memberships raised to m, which is why the algorithm is called c-means; (3.6) makes the membership of a sample in a cluster a decreasing function of its distance to that prototype relative to its distances to all prototypes. The FCM algorithm is the Picard iteration through the two equations, that is, the template of algorithm 2.1 with the Euclidean (or A-) norm. If some DikA = 0, the membership formula is undefined; fuzzyclust, like the MATLAB toolbox, adds 10−10 to the squared distances, which gives the sample a membership of practically one in the coinciding prototype.

The role of the fuzziness exponent

The exponent m determines how fast the membership decays with the relative distance. Writing (3.6) for two prototypes along the line through them (fig. 3.5) makes this visible. As m →1+ the exponent 2∕(m −1) grows without bound, each ratio (Dik∕Djk)2∕(m−1) tends to 0 or ∞, and the partition becomes crisp: FCM turns into k-means. As m →∞ the exponent tends to zero, every ratio tends to one, and μik →1∕c for every sample; the prototypes (3.7) then all coincide with the grand mean of the data. In between, m trades the sharpness of the partition against its robustness: with a small m every sample pulls mainly its own prototype, with a large m every prototype averages over all samples. Two further properties of (3.6) matter in practice. First, the membership is one only at the prototype, and a sample far from all prototypes receives nearly uniform memberships 1∕c; this is the price of the column constraint, which the possibilistic variants of chapter 6 remove. Second, the memberships change more slowly for larger m, so above m ≈2 the number of iterations needed to reach a given tolerance grows with m; close to m = 1 it rises again, because the nearly crisp partition takes several iterations to settle (section 3.4.2). The usual default is m = 2, for which (3.6) reduces to μik = Dik−2∕∑ ⁡ jDjk−2, and values in [1.5,2.5] are the range to explore; the validity indices of chapter 4 can be scanned over m as well as over c.

Algorithm

In a nutshell: Fuzzy c-means

  • Minimizes ∑ ⁡ ikμikmDikA2 over fuzzy partitions; prototypes are μikm-weighted means, memberships are inverse relative distances raised to 2∕(m −1).
  • One global norm A: spherical clusters (Euclidean), axis-parallel or commonly oriented ellipsoids (diagonal, Mahalanobis); clusters of similar size.
  • m →1: k-means; m →∞: all memberships 1∕c, prototypes collapse; default m = 2, explore [1.5,2.5].
  • O(Ncn) per iteration, insensitive to the initialization on compact data, the standard initializer for GK and GG.
  • Parameters: n_clusters, m, norm; attributes norm_matrix_, covariances_ (for inspection).

3.2.4 Gustafson–Kessel

Gustafson and Kessel [18] extended FCM with an adaptive norm: each cluster has its own norm-inducing matrix Ai, which becomes an optimization variable,

J(X;U,V,{Ai}) = ∑ i=1c ∑ k=1Nμ ikmD ikAi2,D ikAi2 = (x k−vi)TA i(xk−vi).
(3.8)

For fixed Ai the memberships and prototypes are those of FCM, (3.6) and (3.7). The functional cannot be minimized over Ai directly, because it is linear in Ai and can be made arbitrarily small by making Ai less positive definite. The matrices must therefore be constrained, and the natural constraint fixes their determinants,

det ⁡ Ai = ρi,ρi > 0,
(3.9)

which lets every cluster adapt its shape while its volume stays constant. Adjoining (3.9) with multipliers λi and differentiating with respect to Ai gives ∑ ⁡ kμikm(xk −vi)(xk −vi)T = λi det ⁡ (Ai)Ai−1, so Ai is proportional to the inverse of the fuzzy covariance matrix of the cluster, and the constraint fixes the factor:

Ai =[ρi det ⁡ (Fi)]1∕nF i−1,F i = ∑ k=1Nμikm(xk −vi)(xk −vi)T ∑ k=1Nμikm .
(3.10)

Substituting (3.10) into (3.8) shows that the GK distance is a Mahalanobis distance with the cluster’s own membership-weighted covariance, multiplied by the volume normalizer [ρi det ⁡ Fi]1∕n. Without prior knowledge all ρi are set to one, so GK can only find clusters of approximately equal volume; a cluster known to be larger can be given a larger ρi (section 3.4.4). In exact arithmetic, any invertible affine transformation of the data multiplies the GK distances of all samples by a common factor, so the partition is affine-invariant (section 2.2.8).

Eigenstructure. The covariance matrix Fi = ΦiΛiΦiT describes the shape and orientation of the cluster: the eigenvectors ϕij are the axes of the ellipsoid and the square roots of the eigenvalues λij its semi-axis lengths (fig. 2.1). The ratio of the largest to the smallest eigenvalue measures the elongation, and the eigenvector of the smallest eigenvalue is the normal of the cluster: if the data of cluster i lie close to a hyperplane, that hyperplane is ϕi1T(x −vi) = 0. This is the bridge from GK to local linear models: in the product space of regressors and output, the normal of a GK cluster gives the parameter vector of a local linear model, which chapter 8 exploits. fuzzyclust stores the eigenvalues in ascending order in eigenvalues_ and the eigenvectors as columns of eigenvectors_.

Regularization. The adaptive norm has a numerical weak spot [19]. When a cluster has few members or its members lie almost on a linear subspace, Fi is nearly singular: its smallest eigenvalue approaches zero, the condition number explodes, Fi−1 is unreliable, and the volume normalization fails as det ⁡ Fi →0. GK can even converge to a degenerate solution in which one cluster collapses onto a line of points, whose zero volume makes its distance to those points zero. Babuška, van der Veen, and Kaymak proposed two independent safeguards, both applied to Fi before inversion:

Fi ←(1 −γ)Fi + γdet ⁡ (F0)1∕nI,0 ≤γ ≤1, (3.11) λij ←λi,max ⁡ ∕βfor all j with λi,max ⁡ ∕λij > β, Fi ←Φi diag ⁡ (λi1,… ⁡ ,λin)ΦiT. (3.12)

The first shrinks every cluster covariance toward a scaled identity; F0 is the covariance of the whole data set, so the scale is that of the data. It is recommended for small or nearly collinear clusters and for identification, where it keeps the local models from overfitting. The second bounds the condition number of Fi by β by raising the small eigenvalues; the MATLAB default β = 1015 is effectively off, and a bound between 102 and 104 is a practical choice when degenerate clusters appear; it acts only on clusters whose condition number exceeds it (section 3.4.4). fuzzyclust implements both as published, with the defaults γ = 0 and β = 1015, and stores the regularized Fi in covariances_. Both devices break the affine invariance of GK, because the identity matrix and the eigenvalues of Fi depend on the units of the data.

Algorithm

In a nutshell: Gustafson–Kessel

  • FCM with a norm-inducing matrix per cluster, Ai = [ρi det ⁡ Fi]1∕nFi−1; the determinant constraint det ⁡ Ai = ρi fixes the volume and lets the shape adapt.
  • Detects ellipsoidal clusters of different orientation and elongation but (for ρi = 1) of similar volume; affine-invariant in exact arithmetic.
  • The eigenstructure of Fi gives axes, elongation, and the normal direction of a cluster—the basis of local linear models.
  • Nearly singular Fi (few points, collinear data) is handled by shrinkage γ toward det ⁡ (F0)1∕nI and by the condition bound β.
  • O(Ncn2 + cn3) per iteration; more start-dependent than FCM on crossing or elongated clusters, so use n_init.
  • Parameters: n_clusters, m, rho, gamma, beta; attributes covariances_, norm_matrices_, eigenvalues_, eigenvectors_.

3.2.5 Gath–Geva

The fuzzy maximum likelihood estimation (FMLE) algorithm of Bezdek and Dunn [20], developed into a clustering method by Gath and Geva [21], interprets cluster i as a Gaussian component with mean vi, covariance Fi, and prior probability αi, and uses the reciprocal of the prior-weighted density as distance,

Dik2 = det ⁡ F wi αi exp ⁡ (1 2(xk −vi)TF wi−1(x k −vi)),
(3.13)

with

Fwi = ∑ k=1Nμikw(xk −vi)(xk −vi)T ∑ k=1Nμikw ,αi = 1 N∑ k=1Nμ ik.
(3.14)

The covariance weighting exponent is w = 1 in the original FMLE algorithm; the MATLAB toolbox and fuzzyclust use w = m (so w = 2 by default), which makes the partition fuzzier to compensate for the exponential term. The two weightings generalize the classical covariance from different starting points, and the exponent w covers both. Memberships and prototypes are updated with the FCM formulas (3.6) and (3.7). Three consequences follow from (3.13). First, 1∕Dik2 is proportional to αiN(xk;vi,Fwi), so for m = 2 the membership μik = Dik−2∕∑ ⁡ jDjk−2 is exactly Bayes’ rule for the posterior probability of component i given xk: GG is a fuzzy relative of the EM algorithm for Gaussian mixtures and differs from it in the weights μikm of the center and covariance updates. Second, volume and density adapt: neither det ⁡ Fi nor αi is constrained, so a large diffuse cluster next to a small dense one is described correctly, whereas GK’s volume constraint forces the dense cluster to steal points (section 3.4.6). Third, the distance grows exponentially with the Mahalanobis distance instead of quadratically, so the memberships fall off fast, the partition is nearly crisp between the clusters, and the algorithm converges quickly, but to the nearest local optimum. GG is therefore more sensitive to the start than FCM or GK and needs a good initialization; the recommended practice, in the MATLAB toolbox and here, is to pass the partition of a converged FCM or GK run as init.

Evaluation in the log domain. The exponential in (3.13) overflows a double for squared Mahalanobis distances above about 1400, which happens routinely for far samples and small clusters; the MATLAB manual warns that GG “can overflow at large c values.” fuzzyclust therefore works with the logarithm log ⁡ Dik2 = 1 2 log ⁡ det ⁡ Fwi −log ⁡ αi + 1 2(xk −vi)TFwi−1(xk −vi), computes it with a stable log-determinant, caps it at 700 (so that Dik2 stays below the largest finite double), and evaluates the membership formula as a softmax over clusters,

μik = exp ⁡ ( − 1 m−1 log ⁡ Dik2) ∑ j exp ⁡ ( − 1 m−1 log ⁡ Djk2),
(3.15)

after subtracting the largest logit per sample. Below the cap this is algebraically identical to (3.6), and it cannot overflow. The distances reported by transform and distances_ are the square roots of the capped values, Dik ≤e350. The covariances can be regularized exactly as in GK (gamma, beta), which is advisable when the clusters have few samples.

Algorithm

In a nutshell: Gath–Geva

  • Distance = reciprocal of a prior-weighted Gaussian density; memberships are posterior probabilities (for m = 2), the clusters a Gaussian mixture with fuzzy weights.
  • Volume, orientation and density of every cluster adapt; handles clusters of very different size and spread, which FCM and GK cannot.
  • Exponential distance: nearly crisp borders, fast convergence to the nearest optimum, hence sensitive to the start—initialize from FCM or GK (init=fcm.membership_).
  • Computed in the log domain (softmax) to avoid the overflow of the exponential; covariances regularized like GK if needed.
  • Parameters: n_clusters, m, gamma, beta, init; attributes covariances_, priors_, eigenvalues_, eigenvectors_.

3.2.6 Comparison

Table 3.1 summarizes the four algorithms. Read from left to right, every column adds freedom to the cluster description and removes an assumption about the data, at the cost of more parameters per cluster (from n for a center to n + n(n + 1)∕2 + 1 for center, covariance, and prior), more computation (the n ×n inversions of GK and GG), and greater sensitivity to the initial partition. In practice the data decide: FCM when the clusters are compact and the features scaled, GK when they are elongated or differently oriented, GG when their sizes or densities differ, and FCM first in any case, because it initializes the other two. The validity indices of the next chapter compare the resulting partitions on a common footing, and the examples below show what happens when each assumption is violated.

Table 3.1. The four partitioning algorithms at a glance. N samples, n features, c clusters.

k-means / k-medoids

FCM

GK

GG

prototype

mean / medoid vi

center vi

center vi, covariance Fi

center vi, covariance Fwi, prior αi

distance

Euclidean

fixed norm A, eq. (3.3)

volume-scaled Mahalanobis, eq. (3.10)

inverse prior-weighted Gaussian density, eq. (3.13)

partition

crisp, Mhc

fuzzy, Mfc

fuzzy, Mfc

fuzzy, nearly crisp borders

cluster shape

spherical, equal size

spherical (or one common ellipsoid), similar size

ellipsoidal, any orientation, equal volume

ellipsoidal, any orientation, size, and density

parameters

c

c, m, A

c, m, ρi, γ, β

c, m, γ, β

cost per iteration

O(Ncn) (medoids: +∑ ⁡ iNi2n)

O(Ncn)

O(Ncn2+cn3)

O(Ncn2+cn3)

start dependence

high

low on compact data

medium (crossing or elongated clusters)

high: initialize from FCM/GK

typical use

fast reference, representative samples

compact clusters, initializer

oriented clusters, local linear models

unequal sizes and densities, mixture interpretation

3.2.7 What is fuzzy about fuzzy clustering? Fuzzifiers and regularization

The fuzzy algorithms above owe their fuzziness to one device: the memberships enter the functional as μikm with m > 1. Without the exponent (m = 1) the c-means functional is linear in every column of U, and a linear function on the simplex {μk : ∑ ⁡ iμik = 1,μik ≥0} attains its minimum at a vertex: every sample goes entirely to its nearest prototype and the partition is crisp. Fuzziness therefore requires that the cost of a column be strictly convex in the memberships, and there are three ways to obtain this: raise the memberships to the power m as FCM does, transform them with another fuzzifier function [22], or keep them linear and add a strictly convex regularization term [23]. The choice decides the shape of the membership functions (fig. 3.2). This section presents the two regularizations, the deterministic-annealing view of the entropy regularization, and the polynomial fuzzifier.

Entropy regularization. Li and Mukaidono [24] and Miyamoto and Mukaidono [23] add the negative entropy of the partition to the hard functional,

JE(X;U,V) = ∑ i=1c ∑ k=1Nμ ikDik2+λ∑ i=1c ∑ k=1Nμ ik log ⁡ μik,λ > 0.
(3.16)

Adjoining the column constraint as in (3.4) and differentiating gives Dik2 + λ(log ⁡ μik + 1) + λk = 0, so μik ∝exp ⁡ (−Dik2∕λ), and normalization yields the Gibbs (softmax) memberships

μik = exp ⁡ (−Dik2∕λ) ∑ j=1c exp ⁡ (−Djk2∕λ),vi = ∑ kμikxk ∑ kμik .
(3.17)

The prototypes are weighted means with the memberships themselves, not their powers, as weights. Two properties distinguish (3.17) from (3.6). First, the membership depends on the differences Djk2 −Dik2 of the squared distances, not on their ratios: far from all prototypes a sample belongs entirely to the nearest one instead of tending to 1∕c, and the membership function of a cluster is a Gaussian bump modulated by its neighbors. Second, λ has the units of a squared distance. It acts as a temperature, with λ →0 giving k-means and λ →∞ uniform memberships, and it must be chosen relative to the squared radius of the clusters (standardize the data first).

Deterministic annealing. Eliminating the memberships from (3.16) with (3.17) turns the functional into the free energy of statistical physics,

F(V;λ) = −λ∑ k=1N log ⁡ ∑ i=1c exp ⁡ ( −D ik2∕λ),
(3.18)

and Rose’s deterministic annealing [25] minimizes it while the temperature is lowered. At a high temperature F has a single minimum, at which every prototype sits at the grand mean of the data. Lowering λ geometrically and re-converging from the previous solution tracks this minimum until it becomes unstable: a cluster with covariance Fi (weights μik) splits when λ falls below the critical temperature

λc,i = 2λmax ⁡ (Fi),
(3.19)

and the first split occurs at twice the largest eigenvalue of the data covariance. The number of distinct prototypes thus grows in phase transitions as the temperature falls, and the annealing history reveals the cluster structure scale by scale: the temperatures at which the number of distinct prototypes jumps are the squared scales of the structure (section 3.4.9). Because the start is the unique high-temperature minimum, annealing removes the dependence on the initial partition, at the price of one convergence per temperature. Coinciding prototypes must be perturbed slightly after every cooling step; otherwise they stay together by symmetry.

Quadratic regularization. Miyamoto and Umayahara [26] use the regularizer λ∑ ⁡ ikμik2 instead,

JQ(X;U,V) = ∑ i=1c ∑ k=1Nμ ikDik2 + λ∑ i=1c ∑ k=1Nμ ik2.
(3.20)

The stationarity condition Dik2 + 2λμik + λk = 0 is linear in μik, and it can hold only for the clusters of an active set Ak; for the others the nonnegativity constraint binds and μik = 0. With Ak the ĉk nearest prototypes,

μik = 1 ĉk(1 + 1 2λ∑ j∈Ak(Djk2 −D ik2))(i ∈A k),μik = 0(i∉Ak),
(3.21)

where ĉk is the largest number of nearest prototypes for which all these values are positive. Equivalently, the column μk is the Euclidean projection of −D⋅k2∕(2λ) onto the simplex, which is computed exactly by sorting. For two clusters, μ1k = 1 2 + (D2k2 −D1k2)∕(4λ) clipped to [0,1]: a linear ramp between the prototypes and exact zeros and ones outside it.

The polynomial fuzzifier. Klawonn and Höppner [22] asked why FCM never assigns a zero membership and found the answer in the derivative of the fuzzifier: d dμμm = 0 at μ = 0, so the marginal cost of giving a sample a tiny membership in a far-away cluster is zero, and the optimum always does so. Every FCM prototype is therefore pulled, if weakly, by every sample of the data set. Any fuzzifier g with g′(0) > 0 removes this effect; they proposed the quadratic polynomial

g(μ) = 1 −β 1 + βμ2 + 2β 1 + βμ,0 ≤β < 1,
(3.22)

which interpolates between μ2 (β = 0, FCM with m = 2) and μ (β →1, k-means), and minimized J = ∑ ⁡ ikg(μik)Dik2. The Kuhn–Tucker conditions give, for the active set Ak of the ĉk nearest prototypes,

μik = 1 1 −β( 1 + (ĉk −1)β ∑ j∈AkDik2∕Djk2 −β)(i ∈Ak),μik = 0(i∉Ak),
(3.23)

with ĉk the largest size for which all values are positive, and prototypes vi = ∑ ⁡ kg(μik)xk∕∑ kg(μik). For two clusters the second membership vanishes as soon as D1k2∕D2k2 ≤β: a sample whose nearest prototype is at distance D1 ignores every cluster farther than D1∕β. The memberships are thus fuzzy between neighboring clusters and crisp around each prototype; only a sample far from all prototypes, whose distance ratios approach one, again shares its membership among them. The distances still enter as ratios, so the result is scale-invariant, unlike that of the regularizations. The authors recommend β = 0.5. The parameter keeps the name β of the paper and of the code parameter beta; it is unrelated to the condition-number bound β of GK.

Figure 3.2

Figure 3.2. Membership functions of two clusters with prototypes v1 = 0 (blue) and v2 = 1 (vermilion) under four fuzzification mechanisms. FCM: the membership is one only at the prototypes and returns toward 1∕2 far away. Entropy regularization: a softmax of the squared-distance differences, crisp far from the border. Quadratic regularization: a linear ramp with exact zeros and ones outside the band |D22 −D12|< 2λ. Polynomial fuzzifier: exact zeros wherever one squared distance is less than β times the other; fuzzy only between the prototypes.

Algorithm

In a nutshell: Regularized fuzzy c-means and deterministic annealing

  • Hard c-means functional plus a convex regularizer: entropy (Gibbs/softmax memberships) or quadratic (piecewise linear memberships with exact zeros); prototypes are means with linear weights.
  • λ is a squared length (temperature): λ →0 gives k-means, λ →∞ uniform memberships; scale it with the squared cluster radius, standardize the data.
  • Entropy memberships depend on differences of squared distances: far samples belong fully to the nearest cluster.
  • Deterministic annealing lowers λ from above 2λmax ⁡ (F0); prototypes split at the critical temperatures 2λmax ⁡ (Fi), which reveals the cluster structure scale by scale and removes the start dependence.
  • Parameters: regularization, lam, annealing, lam_start, anneal_rate, perturbation; attributes cluster_history_, n_effective_clusters_, critical_temperatures_.

Algorithm

In a nutshell: Polynomial fuzzifier

  • Replaces μm by g(μ) = 1−β 1+βμ2 + 2β 1+βμ, whose positive slope at zero makes zero memberships optimal for far clusters.
  • Fuzzy between neighboring clusters, crisp around each prototype: a sample ignores every cluster farther than D1∕β, so the members of one cluster no longer pull the distant prototypes.
  • Distances enter as ratios, so the partition is scale-invariant like FCM; β = 0 is FCM with m = 2, β →1 k-means, β = 0.5 recommended.
  • Same cost per iteration as FCM plus a sort of the c distances per sample; sparse membership matrix.
  • Parameters: n_clusters, beta; attribute n_active_.

3.2.8 Estimating the number and location of clusters from density

The iterative algorithms of this chapter need the number of clusters and a start. Before the validity indices of chapter 4 judge finished partitions, a cheaper question can be put to the data directly: where the density peaks are and how many there are. The mountain method of Yager and Filev [27] and its data-point version, the subtractive clustering of Chiu [28], answer it in one pass without iteration and without random initialization (fig. 3.3).

The mountain method. The data are scaled to the unit hypercube and a grid of nodes g is laid over it. Every node receives the value of the mountain function, the sum of Gaussian influences of all samples,

M(g) = ∑ k=1N exp ⁡ ( −α ‖g −x k‖ 2),α = 4∕r a2,
(3.24)

where ra is the neighborhood radius: samples farther than ra contribute less than e−4 ≈0.02. The highest node g1∗ with height M1∗ is the first center. Its mountain is then destroyed: M(g) ←M(g) −M1∗exp ⁡ (−4 ‖g −g1∗‖2∕rb2) with a second radius rb, so that nodes near the center lose most of their height and distant nodes keep theirs. The next highest node is the next center. The procedure stops when the highest remaining node falls below a fraction δ of M1∗. The grid is the method’s weakness: with G nodes per axis there are Gn nodes, which is affordable for two or three features only.

Subtractive clustering. Chiu [28] took the data points themselves as the candidate centers, which makes the cost O(N2n), linear instead of exponential in the dimension. The potential of sample k is

Pk = ∑ l=1N exp ⁡ ( −α ‖x k −xl‖ 2),α = 4∕r a2,
(3.25)

a kernel density estimate with bandwidth ra∕8. After the selection of the center xi∗ with potential Pi∗ all potentials are revised,

Pk ←Pk −Pi∗exp ⁡ ( −4 ‖x k −xi∗‖2∕r b2),r b = ηra,
(3.26)

with the squash factor η > 1 (Chiu suggests rb = 1.5ra; a common default is η = 1.25), so that no second center is placed close to an existing one. The stopping rule has a gray zone. A candidate with P∗ > 𝜀¯P1∗ is accepted, one with P∗ < 𝜀̲P1∗ ends the search (𝜀¯ = 0.5, 𝜀̲ = 0.15 in Chiu’s paper), and in between the candidate is accepted only if it is far enough from the existing centers relative to its potential, dmin ⁡ ∕ra + P∗∕P1∗ ≥1; otherwise its potential is set to zero and the next candidate is examined. The radius ra, a fraction of the data range, is the parameter that matters; it sets the scale at which the data are viewed, small radii giving many centers and large radii few. Counting the centers over a range of radii and looking for a plateau gives a quick, model-free estimate of the number of clusters (section 3.4.10).

Uses. The centers are good initial prototypes for FCM, GK, and GG, and their number is an estimate of c. Chiu’s own application was fuzzy modeling: run on the product space zk = [xkTyk]T of inputs and output, every center becomes the center of a rule of a Takagi–Sugeno model, so the number of centers is a rule-number estimate and the radius controls the granularity of the model (chapter 8).

Figure 3.3

Figure 3.3. Subtractive clustering in one dimension. The dashed curve is the initial potential, a kernel density estimate of the data. The highest point becomes the first center and a Gaussian bump of radius rb = ηra scaled to its potential is subtracted (solid curve); the highest remaining potential gives the next center. Candidates above 𝜀¯P1∗ are accepted, the search stops below 𝜀̲P1∗, and in between a candidate must also be far enough from the existing centers.

Algorithm

In a nutshell: Subtractive clustering

  • Selects data points of high potential (kernel density) as centers, subtracting the influence of every selected center; no number of clusters, no initialization, no iteration.
  • One essential parameter: the radius ra as a fraction of the data range; a plateau of the number of centers over ra indicates a stable structure.
  • O(N2n) time and O(N2) memory: practical for thousands of samples in any dimension.
  • Uses: initial centers and c for FCM/GK/GG; on product-space data a rule-number estimate for Takagi–Sugeno models.
  • Parameters: radii, squash, accept_ratio, reject_ratio, max_clusters; attributes n_clusters_, center_indices_, potentials_, initial_potentials_.

Algorithm

In a nutshell: Mountain method

  • The grid-based predecessor of subtractive clustering: a density (mountain) function on grid nodes, peaks selected and destroyed one by one.
  • Centers are grid nodes, so their precision is the grid spacing; the stop rule is a single ratio δ.
  • Gn nodes: exponential in the number of features, practical for n ≤3; max_nodes bounds the grid explicitly.
  • Parameters: grid_size, max_nodes, radii, squash, stop_ratio; attributes grid_, mountain_.

3.3 Using it in fuzzyclust

The five core estimators are in fuzzyclust.cluster and are re-exported at the package top level; the estimators of sections 3.2.7 and 3.2.8 are in fuzzyclust.cluster only. The iterative estimators share the constructor parameters, attributes, and methods of section 2.3, so only their algorithm-specific additions are listed here; the two density-based estimators have no n_clusters, tol, or init and are listed in full.

fuzzyclust.cluster.KMeans

n_clusters=3, tol=1e-4, max_iter=300, init="random", n_init=1, random_state=None, verbose=0. The exponent is fixed at m = 1 and the partition is crisp; membership_ holds one-hot rows, objective_ the within-cluster sum of squares. An emptied cluster keeps its previous prototype. For large data sets sklearn.cluster.KMeans is faster; this class exists so that hard and fuzzy methods share one interface and one loop.

fuzzyclust.cluster.KMedoids

n_clusters=3, medoid="exact", tol, max_iter, init, n_init, random_state, verbose. medoid="exact" selects the member with minimal total distance to the other members, "nearest_mean" the member closest to the cluster mean (MATLAB behavior). cluster_centers_ are rows of X, and medoid_indices_ holds their row indices.

fuzzyclust.cluster.FCM

n_clusters=3, m=2.0, norm="euclidean", tol, max_iter, init, n_init, random_state, verbose. norm is "euclidean" (A = I), "diagonal" (inverse feature variances), "mahalanobis" (pseudo-inverse of the data covariance), or an explicit (n,n) matrix; the matrix used is stored in norm_matrix_. Requires m > 1. covariances_ holds the fuzzy covariance matrices of the final partition for inspection and plotting (they are not used by the algorithm).

fuzzyclust.cluster.GK

n_clusters=3, m=2.0, rho=None, gamma=0.0, beta=1e15, tol, max_iter, init, n_init, random_state, verbose. rho is a scalar or a vector of c volumes (None: all one); gamma ∈[0,1] the shrinkage weight (3.11); beta the condition-number bound (3.12). Attributes: covariances_ (c,n,n) after regularization, norm_matrices_ (c,n,n), eigenvalues_(c,n) ascending, eigenvectors_ (c,n,n) with the normal direction in the first column, rho_.

fuzzyclust.cluster.GG

n_clusters=3, m=2.0, gamma=0.0, beta=1e15, tol, max_iter, init, n_init, random_state, verbose. m=1 gives the original FMLE algorithm, m=2 is recommended; the covariance exponent is w = m. Pass init=fcm.membership_ (or gk.membership_) for the recommended initialization. Attributes: covariances_, priors_ (c,), eigenvalues_, eigenvectors_; distances_ and transform return Dik2 capped at e350.

fuzzyclust.cluster.RegularizedFCM

n_clusters=3, regularization="entropy", lam=1.0, annealing=False, lam_start=None, anneal_rate=0.8, perturbation=1e-3, tol, max_iter, init, n_init, random_state, verbose. regularization is "entropy" (3.17) or "quadratic" (3.21); lam is λ in squared data units (the final temperature when annealing). annealing=True (entropy only) starts at lam_start (None: 2.2λmax ⁡ of the data covariance) with all prototypes at the grand mean and cools by anneal_rate; max_iter then applies per temperature. Attributes: lam_ and covariances_; with annealing cluster_history_ (a DataFrame with columns lam, n_effective, and objective), n_effective_clusters_, and critical_temperatures_. The functions entropy_memberships(d2, lam) and quadratic_memberships(d2, lam) evaluate the membership formulas for given squared distances.

fuzzyclust.cluster.PolynomialFuzzifierFCM

n_clusters=3, beta=0.5, tol, max_iter, init, n_init, random_state, verbose. beta ∈[0,1) is the fuzzifier parameter of (3.22). Attributes: n_active_ (number of positive memberships per training sample), covariances_ (weights g(μik)). The functions polynomial_fuzzifier(U, beta) and polynomial_memberships(d2, beta) implement (3.22) and (3.23).

fuzzyclust.cluster.SubtractiveClustering

radii=0.5, squash=1.25, accept_ratio=0.5, reject_ratio=0.15, max_clusters=None. radii is ra as a fraction of the range of every feature (a scalar or one value per feature). There is no n_clusters parameter; the number of clusters is a result, n_clusters_. Attributes: cluster_centers_ (data points in original units), center_indices_, potentials_ (relative potentials at selection), initial_potentials_ (the density estimate), membership_, labels_. predict_proba returns normalized Gaussian memberships exp ⁡ (−4D2∕ra2), transform the Euclidean distances to the centers in the original units.

fuzzyclust.cluster.MountainClustering

grid_size=None, max_nodes=10000, radii=0.5, squash=1.25, stop_ratio=0.15, max_clusters=None. grid_size=None chooses the largest grid with at most max_nodes nodes; an explicit grid that exceeds the bound raises an error. Attributes: grid_, grid_size_, mountain_ (before destruction), potentials_, n_clusters_, cluster_centers_; inference methods as for SubtractiveClustering.

Fitting is one line, and the fitted object exposes prototypes, memberships, and labels:

X, y_true = make_fuzzy_blobs(n_clusters=3, n_samples_per_cluster=100, random_state=0) 
 
fcm = FCM(n_clusters=3, m=2.0, random_state=0).fit(X)
   

The membership function between two prototypes is (3.6) in three lines of numpy:

ms = [1.1, 1.5, 2.0, 3.0, 5.0] 
x = np.linspace(-1.0, 2.0, 601) 
v = np.array([0.0, 1.0]) 
fig, ax = plt.subplots(figsize=(6.5, 4.2)) 
for j, m in enumerate(ms): 
    d2 = (x[:, None] - v[None, :]) ** 2 + 1e-10  # squared distances to v_1, v_2 
    mu = d2 ** (-1.0 / (m - 1.0)) 
    mu /= mu.sum(axis=1, keepdims=True) 
    ax.plot(x, mu[:, 0], lw=2.0, color=PALETTE[j], label=f"m = {m}")
   

The recommended way to run the three fuzzy algorithms on the same data chains them:

fcm = FCM(n_clusters=3, random_state=0).fit(X) 
gk  = GK(n_clusters=3, random_state=0, n_init=5).fit(X) 
gg  = GG(n_clusters=3, init=fcm.membership_).fit(X)   # GG started from the FCM partition 
print(gg.priors_)                                     # estimated cluster proportions 
U_new = gg.predict_proba(X_new)                       # memberships of unseen data

The four fuzzification mechanisms are interchangeable estimators:

models = { 
    "FCM (m = 2)": FCM(n_clusters=4, random_state=0, n_init=3), 
    "entropy (lambda = 0.5)": RegularizedFCM(n_clusters=4, regularization="entropy", lam=0.5, random_state=0, n_init=3), 
    "quadratic (lambda = 2)": RegularizedFCM(n_clusters=4, regularization="quadratic", lam=2.0, random_state=0, n_init=3), 
    "polynomial (beta = 0.5)": PolynomialFuzzifierFCM(n_clusters=4, beta=0.5, random_state=0, n_init=3), 
} 
for name, model in models.items(): 
    model.fit(X) 
    zeros = np.mean(model.membership_ == 0) 
    ari = adjusted_rand_score(y, model.labels_) 
    print(f"{name:24s} exact zeros = {zeros:5.1%}   ARI = {ari:.2f}   iterations = {model.n_iter_}")
   

Deterministic annealing is a flag of RegularizedFCM, and the history of the phase transitions is a DataFrame:

da = RegularizedFCM(n_clusters=4, lam=0.5, annealing=True, anneal_rate=0.9, tol=1e-6, random_state=0).fit(X) 
history = da.cluster_history_  # one row per temperature: lam, n_effective, objective
   

Subtractive clustering returns the number of clusters and the centers, which initialize any of the iterative algorithms:

sub = SubtractiveClustering(radii=0.25).fit(X) 
print(f"{sub.n_clusters_} centers, relative potentials at selection: {np.round(sub.potentials_, 2)}") 
mountain = MountainClustering(radii=0.25).fit(X)  # 100 x 100 grid nodes 
print(f"mountain method: {mountain.n_clusters_} centers on a {mountain.grid_size_} x {mountain.grid_size_} grid")
   
gk = GK(n_clusters=sub.n_clusters_, init=sub.cluster_centers_).fit(X)
   

On product-space data the number of centers is the number of rules of a Takagi–Sugeno model:

Z = np.column_stack([X_train, y_train])  # product space of input and output 
for r in (0.2, 0.3, 0.4): 
    n_rules = SubtractiveClustering(radii=r).fit(Z).n_clusters_ 
    ts = TakagiSugeno(n_clusters=n_rules, random_state=0, n_init=3).fit(X_train, y_train) 
    rmse = np.sqrt(np.mean((ts.predict(X_test) - y_test) ** 2)) 
    print(f"radius {r:.1f}: {n_rules:2d} rules, test RMSE = {rmse:.4f}")
                                                                     

                                                                     
   

3.4 Examples

3.4.1 Fuzzy c-means: memberships and prototypes

The script plot_01_fcm_basics.py fits FCM to three well-separated Gaussian clusters (fig. 1.3). It converges in six iterations, and the memberships printed for the least and the most ambiguous samples show the two faces of a fuzzy partition: samples at the prototypes have memberships (0,1,0), while samples between two clusters share theirs, for example (0.22,0.74,0.03). Figure 3.4 shows the contour maps for m = 1.2, 2, and 4. For m = 1.2 the regions of high membership are wide and the boundaries sharp (partition coefficient PC = 1.00); for m = 4 only the immediate neighborhood of a prototype has a high membership (PC = 0.54). On well-separated data the prototypes barely move with m.

Figure 3.4

Figure 3.4. Fuzzy c-means on three separated clusters for m = 1.2, 2, and 4. The partition coefficient PC in the titles falls from 1.00 to 0.54: a small exponent gives wide regions of high membership and sharp borders, a large one nearly uniform memberships with the same prototypes.

Open in ColabExample plot_01_fcm_basics.py in the gallery

3.4.2 The fuzziness exponent

The script plot_09_fuzziness_exponent.py isolates the exponent. Figure 3.5 plots (3.6) for two fixed prototypes on a line; for m = 2 it is the classical curve μ1(x) = (x −1)2∕((x −1)2 + x2), and the return of every curve toward 1∕2 outside the prototypes is the mark of the column constraint. On three overlapping clusters (fig. 3.6) the same trend appears in the plane. The third figure of the script (not shown) records, for m from 1.1 to 10, how the partition coefficient falls from 0.98 to 0.34, close to 1∕c; how the mean distance of the prototypes from the grand mean, after a slight rise from 3.18 to 3.24 at m = 1.75–2, falls to 2.73 as they drift together; and how the number of iterations behaves. It is lowest, 14, near m = 1.5–1.75, and grows above m ≈2 to 47 at m = 10 because the memberships change more slowly; at m = 1.1 it is 19, because the nearly crisp partition takes several iterations to settle.

Figure 3.5

Figure 3.5. Membership in the cluster of v1 = 0 along the line to v2 = 1 for five exponents. m →1 gives the Voronoi step of k-means, large m a flat function at 1∕2; far from both prototypes every curve tends to 1∕2.

Open in ColabExample plot_09_fuzziness_exponent.py in the gallery

Figure 3.6

Figure 3.6. FCM on three overlapping clusters for m = 1.2, 2, and 4: as m grows, the partition becomes less sharp and the prototypes move slightly toward the grand mean.

3.4.3 Hard versus fuzzy partitions

The script plot_02_hard_vs_fuzzy.py runs k-means, k-medoids, and FCM on three overlapping clusters. The hard labels of the three methods are identical here (adjusted Rand index 0.975 with the generating labels for each of them), and the script verifies that the medoids are rows of the data matrix. Figure 3.7 shows what FCM adds: the mixed colors mark the overlap regions, and the confidence map identifies the samples that a crisp label would misrepresent; with m = 2, 3.9% of the samples have a maximal membership below 0.6. The parameter study of the script shows how this share depends on the exponent while the labels stay put: it is 0.3% for m = 1.2, 11.7% for m = 2.5, and 61% for m = 4, with the agreement with the generating labels between 0.97 and 0.98 throughout.

Figure 3.7

Figure 3.7. The information a fuzzy partition carries beyond the labels. Left: FCM memberships blended into the cluster colors; the overlap regions are mixed. Right: the maximal membership as the confidence of the hard assignment; the ambiguous samples lie between the prototypes.

Open in ColabExample plot_02_hard_vs_fuzzy.py in the gallery

3.4.4 Gustafson–Kessel: shape, volume, and regularization

The script plot_03_gk_ellipses.py generates three elongated clusters with different orientations. In the comparison of FCM and GK (fig. 3.8), the 2σ ellipses of the fuzzy covariance matrices show what each algorithm “sees.” The elongation ratios λi2∕λi1 read from eigenvalues_ are 6.9, 8.7, and 8.4. Figure 3.9 varies the volume of the first cluster, ρ1 ∈{0.2,1,5}: its membership region shrinks or expands while the neighbors adjust, which is the lever to use when one cluster is known to be larger. Figure 3.10 adds a perfectly collinear fourth cluster. Without regularization the condition number of its fuzzy covariance matrix is about 6000, two orders of magnitude above those of the other clusters (50 to 80), and its membership region is a razor-thin line. With γ = 0.1 it obtains a finite width, but the shrinkage acts on every cluster and rounds the other ellipses as well; the bound β = 104 is not active, because no condition number reaches it. The parameter study of the script separates the two safeguards: β = 102 or 103 bounds the collinear cluster alone and keeps the adjusted Rand index at 0.93–0.94 (against 0.945 without regularization), whereas γ ≥0.05 shortens every elongation ratio to below 3 and lowers the index to 0.81 and less.

Figure 3.8

Figure 3.8. Three elongated clusters. FCM (left) draws circular contours that cut across the groups; GK (right) adapts an ellipse to each cluster and recovers the generating labels. Colored ellipses: 2σ ellipses of the fuzzy covariance matrices.

Open in ColabExample plot_03_gk_ellipses.py in the gallery

Figure 3.9

Figure 3.9. The volume parameter of GK. The first cluster is given ρ1 = 0.2, 1, and 5; its region of high membership shrinks and grows accordingly while the partition of the well-separated data stays stable.

Figure 3.10

Figure 3.10. Covariance regularization on a perfectly collinear cluster. Left: without regularization the condition number of its covariance matrix is two orders of magnitude above those of the other clusters, and its membership region degenerates to a line. Right: the shrinkage γ = 0.1 gives the cluster a finite width but also rounds its neighbors; the condition bound β = 104 is not reached.

3.4.5 Local optima of Gustafson–Kessel

Elongated clusters are also where GK shows its start dependence. Section 2.4.3 reported the twenty random starts of plot_10_initialisation_restarts.py on three noisy line segments, together with the remedy (restarts) and the failure of k-means++ seeding on these data; fig. 3.11 shows what the two optima look like. The best run (J = 142) recovers the three lines. The worst (J = 229) fits one prototype along the diagonal line and splits the two upper lines into left and right halves, a configuration that is locally consistent with thin ellipsoids and from which the iteration cannot escape.

Figure 3.11

Figure 3.11. Twenty random starts of GK on three line segments. Left: the final objectives fall into two groups. Middle: the best run recovers the lines. Right: the worst run is a converged local optimum in which two lines are split into halves and a third prototype follows the diagonal.

Open in ColabExample plot_10_initialisation_restarts.py in the gallery

3.4.6 Gath–Geva: size and density

The script plot_04_gg_densities.py generates a large diffuse cluster of 300 points next to two small dense ones of 60 points each. In fig. 3.12, FCM and GK, whose clusters have equal volume, let the two small clusters take over the margin of the big one (adjusted Rand indices 0.70 and 0.44), whereas GG, started from the FCM partition, gives the big cluster a large covariance and a large prior and leaves the small ones intact. The estimated priors (0.14,0.15,0.71) match the true proportions (0.71,0.14,0.14) up to the order of the clusters. The script also runs GG from ten random starts: the agreement with the generating labels varies between 0.83 and 0.98, and the FCM-initialized run matches the best of them without any restarts. Figure 3.13 displays the fitted components as the mixture density ∑ ⁡ iαiN(x;vi,Fi), the reading of (3.13) as a Gaussian mixture.

Figure 3.12

Figure 3.12. Clusters of very different size and density. FCM and GK give the margin of the large diffuse cluster to the small ones because their clusters have equal volume; GG, initialized from FCM, adapts volume and prior and recovers the structure.

Open in ColabExample plot_04_gg_densities.py in the gallery

Figure 3.13

Figure 3.13. The GG result read as a Gaussian mixture: the density ∑ ⁡ iαiN(x;vi,Fi) of the three fitted components over the data.

3.4.7 Evaluating new data

A fitted model defines a membership function over the whole space, not only a partition of the training data. The script plot_06_predict_new_data.py fits GK to 60 % of the samples of three elongated clusters and evaluates the rest with predict_proba, predict, and transform; the test samples fall into the regions of the training clusters (first figure of the script). Figure 3.14, the classical comparison figure of the toolbox manual drawn for these data, confirms the sketch of fig. 3.1. The script ends with a monitoring application: for a point far outside the data the maximal GK membership drops to 0.52 and its distance to the nearest prototype is 28, against a median of 1.2 for the training samples, so both quantities can serve as novelty scores. The same mechanism is used for validation in chapter 4.

Figure 3.14

Figure 3.14. The membership function learned from the same training data by four algorithms: Voronoi cells (k-means), circles (FCM), ellipses (GK), and density-shaped regions with sharp borders (GG). Every algorithm defines its own distance, and predict_proba evaluates it for any new sample.

Open in ColabExample plot_06_predict_new_data.py in the gallery

3.4.8 Real data: motorcycle and iris

Two scripts discussed in section 2.4 also belong here. On the standardized motorcycle data (plot_07_motorcycle_scaling.py), four GK clusters segment the acceleration signal into the phases before, during, and after the impact. In the scaled space (fig. 3.15) the orientation of each cluster is the local slope of the signal, the first appearance of the local-linear-model reading of GK that chapters 8 and 9 develop. On the iris data (plot_08_sklearn_pandas_workflow.py), GK with three clusters separates setosa cleanly and divides versicolor and virginica with the overlap reported in section 2.4.4; the misclassification rate of about 10% agrees with the figures reported for the MATLAB toolbox.

Figure 3.15

Figure 3.15. Gustafson–Kessel contours on the standardized motorcycle data. Each ellipse follows the local slope of the acceleration signal: the covariance of a GK cluster encodes a local linear model.

Open in ColabExample plot_07_motorcycle_scaling.py in the gallery

3.4.9 Fuzzifiers, regularization, and deterministic annealing

The script plot_12_fuzzifiers_annealing.py puts the mechanisms of section 3.2.7 side by side. Figure 3.16 evaluates the membership formulas for three prototypes on a line at 0, 1, and 4. The FCM memberships are positive everywhere: the third cluster keeps a small membership even between the first two prototypes (about 0.01 at their midpoint) and 0.07 at x = −2. The entropy memberships are softmax functions that become crisp a short distance from every border. The quadratic and polynomial memberships are exactly zero for at least one cluster almost everywhere, and between v1 and v2 the third cluster has no influence at all. On four groups in the plane (fig. 3.17) all four mechanisms recover the groups (adjusted Rand index 0.98), but the membership matrices differ: the quadratic regularization (λ = 2) gives 71% and the polynomial fuzzifier (β = 0.5) 74% exact zeros, close to the maximum (c −1)∕c = 75%, while FCM and the entropy regularization give none. In the contours this appears as flat plateaus of membership one inside the groups for the two sparse mechanisms and as ripples around every prototype for FCM.

Figure 3.16

Figure 3.16. Memberships of three clusters with prototypes at 0, 1, and 4 on a line under four fuzzification mechanisms. The dark bar below the curves marks where at least one membership is exactly zero: nowhere for FCM and the entropy regularization, almost everywhere for the quadratic regularization and the polynomial fuzzifier.

Open in ColabExample plot_12_fuzzifiers_annealing.py in the gallery

Figure 3.17

Figure 3.17. Maximal membership on four groups for FCM, entropy and quadratic regularization, and the polynomial fuzzifier: the sparse mechanisms are crisp inside the groups and fuzzy only between neighbors.

Deterministic annealing on the same data (fig. 3.18) starts at λ = 35.4, just above the critical temperature 2λmax ⁡ (F0) = 32.2 of the whole data set, and cools by the factor 0.9. The four prototypes stay together until λ = 28.7, where they split into two pairs (the left and the right halves of the data), and the pairs split at λ = 3.14, just below the critical temperatures 3.27 and 3.53 of the two halves predicted by (3.19). The final partition at λ = 0.5 recovers the four groups with an adjusted Rand index of 0.98, without any random initialization. The parameter study (fig. 3.19) shows the same transition from the other side: at a fixed temperature, the partition coefficient of the entropy-regularized partition stays near one up to λ = 1 (0.97) and drops to 1∕2 for λ ≥5 (0.500 and 0.498), because above the critical temperature of the halves the two prototypes of each half coincide and the four prototypes describe two clusters. The polynomial fuzzifier produces exact zeros as soon as β > 0 (70% already at β = 0.1); a larger β only sharpens the borders, and the partition coefficient rises from 0.87 (β = 0, FCM) to 0.99 at β = 0.5.

Figure 3.18

Figure 3.18. Deterministic annealing on four groups. Left: the number of distinct prototypes against the decreasing temperature jumps from one to two near the critical temperature of the whole data and from two to four near those of the two halves (vertical lines, 2λmax ⁡ of the covariances). Right: the final partition.

Figure 3.19

Figure 3.19. Parameter study: partition coefficient of the entropy regularization against λ (left; the drop to 1∕2 is the merging of the prototype pairs above the critical temperature) and partition coefficient and fraction of exact zeros of the polynomial fuzzifier against β (right).

3.4.10 Subtractive clustering: number of clusters, initialization, and rules

The script plot_13_subtractive_clustering.py generates eight elongated groups with 40 to 150 samples each. With ra = 0.25, subtractive clustering selects eight centers, one per group, in the order of decreasing potential: the relative potentials at selection fall from 1 and 0.97 for the two large groups to 0.26 for the last small one (fig. 3.20, left). The mountain method on a 100 ×100 grid finds the same eight centers (right panel); its mountain function is visibly the same density estimate as the potential of the samples. Passed to GK as init, the subtractive centers lead to the optimum (J = 353.9, adjusted Rand index 0.97) in 33 iterations, against a median of 44 and a maximum of 126 for twenty random starts that all reach the same optimum (second figure of the script).

Figure 3.20

Figure 3.20. Subtractive clustering and the mountain method on eight elongated groups. Left: the potential of every sample and the centers numbered in the order of selection. Right: the mountain function on a 100 ×100 grid and the selected nodes.

Open in ColabExample plot_13_subtractive_clustering.py in the gallery

The radius study (fig. 3.21) shows how the method is used in practice. The number of centers falls with the radius and, with the default squash factor, stays at eight for ra ∈[0.18,0.30]: below the plateau the elongated groups are cut into pieces, above it neighboring groups fall within one radius. A larger squash factor shifts the plateau to smaller radii ([0.14,0.24] for η = 1.5, [0.22,0.38] for η = 1), because the subtracted bump has the radius ηra; the mountain method follows the subtractive curve closely. The last part of the script uses subtractive clustering as Chiu did, as a rule-number estimator for a Takagi–Sugeno model of sin ⁡ (x)∕x (fig. 3.22). Run on the product space of input and output, it suggests 12, 10, 6, 4, and 3 rules for ra = 0.15, 0.2, 0.3, 0.4, and 0.5. The test error, computed for every number of rules, decreases steeply up to six rules (RMSE = 0.039) and flattens beyond ten (0.024); the radius 0.3 thus gives the smallest accurate model and 0.2 the accurate end of the curve, while 0.5 is too coarse (RMSE = 0.13 with three rules).

Figure 3.21

Figure 3.21. Number of centers against the radius for three squash factors and for the mountain method. The plateau at eight (dotted line) indicates the stable structure.

Figure 3.22

Figure 3.22. Test error of Takagi–Sugeno models of sin ⁡ (x)∕x against the number of rules, with the rule numbers estimated by subtractive clustering in the input–output space for five radii (dashed lines).

3.5 Further reading

k-means goes back to MacQueen [17], k-medoids to Kaufman and Rousseeuw [5]; k-means++ seeding is due to Arthur and Vassilvitskii [15]. Fuzzy c-means was introduced by Dunn [2] and generalized and analyzed by Bezdek and co-workers [3, 10, 11, 16]. The Gustafson–Kessel algorithm appeared in [18], its covariance regularization in Babuška, van der Veen, and Kaymak [19]; the use of the eigenstructure of Fi for local linear models is developed in Babuška’s monograph [7]. Fuzzy maximum likelihood estimation is due to Bezdek and Dunn [20] and the Gath–Geva algorithm to Gath and Geva [21], whose paper also introduced the volume-based validity measures of the next chapter. The exposition of the four algorithms follows the MATLAB toolbox manual [12] and the same monograph [7]; Höppner et al. [6] discuss all of them with their shell and variety relatives. The entropy regularization is due to Li and Mukaidono [24] and Miyamoto and Mukaidono [23], the quadratic one to Miyamoto and Umayahara [26]; Rose [25] surveys deterministic annealing with its phase transitions and its applications beyond clustering. Klawonn and Höppner [22] analyze what makes a fuzzifier and propose the polynomial one. The mountain method is from Yager and Filev [27], subtractive clustering and its use for fuzzy model identification from Chiu [28].