Fuzzy Clustering and Data Analysis in PythonThe fuzzyclust toolbox

Chapter 2
Foundations of prototype-based clustering

The previous chapter motivated fuzzy partitions; this one lays the common ground on which every algorithm of the toolbox stands. We fix the data matrix and the notation, define the distance norms that decide what a cluster can look like, introduce the hard, fuzzy, and possibilistic partition spaces, and describe the kinds of prototypes that the later chapters fit. We then present the objective-function view of clustering, with alternating optimization as the template that all algorithms share, discuss initialization, termination, and scaling, and collect the notation in a table. The chapter closes with the scikit-learn interface shared by the clustering estimators of fuzzyclust; the individual algorithms follow in chapter 3.

2.1 Problem and idea

Prototype-based clustering fits a small number of geometric objects, the prototypes, to a large number of samples and describes every sample by its distances to the prototypes. Three ingredients are involved: the data, a set of N samples in ℝn; the prototypes, c objects of a chosen kind; and the partition, which says to what degree each sample belongs to each prototype. An objective function scores how well the prototypes fit the data given the partition, and an iterative algorithm improves the partition and the prototypes in turn. The algorithms of this book (hard or fuzzy, with points, ellipsoids, lines, or shells as prototypes) are instances of this one scheme, and almost all of their differences come down to two choices: which prototype and which distance.

Figure 2.1 shows the four kinds of prototypes that appear in the book. A point prototype with a fixed norm detects spherical clusters (or, with a diagonal or Mahalanobis norm, ellipsoidal clusters that all have the same shape); this is fuzzy c-means. A point prototype with a norm adapted to each cluster detects ellipsoids of different shape and orientation (and, in the Gath–Geva algorithm, of different size); these are the Gustafson–Kessel and Gath–Geva algorithms, whose prototype is in fact the pair (center, covariance). A linear-variety prototype measures the distance of a sample to a line, plane, or hyperplane and detects flat clusters, which is what local linear models in identification need. A shell prototype measures the distance to a circle or ellipse and detects hollow clusters. The rest of this chapter is about what all of them have in common.

Figure 2.1

Figure 2.1. The prototypes of this book and the cluster shapes they detect. A point prototype with one fixed norm detects spheres (chapter 3, FCM); a point with its own covariance matrix detects ellipsoids whose axes are the eigenvectors ϕj of Fi scaled by λj (GK, GG); a linear variety measures the orthogonal distance of a sample to a line or hyperplane and detects flat clusters; a shell prototype measures the distance to a circle of radius ri and detects hollow clusters (both in chapter 6). Whatever the prototype, the algorithm needs only the distances Dik of every sample to every prototype.

2.2 Theory

This section follows the order of the ingredients: data (section 2.2.1), distances (section 2.2.2), partitions (section 2.2.3), and prototypes (section 2.2.4); then the objective function and the alternating optimization that ties them together (section 2.2.5); the practical matters of initialization, termination, and scaling (sections 2.2.6 to 2.2.8); and finally the notation table (section 2.2.9). The notation is that of Babuška [7], which the MATLAB toolbox [12] also used.

2.2.1 The data

Clustering is applied here to quantitative data. Each observation consists of n measured variables, grouped into a row vector xk = [xk1,xk2,…,xkn] ∈ ℝn, and the N observations form the data matrix

X = [ x11 x12 ⋯ x1n x21 x22 ⋯ x2n ⋮ ⋮ ⋱ ⋮ ] ∈ ℝN×n,X = [x 1,…,xN]T.
(2.1)

In pattern recognition the rows are called patterns or objects, and the columns features or attributes. The meaning of the rows depends on the application (section 1.1): independent observations in data analysis, consecutive samples or delay vectors of signals in time-series analysis, and regression vectors built from lagged inputs and outputs in system identification, where X spans the product space of regressors and regressands and the clusters are regions in which one local model is valid. In the last two cases, past values of the variables usually enter X as extra columns; make_regressors and lagged_matrix of fuzzyclust.preprocessing build them. Throughout the book k = 1,…,N indexes samples and i,j = 1,…,c index clusters; in code the data are stored row-wise, exactly as in (2.1).

