Fuzzy Clustering and Data Analysis in PythonThe fuzzyclust toolbox

Chapter 11
Incomplete, very large, and image data

The algorithms of the previous chapters assume a complete data matrix of moderate size whose rows are unrelated samples. Real data often violate all three assumptions. Values are missing because sensors fail or records are merged from sources that measure different things; data sets are very large or arrive as an endless stream; and the samples may be the pixels of an image, where neighbors almost always belong to the same region. This chapter keeps the fuzzy c-means functional and adapts it to each situation: partial distances and optimal completion for incomplete data (Hathaway and Bezdek); weighted fuzzy c-means with sampling, single-pass, and online schemes for very large data and streams (Havens, Bezdek, and co-workers); and six ways of bringing the pixel neighborhood into the functional for image segmentation. The three sub-packages fuzzyclust.incomplete, fuzzyclust.large, and fuzzyclust.image share the notation and the membership formula of fuzzy c-means, and the image methods reuse weighted fuzzy c-means to cluster gray-level histograms.

11.1 Problem and idea

Missing values. Fuzzy c-means measures the distance of a sample to a prototype as a sum over all features, so a single missing value makes the distance undefined. The common remedies outside clustering—dropping incomplete samples, or filling the holes with the column mean before clustering—either waste data or invent values that ignore the cluster structure: a column mean lies between the clusters and drags the filled samples there. Hathaway and Bezdek [151] compared four strategies for running fuzzy c-means on incomplete data (fig. 11.1). The whole-data strategy (WDS) drops the incomplete samples, which is defensible only when they are few. The partial-distance strategy (PDS) measures the distance over the observed features only and rescales it to the full dimension, following Dixon [152]; a sample is then judged by what is known about it. The optimal-completion strategy (OCS) treats every missing value as an additional variable of the c-means functional and optimizes it together with the partition and the prototypes, so that the data are imputed while they are clustered; the optimal value is a membership-weighted mean of the prototype coordinates. The nearest-prototype strategy (NPS) is its crisp version and copies the coordinate of the nearest prototype. All four assume that the values are missing completely at random, so that the hole pattern itself carries no information about the clusters [153].

Figure 11.1

Figure 11.1. Partial distances and the completion of a missing value. A sample with xk1 = 2 observed and xk2 missing can lie anywhere on the dashed line. The partial distance compares it with the prototypes along the observed axis only (arrows) and rescales the result to the full dimension; the memberships follow from these distances as in fuzzy c-means. Optimal completion places the missing value at the membership-weighted mean of the prototype coordinates (circle), the nearest-prototype strategy at the coordinate of the nearest prototype (square).

Very large data. Fuzzy c-means touches every sample in every iteration and stores the N ×c partition. With N in the millions, or with data that arrive as a stream, both become a problem. Since the efficient implementation of Cannon, Dave, and Bezdek [154], many schemes have been proposed that either make each iteration cheaper [155] or cluster only samples or chunks of the data; Havens, Bezdek, Leckie, Hall, and Palaniswami [156] compared the latter systematically. This chapter covers three of them (fig. 11.2). Random sample and extend (rseFCM) clusters a random sample and computes the memberships of all samples in one pass from the fixed prototypes. The other two rest on weighted fuzzy c-means, in which a sample with weight w counts as w identical samples, so that a prototype standing for a thousand observations can be clustered together with raw samples. Single-pass FCM (spFCM) of Hore, Hall, and Goldgof [157] processes the data in chunks and carries the c prototypes of a chunk, weighted by the membership mass they collected, into the next chunk. Online FCM (oFCM) [158] clusters every chunk separately and then clusters the weighted chunk prototypes. In both chunked schemes every chunk is seen once and only one chunk is held in memory, so they can also process a stream.

Figure 11.2

Figure 11.2. The chunk pipelines of single-pass and online FCM. Top: spFCM clusters each chunk together with the weighted prototypes of the previous one, so the prototypes accumulate the whole history. Bottom: oFCM clusters the chunks independently and merges their weighted prototypes with weighted FCM. Both obtain the memberships of all samples by one extension step from the final prototypes; rseFCM is the special case of a single sampled chunk.

Images. A gray-level image is a data set of N = H ⋅W one-dimensional samples, and fuzzy c-means on the pixel values is the simplest segmentation algorithm. It ignores what distinguishes an image from an arbitrary data set: a pixel and its neighbors almost always belong to the same region. Noise that pushes a pixel value across the midpoint between two prototypes therefore produces a wrong label, however clear the surrounding region is. The spatially constrained variants bring the neighborhood Nk of every pixel into the functional (fig. 11.3). FCM_S of Ahmed et al. [159] adds the distances of the neighbors to the prototype; FCM_S1 and FCM_S2 of Chen and Zhang [160] replace them with the distance of a mean- or median-filtered pixel computed once in advance; EnFCM of Szilágyi et al. [161] forms a smoothed image once and clusters its gray-level histogram, with iterations whose cost does not depend on the image size; FGFCM of Cai, Chen, and Zhang [162] does the same with locally adaptive weights that respect edges and ignore outliers; and FLICM of Krinidis and Chatzis [163] adds a parameter-free fuzzy factor that weighs each neighbor by its spatial distance and its lack of membership in the cluster.

