Fuzzy Clustering and Data Analysis in PythonThe fuzzyclust toolbox

Chapter 10
Clustering relational, categorical, and mixed data

All algorithms of the previous chapters work on a matrix of numeric feature vectors: a prototype is a weighted mean, and the distance to it is a norm. This chapter drops that assumption in three directions. When only the pairwise dissimilarities of the objects are known—time series compared by dynamic time warping, records compared by a coefficient of their own—relational fuzzy c-means minimizes the familiar functional through the dissimilarity matrix alone, NERF c-means repairs it for matrices that no point configuration can realize, and fuzzy c-medoids chooses actual objects as prototypes and accepts any dissimilarity. For categorical attributes fuzzy k-modes replaces the mean by the mode, and for mixed records fuzzy k-prototypes combines the two; dissimilarities built for time series and mixed records turn such data into input for the relational methods. The methods extend the medoid idea of the geodesic clustering of chapter 7 and live in fuzzyclust.relational.

10.1 Problem and idea

Fuzzy c-means needs two operations: it averages samples to obtain a prototype, vi = ∑ ⁡ kμikmxk∕∑ kμikm, and it measures the distance of a sample to that average. Both presuppose that the objects are vectors of a common space in which a mean exists and means something. Many data sets violate this. Time series that are shifted and stretched in time can be compared sensibly only after they have been aligned, and the result of the alignment is a number per pair of series, not a coordinate per series. Survey answers, diagnoses, and product types are categories: one can say whether two answers agree, but there is no average of “yes”, “no”, and “don’t know”. Customer records combine both—age and income next to occupation and region. In some applications the dissimilarities are all there is: subjective ratings of the similarity of products, edit distances between strings, and distances between graphs.

The common way out is to force the objects into a vector space—resample and align the series, code the categories as numbers or 0/1 indicators—and run FCM. The geometry is then an accident of the encoding: the indicator coding makes every categorical mismatch cost the same whatever the attribute, the numeric columns count in their arbitrary units, and the centers are fractional indicator vectors that describe no record. This chapter takes the other route and changes the algorithm instead of the data. Two observations make that possible.

The first is that fuzzy c-means never needs the coordinates themselves, only the squared distances between objects. A prototype that is a weighted mean of the objects can be stored as the vector of its weights, vi ∈ ℝN, and the squared distance of an object to such a combination follows from the pairwise squared distances by an identity of elementary geometry. Hathaway, Davenport, and Bezdek [141] turned this into relational fuzzy c-means (RFCM), which produces the FCM partition of points it has never seen. Figure 10.1 contrasts the two kinds of data and shows where the prototype lives in each: in the feature space as a point, in the relational setting as a weight vector over the objects or as one of the objects.

Figure 10.1

Figure 10.1. Object–feature and object–object data. Left: in the feature setting every object is a row of X and the prototype is a point of the same space, a weighted mean of the rows. Right: in the relational setting only the symmetric matrix R of pairwise dissimilarities is known; the prototype of relational c-means is a weight vector over the objects (the shade of a cell is the weight), and that of fuzzy c-medoids is a single object.

The identity behind RFCM holds only if the dissimilarities are squared distances of some point configuration, that is, if R is Euclidean. Dynamic-time-warping matrices, subjective ratings, and most purpose-built dissimilarities are not, and then the relational distance of an object to a prototype can come out negative, a geometric impossibility that breaks the membership formula. Figure 10.2 shows the smallest example: three objects whose dissimilarities violate the triangle inequality, so that no position in any space fits the middle one. Adding the same constant β to all off-diagonal dissimilarities pushes the objects apart until a configuration exists. This β-spread is the idea of NERF c-means [142], which applies it adaptively: only when a negative distance appears, and only as far as needed to remove it.

Figure 10.2

Figure 10.2. The β-spread of NERF c-means. Left: three objects with squared dissimilarities r12 = r23 = 1 and r13 = 4.5; the long side exceeds the path through object 2, so no point configuration realizes them, and the relational distance of object 2 to the midpoint prototype of objects 1 and 3 is negative. Right: adding β = 1∕6 to every off-diagonal entry makes the matrix Euclidean—the three objects lie on a line—and the distance of object 2 to the prototype becomes exactly zero; this β is the smallest admissible spread.

The second observation is that a prototype need not be a mean at all. Restricting it to the objects themselves—the medoid, the object with the smallest weighted sum of dissimilarities to its cluster—requires only the dissimilarities between objects and therefore works with any dissimilarity, Euclidean or not. Krishnapuram, Joshi, Nasraoui, and Yi [143] made the fuzzy c-medoids algorithm (FCMdd) practical for large relational data by searching for the medoid of a cluster only among its most typical members. For categorical attributes the analogous prototype is the mode, chosen attribute by attribute as the category that the members of the cluster share most. Huang [144] introduced it for k-means and Huang and Ng [145] for fuzzy partitions, where “most” is measured in membership mass. Figure 10.3 shows why both describe a cluster better than a mean when the mean lies outside the data or is undefined.

Figure 10.3

Figure 10.3. Mean, medoid, and mode. Left: the weighted mean of a curved cluster lies in empty space; the medoid is one of the objects and summarizes the cluster where it is. Right: for categorical attributes the prototype is the mode, chosen per attribute by membership mass rather than by count; in the color column blue is more frequent but red carries 1.7 of the mass against 0.6.

All methods of the chapter keep the c-means functional and its alternating optimization: the memberships follow from the FCM formula with whatever plays the role of the squared distance, and the prototypes from whatever minimizes the functional for fixed memberships. What changes is the prototype (weights over the objects, an object, a mode, or means and modes) and with it the kind of data the algorithm accepts. The last part of the theory constructs dissimilarities that turn time series and mixed records into relational data.