2.2.2 Distance norms

A cluster is a group of objects that are more similar to one another than to the members of other clusters, and in a metric space similarity is measured by a distance norm. Except for Gath–Geva, the algorithms of chapter 3 measure the distance of a sample to a prototype with the squared inner-product norm

DikA2 = ‖x k −vi‖ A2 = (x k −vi)TA(x k −vi),
(2.2)

where the symmetric positive definite matrix A ∈ ℝn×n is the norm-inducing matrix. Its unit sphere {x : xTAx = 1}, the boundary of the unit ball, holds the points at unit distance from the origin; centered on a prototype, it gives the shape of the iso-membership contours near that prototype (fig. 2.2). Three global choices are classical:

Any positive definite A can be factored as A = LTL, and then DikA2 = ‖Lxk −Lvi‖ 2: clustering with the norm A is Euclidean clustering of the linearly transformed data Lxk. A global norm therefore cannot give clusters different shapes; it fixes one shape for all of them. The Gustafson–Kessel algorithm (section 3.2.4) gives every cluster its own matrix Ai, derived from the covariance of its members, and the Gath–Geva algorithm (section 3.2.5) replaces the inner-product norm with an exponential distance. Both are treated in the next chapter; fig. 2.2 already shows what the adaptive norm adds.

Figure 2.2

Figure 2.2. Unit spheres {x : xTAx = 1} of the inner-product norms. The Euclidean norm gives spheres, the diagonal norm axis-parallel ellipsoids (equivalent to standardizing the features), and the Mahalanobis norm ellipsoids oriented like the whole data cloud. All three are global, so every cluster has the same shape; the Gustafson–Kessel algorithm (right) gives each cluster its own norm-inducing matrix and thus its own ellipsoid.

2.2.3 Partition spaces

The clusters are subsets of the data, and the partition says which sample belongs to which subset. A hard partition of X into c clusters is a family of subsets A1,…,Ac with

⋃ i=1cA i = X,Ai ∩Aj = ∅(i≠j),∅⊂Ai ⊂X,
(2.4)

that is, the subsets cover the data, they are disjoint, and none is empty or equal to the whole data set. In terms of the characteristic functions μi(xk) = μik ∈{0,1} of the subsets, these conditions read

μik ∈{0,1},∑ i=1cμ ik = 1∀ ⁡k,0 < ∑ k=1Nμ ik < N∀ ⁡i,
(2.5)

and the memberships are collected in the partition matrix U = [μik] ∈ ℝc×N, whose i-th row is the membership function of cluster i and whose k-th column holds the memberships of sample k.

Definition 2.1 (Hard partitioning space). Let X = {x1,…,xN} be a finite set and 2 ≤c < N an integer. The hard partitioning space of X is

Mhc ={U ∈ ℝc×N |μ ik ∈{0,1}∀ ⁡i,k;∑ i=1cμ ik = 1∀ ⁡k;0 < ∑ k=1Nμ ik < N∀ ⁡i}.
(2.6)

A fuzzy partition [1] relaxes the first condition and lets the memberships take any value in [0,1]. The sum of each column is still one, so the total membership of each sample is distributed over the clusters; how it is distributed is not constrained.

Definition 2.2 (Fuzzy partitioning space). With X and c as above, the fuzzy partitioning space is

Mfc ={U ∈ ℝc×N |μ ik ∈[0,1]∀ ⁡i,k;∑ i=1cμ ik = 1∀ ⁡k;0 < ∑ k=1Nμ ik < N∀ ⁡i}.
(2.7)

The column constraint ∑ ⁡ iμik = 1 makes the memberships relative: a sample far from all prototypes still has memberships that sum to one, and a sample equidistant from all prototypes has μik = 1∕c in every cluster, however far away it is (fig. 1.1, bottom). This is sometimes called the probabilistic constraint. The possibilistic partition [14] drops it and only requires every sample to belong to at least one cluster to some degree:

Definition 2.3 (Possibilistic partitioning space).

Mpc ={U ∈ ℝc×N |μ ik ∈[0,1]∀ ⁡i,k;∀ ⁡k∃ ⁡i : μik > 0;0 < ∑ k=1Nμ ik < N∀ ⁡i}.
(2.8)

Possibilistic memberships are absolute degrees of typicality: a sample far from everything has small memberships in all clusters, so an outlier is recognized as such. The price is that the clusters are no longer coupled through the column sum, and the clustering problem splits into c independent problems that may all converge to the same cluster unless additional terms hold them apart; this is the subject of chapter 6. Figure 2.3 shows a partition matrix in each of the three spaces. The nesting Mhc ⊂Mfc ⊂Mpc is immediate, and so is the fact that Mfc is a convex set, whereas Mhc is a finite one; the former is why fuzzy clustering can be treated with calculus, and the latter why hard clustering is a combinatorial problem.

Figure 2.3

Figure 2.3. One partition matrix of three clusters and five samples in each of the three partitioning spaces. In the hard space every column is a unit vector; in the fuzzy space the columns are points of the probability simplex, so memberships are relative; in the possibilistic space the columns are free, so memberships are absolute degrees of typicality and an outlier (highlighted column) has small memberships everywhere.

2.2.4 Prototypes

The prototype of cluster i is the object the distances are measured to. In the simplest case it is a point vi ∈ ℝn of the data space, the cluster center, and the matrix V = [v1,…,vc]T ∈ ℝc×n collects the centers. The algorithms of chapter 3 all have point prototypes. The Gustafson–Kessel and Gath–Geva algorithms add to each center a covariance matrix Fi that shapes the norm around it, so their prototype is in effect the ellipsoid (vi,Fi); Gath–Geva also adds a prior probability αi that scales the size of the cluster. A medoid (section 3.2.2) is a point prototype constrained to be one of the samples, which is useful when the mean of a group has no meaning. Prototypes of higher order are linear varieties (points, lines, and planes) and shells (circles and ellipses), treated in chapter 6. In the identification setting of chapter 8 the prototype of a cluster is a local linear model, whose parameters are read off the eigenstructure of Fi or fitted by weighted least squares. Whatever the prototype, the clustering algorithm needs only the distances Dik of every sample to every prototype, and this is the interface that the base class of the toolbox asks an algorithm to provide.

2.2.5 Objective functions and alternating optimization

Most of the algorithms in this book minimize a sum of weighted squared distances, the c-means functional of Dunn [2] and Bezdek [3],

J(X;U,V) = ∑ i=1c ∑ k=1Nμ ikmD ik2,U ∈M fc,m > 1,
(2.9)

where Dik2 is the squared distance of xk to the prototype of cluster i in the norm of the algorithm and m is the fuzziness or weighting exponent. Statistically, J measures the total variance of the samples about the prototypes, with each sample counted in cluster i with weight μikm. For m →1 and U ∈Mhc it is the within-cluster sum of squares of k-means. Most algorithms of chapter 3 and of the later chapters are defined by (2.9) together with a choice of distance and prototype; the Gath–Geva algorithm, the possibilistic variants, and the fuzzy self-organizing map modify the functional but keep its structure.

Minimizing J over U and V jointly is a nonconvex problem. It is, however, convex in U for fixed prototypes and easy in V for fixed U. With the column constraint adjoined by Lagrange multipliers, setting the gradient with respect to U to zero yields a closed-form expression for the memberships in terms of the distances (derived in section 3.2.3), and setting the gradient with respect to the prototypes to zero yields the prototypes as membership-weighted means (or an analogous update for ellipsoids, lines, and shells). The classical way to exploit this is alternating optimization, also called Picard iteration or grouped coordinate descent: fix U and update the prototypes, fix the prototypes and update U, and repeat. Neither half-step can increase J, so the sequence J(1) ≥J(2) ≥… is monotone and bounded below. Bezdek’s original theorem [10] claimed convergence to a local minimum; the corrected theorem of Bezdek, Hathaway, Sabin, and Tucker [11] states that every convergent subsequence of the iterates tends to a local minimum or a saddle point of J, and saddle points are rarely met in practice. Figure 2.4 shows the loop as it is implemented once in BaseFuzzyClusterer. An algorithm provides the prototype update and the distance computation; the base class provides everything else.