Figure 11.3

Figure 11.3. Spatial constraints for image segmentation. Top left: the 3 ×3 neighborhood of a pixel with the spatial weights of FLICM. Top right: the effective squared distance that every method substitutes into the FCM membership formula. Bottom: EnFCM and FGFCM smooth the image once and cluster the gray-level histogram with weighted FCM.

11.2 Theory

We use the notation of section 2.2.9: rows xk of X ∈ ℝN×n, prototypes vi, and memberships μik in U ∈ ℝc×N (stored transposed, N ×c, in the code), with i (or j) indexing clusters and k samples. All algorithms of the chapter use the membership formula of fuzzy c-means [3],

μik = 1 ∑ j=1c (Dik2∕Djk2 )1∕(m−1),
(11.1)

each with its own squared distance Dik2. We treat incomplete data first (section 11.2.1), then weighted fuzzy c-means and the three schemes for very large data (sections 11.2.2 to 11.2.5), and finally the six image segmentation methods (section 11.2.6).

11.2.1 Fuzzy c-means with missing values

Let Ikj = 1 when xkj is observed and 0 when it is missing, Ik = ∑ ⁡ jIkj the number of observed features of sample k, XP the set of observed and XM the set of missing values. Every sample must have at least one observed feature, and every feature must be observed in at least one sample.

Whole-data strategy (WDS). Fuzzy c-means runs on the complete samples only; the incomplete ones are classified afterwards with partial distances. With n features and values missing independently with probability p, a sample is complete with probability (1 −p)n; with four features and 30% of the values missing, three quarters of the samples are lost.

Partial-distance strategy (PDS). The squared distance is computed over the observed features and rescaled to the full dimension,

Dik2 = n Ik ∑ j=1nI kj(xkj −vij)2,
(11.2)

which is the ordinary squared Euclidean distance for a complete sample and an unbiased estimate of it for an incomplete one when the coordinates contribute equally on average [152]. The memberships follow from (11.1), and every prototype coordinate is the membership-weighted mean of the samples that observe it,

vij = ∑ k=1NμikmIkjxkj ∑ k=1NμikmIkj .
(11.3)

Optimal-completion strategy (OCS). The c-means functional on the completed data is minimized over the partition, the prototypes, and the missing values,

min ⁡ U,V,XMJ = ∑ i=1c ∑ k=1Nμ ikm ‖x k −vi‖ 2.
(11.4)

For fixed U and V the functional is a sum of independent quadratics in the missing values, and setting the derivative to zero gives

xkj = ∑ i=1cμikmvij ∑ i=1cμikm ,xkj ∈XM,
(11.5)

the membership-weighted mean of the prototype coordinates (fig. 11.1). For fixed XM the conditions are those of fuzzy c-means on the completed data. Alternating the three blocks decreases J monotonically, and the clustering yields an imputation of the data as a by-product. The price is a functional with more local optima. The imputed values take part in the distances, so an imputed value that leans toward one prototype makes the sample look closer to it, which raises its membership and pulls the value further toward that prototype in the next step. From a poor start, samples can be captured by the wrong cluster in this way, which is why OCS is best started from the prototypes of a PDS fit (init=pds.cluster_centers_).

Nearest-prototype strategy (NPS). NPS is the crisp version of (11.5): the missing value is the coordinate of the prototype nearest to the sample, xkj = vi∗j with i∗ = argmin ⁡ iDik2, the nearest prototype being judged by the partial distance (11.2). It is cheaper than OCS and a little coarser.

For every strategy fuzzyclust returns a completed data matrix: the optimized values for OCS and NPS, and a post hoc estimate by (11.5) from the final partition for PDS and WDS. New samples, complete or not, are classified by their partial distances. The initial prototypes are seeded on the data with the holes provisionally filled by column means, but the initial partition is computed from partial distances, and OCS and NPS start from the imputation of that partition rather than from the column means.

Algorithm

In a nutshell: Fuzzy c-means for incomplete data

  • Four strategies for data with values missing completely at random: drop incomplete samples (WDS), partial distances (PDS), missing values as optimization variables (OCS), and nearest-prototype completion (NPS).
  • PDS keeps every observed value at no extra cost and is the most reliable; it is the default. OCS and NPS impute while they cluster; OCS has more local optima and should be started from the PDS prototypes.
  • Every fit comes with a completed data matrix, which is a good imputation when the data have cluster structure.
  • Parameters: strategy; c, m, init, and n_init as for FCM.

11.2.2 Weighted fuzzy c-means and the extension step

Let every sample carry a non-negative weight wk, the number of observations it stands for. Weighted fuzzy c-means (wFCM) minimizes

Jw = ∑ i=1c ∑ k=1Nw kμikm ‖x k −vi‖ 2.
(11.6)

The weight multiplies all terms of sample k and cancels in its membership condition, so the memberships follow (11.1) with the Euclidean distance unchanged; the prototypes become weighted means,