10.2 Theory

The notation is that of the book: the memberships μik form the matrix U ∈ ℝc×N (stored transposed, N ×c, in the code), and the index i (or j) runs over clusters and k (or l, q) over objects. Relational data form a matrix R = [rkl] ∈ ℝN×N with rkl = rlk ≥0 and rkk = 0. The matrix R is called Euclidean if there are points x1,…,xN of some ℝp with rkl = ‖xk −xl‖ 2, that is, if its entries are squared distances of a configuration. By the classical result of Schoenberg and of Young and Householder, this is the case exactly when the doubly centered matrix −1 2HRH, H = I −1 N 11T, is positive semi-definite [146]. The matrix of squared Euclidean distances of any data set is Euclidean in this sense. So is the matrix of unsquared distances, because an entrywise power 0 < p ≤1 of a Euclidean matrix remains Euclidean, but it belongs to a different configuration. Squared city-block distances, cubed distances, and dynamic-time-warping matrices are in general not Euclidean.

10.2.1 Relational fuzzy c-means

Let the prototype of cluster i be a convex combination of the objects, pi = ∑ ⁡ lvilxl with weights vil ≥0, ∑ ⁡ lvil = 1, collected in vi ∈ ℝN. For any point xk and any weights summing to one, expanding the squares gives

‖xk −∑ lvilxl‖ 2 = ∑ lvil ‖xk −xl‖ 2 −1 2 ∑ l,qvilviq ‖xl −xq‖ 2.
(10.1)

The right-hand side contains only squared distances between objects. Replacing them by the entries of R defines the relational distance

dik2 = (Rv i)k −1 2viTRv i,
(10.2)

which equals the squared Euclidean distance of xk to the weighted mean whenever R holds squared Euclidean distances. The FCM prototype is the weighted mean with weights μikm∕∑ ⁡ lμilm, so RFCM [141] alternates

vi = (μi1m,…,μiNm)T ∑ k=1Nμikm ,dik2by (10.2),μ ik = 1 ∑ j=1c (dik2∕djk2 )1∕(m−1),
(10.3)

and minimizes J = ∑ ⁡ i ∑ kμikmdik2, which in the Euclidean case is the c-means functional of Bezdek [3]. The duality theorem of the paper states that on the matrix of squared Euclidean distances of a data set, RFCM started from the same initial partition generates exactly the iterates of FCM on that data set (memberships, objective values, and number of iterations), and that the dual centers ∑ ⁡ lvilxl are the FCM centers. RFCM is therefore not an approximation but FCM written in the language of R. The relational prototype vi is a probability vector over the objects: it states how much each object contributes to the center of cluster i, and it is concentrated on the typical members of the cluster.

The price is the matrix: one iteration needs the products Rvi, that is, O(cN2) operations, and the matrix itself takes O(N2) memory. A new object enters through its squared distances to the N training objects. Since (10.1) holds for any point, its relational distance is (10.2) with the row of new dissimilarities in place of the k-th row of R, and the membership follows. When R is not Euclidean, (10.2) has no geometric meaning and can be negative (fig. 10.2); RFCM is then undefined, and the implementation stops with an error that points to NERF.

Algorithm

In a nutshell: Relational fuzzy c-means

  • FCM on a matrix of squared dissimilarities instead of feature vectors; prototypes are weight vectors over the objects.
  • Exact dual of FCM: on squared Euclidean distances it reproduces the FCM iterates and centers.
  • Assumes a Euclidean R; otherwise negative relational distances stop it.
  • Parameters as in FCM (c, m, initialization, restarts); O(N2) memory, O(cN2) per iteration.

10.2.2 NERF c-means: the β-spread

Hathaway and Bezdek [142] make relational c-means usable on any dissimilarity matrix by transforming it,

Rβ = R + β(11T −I),β ≥0,
(10.4)

which adds β to every off-diagonal dissimilarity and keeps the zero diagonal. For a large enough β the transformed matrix is Euclidean: the doubly centered matrix − 1 2HRβH = −1 2HRH + β 2 H gains β∕2 on every eigenvalue in the subspace orthogonal to 1. The effect on the relational distances can be computed without forming Rβ. Substituting (10.4) into (10.2) and using 1Tvi = 1 gives

dik2(β) = d ik2(0) + β 2 ‖ek −vi‖ 2, ‖e k −vi‖ 2 = 1 −2v ik + ‖vi‖ 2,
(10.5)

with ek the k-th unit vector. Every distance grows by a positive amount, and the growth is largest for objects that carry little weight in the prototype. The algorithm starts with β = 0, so that a Euclidean matrix gives the RFCM result, and raises β only when a negative distance appears, by the smallest increment that removes all of them,

Δβ = max ⁡ i,k −2dik2 ‖ek −vi‖ 2,β ←β + Δβ,dik2 ←d ik2 + Δβ 2 ‖ek −vi‖ 2.
(10.6)

The pair (i,k) that attains the maximum then has distance zero and membership one in cluster i, and the iteration continues with the shifted distances. In the example of fig. 10.2, d22(0) = −1 8 and ‖e2 −v‖2 = 3 2, so Δβ = 1 6.

The spread has a price. Adding the same constant to all dissimilarities compresses the ratio of far to near dissimilarities, on which the membership formula depends, so a large β flattens the partition toward 1∕c. The objective J, in turn, is that of Rβ, so the objectives of runs that ended with different β cannot be compared. The final β relative to the mean dissimilarity serves as a diagnostic: zero means that the data behaved as a Euclidean matrix, a large value that the clustering had to distort them considerably. New objects receive the shift with ‖e −vi‖ 2 = 1 + ‖vi‖ 2, the value for an object outside the training set.