Figure 2.4

Figure 2.4. Alternating optimization as implemented once in BaseFuzzyClusterer. An algorithm defines only how prototypes are computed from the weighted partition and how distances to its prototypes are measured (blue blocks); the base class provides the initialization and the membership update (green blocks, which an algorithm may override), the termination test, the objective history, and the restarts.

Algorithm

In a nutshell: The common template

  • Every algorithm minimizes a sum of membership-weighted squared distances J = ∑ ⁡ ikμikmDik2 over a partition U and prototypes V.
  • Two choices define an algorithm: the prototype (point, ellipsoid, medoid, line, shell) and the distance (fixed norm, adaptive norm, exponential).
  • Alternating optimization updates prototypes and memberships in turn; J decreases monotonically, and the iteration converges to a local minimum (in rare cases to a saddle point).
  • Which optimum is reached depends on the start: restarts (n_init) and good seeds are the remedy; a converged run with a poor J is a poor optimum, not an unfinished one.
  • Parameters shared by the estimators: n_clusters, tol, max_iter, init, n_init, random_state, and, in the fuzzy ones, m.

2.2.6 Initialization and local optima

The alternating optimization is a local method, so the initial partition decides which stationary point is reached. The toolbox offers three ways to start. The default, init="random", reproduces the MATLAB toolbox: c prototypes are drawn uniformly from a box that is centered on the data mean and encloses all samples, vi(0) = x¯ + (2ui −1) ⊙h with ui ∼U[0,1]n and hj = max ⁡ k |xkj −x¯j|, and the initial memberships follow from the Euclidean distances to these prototypes through the fuzzy membership formula. Starting from random prototypes rather than from a random membership matrix avoids the near-uniform partitions that a random U(0) produces for large N. The second option, init="kmeans++", is the seeding of Arthur and Vassilvitskii [15]: the first seed is a random sample, and every further seed is a sample drawn with probability proportional to its squared distance from the seeds chosen so far, so that the seeds spread over the data. The toolbox calls the scikit-learn implementation, a greedy variant that draws 2 + ⌊ln ⁡ c⌋ candidates in this way for every further seed and keeps the one that most reduces the sum of squared distances to the nearest seed. The seeding is designed for compact groups; on elongated or crossing clusters its preference for far-apart seeds can be a disadvantage (section 2.4.3). The third option is an explicit array, either initial centers of shape (c,n) or an initial partition of shape (N,c). This is how the Gath–Geva algorithm is started from a converged FCM or GK result, and how a clustering can be continued or reproduced.

Restarts complement the seeding. With n_init = r > 1 the loop of algorithm 2.1 is run r times from fresh starts, and the run with the smallest final J is kept; the final objective is the only criterion, because it is the only one the algorithm itself can evaluate. On well-separated compact clusters nearly every start reaches the same optimum, and r = 1 suffices. On data with elongated, crossing, or differently sized clusters, the spread of the final objectives over seeds (fig. 2.7) is the quickest diagnostic of a multimodal objective, and r between 5 and 20 is cheap insurance. When init is an array, n_init is ignored.

2.2.7 Termination

The iteration stops when the partition no longer changes,

max ⁡ i,k |μik(l) −μ ik(l−1)| < 𝜖,
(2.10)