vi = ∑ k=1Nwkμikmxk ∑ k=1Nwkμikm .
(11.7)

With integer weights, wFCM is fuzzy c-means on the data set in which sample k is repeated wk times; with all weights equal to one, it is fuzzy c-means. The weight of a prototype after a weighted clustering is the membership mass it collected, w′i = ∑ ⁡ kwkμik. These weights add up to the total weight of the data, so a set of weighted prototypes is a lossy but mass-preserving summary. The second building block is the extension: for fixed prototypes, one evaluation of (11.1) gives the memberships of any number of samples, chunk by chunk with O(chunk ⋅c) memory. The histogram-based image methods of section 11.2.6 use wFCM with the gray-level counts as weights.

Algorithm

In a nutshell: Weighted fuzzy c-means

  • Fuzzy c-means in which sample k counts wk times; the membership formula is unchanged and the prototypes are weighted means.
  • Lets weighted summaries (prototypes, histogram bins) be clustered together with raw data; the building block of spFCM, oFCM, EnFCM, and FGFCM.
  • Parameters: those of FCM; the weights are passed to fit as sample_weight.

11.2.3 Random sample and extend (rseFCM)

The simplest scheme draws ns «N samples at random, runs fuzzy c-means on them, and extends the result to all samples. Its cost is one FCM run on ns samples plus one pass over the data, O(nscl + Nc) for l iterations, and Havens et al. [156], who measure every scheme against literal fuzzy c-means (LFCM), recommend it for very large image data in more than one dimension. The scheme has no approximation guarantee. If FCM on the sample finds a different local optimum than FCM on the whole data, for instance because a small cluster is underrepresented in the sample, the extension carries the error to all samples.

Algorithm

In a nutshell: Random sample and extend FCM

  • FCM on a random sample, one membership step for the rest; the fastest scheme.
  • Adequate when the sample is large enough for FCM to find the right solution on it; small clusters are at risk.
  • Parameters: sample_size (count or fraction), chunk_size of the extension, and those of FCM.

11.2.4 Single-pass FCM (spFCM)

The data are split into chunks X1,…,Xs of nl samples each. The first chunk is clustered with fuzzy c-means; its prototypes V1 with the weights w′1i = ∑ ⁡ kμik are appended to the second chunk as c weighted samples, and the augmented chunk is clustered with wFCM, initialized at V1:

(Ul,Vl) = wFCM ([Xl;Vl−1],[1;λw′ l−1] ),w′ li = ∑ kwkμik,
(11.8)

for l = 2,…,s, where the sum runs over the augmented chunk. The prototypes of the last chunk summarize the data set, and the memberships of all samples follow by extension. Because a carried prototype weighs as much as the observations it represents, the final prototypes approximate those of fuzzy c-means on the whole data; the approximation is good when every chunk contains all clusters. The weights also explain the weakness of the scheme: after a few chunks the carried prototypes outweigh any new chunk, so the result is anchored at the solution of the first chunk, and a poor local optimum there, such as two merged clusters, is never left. Restarts on the first chunk (n_init) are a cheap safeguard.

The published algorithm uses λ = 1; fuzzyclust adds a forgetting factor λ ∈[0,1] that multiplies the carried weights before every chunk. The weight of chunk l in the summary after chunk L is then λL−l, an effective memory of about 1∕(1 −λ) chunks, which lets the prototypes follow clusters that drift in a stream; λ = 0 clusters every chunk on its own, started from the previous prototypes.

Algorithm

In a nutshell: Single-pass FCM

  • Each chunk is clustered together with the weighted prototypes of the previous one; one pass over the data, memory of one chunk, partial_fit for streams.
  • Close to FCM when every chunk contains all clusters; inherits the solution of the first chunk, so give that chunk restarts.
  • The forgetting factor λ < 1 (an extension of the published algorithm) lets the prototypes follow drifting clusters.
  • Parameters: chunk_size, forgetting_factor, shuffle, and those of FCM.

11.2.5 Online FCM (oFCM)

Online FCM clusters the chunks independently and merges the results:

(Ul,Vl) = FCM(Xl),wli = ∑ kμik,l = 1,…,s, V = wFCM ([V1;…;Vs],[w1;…;ws] ),
(11.9)

followed by the extension U = extend(X,V). In the original formulation the chunk clusterings do not influence each other, so they can run in parallel, on different machines, or in any order as the chunks arrive; the final weighted clustering of s ⋅c prototypes is cheap and can be repeated after every chunk, which is what partial_fit does. A poor local optimum on one chunk contributes only c of the s ⋅c merged points and is outvoted. The price is the storage of all chunk prototypes and a full FCM run to convergence on every chunk, which makes oFCM the slowest of the three schemes. By default, fuzzyclust starts each chunk run from the prototypes of the previous chunk, which saves iterations and keeps the cluster order aligned; chunk_init="independent" restores fully independent starts. Like spFCM with λ = 1, oFCM summarizes the whole past and lags behind drifting clusters; its chunk prototypes Vl, on the other hand, are memoryless estimates of the current clusters.