Algorithm

In a nutshell: NERF c-means

  • Relational c-means for matrices that are not Euclidean (DTW, ratings, squared non-Euclidean metrics).
  • The β-spread adds a constant to all off-diagonal dissimilarities; it is raised adaptively and only as far as needed, so a Euclidean matrix gives the RFCM result.
  • A large final β flattens the memberships and signals strongly non-Euclidean data; objectives at different β are not comparable.
  • Same parameters and costs as RFCM.

10.2.3 Fuzzy c-medoids

Fuzzy c-medoids restricts the prototypes to the objects, vi ∈{x1,…,xN}, and minimizes the membership-weighted sum of dissimilarities to them,

J = ∑ i=1c ∑ k=1Nμ ikmr(x k,vi),
(10.7)

where r is any dissimilarity: it need not be squared, Euclidean, or even a metric, and apart from non-negativity only r(x,x) = 0 is used. For fixed medoids the memberships follow from the FCM formula with r in the role of the squared distance,

μik = (1∕r(xk,vi) )1∕(m−1) ∑ j=1c (1∕r(xk,vj) )1∕(m−1),
(10.8)

with μik = 1 when xk is the medoid of cluster i. For fixed memberships the functional splits into one term per cluster, and the best medoid of cluster i is the object with the smallest weighted sum of dissimilarities,

vi = xq,q = argmin ⁡ l∈Ci ∑ k=1Nμ ikmr(x k,xl).
(10.9)

With the candidate set Ci containing all objects, the update is exact and costs O(N2) per cluster. Krishnapuram et al. [143] observed that the medoid of a cluster is almost always one of its most typical members; restricting Ci to the p objects with the largest memberships in cluster i makes the update O(pN) and the whole iteration linear in N (the linear FCMdd). The price is that a poor initial cluster may not contain its best medoid among its top candidates, so the iteration can stop in a worse local minimum; a moderate number of candidates and a few random restarts are the remedy. Since the medoids are discrete, the iteration terminates when they no longer change, typically after a few iterations. If two clusters select the same object, the implementation gives the second its best unused candidate, so that the medoids stay distinct.

The same paper proposes a robust variant, RFCMdd. It scores every object by a harmonic-mean-type dissimilarity to all medoids, hk = (∑ ⁡ ir(xk,vi)1∕(1−m) )1−m, keeps only the objects with the smallest scores, and computes the memberships and the medoids from these objects alone, so that a share of badly fitting objects (outliers or noise) cannot pull the medoids. fuzzyclust implements a simpler rule in the same spirit, which we call fuzzy c-trimmed medoids (FCTMdd): in (10.9) only the K = ⌈(1 −τ)N⌉ smallest terms μikmr(xk,xl) are summed for every candidate, the memberships of all objects are kept, and the reported objective is the same trimmed sum. FCMdd is related to the geodesic c-medoids of section 7.2.5, which applies the same alternation to graph distances; here, however, the dissimilarity is an input, and the candidate search can be restricted.

Algorithm

In a nutshell: Fuzzy c-medoids

  • Prototypes are objects; works with any dissimilarity (no Euclidean assumption, no spread) and returns representative objects that can be shown.
  • The linear variant searches for the medoid among the p most typical members: O(cpN) instead of O(cN2) per iteration, at a small risk of a worse local minimum.
  • Trimming the share τ of worst-fitting objects in the medoid update makes the medoids robust to outliers.
  • Parameters c, m, p, and τ; restarts are recommended because the medoids are discrete.

10.2.4 Fuzzy k-modes

Let all n attributes be categorical, attribute j taking values in a finite set Aj = {aj(1),…,aj(nj)}. The simple matching dissimilarity counts the attributes in which two records differ,

