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 , 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 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 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.
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 (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 is , 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 disjoint subsets and minimizes the within-cluster sum of squares,
|
| (3.1) |
which is the c-means functional (2.9) for and a hard partition. For fixed subsets the minimizing prototype is the mean of the members,
|
| (3.2) |
and for fixed prototypes the minimizing partition assigns every sample to its nearest prototype, if and otherwise. Alternating the two steps decreases 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.
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 ( 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 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 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, . 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 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.
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 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,
|
| (3.3) |
where , , and is a fixed norm-inducing matrix (identity, diagonal, or Mahalanobis, section 2.2.2). The stationary points are found by adjoining the column constraint with Lagrange multipliers ,
|
| (3.4) |
and setting the partial derivatives to zero. The derivative with respect to a single membership gives
|
| (3.5) |
and summing (3.5) over under the column constraint gives
so that dividing (3.5) by this sum eliminates the multiplier:
|
| (3.6) |
The derivative with respect to gives , hence
|
| (3.7) |
independently of . If for all and , then can minimize (3.3) only if (3.6) and (3.7) hold [3]; the solution automatically satisfies the remaining constraints of . Equation (3.7) is the mean of the data weighted by the memberships raised to , 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 -) norm. If some , the membership formula is undefined; fuzzyclust, like the MATLAB toolbox, adds 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 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 the exponent grows without bound, each ratio tends to or , and the partition becomes crisp: FCM turns into k-means. As the exponent tends to zero, every ratio tends to one, and for every sample; the prototypes (3.7) then all coincide with the grand mean of the data. In between, trades the sharpness of the partition against its robustness: with a small every sample pulls mainly its own prototype, with a large 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 ; this is the price of the column constraint, which the possibilistic variants of chapter 6 remove. Second, the memberships change more slowly for larger , so above the number of iterations needed to reach a given tolerance grows with ; close to it rises again, because the nearly crisp partition takes several iterations to settle (section 3.4.2). The usual default is , for which (3.6) reduces to , and values in are the range to explore; the validity indices of chapter 4 can be scanned over as well as over .
In a nutshell: Fuzzy c-means
- Minimizes over fuzzy partitions; prototypes are -weighted means, memberships are inverse relative distances raised to .
- One global norm : spherical clusters (Euclidean), axis-parallel or commonly oriented ellipsoids (diagonal, Mahalanobis); clusters of similar size.
- : k-means; : all memberships , prototypes collapse; default , explore .
- 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 , which becomes an optimization variable,
|
| (3.8) |
For fixed the memberships and prototypes are those of FCM, (3.6) and (3.7). The functional cannot be minimized over directly, because it is linear in and can be made arbitrarily small by making less positive definite. The matrices must therefore be constrained, and the natural constraint fixes their determinants,
|
| (3.9) |
which lets every cluster adapt its shape while its volume stays constant. Adjoining (3.9) with multipliers and differentiating with respect to gives , so is proportional to the inverse of the fuzzy covariance matrix of the cluster, and the constraint fixes the factor:
|
| (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 . Without prior knowledge all 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 (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 describes the shape and orientation of the cluster: the eigenvectors are the axes of the ellipsoid and the square roots of the eigenvalues 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 lie close to a hyperplane, that hyperplane is . 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, is nearly singular: its smallest eigenvalue approaches zero, the condition number explodes, is unreliable, and the volume normalization fails as . 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 before inversion:
The first shrinks every cluster covariance toward a scaled identity; 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 by by raising the small eigenvalues; the MATLAB default is effectively off, and a bound between and 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 and , and stores the regularized in covariances_. Both devices break the affine invariance of GK, because the identity matrix and the eigenvalues of depend on the units of the data.
In a nutshell: Gustafson–Kessel
- FCM with a norm-inducing matrix per cluster, ; the determinant constraint fixes the volume and lets the shape adapt.
- Detects ellipsoidal clusters of different orientation and elongation but (for ) of similar volume; affine-invariant in exact arithmetic.
- The eigenstructure of gives axes, elongation, and the normal direction of a cluster—the basis of local linear models.
- Nearly singular (few points, collinear data) is handled by shrinkage toward and by the condition bound .
- 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 as a Gaussian component with mean , covariance , and prior probability , and uses the reciprocal of the prior-weighted density as distance,
|
| (3.13) |
with
|
| (3.14) |
The covariance weighting exponent is in the original FMLE algorithm; the MATLAB toolbox and fuzzyclust use (so 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 covers both. Memberships and prototypes are updated with the FCM formulas (3.6) and (3.7). Three consequences follow from (3.13). First, is proportional to , so for the membership is exactly Bayes’ rule for the posterior probability of component given : GG is a fuzzy relative of the EM algorithm for Gaussian mixtures and differs from it in the weights of the center and covariance updates. Second, volume and density adapt: neither nor 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 , which happens routinely for far samples and small clusters; the MATLAB manual warns that GG “can overflow at large values.” fuzzyclust therefore works with the logarithm , computes it with a stable log-determinant, caps it at (so that stays below the largest finite double), and evaluates the membership formula as a softmax over clusters,
|
| (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, . The covariances can be regularized exactly as in GK (gamma, beta), which is advisable when the clusters have few samples.
In a nutshell: Gath–Geva
- Distance reciprocal of a prior-weighted Gaussian density; memberships are posterior probabilities (for ), 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 for a center to for center, covariance, and prior), more computation (the 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.
| k-means / k-medoids | FCM | GK | GG |
|
| prototype | mean / medoid | center | center , covariance | center , covariance , prior |
| distance | Euclidean | fixed norm , eq. (3.3) | volume-scaled Mahalanobis, eq. (3.10) | inverse prior-weighted Gaussian density, eq. (3.13) |
| partition | crisp, | fuzzy, | fuzzy, | 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 |
| , , | , , , , | , , , |
| cost per iteration | (medoids: ) |
|
|
|
| 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 with . Without the exponent () the c-means functional is linear in every column of , and a linear function on the simplex 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 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,
|
| (3.16) |
Adjoining the column constraint as in (3.4) and differentiating gives , so , and normalization yields the Gibbs (softmax) memberships
|
| (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 of the squared distances, not on their ratios: far from all prototypes a sample belongs entirely to the nearest one instead of tending to , 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 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,
|
| (3.18) |
and Rose’s deterministic annealing [25] minimizes it while the temperature is lowered. At a high temperature 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 (weights ) splits when falls below the critical temperature
|
| (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 instead,
|
| (3.20) |
The stationarity condition is linear in , and it can hold only for the clusters of an active set ; for the others the nonnegativity constraint binds and . With the nearest prototypes,
|
| (3.21) |
where is the largest number of nearest prototypes for which all these values are positive. Equivalently, the column is the Euclidean projection of onto the simplex, which is computed exactly by sorting. For two clusters, clipped to : 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: at , 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 with removes this effect; they proposed the quadratic polynomial
|
| (3.22) |
which interpolates between (, FCM with ) and (, k-means), and minimized . The Kuhn–Tucker conditions give, for the active set of the nearest prototypes,
|
| (3.23) |
with the largest size for which all values are positive, and prototypes . For two clusters the second membership vanishes as soon as : a sample whose nearest prototype is at distance ignores every cluster farther than . 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 . The parameter keeps the name of the paper and of the code parameter beta; it is unrelated to the condition-number bound of GK.
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): 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 ; prototypes split at the critical temperatures , 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_.
In a nutshell: Polynomial fuzzifier
- Replaces by , 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 , so the members of one cluster no longer pull the distant prototypes.
- Distances enter as ratios, so the partition is scale-invariant like FCM; is FCM with , k-means, recommended.
- Same cost per iteration as FCM plus a sort of the 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 is laid over it. Every node receives the value of the mountain function, the sum of Gaussian influences of all samples,
|
| (3.24) |
where is the neighborhood radius: samples farther than contribute less than . The highest node with height is the first center. Its mountain is then destroyed: with a second radius , 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 . The grid is the method’s weakness: with nodes per axis there are 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 , linear instead of exponential in the dimension. The potential of sample is
|
| (3.25) |
a kernel density estimate with bandwidth . After the selection of the center with potential all potentials are revised,
|
| (3.26) |
with the squash factor (Chiu suggests ; a common default is ), so that no second center is placed close to an existing one. The stopping rule has a gray zone. A candidate with is accepted, one with ends the search (, 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, ; otherwise its potential is set to zero and the next candidate is examined. The radius , 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 . Chiu’s own application was fuzzy modeling: run on the product space 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).
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 as a fraction of the data range; a plateau of the number of centers over indicates a stable structure.
- time and memory: practical for thousands of samples in any dimension.
- Uses: initial centers and 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_.
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 .
- nodes: exponential in the number of features, practical for ; 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 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" (), "diagonal" (inverse feature variances), "mahalanobis" (pseudo-inverse of the data covariance), or an explicit matrix; the matrix used is stored in norm_matrix_. Requires . 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 volumes (None: all one); gamma the shrinkage weight (3.11); beta the condition-number bound (3.12). Attributes: covariances_ after regularization, norm_matrices_ , eigenvalues_ ascending, eigenvectors_ 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 . Pass init=fcm.membership_ (or gk.membership_) for the recommended initialization. Attributes: covariances_, priors_ , eigenvalues_, eigenvectors_; distances_ and transform return capped at .
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: 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 is the fuzzifier parameter of (3.22). Attributes: n_active_ (number of positive memberships per training sample), covariances_ (weights ). 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 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 , 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 , while samples between two clusters share theirs, for example . Figure 3.4 shows the contour maps for , , and . For the regions of high membership are wide and the boundaries sharp (partition coefficient ); for only the immediate neighborhood of a prototype has a high membership (). On well-separated data the prototypes barely move with .
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 it is the classical curve , and the return of every curve toward 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 from to , how the partition coefficient falls from to , close to ; how the mean distance of the prototypes from the grand mean, after a slight rise from to at –, falls to as they drift together; and how the number of iterations behaves. It is lowest, , near –, and grows above to at because the memberships change more slowly; at it is , because the nearly crisp partition takes several iterations to settle.
Open in ColabExample plot_09_fuzziness_exponent.py in the gallery
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 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 , of the samples have a maximal membership below . The parameter study of the script shows how this share depends on the exponent while the labels stay put: it is for , for , and for , with the agreement with the generating labels between and throughout.
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 ellipses of the fuzzy covariance matrices show what each algorithm “sees.” The elongation ratios read from eigenvalues_ are , , and . Figure 3.9 varies the volume of the first cluster, : 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 , two orders of magnitude above those of the other clusters ( to ), and its membership region is a razor-thin line. With it obtains a finite width, but the shrinkage acts on every cluster and rounds the other ellipses as well; the bound is not active, because no condition number reaches it. The parameter study of the script separates the two safeguards: or bounds the collinear cluster alone and keeps the adjusted Rand index at – (against without regularization), whereas shortens every elongation ratio to below and lowers the index to and less.
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 () recovers the three lines. The worst () 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.
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 and ), 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 match the true proportions up to the order of the clusters. The script also runs GG from ten random starts: the agreement with the generating labels varies between and , and the FCM-initialized run matches the best of them without any restarts. Figure 3.13 displays the fitted components as the mixture density , the reading of (3.13) as a Gaussian mixture.
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 and its distance to the nearest prototype is , against a median of for the training samples, so both quantities can serve as novelty scores. The same mechanism is used for validation in chapter 4.
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 agrees with the figures reported for the MATLAB toolbox.
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 , , and . The FCM memberships are positive everywhere: the third cluster keeps a small membership even between the first two prototypes (about at their midpoint) and at . 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 and 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 ), but the membership matrices differ: the quadratic regularization () gives and the polynomial fuzzifier () exact zeros, close to the maximum , 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.
Open in ColabExample plot_12_fuzzifiers_annealing.py in the gallery
Deterministic annealing on the same data (fig. 3.18) starts at , just above the critical temperature of the whole data set, and cools by the factor . The four prototypes stay together until , where they split into two pairs (the left and the right halves of the data), and the pairs split at , just below the critical temperatures and of the two halves predicted by (3.19). The final partition at recovers the four groups with an adjusted Rand index of , 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 () and drops to for ( and ), 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 ( already at ); a larger only sharpens the borders, and the partition coefficient rises from (, FCM) to at .
3.4.10 Subtractive clustering: number of clusters, initialization, and rules
The script plot_13_subtractive_clustering.py generates eight elongated groups with to samples each. With , subtractive clustering selects eight centers, one per group, in the order of decreasing potential: the relative potentials at selection fall from and for the two large groups to for the last small one (fig. 3.20, left). The mountain method on a 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 (, adjusted Rand index ) in iterations, against a median of and a maximum of for twenty random starts that all reach the same optimum (second figure of the script).
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 : 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 ( for , for ), because the subtracted bump has the radius ; 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 (fig. 3.22). Run on the product space of input and output, it suggests , , , , and rules for , , , , and . The test error, computed for every number of rules, decreases steeply up to six rules () and flattens beyond ten (); the radius thus gives the smallest accurate model and the accurate end of the curve, while is too coarse ( with three rules).
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 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].