Algorithm

In a nutshell: Online FCM

  • Independent FCM runs on the chunks, a weighted FCM of their prototypes at the end; chunks can be processed in parallel or in any order.
  • The least sensitive of the three schemes to poor chunk solutions, and the slowest.
  • Parameters: chunk_size, chunk_init ("previous" or "independent"), shuffle, and those of FCM.

11.2.6 Spatially constrained fuzzy c-means for images

Let xk be the value of pixel k (a gray level, or a vector of channels for the pixel-based methods), pk its position (row and column index), Nk the set of its neighbors in a square window of side a with the center excluded, NR = a2 −1 their number, dkr = ‖pk −pr‖ the Euclidean distance between the positions of k and r, and vi the prototype of region i. All methods iterate the membership formula (11.1) with an effective squared distance D~ik2 (fig. 11.3) and an adapted prototype update. Windows that extend beyond the image border are filled by reflection.

FCM_S. Ahmed et al. [159] add a term to the functional that penalizes neighbors of a pixel that lie far from the prototype of the pixel’s cluster,

JS = ∑ i=1c ∑ k=1Nμ ikm ‖x k −vi‖ 2+ α NR ∑ i=1c ∑ k=1Nμ ikm ∑ r∈Nk ‖xr −vi‖ 2,
(11.10)

which gives the effective distance and the prototype update

D~ik2 = ‖x k −vi‖ 2 + α NR ∑ r∈Nk ‖xr −vi‖ 2, vi = ∑ kμikm (xk + α NR ∑ r∈Nkxr ) (1 + α)∑ kμikm .
(11.11)

A pixel whose value is corrupted but whose neighbors are clean is pulled into the neighbors’ cluster; the weight α sets how strongly. The paper’s second component, the estimation of the intensity bias field of MR images, is not implemented. The neighborhood sums of the distances to every prototype must be recomputed in every iteration.

Algorithm

In a nutshell: FCM_S

  • Adds the distances of the neighbors to the prototype; suppresses Gaussian noise but smooths with fixed weights.
  • Cost O(NcNR) per iteration; mean-type smoothing spreads impulse noise instead of removing it.
  • Parameters: alpha (α), window_size.

FCM_S1 and FCM_S2. Chen and Zhang [160] replace the neighbors with a single filtered value x¯k, the mean (S1) or the median (S2) of the window, computed once in advance:

JS1,2 = ∑ i=1c ∑ k=1Nμ ikm ( ‖x k −vi‖ 2+α ‖x¯ k −vi‖ 2 ),v i = ∑ kμikm(xk + αx¯k) (1 + α)∑ kμikm .
(11.12)

The cost per iteration is that of fuzzy c-means. The median makes FCM_S2 robust to impulse noise, but only when the median outweighs the pixel: for a white impulse in a gray region the pixel term favors the white cluster and the median term the gray one, and with α = 1 the two balance exactly, so α > 1 is needed. The paper’s main contribution, a kernel-induced distance, is not implemented.

Algorithm

In a nutshell: FCM_S1 and FCM_S2

  • The filtered pixel is a second observation weighted by α; the cost per iteration is that of FCM.
  • S1 (mean) suits Gaussian noise; S2 (median) removes impulses and keeps edges, but needs α > 1 against salt-and-pepper noise.
  • Parameters: alpha, window_size.

EnFCM. Szilágyi et al. [161] form the linearly weighted sum image once,

ξk = 1 1 + α (xk + α NR ∑ r∈Nkxr ),
(11.13)

quantize it into q gray levels ξl with pixel counts γl, and cluster the levels with the counts as weights,

JEn = ∑ i=1c ∑ l=1qγ lμilm(ξ l −vi)2,v i = ∑ lγlμilmξl ∑ lγlμilm ,
(11.14)

which is wFCM (11.6) on the q levels. A pixel inherits the memberships of its level. After one pass over the image, the iterations cost O(qc) instead of O(Nc), about a thousand times less for a 512 ×512 image and q = 256. The method needs a single-channel image.

Algorithm

In a nutshell: EnFCM

  • Linear smoothing once, then fuzzy c-means on the gray-level histogram; the fastest method, with iterations independent of the image size.
  • Same noise behavior as FCM_S1 (good for Gaussian, poor for impulse noise); gray-level images only.
  • Parameters: alpha, window_size, n_levels (q).

FGFCM. Cai, Chen, and Zhang [162] keep the histogram route but form the summed image with locally adaptive weights,

ξk = ∑ r∈NkSkrxr ∑ r∈NkSkr , Skr = exp ⁡ ( − ‖pk −pr‖ ∞ λs ) exp ⁡ ( − (xk −xr)2 λgσk2 ),
(11.15)

where ‖⋅‖∞ is the maximum norm, so that the spatial factor depends on the larger of the row and column offsets, and σk2 = 1 NR ∑ ⁡ r∈Nk(xr −xk)2 is the local mean squared difference. The gray-level factor compares a neighbor’s difference with the typical difference in the window: in a flat region all neighbors count, whereas an outlier among them or a neighbor on the far side of an edge hardly counts at all. Noise is smoothed without blurring edges, and an impulse does not leak into its neighbors. The clustering is then (11.14) on the histogram of ξ.

