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, , 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, , 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.
The identity behind RFCM holds only if the dissimilarities are squared distances of some point configuration, that is, if 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.
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.
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 form the matrix (stored transposed, , in the code), and the index (or ) runs over clusters and (or , ) over objects. Relational data form a matrix with and . The matrix is called Euclidean if there are points of some with , 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 , , 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 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 be a convex combination of the objects, with weights , , collected in . For any point and any weights summing to one, expanding the squares gives
|
| (10.1) |
The right-hand side contains only squared distances between objects. Replacing them by the entries of defines the relational distance
|
| (10.2) |
which equals the squared Euclidean distance of to the weighted mean whenever holds squared Euclidean distances. The FCM prototype is the weighted mean with weights , so RFCM [141] alternates
|
| (10.3) |
and minimizes , 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 are the FCM centers. RFCM is therefore not an approximation but FCM written in the language of . The relational prototype is a probability vector over the objects: it states how much each object contributes to the center of cluster , and it is concentrated on the typical members of the cluster.
The price is the matrix: one iteration needs the products , that is, operations, and the matrix itself takes memory. A new object enters through its squared distances to the 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 -th row of , and the membership follows. When 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.
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 ; otherwise negative relational distances stop it.
- Parameters as in FCM (, , initialization, restarts); memory, 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,
|
| (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 gains on every eigenvalue in the subspace orthogonal to . The effect on the relational distances can be computed without forming . Substituting (10.4) into (10.2) and using gives
|
| (10.5) |
with the -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 , 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,
|
| (10.6) |
The pair that attains the maximum then has distance zero and membership one in cluster , and the iteration continues with the shifted distances. In the example of fig. 10.2, and , so .
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 . The objective , in turn, is that of , 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 , the value for an object outside the training set.
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, , and minimizes the membership-weighted sum of dissimilarities to them,
|
| (10.7) |
where is any dissimilarity: it need not be squared, Euclidean, or even a metric, and apart from non-negativity only is used. For fixed medoids the memberships follow from the FCM formula with in the role of the squared distance,
|
| (10.8) |
with when is the medoid of cluster . For fixed memberships the functional splits into one term per cluster, and the best medoid of cluster is the object with the smallest weighted sum of dissimilarities,
|
| (10.9) |
With the candidate set containing all objects, the update is exact and costs per cluster. Krishnapuram et al. [143] observed that the medoid of a cluster is almost always one of its most typical members; restricting to the objects with the largest memberships in cluster makes the update and the whole iteration linear in (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, , 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 smallest terms 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.
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 most typical members: instead of 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 , , , and ; restarts are recommended because the medoids are discrete.
10.2.4 Fuzzy k-modes
Let all attributes be categorical, attribute taking values in a finite set . The simple matching dissimilarity counts the attributes in which two records differ,
|
| (10.10) |
and the prototype of a cluster is a mode, a record that need not occur in the data. Huang [144] built k-modes on this pair; Huang and Ng [145] minimize the fuzzy functional
|
| (10.11) |
For fixed modes the memberships follow from the FCM formula with in the role of the squared distance ( for a record identical to mode ). For fixed memberships the functional separates into one term per cluster and attribute, , and by the theorem of Huang and Ng each term is minimized by the category of attribute that carries the largest membership mass in cluster ,
|
| (10.12) |
This is “the most frequent category” with every record counted with its weight (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 attributes from one mode and in from another is . For and the ratio is at but only at . The partition is therefore much fuzzier than that of FCM on continuous data at the same , and values of close to one are appropriate. The update is per iteration, linear in the number of records, which made k-modes popular for large categorical data sets.
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 small (about –).
- Linear in the number of records; restarts guard against local minima.
10.2.5 Fuzzy k-prototypes
Mixed records have numeric attributes and categorical attributes . Huang’s k-prototypes dissimilarity [144] treats each kind in its own terms and adds them with a weight ,
|
| (10.13) |
and the fuzzy version minimizes by the FCM membership formula and a prototype update that combines the two previous cases: the numeric part of is the fuzzy mean (), and the categorical part is the membership-mass mode (10.12) (). 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 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.
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 () 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 .
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 and of the same shape but with events at slightly different times are far apart in the Euclidean sense, which compares with . Dynamic time warping [147] compares each with a matching instead. A warping path is a sequence of index pairs from to that advances by one in , in , 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
|
| (10.14) |
with and outside the admissible region. The Sakoe–Chiba band 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 to per pair. With 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 ,
|
| (10.15) |
and compare series by the Euclidean distance of these vectors. The implementation adds optional lag weights (all equal to one by default),
|
| (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 , which must reach the lags at which the processes differ, and the weights , which can damp the high lags whose estimates are noisy.
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.
- must cover the lags at which the processes differ, but every extra lag adds estimation noise of order ; decaying weights make a generous 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 : the range-scaled absolute difference for a numeric attribute with range , and the mismatch indicator for a categorical one. The dissimilarity is the weighted mean of the scores over the attributes observed in both records,
|
| (10.17) |
so missing values need no imputation. By construction every attribute contributes on the same scale, and the weights 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 is a Euclidean distance [146, 149]; the matrix 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.
| algorithm | input | prototype | requirement |
| RFCM | (squared) | object weights | Euclidean |
| NERF c-means | any | object weights | none (see ) |
| FCMdd | any | 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 matrix and predict_proba the rectangular matrix of the new objects against the 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_ (),
cluster_centers_ (dual centers
with a feature metric, else the relational centers), dissimilarity_matrix_, membership_, labels_,
distances_ (),
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 .
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
(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
, or of
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 , 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 ) and recovers the three groups exactly. The parameter study (fig. 10.6) feeds powers of the Euclidean distances to NERF. Up to the matrix is Euclidean and ; beyond that the spread grows to of the mean dissimilarity at and to at , and the mean maximal membership falls from to . The spread flattens the partition, but the hard labels stay correct. (Below 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 , and that both initializations find the groups; their objectives differ because the runs end with different .
Open in ColabExample plot_01_rfcm_fcm_duality.py in the gallery
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 samples they are clear, and the alignment of two bells reduces their dissimilarity from to (fig. 10.8). Fuzzy c-medoids with five restarts reaches an adjusted Rand index (ARI) of on the DTW matrix and 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 ( and ), five come within 1.5 % of the full search ( against ), and fifty reach it in about a quarter of the time. The printed band study shows the ARI rising from at (Euclidean) and through at to at and without a band: the band must cover the displacements in the data. The medoids hardly move with , while the mean maximal membership falls from at to at .
Open in ColabExample plot_02_fcmdd_dtw_series.py in the gallery
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 . Fuzzy k-modes with recovers the three planted modes exactly (ARI ), 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 and %. 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 , while the mean maximal membership falls from to ; at the modes drift and the ARI drops to , and at to . The printed noise study shows that the modes are recovered even when % of the answers are replaced at random, although the assignment of individual respondents degrades (ARI ). The objective against (fig. 10.15) has a clear knee at three groups.
Open in ColabExample plot_03_kmodes_survey.py in the gallery
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 (fig. 10.16). Fuzzy k-prototypes with the default (the mean standard deviation of the numeric columns) reaches an ARI of and returns prototypes with means and modes (fig. 10.17). The study (fig. 10.18) traces the interpolation: at the partition is that of FCM on the numeric columns (agreement , ARI ), for it approaches fuzzy k-modes on the categorical columns (agreement , ARI ), and in between the two parts correct each other, with the best ARI of at . The default lies on the rising flank just below this optimum. The exponent softens the partition as usual (mean maximal membership , , and for , , and ) while the ARI stays at –, all five random starts reach the same objective, and a new record with an unseen category is assigned with one mismatch to every mode.
Open in ColabExample plot_04_kprototypes_mixed.py in the gallery
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 , 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 , Gower with RFCM , one-hot FCM , and k-prototypes (fig. 10.20); the difference is that the medoids are real records. NERF on the Gower matrix never needs a spread (), 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 , equal weights –, a moderately larger weight up to , and a weight of 100 (practically numeric only) falls back to . Gower’s coefficient is defined without imputation, and in the printed missing-value study NERF on it keeps an ARI of with % and with % missing entries. Fuzzy c-medoids, however, collapses to about from % 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 %, 34 at %).
Open in ColabExample plot_05_gower_fcmdd_vs_onehot.py in the gallery
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 , an MA(1) process with , and an AR(1) process with (fig. 10.22). The first two have practically the same lag-1 autocorrelation ( against ) and differ from lag 2 on; the estimated autocorrelation functions scatter around the theoretical ones by about . With lags, A-FCM reaches an ARI of and A-FCMd , 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 ), 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 , and their memberships are correspondingly shared. New AR(1) series with swept from to (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 –, and the persistent cluster takes over toward . The parameter study (fig. 10.25) shows the roles of and . With one lag the AR(1) and MA(1) classes are merged (ARI at most 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 the ARI reaches . The printed study runs A-FCMd with : uniform weights give an ARI of , and decaying lag weights raise it to , slightly above the of A-FCMd with five lags.
Open in ColabExample plot_06_autocorrelation_series.py in the gallery
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.