with the tolerance tol = 𝜖 (default 10−4, the value in the code of the MATLAB toolbox, although its manual states 10−3), or after max_iter iterations (default 300). The maximum change of a membership is a scale-free criterion: it depends neither on the units of the data nor on the size of J. It is the termination test of Bezdek’s FCM algorithm [3, 16]. For hard partitions it reduces to “no sample changed cluster.” The number of iterations actually run is stored in n_iter_, and the objective after every iteration in objective_history_; a history that is still falling steeply at max_iter indicates that the limit, not convergence, stopped the run. A smaller 𝜖 locates the prototypes more precisely but costs iterations; because the memberships change slowly when m is large (eq. (3.7)), partitions with m above about two need more iterations for the same 𝜖. Two numerical safeguards protect the membership update: squared distances are clipped at zero, and a constant 10−10 is added to them before negative powers are taken (as in the MATLAB toolbox), so that a sample that coincides with a prototype receives a membership of almost one instead of causing a division by zero.

2.2.8 Scaling the data

Distances compare features, and features have units. If one feature ranges over hundreds and another over fractions, the Euclidean distance is in effect the first feature alone, and so is the clustering (section 2.4.1). Scaling the data is therefore part of the clustering method, not a preliminary detail. Two linear scalings are standard; fuzzyclust.preprocessing.normalize reproduces the MATLAB function clust_normalize, and the scaler it returns reproduces clust_denormalize:

range:x~kj = xkj −min ⁡ kxkj max ⁡ kxkj −min ⁡ kxkj ∈[0,1],variance:x~kj = xkj −x¯j σj .
(2.11)

Range scaling is bounded and easy to interpret but sensitive to outliers; variance scaling (standardization) depends less on single extreme values but is still affected by heavy tails. Both correspond to a diagonal norm in the original units (AD for variance scaling), and both must be inverted to report prototypes in physical units, which the returned scaler does with inverse_transform. The recommended pattern is a scikit-learn Pipeline: the scaler is fitted on the training data and applied automatically to every new sample passed to predict_proba.

For the adaptive norm of Gustafson–Kessel the situation is subtler. In exact arithmetic the GK distance DikAi2 with Ai = [ρi det ⁡ Fi]1∕nFi−1 is invariant up to a common factor under any invertible linear map xk↦Sxk: the covariance becomes SFiST, its determinant is multiplied by (det ⁡ S)2, and all squared distances are multiplied by the same constant (det ⁡ S)2∕n, which the membership formula cancels. GK is therefore affine-invariant in principle, and so is Gath–Geva. In practice the invariance is only partial. The random initialization in an axis-parallel box is not invariant. The regularization of the covariance matrices (section 3.2.4) shrinks every Fi toward a multiple of the identity and bounds its condition number, and neither operation is invariant under anisotropic scaling, so with γ > 0, or when the bound β is active, the result depends on the units. Finally, the validity indices of chapter 4 are computed with Euclidean distances. Scaling the data is therefore good practice for every algorithm of the toolbox, and indispensable for k-means and for FCM with the Euclidean norm.

2.2.9 Notation

Table 2.1 collects the symbols of the book together with their names in code. The convention that index i (and j) runs over clusters and k over samples is used without exception; the partition matrix is c ×N in formulas, as in Bezdek and Babuška, and is stored transposed in code so that it aligns with the (N,c) layout of predict_proba.

Table 2.1. Notation of the book and the corresponding names in fuzzyclust.
Symbol

Meaning

Code

N

number of samples

n_samples

n

number of features

n_features

c

number of clusters

n_clusters

X ∈ℝN×n

data matrix [x1,…,xN]T, rows are samples

X

xk, k = 1,…,N

k-th sample (row)

X[k]

vi, i = 1,…,c

prototype (center) of cluster i

cluster_centers_[i]

V ∈ℝc×n

matrix of prototypes [v1,…,vc]T

cluster_centers_

μik ∈[0,1]

membership of sample k in cluster i

membership_[k, i]

U = [μik] ∈ℝc×N

fuzzy partition matrix

membership_ is UT, shape (N, c)

m > 1

fuzziness exponent

m

DikAi2, eq. (2.2)

squared inner-product distance of xk to vi

transform(X) returns Dik, shape (N, c)

Ai

norm-inducing matrix of cluster i