Algorithm

In a nutshell: FGFCM

  • EnFCM with edge-preserving, outlier-rejecting weights; as fast as EnFCM.
  • Handled both Gaussian and impulse noise well in our experiments; gray-level images only.
  • Parameters: lambda_s, lambda_g (scales of the spatial and gray-level factors), window_size, n_levels.

FLICM. Krinidis and Chatzis [163] add a fuzzy factor to the distance,

Gki = ∑ r∈Nk 1 dkr + 1(1 −μir)m ‖x r −vi‖ 2,D~ ik2 = ‖x k −vi‖ 2 + G ki,
(11.16)

with the prototypes updated as in fuzzy c-means, vi = ∑ ⁡ kμikmxk∕∑ kμikm. A neighbor that belongs firmly to cluster i (μir ≈1) adds nothing to the distance of pixel k to vi; a neighbor that does not belong to it adds its own distance, damped by the spatial distance. A pixel surrounded by members of cluster i is thus drawn into it even when its own value is far from vi, and the factor needs no weight parameter. Because Gki depends on the memberships, it is evaluated with the memberships of the previous iteration. The iteration is therefore a fixed-point scheme rather than an exact minimization of the functional ∑ ⁡ i,k(μikm ‖xk −vi‖ 2 + Gki), and in our experiments its result depended more on the initialization than that of the other methods; the examples use k-means++ seeding.

Algorithm

In a nutshell: FLICM

  • A fuzzy factor built from the neighbors’ distances and their lack of membership; no smoothing weight to tune.
  • Among the best under Gaussian noise; moves strong impulses only halfway when the extreme gray levels are classes of their own.
  • Cost O(NcNR) per iteration; sensitive to the initialization. Parameters: window_size, m.

11.3 Using it in fuzzyclust

The incomplete-data estimator and the very-large-data schemes derive from BaseFuzzyClusterer and have the usual methods fit, predict, predict_proba, transform, and score; the chunked schemes add partial_fit. SpatialFCM takes an image of shape (H,W) or (H,W,C) instead of a data matrix and produces label and membership images.

fuzzyclust.incomplete.IncompleteFCM

n_clusters=3, m=2.0, strategy="pds"|"wds"|"ocs"|"nps", tol, max_iter, init (string or prototypes, e.g. those of a PDS fit), n_init, random_state, verbose. Missing values are NaN.
Attributes cluster_centers_, membership_, labels_ (all samples), distances_, missing_mask_, n_missing_, X_completed_ (optimized for OCS/NPS, post hoc for PDS/WDS), covariances_, objective_, n_iter_. predict_proba and transform accept incomplete samples (partial distances).

fuzzyclust.large.WeightedFCM

Parameters of FCM; fit(X, sample_weight=None). Attributes as for FCM, plus sample_weight_. The function extend_partition(X, V, m=2.0,  chunk_size=None) returns memberships and squared distances for fixed prototypes.

fuzzyclust.large.RandomSampleFCM

n_clusters=3, sample_size=0.1 (count or fraction), m, tol, max_iter, init, n_init, chunk_size=None (extension), random_state, verbose.
Attributes sample_indices_, fcm_ (the FCM fitted on the sample), cluster_centers_, membership_, labels_, objective_ (on all data).

fuzzyclust.large.SinglePassFCM, fuzzyclust.large.OnlineFCM

n_clusters=3, chunk_size=10000, m, tol, max_iter, init, n_init (first chunk; every chunk of OnlineFCM with chunk_init="independent"), shuffle=True, random_state, verbose; SinglePassFCM also forgetting_factor=1.0, OnlineFCM also chunk_init="previous"|"independent".
Methods fit(X) and partial_fit(chunk). Attributes cluster_centers_, center_weights_, chunk_centers_, chunk_weights_, chunk_objective_, chunk_n_iter_, n_chunks_, membership_, labels_ (of the data passed last); OnlineFCM.centers_model_ is the final weighted clusterer.

fuzzyclust.image.SpatialFCM

n_clusters=3, method="flicm"|"fcm"|"fcm_s"|"fcm_s1"|"fcm_s2"| "enfcm"|"fgfcm", m=2.0, alpha=1.0, window_size=3, lambda_s=3.0, lambda_g=6.0, n_levels=256, tol, max_iter=100, init, n_init, random_state, verbose.
Attributes cluster_centers_, membership_ (H,W,c), labels_ (H,W), filtered_image_, histogram_, level_values_, level_membership_ (histogram methods), objective_, n_iter_. predict(image) segments a new image with the fitted prototypes.

helpers, data generators, and plots

partial_distances(X, V); make_mcar(X, missing_rate), make_incomplete_blobs; plot_incomplete_clusters, plot_imputation. make_large_blobs, make_drifting_stream (a generator of chunks); plot_chunk_timeline, plot_center_trajectories. neighborhood_sum, weighted_sum_image, local_similarity_image; make_synthetic_image, add_image_noise; segmentation_accuracy, match_labels; plot_image, plot_label_image, plot_membership_maps, plot_segmentation.

