Fuzzy Clustering and Data Analysis in PythonThe fuzzyclust toolbox

Appendix B
Migrating from the MATLAB toolbox

This appendix is for readers who know the Fuzzy Clustering and Data Analysis Toolbox for MATLAB [12]. It maps every MATLAB function, parameter, and result field to its counterpart in fuzzyclust and lists the places where the Python toolbox deliberately behaves differently. The chapter column of the first table points to the full treatment of each method.

B.1 Functions

The MATLAB toolbox passed a data structure and a param structure to every function and returned a nested result structure. In fuzzyclust every algorithm is a scikit-learn estimator: the parameters are constructor arguments, the data matrix is the argument of fit, and the results are attributes of the fitted object. Table B.1 maps the functions.

Table B.1. MATLAB toolbox functions and their fuzzyclust counterparts.

MATLAB

fuzzyclust

Chapter

Kmeans(data,param)

cluster.KMeans(n_clusters).fit(X)

3

Kmedoid(data,param)

cluster.KMedoids(n_clusters).fit(X)

3

FCMclust(data,param)

cluster.FCM(n_clusters, m).fit(X)

3

GKclust(data,param)

cluster.GK(n_clusters,  m,  rho,  gamma,  beta).fit(X)

3

GGclust(data,param)

cluster.GG(n_clusters, m).fit(X)

3

clusteval(new, result, param)

est.predict_proba(X_new), est.transform(X_new), plotting. plot_membership_contours

3

validity(result, data, param)

validity.validity_indices(X, U, V, m)

4

optnumber (demo)

validity.scan_n_clusters, suggest_n_clusters

4

clust_normalize(data, ’range’|’var’)

preprocessing.normalize(X,  ’range’|’var’) or scikit-learn scalers

2

clust_denormalize(data)

scaler. inverse_transform(Z)

2

PCA(data,param,result)

viz.pca_projection(X, n_components, centers)

5

Sammon(proj, data, result, param)

viz.Sammon(n_components). fit_transform(X)

5

FuzSam(proj, result, param)

viz.FuzzySammon().fit(est, X)

5

projeval(result,param)

viz.projection_quality(U, Y, Z, m)

5

samstr(data, result) (stress)

viz.sammon_stress(X, Y)

5

nDexample(cx,N,n,seed)

datasets.make_fuzzy_blobs(...)

2

MotorCycle.txt

datasets.load_motorcycle()

3

B.2 Parameters

Table B.2 maps the fields of the MATLAB param structure to the constructor arguments of the estimators.

Table B.2. Fields of the MATLAB param structure and the corresponding constructor arguments.

param.*

constructor argument

remark

param.c (scalar)

n_clusters

number of clusters

param.c (matrix N ×c)

init=U0

initial partition matrix

param.c (matrix c ×n, k-means)

init=V0

initial centers

param.m

m

fuzziness exponent (default 2)

param.e

tol

termination tolerance on max ⁡ |Δμik| (default 10−4)

param.ro

rho

GK cluster volumes (default all 1); MATLAB’s (det ⁡ Fi∕ρi)1∕nF i−1 gave det ⁡ Ai = 1∕ρi, fuzzyclust follows det ⁡ Ai = ρi

param.gamma

gamma

covariance regularization weight of GK, here also of GG (default 0)

param.beta

beta

condition-number bound of GK, here also of GG (default 1015)

param.val (1/2/3)

indices=[...] of validity_indices

1: PC, CE; 2: SC, S, XB; 3: DI, ADI

param.vis

plotting.* after fitting

plotting is separated from fitting

param.q

n_components

projection dimension (PCA; Sammon and FuzSam took it from proj.P)

param.max

max_iter

iteration count of Sammon and FuzSam (default 100)

param.alpha

alpha

gradient step size of Sammon and FuzSam

—

init, n_init, max_iter, random_state

new in the clustering estimators: initialization strategy, restarts, iteration cap, seed

B.3 Results

Table B.3 maps the fields of the MATLAB result structure to the attributes of a fitted estimator.

Table B.3. Fields of the MATLAB result structure and the fitted attributes.

result.*

attribute

shape

result.data.f

membership_

(N,c) — same orientation as MATLAB

result.data.d

distances_

(N,c), Dik (not squared)

result.cluster.v

cluster_centers_

(c,n)

result.cluster.P

covariances_

(c,n,n) (MATLAB: n ×n ×c)

result.cluster.M

norm_matrices_

(c,n,n), GK only

result.cluster.V

eigenvectors_

(c,n,n), all eigenvectors as columns, in ascending order of the eigenvalues (MATLAB kept only that of the smallest eigenvalue)

result.cluster.D

eigenvalues_

(c,n), ascending

result.cluster.Pi (GG)