norm_matrices_[i] (norm_matrix_ if shared)

Fi

fuzzy covariance matrix ∑ ⁡ kμikm(xk−vi)(xk−vi)T∕∑ kμikm

covariances_[i]

αi = 1 N ∑ ⁡ kμik

prior probability of cluster i (GG)

priors_[i]

J(X;U,V)

objective, ∑ ⁡ i ∑ kμikmDik2

objective_, objective_history_

𝜖

termination tolerance on max ⁡ ik |μik(l) −μik(l−1)|

tol

l, lmax ⁡

iteration counter, maximum

n_iter_, max_iter

ρi

cluster volume (GK)

rho

γ

covariance regularization weight (GK, GG)

gamma

β

condition-number bound (GK, GG)

beta

yk ∈ℝq

low-dimensional projection of xk

embedding_

zi

projected cluster center

embedded_centers_

Mhc,Mfc,Mpc

hard, fuzzy, possibilistic partitioning spaces

–

2.3 Using it in fuzzyclust

The clustering estimators derive from the base class BaseFuzzyClusterer of fuzzyclust.base, which mixes in the scikit-learn classes BaseEstimator, ClusterMixin, and TransformerMixin and implements the alternating optimization of algorithm 2.1. The contract below therefore holds for FCM, GK, GG, the hard methods, and most estimators of the later chapters.

fuzzyclust.base.BaseFuzzyClusterer – constructor parameters shared by every estimator

n_clusters=3 (c); m=2.0 (m; not a parameter of the hard methods, which fix m = 1); tol=1e-4 (𝜖); max_iter=300 (lmax ⁡ ); init="random" ("random": random prototypes in a box around the data, as in MATLAB; "kmeans++"; or an array of initial centers (c,n) or an initial partition (N,c)); n_init=1 (restarts; the run with the lowest final J is kept; ignored for an array init); random_state=None; verbose=0 (a positive value prints J at every iteration). Algorithm-specific parameters, e.g. norm for FCM or rho, gamma, and beta for GK, follow n_clusters (and m, where present) in the signatures, so pass them by keyword. Nothing is validated or computed in the constructor (a scikit-learn rule); all work happens in fit.

fitted attributes (trailing underscore)

cluster_centers_(c,n): V. membership_ (N,c): UT, rows sum to one. labels_ (N,): argmax ⁡ iμik. distances_ (N,c): Dik of the training data at convergence, in the norm of the algorithm. objective_: final J; objective_history_ (l,): J per iteration; n_iter_. Where defined: covariances_ (c,n,n) for Fi, norm_matrices_ (c,n,n) for Ai, norm_matrix_ (n,n) for the shared A of FCM, priors_ (c,) for αi, eigenvalues_, and eigenvectors_. Set by scikit-learn’s validation: n_features_in_, and feature_names_in_ when a DataFrame was fitted.

methods

fit(X, y=None) runs the alternating optimization of algorithm 2.1 and returns self. predict_proba(X) returns the memberships (N′,c) of new samples, computed from their distances to the fitted prototypes with the algorithm’s own membership rule (the MATLAB clusteval); predict(X) returns their arg-max; transform(X) returns the distances Dik (N′,c), so a clusterer is a transformer that maps n features to c distance features (get_feature_names_out gives dist_cluster_0, …, and set_output(transform="pandas") is honored). fit_predict and fit_transform are available, and score(X) returns −J(X) (higher is better, so grid search maximizes it). Inputs may be numpy arrays, pandas data frames, or anything scikit-learn accepts; they are never modified and never scaled inside the estimator.

implementing a new algorithm

A subclass defines _update_prototypes(X, Um), which sets cluster_centers_ (and shape attributes) from X and the matrix Um of shape (N,c), and _distances(X), which returns the squared distances (N,c) to the current prototypes. Optionally it overrides _memberships(d2) (the hard methods return one-hot rows, Gath–Geva a log-domain softmax), _check_params(X) for parameter validation, _init_state(X, rng) for a special initialization, and _finalize(X, Um) for attributes computed once after convergence. Everything else (restarts, history, the scikit-learn API, and pandas support) is inherited.