All four strategies run on the same incomplete matrix, and OCS is best started from the PDS prototypes:

Xm = make_mcar(X, missing_rate=0.25, random_state=0) 
fits = {s: IncompleteFCM(n_clusters=3, strategy=s, random_state=0).fit(Xm) for s in STRATEGIES} 
for s, model in fits.items(): 
    print(f"{s.upper()}: {model.n_iter_:3d} iterations, ARI = {adjusted_rand_score(y, model.labels_):.3f}, " 
          f"prototype error = {center_error(model.cluster_centers_, reference.cluster_centers_):.3f}")
   
Xm, mask = make_mcar(X, missing_rate=0.2, random_state=0, return_mask=True) 
pds = IncompleteFCM(n_clusters=4, strategy="pds", random_state=0).fit(Xm) 
models = { 
    "PDS (post hoc)": pds, 
    "NPS": IncompleteFCM(n_clusters=4, strategy="nps", random_state=0).fit(Xm), 
    "OCS, random start": IncompleteFCM(n_clusters=4, strategy="ocs", random_state=0).fit(Xm), 
    "OCS, PDS start": IncompleteFCM(n_clusters=4, strategy="ocs", init=pds.cluster_centers_).fit(Xm), 
} 
errors = {name: rmse(model.X_completed_, mask) for name, model in models.items()}
   

The very-large-data schemes are drop-in replacements for FCM, and the chunked ones consume a stream with partial_fit:

literal, t_literal = timed_fit(WeightedFCM(n_clusters=5, random_state=0), X) 
schemes = { 
    "rseFCM": RandomSampleFCM(n_clusters=5, sample_size=0.01, random_state=0), 
    "spFCM": SinglePassFCM(n_clusters=5, chunk_size=2000, random_state=0), 
    "oFCM": OnlineFCM(n_clusters=5, chunk_size=2000, random_state=0), 
} 
results = {} 
for name, model in schemes.items(): 
    model, seconds = timed_fit(model, X) 
    results[name] = (t_literal / seconds, adjusted_rand_score(literal.labels_, model.labels_)) 
    print(f"{name}: speedup {results[name][0]:6.1f}, ARI with literal FCM {results[name][1]:.4f}")
   
models = { 
    "spFCM, $\\lambda=1$ (paper)": SinglePassFCM(n_clusters=3, chunk_size=500, random_state=0), 
    "spFCM, $\\lambda=0.5$": SinglePassFCM(n_clusters=3, chunk_size=500, forgetting_factor=0.5, random_state=0), 
    "oFCM (merged)": OnlineFCM(n_clusters=3, chunk_size=500, random_state=0), 
} 
errors = {name: [] for name in models} 
errors["oFCM, last chunk only"] = [] 
for Xc, _, C in stream: 
    for name, model in models.items(): 
        model.partial_fit(Xc) 
        errors[name].append(tracking_error(model.cluster_centers_, C)) 
    errors["oFCM, last chunk only"].append(tracking_error(models["oFCM (merged)"].chunk_centers_[-1], C))
   

An image is segmented with a single call:

noisy = add_image_noise(base.clean, noise="gaussian", noise_level=0.2, random_state=0) 
model = SpatialFCM(n_clusters=4, method="flicm", init="kmeans++", random_state=0).fit(noisy) 
accuracy = segmentation_accuracy(base.truth, model.labels_)
   
model = SpatialFCM(n_clusters=4, method="enfcm", alpha=4.0, window_size=5, init="kmeans++", random_state=0) 
labels = model.fit(gauss).labels_ 
interior_acc, detail_acc = scores(labels)
   

11.4 Examples

11.4.1 Four strategies for missing values

Three well-separated Gaussian clusters of 150 points each in the plane lose 25% of their values (fig. 11.4). WDS, PDS, and NPS recover the groups (ARI 0.99), with prototype errors against complete-data FCM of 0.11, 0.05, and 0.04. The completed coordinates show the character of each strategy: NPS snaps the imputed coordinates onto the prototypes, whereas PDS and WDS impute only afterwards. OCS from a random start ends in a poor solution (ARI 0.82, prototype error 0.47): samples of the lower-left cluster that lost their first coordinate were imputed with the first coordinate of the right cluster early on and remain captured there, forming the vertical streak of hollow markers in the figure. The memberships of incomplete samples (fig. 11.5) are lower when the observed coordinate is ambiguous. The parameter study in four dimensions (fig. 11.6) follows the experiment of Hathaway and Bezdek: WDS loses samples quickly, since only (1 −p)4 of them remain complete, and its prototypes wander off beyond 40%; PDS degrades most gracefully (prototype error 0.13 at 40%), NPS is close to it (0.14), and the randomly started OCS falls behind (0.28).

Figure 11.4

Figure 11.4. The four strategies on data with 25 % missing values; hollow markers are incomplete samples at their completed coordinates, crosses are the prototypes of each strategy, and plus signs those of FCM on the complete data. The randomly started OCS captures samples in the wrong cluster.