priors_

(c,)

result.iter

n_iter_

result.cost

objective_history_, objective_

J per iteration, final J; MATLAB’s cost summed μikDik2 without the exponent m (GGclust: after the distances were transformed), so its values differ

result.validity.PC …

validity_indices(...) [’PC’]

dictionary

eval.f, eval.d (clusteval)

predict_proba(X), transform(X)

(Nnew,c)

result.proj.P

embedding_; first output Y of pca_projection

(N,q)

result.proj.vp

embedded_centers_ (FuzzySammon); second output Z of pca_projection

(c,q)

result.proj.e

stress_ (Sammon) or sammon_stress(X,  Y)

float; the function scores any projection

B.4 Behavioral differences

Initialization.

The fuzzy algorithms of the MATLAB toolbox drew random prototypes uniformly from the box centered at the data mean whose half-widths are the largest absolute deviations from it, with a fixed seed (rand(’state’,0)); Kmeans and Kmedoid started from randomly chosen samples. fuzzyclust offers the same start (init="random", the default) and k-means++ seeding for every estimator, controls the seed through random_state, and can run several restarts (n_init), keeping the partition with the lowest J (section 2.2.6).

Termination.

MATLAB iterated while the largest membership increase, max ⁡ ik(μik(l) −μik(l−1)) without the absolute value, exceeded 𝜖, and had no iteration cap; fuzzyclust tests max ⁡ ik|Δμik|< 𝜖 and adds max_iter.

Optional parameters.

FCMclust, GKclust, and GGclust tested their optional fields with exist(’param.m’)==1. exist looks for a variable or a file of that name, never for a structure field, so the test was always false: m and e (and, in GKclust, ro, gamma, and beta) always took their default values, and clusteval and validity always used m = 2 for the same reason. The tolerance line also read param.m where param.e was meant. Results computed in MATLAB with other settings therefore correspond to the defaults; fuzzyclust honors every constructor argument.

GK covariance regularization.

The MATLAB code shrank the covariance toward A0.^(1/n), and since A0 already contained det ⁡ (F0)1∕n, it computed Fi ←(1 −γ)Fi + γdet ⁡ (F0)1∕n2 I; the Python implementation follows the published formula Fi ←(1 −γ)Fi + γdet ⁡ (F0)1∕nI of Babuška et al. [19] exactly (section 3.2.4). Since gamma was always zero in MATLAB (see above), the difference never showed in MATLAB results.

Gath–Geva.

The exponential distance is evaluated in the logarithmic domain, so far-away samples no longer overflow. The covariance weighting exponent equals m, as in MATLAB, but the priors are computed from the memberships themselves, αi = 1 N ∑ ⁡ kμik, where MATLAB used μikm. The regularization of GK (gamma, beta) is also available.

Validity.

All indices are computed at once from the data, the partition, the centers, and m, with Euclidean distances whatever the clustering algorithm (for SC, S, XB, and ADI, MATLAB used the algorithm’s distance matrix result.data.d). The Fukuyama–Sugeno, PBM-F, Kwon, and PCAES indices, the volume and density indices of Gath and Geva (FHV, PD, APD), MPC, and the silhouette were added. The param.val groups are reproduced by passing the index names.

Plotting.

param.vis and the contour map of clusteval are replaced by explicit plotting helpers that draw on a matplotlib Axes; fitting never opens a figure.

Data.

The data matrix is a NumPy array or a pandas DataFrame; no wrapper structure is needed. Feature names are kept in feature_names_in_.

Normalization.

clust_normalize stored the scaling inside the data structure; here the scaler is a separate object (or a step in a scikit-learn Pipeline) whose inverse_transform plays the role of clust_denormalize. The MATLAB Kmeans range-normalized its input internally; KMeans does not scale the data.

A minimal translation of a typical MATLAB session,

data = clust_normalize(data,’range’);
param.c = 3; param.m = 2; param.e = 1e-4;
result = GKclust(data,param);
param.val = 2;
result = validity(result,data,param);
new.X = (new.X - repmat(data.min,size(new.X,1),1)) ./ ...
        repmat(data.max - data.min,size(new.X,1),1);
eval = clusteval(new,result,param);

reads in Python as

from fuzzyclust.cluster import GK 
from fuzzyclust.preprocessing import normalize 
from fuzzyclust.validity import validity_indices 
 
Xs, scaler = normalize(X, "range") 
gk = GK(n_clusters=3, m=2.0, tol=1e-4, random_state=0).fit(Xs) 
indices = validity_indices(Xs, gk.membership_, gk.cluster_centers_, m=gk.m, 
                           indices=["SC", "S", "XB"]) 
U_new = gk.predict_proba(scaler.transform(X_new))