fuzzyclust.preprocessing.normalize(X, method="var")

Returns (X_scaled, scaler): the data standardized to zero mean and unit variance ("var") or scaled to the range [0,1] ("range"), and the fitted StandardScaler or MinMaxScaler, whose inverse_transform is the MATLAB clust_denormalize. A DataFrame comes back as a DataFrame. For new data, put the scaler into a Pipeline.

The three built-in norms of FCM are selected by name, and an explicit matrix is accepted as well:

norms = { 
    "euclidean": "euclidean", 
    "diagonal": "diagonal", 
    "mahalanobis": "mahalanobis", 
    r"explicit $\mathbf{A}=\mathbf{\Sigma}^{-1}$": np.linalg.inv(S @ S.T), 
} 
fig, axes = plt.subplots(1, 4, figsize=(19, 4.5), sharex=True, sharey=True) 
for ax, (name, norm) in zip(axes, norms.items(), strict=True): 
    fcm = FCM(n_clusters=3, norm=norm, random_state=0, n_init=5).fit(X) 
    plot_membership_contours(fcm, X, ax=ax, labels=False) 
    plot_covariance_ellipses(fcm.cluster_centers_, fcm.covariances_, ax=ax) 
    ax.set_title(f"{name}: ARI = {adjusted_rand_score(y_true, fcm.labels_):.2f}")
                                                                     

                                                                     
   

Restarts take one keyword, and the spread of the final objective over seeds diagnoses local optima:

seeds = range(20) 
runs = [GK(n_clusters=3, random_state=s).fit(X) for s in seeds] 
J = np.array([r.objective_ for r in runs]) 
ari = np.array([adjusted_rand_score(y_true, r.labels_) for r in runs])
   

Scaling composes with any estimator through a pipeline, which then scales new data automatically:

from sklearn.pipeline import make_pipeline 
from sklearn.preprocessing import StandardScaler 
 
pipe = make_pipeline(StandardScaler(), GK(n_clusters=4, random_state=0)).fit(X) 
pipe.predict_proba(new_points)          # scaled, then evaluated with the GK norms 
pipe[-1].cluster_centers_               # prototypes in the scaled space 
pipe[0].inverse_transform(pipe[-1].cluster_centers_)   # ... and in physical units

2.4 Examples

2.4.1 Distance norms

The script plot_11_distance_norms.py generates three clusters with the same elongated, rotated covariance and clusters them with the three built-in norms and with the explicit inverse of the generating covariance (fig. 2.5). The Euclidean norm cuts the elongated groups with circles and mixes neighboring clusters (adjusted Rand index, ARI, 0.47); the diagonal norm helps only insofar as the variances differ along the axes (0.61). The Mahalanobis norm, whose unit ball has the orientation of the pooled data, does better (0.78) but not perfectly, because the covariance of the pooled data also contains the spread of the cluster centers and is rounder than the clusters themselves (its eigenvalue ratio is 5.4, against 39.5 for the true within-cluster covariance). The explicit within-cluster norm recovers the groups exactly. The second figure of the script (not shown) stretches one feature by a factor of twenty. The Euclidean norm then produces horizontal bands, whereas the diagonal norm and standardization followed by the Euclidean norm give identical partitions, the same as without the stretch, because the two are the same operation.

Figure 2.5

Figure 2.5. Fuzzy c-means with four norms on three clusters of identical elongated shape. The level curves of the maximal membership follow the shape of the unit ball of the norm; the colored ellipses are the 2σ ellipses of the fuzzy covariance matrices of the clusters found. From left to right the norm fits the clusters better, and the ARI with the generating labels rises from 0.47 to 1.00.

Open in ColabExample plot_11_distance_norms.py in the gallery

2.4.2 Scaling: the motorcycle data