Open in ColabExample plot_01_missing_strategies.py in the gallery

Figure 11.5

Figure 11.5. The PDS partition at the true coordinates (left) and the maximal membership of the incomplete samples (right): an ambiguous observed coordinate gives a low membership.

Figure 11.6

Figure 11.6. Prototype error against complete-data FCM and agreement with the true groups for missing rates up to 60 % (four-dimensional blobs), and the share of complete samples.

11.4.2 Imputation by clustering

The second data set has four clusters in four dimensions with 20% of the values missing (fig. 11.7). Imputation by the column mean has an RMSE of 2.56; an oracle that knows every sample’s cluster mean reaches 0.64. The clustering-based imputations lie close to the oracle: PDS post hoc 0.81, NPS 0.83, and OCS started from the PDS prototypes 0.90, while OCS from a random start reaches only 1.29; the horizontal bands in its panel are samples imputed with the coordinates of a wrong prototype. Figure 11.8 shows why: the randomly started OCS is far more confident about the incomplete samples than PDS, which computes the memberships from the observed features only, and its large errors sit on samples that PDS considers ambiguous. The scans (fig. 11.9) show that the ranking holds at every missing rate (at 30%: PDS 0.94, NPS and OCS from the PDS start 1.03, OCS from a random start 1.54) and that the exponent matters little for PDS, with a shallow optimum near m = 2; the randomly started OCS improves with m because softer memberships weaken the self-reinforcement of the imputed values.

Figure 11.7

Figure 11.7. Imputed against true values with 20 % of the values missing, for PDS (post hoc), NPS, and OCS from a random and from the PDS start.

Open in ColabExample plot_02_ocs_imputation.py in the gallery

Figure 11.8

Figure 11.8. Memberships of the incomplete samples under OCS and PDS (left), and the largest imputation error of a sample against its PDS membership (right).

Figure 11.9

Figure 11.9. Imputation error against the missing rate (left) and against the exponent m at 30 % missing (right), with the column mean and the oracle as references.

11.4.3 200 000 samples

The third data set has 200 000 points in five clusters of very different sizes, from 35% down to 5% of the data (fig. 11.10). Literal fuzzy c-means needs 32 iterations over all samples. With 1 % of the data at a time, rseFCM is more than ten times, spFCM about six times, and oFCM about twice as fast as literal FCM, and all three agree with the literal partition with an ARI of 0.998 or better; the measured speedups vary from run to run with the machine and its load. The chunk timeline of spFCM (fig. 11.11, left) is flat after the first chunks: the carried prototypes soon outweigh any new chunk. The chunk prototypes of oFCM scatter around the merged ones by the sampling error of a chunk, most for the small cluster, of which a chunk holds only about a hundred members. The chunk-size study (fig. 11.12) exposes the weakness of the first two schemes: with 600 samples or fewer, FCM on the sample (or on the first chunk) merges two clusters and splits the largest (ARI 0.87 with the literal partition), and spFCM carries this solution through all later chunks. oFCM outvotes the poor chunk solutions and stays above 0.99 at every size, and five restarts on the first chunk repair spFCM at a small cost.

Figure 11.10

Figure 11.10. Literal FCM and the three schemes with 1 % chunks on 200 000 samples (5000 of them plotted); the white crosses are the prototypes of each scheme and cover the plus signs of the literal FCM prototypes, and the panel titles give speedup and agreement.

Open in ColabExample plot_03_large_data.py in the gallery

Figure 11.11

Figure 11.11. The spFCM prototypes after every chunk, marker area proportional to the carried weight (left), and the oFCM chunk prototypes relative to the merged ones (right).

Figure 11.12

Figure 11.12. Speedup over literal FCM (left) and agreement with its partition (right) against the sample or chunk size.

11.4.4 A drifting stream

Three clusters move along straight lines while 40 chunks of 500 samples are fed to partial_fit (fig. 11.13). The published spFCM and oFCM summarize the whole past, so their prototypes sit near the time average of the centers, halfway along the path; with λ = 0.5 spFCM follows the clusters. The tracking error (fig. 11.14) grows linearly for the two published schemes and settles at a small constant for λ = 0.5, close to that of a memoryless FCM on the last chunk. The parameter study with chunks of 200 samples (fig. 11.15) shows the trade-off between lag and noise: without drift, a long memory is best (λ = 0.95, error 0.014 against 0.097 for λ = 0); with a drift of 0.02 per chunk, the best factor is 0.5; and with 0.05 or more, it is 0.25.

Figure 11.13

Figure 11.13. The first and the last chunk of a drifting stream with the true center paths (dotted), the prototype paths of spFCM with λ = 1 and λ = 0.5, and the final prototypes of the three models.

Open in ColabExample plot_04_stream_drift.py in the gallery

Figure 11.14

Figure 11.14. Distance of the prototypes from the current true centers along the stream.

Figure 11.15

Figure 11.15. Mean tracking error over the second half of the stream against the forgetting factor for four drift speeds; circles mark the best factor.

11.4.5 Segmentation under noise