δ(xk,xl) = ∑ j=1nδ(x kj,xlj),δ(a,b) = { 0,a = b,
(10.10)

and the prototype of a cluster is a mode, a record vi ∈A1 ×⋯ ×An that need not occur in the data. Huang [144] built k-modes on this pair; Huang and Ng [145] minimize the fuzzy functional

J = ∑ i=1c ∑ k=1Nμ ikmδ(x k,vi).
(10.11)

For fixed modes the memberships follow from the FCM formula with δ in the role of the squared distance (μik = 1 for a record identical to mode i). For fixed memberships the functional separates into one term per cluster and attribute, ∑ ⁡ kμikmδ(xkj,vij), and by the theorem of Huang and Ng each term is minimized by the category of attribute j that carries the largest membership mass in cluster i,

vij = aj(r)with∑ k:xkj=aj(r)μikm ≥∑ k:xkj=aj(t)μikmfor all t.
(10.12)

This is “the most frequent category” with every record counted with its weight μikm (fig. 10.3, right). Ties are broken in favor of the first category in a fixed order. Because δ is integer-valued, many records are equally far from several modes, and the membership ratio of a record that differs in a attributes from one mode and in b from another is (b∕a)1∕(m−1). For a = 1 and b = 2 the ratio is 4 at m = 1.5 but only 1.4 at m = 3. The partition is therefore much fuzzier than that of FCM on continuous data at the same m, and values of m close to one are appropriate. The update is O(cNn) per iteration, linear in the number of records, which made k-modes popular for large categorical data sets.

Algorithm

In a nutshell: Fuzzy k-modes

  • Fuzzy c-means for categorical records: simple matching dissimilarity and modes chosen by membership mass.
  • The modes are typical records and read as a table of group profiles.
  • The integer-valued dissimilarity makes the partition fuzzy; keep m small (about 1.1–2).
  • Linear in the number of records; restarts guard against local minima.

10.2.5 Fuzzy k-prototypes

Mixed records have numeric attributes j ∈N and categorical attributes j ∈C. Huang’s k-prototypes dissimilarity [144] treats each kind in its own terms and adds them with a weight γ ≥0,

d(xk,vi) = ∑ j∈N(xkj −vij)2 + γ∑ j∈Cδ(xkj,vij),
(10.13)

and the fuzzy version minimizes J = ∑ ⁡ i ∑ kμikmd(xk,vi) by the FCM membership formula and a prototype update that combines the two previous cases: the numeric part of vi is the fuzzy mean vij = ∑ ⁡ kμikmxkj∕∑ kμikm (j ∈N), and the categorical part is the membership-mass mode (10.12) (j ∈C). Both updates are optimal for their part, so the functional decreases monotonically.

The weight γ states how many units of squared numeric distance one categorical mismatch is worth. With γ = 0 the method is FCM on the numeric attributes; as γ →∞ the categorical part dominates and the method becomes fuzzy k-modes on the categorical attributes. Huang relates the scale of γ to the average standard deviation of the numeric attributes, and this average is the default γ of the implementation; the numeric attributes should be standardized first, so that this scale is meaningful and no attribute dominates through its unit. The prototypes are hybrid records, with means for the measurements and modes for the categories, and remain interpretable.

Algorithm

In a nutshell: Fuzzy k-prototypes

  • Fuzzy clustering of mixed records: squared Euclidean distance on the numeric part, matching dissimilarity on the categorical part, weighted by γ.
  • Interpolates between FCM on the numeric attributes (γ = 0) and fuzzy k-modes on the categorical ones (γ →∞).
  • Default γ: the mean standard deviation of the numeric attributes; standardize the numeric attributes first.
  • Prototypes are records with means and modes; linear in N.

10.2.6 Dissimilarities for objects that are not vectors

The relational algorithms are only as good as the dissimilarity they receive. Three constructions cover common cases; each also produces the rectangular matrix of new objects against the training objects that the estimators need for prediction.

Dynamic time warping. Two series x = (x1,…,xT ) and y = (y1,…,yT ) of the same shape but with events at slightly different times are far apart in the Euclidean sense, which compares xt with yt. Dynamic time warping [147] compares each xt with a matching ys instead. A warping path is a sequence of index pairs from (1,1) to (T,T) that advances by one in t, in s, or in both at every step, and the DTW distance is the square root of the smallest summed local cost along such a path. Dynamic programming computes it through the accumulated cost

g(t,s) = (xt −ys)2 + min ⁡ {g(t −1,s),g(t,s −1),g(t −1,s −1)}, DTW(x,y) = g(T, T),
(10.14)

with g(0,0) = 0 and g = ∞ outside the admissible region. The Sakoe–Chiba band |t −s| ≤w restricts the path to the neighborhood of the diagonal: it limits the warping to plausible displacements, prevents pathological alignments that map one point to a long stretch, and reduces the cost from O(T2) to O(Tw) per pair. With w = 0 DTW is the Euclidean distance. DTW is not a metric—the triangle inequality can fail—and its squared matrix is in general not Euclidean, so fuzzy c-medoids (or NERF) is the appropriate partner.

Autocorrelation-based distance. When the series are realizations of stochastic processes, their values cannot be compared point by point, but their dependence structure can. D’Urso and Maharaj [148] represent every series by its estimated autocorrelations up to lag L,

ρ^k(l) = ∑ t=l+1T (xk,t −x¯k)(xk,t−l −x¯k) ∑ t=1T (xk,t −x¯k)2 ,l = 1,…,L,
(10.15)

and compare series by the Euclidean distance of these vectors. The implementation adds optional lag weights wq (all equal to one by default),

dACF(xk,xl) = (∑ q=1Lw q (ρ^k(q) −ρ^l(q) )2 )1∕2.
(10.16)

The representation ignores level, scale, and phase, has the same length for series of any length, and identifies stationary processes of low order by a few lags. D’Urso and Maharaj cluster the vectors with fuzzy c-means (A-FCM); fuzzy c-medoids on the squared distances (A-FCMd) returns representative series instead of centers. Because the representation is a feature vector, the squared matrix of (10.16) is Euclidean, and RFCM on it reproduces A-FCM. Two choices remain: the number of lags L, which must reach the lags at which the processes differ, and the weights wq, which can damp the high lags whose estimates are noisy.

Algorithm

In a nutshell: Autocorrelation-based clustering

  • Clusters series by their dependence structure, not their values: invariant to level, scale, and phase, and applicable to series of different lengths.
  • A Euclidean representation: FCM, RFCM, and fuzzy c-medoids all apply directly.
  • L must cover the lags at which the processes differ, but every extra lag adds estimation noise of order 1∕T; decaying weights wq make a generous L safe.
  • Meant for (approximately) stationary series; for shapes and events use DTW instead.

Gower’s coefficient. Gower [149] defined a general coefficient for records with numeric and categorical attributes. In its dissimilarity form each attribute contributes a score in [0,1]: the range-scaled absolute difference |xkj −xlj| ∕Rj for a numeric attribute with range Rj, and the mismatch indicator for a categorical one. The dissimilarity is the weighted mean of the scores over the attributes observed in both records,

dG(xk,xl) = ∑ jwjδkljsklj ∑ jwjδklj ,δklj = { 1,xkj and xlj observed,
(10.17)

so missing values need no imputation. By construction every attribute contributes on the same scale, and the weights wj play the role of γ in k-prototypes. Gower showed that the corresponding similarity matrix is positive semi-definite when no values are missing, so that dG is a Euclidean distance [146, 149]; the matrix [dG] itself, read as squared distances, is therefore a valid input for RFCM. With missing values this guarantee is lost, and records compared on few attributes can appear close to many others.

Table 10.1 summarizes which algorithm accepts which data.

Table 10.1. The algorithms of the chapter differ in the data they accept, in their prototypes, and in their requirements. “any R” means a symmetric, non-negative matrix with a zero diagonal.
algorithm input prototype requirement
RFCM R (squared) object weights R Euclidean
NERF c-means any R object weights none (see β)
FCMdd any R an object none
fuzzy k-modes categorical mode none
fuzzy k-prototypes mixed means and modes a sensible γ
A-FCM / A-FCMd time series ACF vector / series stationarity

10.3 Using it in fuzzyclust

Everything in this chapter is in fuzzyclust.relational. The five estimators derive from BaseFuzzyClusterer and have the usual methods fit, predict, predict_proba, transform, and score, so they work in scikit-learn pipelines and with the validity functions of chapter 4. The relational estimators follow scikit-learn’s convention for precomputed matrices: with metric="precomputed", fit takes the square N ×N matrix and predict_proba the rectangular matrix of the new objects against the N training objects. Any other metric names a SciPy distance, and the matrix is computed from feature vectors; the distances are squared for RFCM and NERF, as in FCM, and used as they are for fuzzy c-medoids.

fuzzyclust.relational.RelationalFCM

n_clusters=3, metric="euclidean"|"precomputed"|any SciPy metric, m=2.0, tol=1e-4, max_iter=300, init="random"|"kmeans++"|partition| object indices, n_init=1, random_state, verbose.
Attributes relational_centers_ (vi ∈ ℝN), cluster_centers_ (dual centers ∑ ⁡ lvilxl with a feature metric, else the relational centers), dissimilarity_matrix_, membership_, labels_, distances_ (dik 2), objective_, objective_history_, n_iter_. Raises an error on a negative relational distance.

fuzzyclust.relational.NERFCM

Same parameters and attributes as RelationalFCM. Here beta_ holds the final spread β and n_spread_updates_ the number of times β was raised (both are always zero for RelationalFCM); the objective is that of Rβ.

fuzzyclust.relational.FuzzyCMedoids

n_clusters=3, metric="euclidean"|"precomputed"|any SciPy metric (dissimilarities used as they are, not squared), n_candidates=None (all objects) or p (linear FCMdd), trim=0.0 (τ, FCTMdd), m=2.0, tol=1e-4, max_iter=100, init="kmeans++"|"random"| index array, n_init=1, random_state, verbose.
Attributes medoid_indices_, cluster_centers_ (medoid rows of X, or of R when precomputed), dissimilarity_matrix_, membership_, labels_, distances_ (dissimilarities to the medoids), objective_, objective_history_, n_iter_.

fuzzyclust.relational.FuzzyKModes, FuzzyKPrototypes

FuzzyKModes(n_clusters=3, m=1.5, tol, max_iter, init="random",  n_init, random_state, verbose); all columns categorical (strings, categories, booleans, or integer codes).
FuzzyKPrototypes(n_clusters=3, gamma=None, categorical_features=None,  m=2.0, ...); gamma=None uses the mean standard deviation of the numeric columns; categorical_features=None detects the categorical columns from the dtypes of a DataFrame; alternatively, pass "all", a boolean mask, or column names or positions.
Attributes modes_ and prototypes_ (with the original labels; DataFrames for DataFrame input), numeric_centers_, cluster_centers_ (encoded), categorical_features_, numeric_features_, categories_, gamma_, membership_, labels_, objective_. Unknown categories of new records count as one mismatch.

dissimilarities, generators, and plot helpers

pairwise_dissimilarity(X, Y=None, metric) (any SciPy metric), dtw_distance_matrix(X, Y=None, window) and dtw_alignment(x, y, window) → distance, path; autocorrelation_features(X, n_lags), autocorrelation_distance_matrix(X,  Y=None, n_lags, weights); gower_distance_matrix(X, Y=None,  categorical_features, ranges, feature_weights); matching_dissimilarity(A,  B); relational_distances(R, V, beta); check_dissimilarity_matrix(R). Generators make_categorical_blobs, make_mixed_blobs, make_warped_series. Plots plot_dissimilarity_matrix(R, labels), plot_dtw_alignment(x, y), plot_modes(model, X), plot_series_clusters(X, labels, medoids).

The duality of RFCM and FCM, and NERF on a matrix that RFCM rejects:

R = pairwise_dissimilarity(X, metric="sqeuclidean")  # squared Euclidean distances 
U0 = np.random.RandomState(0).rand(N, 3)             # a common random start 
fcm = FCM(n_clusters=3, init=U0).fit(X) 
rfcm = RelationalFCM(n_clusters=3, metric="precomputed", init=U0).fit(R) 
print(f"max |U_RFCM - U_FCM| = {np.abs(rfcm.membership_ - fcm.membership_).max():.1e}, " 
      f"iterations {rfcm.n_iter_} vs {fcm.n_iter_}, " 
      f"J = {rfcm.objective_:.4f} vs {fcm.objective_:.4f}") 
dual_centers = rfcm.relational_centers_ @ X 
print("dual centers - FCM centers:", np.abs(dual_centers - fcm.cluster_centers_).max())
   
R_l1 = pairwise_dissimilarity(X, metric="cityblock") ** 2   # squared L1 distances: not Euclidean 
try: 
    RelationalFCM(n_clusters=3, metric="precomputed", random_state=0).fit(R_l1) 
except ValueError as err: 
    print("RFCM:", str(err)[:70], "...") 
nerf = NERFCM(n_clusters=3, metric="precomputed", random_state=0).fit(R_l1) 
print(f"NERF: beta = {nerf.beta_:.3f} after {nerf.n_spread_updates_} spread update(s), " 
      f"ARI = {adjusted_rand_score(y, nerf.labels_):.2f}, {nerf.n_iter_} iterations")
   

Fuzzy c-medoids takes any precomputed dissimilarity, here dynamic time warping, and its linear variant needs only one more parameter, n_candidates:

R_euclid = pairwise_dissimilarity(X)                 # compare values at equal times 
t0 = time.perf_counter() 
R_dtw = dtw_distance_matrix(X, window=12)            # Sakoe-Chiba band of 12 samples 
print(f"DTW matrix of {N} series of length {T}: {time.perf_counter() - t0:.2f} s")
   
fcmdd_dtw = FuzzyCMedoids(n_clusters=3, metric="precomputed", n_init=5, random_state=0).fit(R_dtw) 
fcmdd_euc = FuzzyCMedoids(n_clusters=3, metric="precomputed", n_init=5, random_state=0).fit(R_euclid) 
for name, model in (("DTW", fcmdd_dtw), ("Euclidean", fcmdd_euc)): 
    print(f"{name:9s}: ARI = {adjusted_rand_score(y, model.labels_):.2f}, " 
          f"medoids = {model.medoid_indices_.tolist()}, J = {model.objective_:.2f}, " 
          f"{model.n_iter_} iterations")
   

Categorical and mixed records are clustered directly from a DataFrame:

km = FuzzyKModes(n_clusters=3, m=1.5, n_init=5, random_state=0).fit(X) 
print(km.modes_)                       # DataFrame with the original categories 
print(f"ARI = {adjusted_rand_score(y, km.labels_):.2f}, {km.n_iter_} iterations, J = {km.objective_:.1f}")
   
kp = FuzzyKPrototypes(n_clusters=3, n_init=5, random_state=0).fit(X) 
print(f"gamma = {kp.gamma_:.2f}, categorical columns: {list(X.columns[kp.categorical_features_])}") 
print(kp.prototypes_.round(2)) 
print(f"ARI = {adjusted_rand_score(y, kp.labels_):.2f}")
   

Gower’s coefficient and the autocorrelation distance turn mixed records and time series into relational data:

G = gower_distance_matrix(X)                          # categorical columns detected from the dtypes 
onehot = pd.get_dummies(X, columns=cat_cols, dtype=float) 
print(f"Gower matrix {G.shape}, entries in [{G.min():.2f}, {G.max():.2f}]; one-hot data {onehot.shape}")
   
A = autocorrelation_features(X, n_lags=5)                    # (75, 5) feature vectors 
D2 = autocorrelation_distance_matrix(X, n_lags=5) ** 2        # squared ACF distances 
afcm = FCM(n_clusters=3, n_init=5, random_state=0).fit(A)                              # A-FCM 
afcmd = FuzzyCMedoids(n_clusters=3, metric="precomputed", n_init=5, random_state=0).fit(D2)  # A-FCMd 
rfcm = RelationalFCM(n_clusters=3, metric="precomputed", init=afcm.membership_).fit(D2) 
raw = FuzzyCMedoids(n_clusters=3, metric="precomputed", n_init=5, random_state=0).fit(pairwise_dissimilarity(X)) 
for name, model in (("A-FCM", afcm), ("A-FCMd", afcmd), ("RFCM on ACF", rfcm), ("raw values", raw)): 
    print(f"{name:12s}: ARI = {adjusted_rand_score(y, model.labels_):.2f}") 
print(f"max |U_RFCM - U_A-FCM| = {np.abs(rfcm.membership_ - afcm.membership_).max():.1e}") 
print("medoid series of A-FCMd:", afcmd.medoid_indices_.tolist())
   

10.4 Examples

10.4.1 RFCM as the dual of FCM, and NERF

Three Gaussian groups of 100 points are clustered by FCM on the coordinates and by RFCM on the matrix of squared Euclidean distances, both from the same random partition (fig. 10.4). The memberships differ by at most 2 ⋅10−15, both runs need eight iterations, the objective trajectories coincide, and the dual centers equal the FCM centers to machine precision. The relational prototypes (fig. 10.5) are weight vectors over the 300 objects, nearly uniform on the members of their cluster and close to zero elsewhere; the ordered dissimilarity matrix shows the block structure the algorithm exploits. The squared city-block distances of the same points are not Euclidean: RFCM stops at a negative relational distance, while NERF raises β once (to 1.5) and recovers the three groups exactly. The parameter study (fig. 10.6) feeds powers p of the Euclidean distances to NERF. Up to p = 2 the matrix is Euclidean and β = 0; beyond that the spread grows to 0.21 of the mean dissimilarity at p = 3 and to 0.63 at p = 5, and the mean maximal membership falls from 0.96 to 0.57. The spread flattens the partition, but the hard labels stay correct. (Below p = 2 the partition is softer for a different reason: a small power compresses the ratio of far to near distances.) The printed study shows the usual effect of m, and that both initializations find the groups; their objectives differ because the runs end with different β.

Figure 10.4

Figure 10.4. FCM on the coordinates (left) and RFCM on the matrix of squared distances with its dual centers (middle) give the same partition; the objective trajectories coincide (right).

Open in ColabExample plot_01_rfcm_fcm_duality.py in the gallery

Figure 10.5

Figure 10.5. The relational prototypes are weight vectors over the objects (left); the squared-distance matrix ordered by cluster shows three blocks (right).

Figure 10.6

Figure 10.6. NERF on powers p of the Euclidean distances. Left: the final spread relative to the mean dissimilarity is zero up to p = 2 and grows beyond it. Right: the partition flattens with the spread while the groups are kept.

10.4.2 Fuzzy c-medoids on dynamic time warping

Three shape classes (a bell, a step, and a double bump) are generated with random time warps and shifts, 25 series of length 60 per class (fig. 10.7). In the Euclidean matrix the class blocks are blurred, because shifted peaks produce large distances within a class; in the DTW matrix with a band of w = 12 samples they are clear, and the alignment of two bells reduces their dissimilarity from 1.73 to 0.65 (fig. 10.8). Fuzzy c-medoids with five restarts reaches an adjusted Rand index (ARI) of 0.92 on the DTW matrix and 0.49 on the Euclidean one, whose clusters group the series by when the peak occurs rather than by its shape; the medoids of the DTW clustering are typical, well-centered members of the classes (fig. 10.9). The memberships (fig. 10.10) are crisp for the steps and shared between bells and double bumps, whose warped versions can resemble each other. On 360 series, the candidate study (fig. 10.11) shows that one or two candidates leave the search in clearly worse optima (J = 186 and 176), five come within 1.5 % of the full search (J = 170.7 against 168.5), and fifty reach it in about a quarter of the time. The printed band study shows the ARI rising from 0.49 at w = 0 (Euclidean) and w = 4 through 0.85 at w = 8 to 1.0 at w = 20 and without a band: the band must cover the displacements in the data. The medoids hardly move with m, while the mean maximal membership falls from 0.95 at m = 1.3 to 0.52 at m = 3.

Figure 10.7

Figure 10.7. Three shape classes with random time warps and shifts: a bell, a step, and a double bump.

Open in ColabExample plot_02_fcmdd_dtw_series.py in the gallery

Figure 10.8

Figure 10.8. Euclidean (left) and DTW (middle) dissimilarities ordered by the true class, and the DTW alignment of two bells (right): the class blocks are clear only under DTW.

Figure 10.9

Figure 10.9. Fuzzy c-medoid clusters on the DTW matrix (top) and on the Euclidean matrix (bottom), with the medoid series in black.

Figure 10.10

Figure 10.10. Memberships of the DTW c-medoid clustering, with the series ordered by the true class.

Figure 10.11

Figure 10.11. Linear fuzzy c-medoids: final objective (left) and time of thirty restarts (right) against the number of medoid candidates.

10.4.3 Fuzzy k-modes on survey data

Three hundred respondents answer six questions with four possible answers each. Each of three groups has a typical answer pattern, and every answer is replaced by a uniformly random one with probability 0.25. Fuzzy k-modes with m = 1.5 recovers the three planted modes exactly (ARI 0.98), and the table of modes (fig. 10.12) reads directly as a table of group profiles; the shade of a cell is the share of the membership mass on the modal answer, between 75 and 85 %. Most respondents differ from their own mode in one or two answers. Figure 10.13 illustrates the mode theorem for one question: the modal answer of each cluster is the one with the largest membership mass. The exponent study (fig. 10.14) confirms the sensitivity predicted by the integer dissimilarity: the planted modes are found up to m = 2.5, while the mean maximal membership falls from 0.99 to 0.68; at m = 3 the modes drift and the ARI drops to 0.72, and at m = 4 to 0.41. The printed noise study shows that the modes are recovered even when 65 % of the answers are replaced at random, although the assignment of individual respondents degrades (ARI 0.45). The objective against c (fig. 10.15) has a clear knee at three groups.

Figure 10.12

Figure 10.12. Fitted modes with the share of the membership mass on the mode (left) and the matching dissimilarity of the respondents to their group’s mode (right).

Open in ColabExample plot_03_kmodes_survey.py in the gallery

Figure 10.13

Figure 10.13. Membership mass of the answers to question q1 in each cluster; the mode is the answer with the largest mass.

Figure 10.14

Figure 10.14. Agreement with the groups and mean maximal membership of fuzzy k-modes against the exponent m.

Figure 10.15

Figure 10.15. The objective of fuzzy k-modes against the number of clusters has its knee at the three planted groups.

10.4.4 Fuzzy k-prototypes and the weight γ

Mixed records with two numeric and three categorical attributes are generated so that neither part separates the three groups alone: the numeric centers are three units apart with unit spread, and every categorical entry is replaced by a random category with probability 0.25 (fig. 10.16). Fuzzy k-prototypes with the default γ = 1.64 (the mean standard deviation of the numeric columns) reaches an ARI of 0.94 and returns prototypes with means and modes (fig. 10.17). The γ study (fig. 10.18) traces the interpolation: at γ = 0 the partition is that of FCM on the numeric columns (agreement 1.0, ARI 0.75), for γ = 100 it approaches fuzzy k-modes on the categorical columns (agreement 0.97, ARI 0.83), and in between the two parts correct each other, with the best ARI of 0.97 at γ = 5. The default lies on the rising flank just below this optimum. The exponent softens the partition as usual (mean maximal membership 0.91, 0.76, and 0.58 for m = 1.5, 2, and 3) while the ARI stays at 0.93–0.94, all five random starts reach the same objective, and a new record with an unseen category is assigned with one mismatch to every mode.

Figure 10.16

Figure 10.16. Mixed data: the numeric part colored by the true group, with the planted centers as crosses (left), and the planted modes of the categorical part with their frequencies (right).

Open in ColabExample plot_04_kprototypes_mixed.py in the gallery

Figure 10.17

Figure 10.17. Fuzzy k-prototypes with the default weight: the numeric part of the partition with the prototypes (left) and the modes of the categorical part (right).

Figure 10.18

Figure 10.18. The weight γ interpolates between fuzzy c-means on the numeric part (γ = 0) and fuzzy k-modes on the categorical part (γ →∞); the combination outperforms both.

10.4.5 Gower’s coefficient versus one-hot encoding

Data of the same kind, now with four categorical attributes whose entries are replaced at random with probability 0.3, are clustered along two routes. In the Gower matrix every attribute counts equally; in the Euclidean distance of the one-hot encoded records the two numeric columns dominate the twelve indicator columns (fig. 10.19). On these complete data the routes agree: Gower with fuzzy c-medoids reaches an ARI of 0.89, Gower with RFCM 0.90, one-hot FCM 0.91, and k-prototypes 0.92 (fig. 10.20); the difference is that the medoids are real records. NERF on the Gower matrix never needs a spread (β = 0), as Gower’s theorem predicts. Scaling the weight of the numeric attributes (fig. 10.21) traces the same path as γ: zero weight (categories only) gives an ARI of about 0.8, equal weights 0.89–0.90, a moderately larger weight up to 0.97, and a weight of 100 (practically numeric only) falls back to 0.78. Gower’s coefficient is defined without imputation, and in the printed missing-value study NERF on it keeps an ARI of 0.86 with 10 % and 0.84 with 20 % missing entries. Fuzzy c-medoids, however, collapses to about 0.45 from 10 % on, because a record compared on only two or three attributes looks close to many others and is chosen as a medoid; the medoids carry up to four missing entries out of six. The one-hot route has to discard incomplete records and keeps its accuracy only on the shrinking remainder (165 of 300 records at 10 %, 34 at 30 %).

Figure 10.19

Figure 10.19. Gower’s dissimilarity (left) and the Euclidean distance of the one-hot encoded records (right), ordered by the true group.

Open in ColabExample plot_05_gower_fcmdd_vs_onehot.py in the gallery

Figure 10.20

Figure 10.20. Gower with fuzzy c-medoids (left, medoids as crosses), one-hot encoding with FCM (middle), and fuzzy k-prototypes (right), shown in the numeric plane.

Figure 10.21

Figure 10.21. Agreement with the groups against the weight of the numeric attributes in Gower’s coefficient, for fuzzy c-medoids and NERF c-means.

10.4.6 Autocorrelation-based clustering of time series

Twenty-five series of length 200 are drawn from each of three processes: an AR(1) process with ϕ = 0.5, an MA(1) process with 𝜃 = 0.9, and an AR(1) process with ϕ = −0.6 (fig. 10.22). The first two have practically the same lag-1 autocorrelation (0.5 against 0.497) and differ from lag 2 on; the estimated autocorrelation functions scatter around the theoretical ones by about 1∕T. With L = 5 lags, A-FCM reaches an ARI of 0.88 and A-FCMd 0.85, RFCM on the squared autocorrelation distances reproduces A-FCM, and fuzzy c-medoids on the Euclidean distances of the raw values finds no structure (ARI 0.02), because independent realizations of one process are as far apart as realizations of different processes. In the plane of the first two autocorrelations (fig. 10.23) the alternating class lies far from the others, while the AR(1) and MA(1) classes are separated only along ρ^(2), and their memberships are correspondingly shared. New AR(1) series with ϕ swept from −0.9 to 0.9 (fig. 10.24) receive graded memberships: the alternating cluster dominates for negative ϕ, the three clusters share the membership near white noise, the MA(1) cluster peaks at ϕ ≈0.2–0.3, and the persistent cluster takes over toward ϕ = 0.5. The parameter study (fig. 10.25) shows the roles of L and T. With one lag the AR(1) and MA(1) classes are merged (ARI at most 0.55 for every length), from two lags on they are separated, and beyond a few lags every additional coordinate adds estimation noise, flattens the memberships, and, for short series, lowers the ARI. Longer series improve the result throughout; with T = 400 the ARI reaches 0.96. The printed study runs A-FCMd with L = 20: uniform weights give an ARI of 0.70, and decaying lag weights wq = 0.8q−1 raise it to 0.88, slightly above the 0.85 of A-FCMd with five lags.

Figure 10.22

Figure 10.22. Two series of each process (top) and the estimated autocorrelation functions of all series of a class with the theoretical one (bottom).

Open in ColabExample plot_06_autocorrelation_series.py in the gallery

Figure 10.23

Figure 10.23. A-FCM in the plane of the first two autocorrelations, with centers, A-FCMd medoids, and the theoretical values (left), and the memberships ordered by the true class (right).

Figure 10.24

Figure 10.24. Mean memberships of new AR(1) series in the fitted clusters against their coefficient ϕ.

Figure 10.25

Figure 10.25. Agreement with the processes (left) and mean maximal membership (right) against the number of lags L for four series lengths T.

10.5 Further reading

Relational fuzzy c-means and its duality with FCM are due to Hathaway, Davenport, and Bezdek [141], the non-Euclidean extension with the β-spread to Hathaway and Bezdek [142]; both rest on the c-means functional of Bezdek [3], and the relational methods are surveyed in the broader context of fuzzy pattern recognition in [150]. The Euclidean property of dissimilarity matrices, the double centering, and the effect of additive constants are treated thoroughly by Gower and Legendre [146]. Fuzzy c-medoids, its linear-complexity candidate search, and the robust variant RFCMdd are due to Krishnapuram et al. [143]; the crisp medoid methods PAM and CLARA and the fuzzy relational method FANNY are described in the book of Kaufman and Rousseeuw [5], which also uses Gower’s coefficient [149] for mixed data. Huang introduced k-modes and k-prototypes in [144], and Huang and Ng the fuzzy k-modes algorithm and the theorem on the fuzzy mode in [145]. Dynamic time warping with the band constraint goes back to Sakoe and Chiba [147], the autocorrelation-based fuzzy clustering of time series to D’Urso and Maharaj [148]. The geodesic c-medoids of chapter 7 and the kernel fuzzy c-means of chapter 6 are close relatives of the methods of this chapter: both replace the Euclidean geometry of FCM by one derived from pairwise relations of the samples.