The motorcycle data set (time after impact in milliseconds against head acceleration in g) is the real data set that the MATLAB toolbox used throughout. The two variables have ranges of about 55 and 210, so the raw Euclidean distance is dominated by the acceleration, and a Euclidean method such as k-means or FCM sees mainly that variable. Figure 2.6 (script plot_07_motorcycle_scaling.py) clusters the raw, the range-scaled, and the variance-scaled data with Gustafson–Kessel and maps the prototypes back to physical units. All three partitions are identical, with the same prototypes in physical units: the clusters follow the course of the signal in time, which is the physically meaningful segmentation. This is the affine invariance of GK (section 2.2.8) at work: on these data the units do not change the optimum that the iteration reaches. With regularization switched on, or on data where the box initialization leads to different local optima, the scaled and raw results can differ, so scaling remains the safe default.

Figure 2.6

Figure 2.6. Gustafson–Kessel clustering of the motorcycle data without scaling (left), after range scaling (middle), and after variance scaling (right), with the prototypes shown in the original units. The three partitions coincide: the adaptive norm of GK makes the result independent of the units of the features, and every cluster is a segment of the signal in time.

Open in ColabExample plot_07_motorcycle_scaling.py in the gallery

2.4.3 Initialization and restarts

The script plot_10_initialisation_restarts.py fits GK with three clusters to three noisy line segments from twenty random starts. The final objectives take two distinct values, J = 142.1 in six runs and J = 229.4 in fourteen, with adjusted Rand indices of 0.94 and 0.47; the objective histories of all runs decrease monotonically, so the poor runs are converged runs. Figure 2.7 compares four strategies over twenty outer seeds: a single random start reaches the good optimum in 30% of the cases, five restarts in 70%, and ten restarts in 80%. Seeding with k-means++, which places the seeds far apart, reaches it in none: on line-shaped clusters the far-apart seeds are the ends of different lines, the configuration from which GK slides into the poor optimum. Seeding heuristics are tuned to compact groups and are no substitute for restarts.

Figure 2.7

Figure 2.7. Final objective of Gustafson–Kessel on three line segments for twenty outer seeds and four initialization strategies. Restarts (n_init) move most runs to the good optimum (dashed line); k-means++ seeding, designed for compact groups, fails on these data in every run.

Open in ColabExample plot_10_initialisation_restarts.py in the gallery

2.4.4 The scikit-learn interface

The script plot_08_sklearn_pandas_workflow.py exercises the interface on the iris data, given as a pandas data frame. A pipeline of a StandardScaler and GK with set_output(transform="pandas") returns the distance matrix as a data frame with columns dist_cluster_0, …, and keeps the feature names in feature_names_in_. Aggregated per species, the memberships recover setosa with a mean membership of 0.95, whereas versicolor and virginica overlap (0.72 and 0.70). GridSearchCV selects c and m of FCM with the Xie–Beni index on held-out folds as the scoring function (fig. 2.8), and the fitted pipeline survives a pickle round trip. The grid search prefers two clusters, a well-known property of the iris data: validity indices measure geometric separation, not agreement with external labels, and two of the three species are not geometrically separated.

Figure 2.8

Figure 2.8. Xie–Beni index of FCM on held-out folds of the standardized iris data for several c and m, computed inside GridSearchCV with predict_proba. The index is lowest for two clusters because versicolor and virginica overlap.

Open in ColabExample plot_08_sklearn_pandas_workflow.py in the gallery

2.5 Further reading

The data–clusters–partition exposition follows Babuška [7] and the MATLAB toolbox manual [12]. The partitioning spaces are Bezdek’s [3]; Ruspini [1] introduced fuzzy partitions, and Krishnapuram and Keller [14] the possibilistic ones. The c-means functional goes back to Dunn [2], its alternating optimization and the convergence theorem to Bezdek [10, 16], with the corrected theorem by Bezdek, Hathaway, Sabin, and Tucker [11]; Höppner et al. [6] give a unified treatment of the objective-function family, including linear varieties and shells. The k-means++ seeding is due to Arthur and Vassilvitskii [15]. The estimator interface follows scikit-learn [13].