A 128 ×128 image with four regions at gray levels 0, 1∕3, 2∕3, and 1, and one disc of every class inside another region, is segmented by all seven methods with α = 4, a 3 ×3 window, and k-means++ seeding. Under Gaussian noise with σ = 0.2 (fig. 11.16), pixel-wise FCM labels 62% of the pixels correctly; FCM_S leaves clumps (0.91), FCM_S1 and FCM_S2 leave isolated specks (0.95, 0.94), and EnFCM, FGFCM, and FLICM give clean regions (0.96–0.97). All smoothing methods share one artifact: where the black and the white regions meet, the smoothed values are intermediate and a one-pixel band is assigned to a gray class. Salt-and-pepper noise on 20% of the pixels (fig. 11.17) reverses the picture. The impulses coincide with the darkest and the brightest class, so FCM still labels 85% of the pixels correctly. The mean-based methods spread the impulses and lose accuracy (FCM_S 0.68, EnFCM 0.80), whereas the median of FCM_S2 removes them (0.93) and the adaptive weights of FGFCM ignore them (0.92). FLICM (0.72) moves many impulses only halfway: a white pixel in the black region ends up in the dark-gray class, because its distance to the black prototype plus the small fuzzy factor of the black class exceeds its smaller distance to the dark-gray prototype plus the moderate fuzzy factor of that class. Across the noise levels (fig. 11.18), the adaptive methods keep their accuracy longest under Gaussian noise (at σ = 0.3: FLICM 0.90, FGFCM 0.88, FCM 0.51), and only FCM_S2 and FGFCM beat FCM consistently under impulse noise.

Figure 11.16

Figure 11.16. Seven segmentations of an image with Gaussian noise (σ = 0.2); the titles give the share of correctly labeled pixels.

Open in ColabExample plot_05_image_noise.py in the gallery

Figure 11.17

Figure 11.17. The same image with 20 % salt-and-pepper noise: averaging spreads the impulses, whereas the median and the adaptive weights remove them.

Figure 11.18

Figure 11.18. Segmentation accuracy against the level of Gaussian (left) and salt-and-pepper noise (right).

11.4.6 How much neighborhood?

Two thin bars, one and two pixels wide, are added to the test image, and the accuracy is measured separately on the interior of the regions and on the 11% of the pixels next to a region boundary, labeled “detail” in the figures (fig. 11.19). For EnFCM under Gaussian noise, increasing α from 0 to 4 raises the interior accuracy from 0.63 to 0.99 but lowers the boundary accuracy from 0.65 to 0.54, and the one-pixel bar breaks up; larger windows round the corners, shrink the discs, and dissolve both bars. The α scan (fig. 11.20) shows the same trade-off for all three methods under Gaussian noise: the boundary accuracy peaks at α ≈0.25–1 for FCM_S and EnFCM and at α ≈2 for the edge-preserving median of FCM_S2. Under salt-and-pepper noise, FCM_S and EnFCM gain at most a few points on the interior over pixel-wise FCM (0.89; at best 0.92 for FCM_S at α = 16) and lose half of the boundary accuracy (from 0.90 to below 0.50), and FCM_S2 helps only for α > 1 (0.92 at α = 2, 0.95 at 4, and 0.999 at 8), as predicted by the balance of the pixel and median terms. Enlarging the window with α = 4 (fig. 11.21) costs boundary accuracy for all methods and, for FCM_S, interior accuracy as well (0.97 at 5 ×5, 0.84 at 11 ×11), while the median keeps the interior of FCM_S2 at 0.995.

Figure 11.19

Figure 11.19. EnFCM with increasing weight α in a 3 ×3 window (top row and bottom left) and with increasing window size at α = 4 (rest of the bottom row); the titles give the accuracy on the interior and on the boundary (detail) pixels.

Open in ColabExample plot_06_spatial_alpha_window.py in the gallery

Figure 11.20

Figure 11.20. Interior (solid) and boundary (dashed) accuracy against α for FCM_S, EnFCM, and FCM_S2 under Gaussian (left) and salt-and-pepper noise (right).

Figure 11.21

Figure 11.21. Interior and boundary accuracy against the window size with α = 4 under Gaussian noise.

11.5 Further reading

The four strategies for incomplete data are compared in [151]; the partial distance goes back to Dixon [152], and the statistical framework of missing data, including the distinction between values missing completely at random and other mechanisms, is given in [153]. Havens et al. [156] compare fuzzy c-means algorithms for very large data, covering rseFCM, spFCM, oFCM, and their kernel versions. Single-pass FCM is introduced in [157], and online FCM and its use for large magnetic resonance volumes in [158]; earlier work on making each FCM iteration cheaper includes [154, 155]. The spatially constrained segmentation methods are FCM_S [159], FCM_S1 and FCM_S2 with their kernel versions [160], EnFCM [161], FGFCM [162], and FLICM [163]. A related approach for MR images, which estimates the bias field together with the partition and adds a smoothness penalty on that field, is the adaptive fuzzy c-means of Pham and Prince [164]. All rest on the c-means functional of Bezdek [3].