Fuzzy Clustering and Data Analysis in PythonThe fuzzyclust toolbox

Chapter 9
Clustering of time series

The previous chapter turned clusters into local models of static and dynamic functions; this chapter adds the ingredient that ordered data bring, time. Four problems of time-series analysis are solved with one tool, a fuzzy clustering whose prototype is adapted to the question. For segmentation the prototype combines a Gaussian membership function in time with a local PCA model of the observations, and the number of segments follows from merging compatible neighbors; for model-order selection Gath–Geva clusters supply the threshold of the false-nearest-neighbor test as local slopes of the regression surface. Clustering the delay vectors of a chaotic series together with their successors gives the embedding dimension, the local dimension of the attractor and a predictor, and fuzzy c-means partitions let structure selection treat continuous inputs like categorical ones. All methods live in fuzzyclust.timeseries; the fuzzy Sammon mapping of chapter 5 displays the clusters of a reconstructed state space.

9.1 Problem and idea

A time series T = {xk∣1 ≤k ≤N} is a sequence of observations xk ∈ ℝn labeled by time points t1 < ⋯ < tN. The observations are not exchangeable: their order carries information, and the questions asked of a time series are questions about that order. Four such questions recur in the analysis of process data, and each has a clustering-based answer in this chapter.

Segmentation. A c-segmentation splits T into c disjoint intervals that are internally homogeneous—stable periods of operation, product grades, regimes—separated by change points. For one variable the cost of a segment is the error of a constant or linear fit; for many correlated variables the right notion of homogeneity is that the samples lie on a common hyperplane, i.e. that one PCA model with a few components describes them. Changes of the mean, of the variance and of the correlation structure then all become changes of the hyperplane, and the last kind is invisible to any univariate method. Minimizing the summed segment costs by dynamic programming is too expensive for long series, so greedy top-down, bottom-up and sliding-window heuristics are used instead [112, 113]. Abonyi, Feil, Németh and Árva [114] treat segmentation as clustering with a time-ordered structure (their conference paper [115], the precursor of the method, used the simpler Q and T2 distances of section 9.2.1). They cluster the extended samples zk = [tkxkT]T with a prototype made of a Gaussian membership function in time, which keeps the cluster contiguous, and a probabilistic PCA model in the feature space, which measures homogeneity (fig. 9.1). The borders are fuzzy, as the transitions of real processes are, and the number of segments is found by merging compatible neighbors.

Figure 9.1

Figure 9.1. Fuzzy segmentation as clustering with a time-aware prototype. Left: three regimes of a bivariate series; each differs from the previous one in the mean of x1 and in the correlation of the two variables (reversed in the second regime, absent in the third), and the change of correlation is visible in neither variable alone. Below them: the Gaussian membership functions in time, normalized to βi(tk), are the fuzzy segments. Right: every segment carries a probabilistic PCA model in the feature space whose hyperplane reacts to changes of mean, variance and correlation. Bottom: the distance of the clustering is the inverse of the joint probability density of the time stamp and the observation.

Model order. Before a nonlinear dynamic model yk = f(xk) can be identified, the regression vector xk = [yk−1,…,yk−na,uk−1,…,uk−nb]T has to be chosen. Information criteria (AIC, FPE, MDL) presuppose a model class; the false-nearest-neighbor (FNN) test [116, 117, 118] does not: it checks whether samples that are close in the regression space have close outputs. Its weak point is a threshold that depends on the slope of the unknown function, and Feil, Abonyi and Szeifert [119, 120] estimate that slope locally from Gath–Geva clusters, which are local linear models of the regression surface.

State-space reconstruction. The state space of a chaotic system observed through one variable yk can be reconstructed from the delay vectors yk = [yk,yk−τ,…,yk−τ(de−1)]T [121, 122]. Choosing the embedding dimension de, estimating the intrinsic dimension of the attractor and building a predictor are usually three separate tasks; the clustering method of [123] solves them together, because the clusters of the pairs (yk,yk+1) are local linear models of the map whose prediction error decides de and whose flatness reveals the local dimension.

Structure selection. A nonlinear model often has many candidate inputs, some continuous and some categorical, of which only a few are needed. Girimonte, Babuška and Abonyi [124] rank all small subsets of inputs by the variance of the output inside the segments spanned by the values of the inputs; fuzzy c-means partitions turn continuous inputs into fuzzy “values”, so that no model has to be fitted and the two kinds of input are treated alike.

9.2 Theory

The notation is that of the book: X ∈ ℝN×n with rows xk, memberships μik in the matrix U ∈ ℝc×N (stored transposed in the code), prototypes with index i, samples with index k. Time stamps are tk, the extended sample is zk = [tkxkT]T, delay vectors are yk, and ηi denotes cluster i together with the parameters of its prototype. We treat segmentation first (sections 9.2.1 and 9.2.2), then FNN-based model-order selection (section 9.2.3), the reconstruction of chaotic series (section 9.2.4) and structure selection (section 9.2.5).

9.2.1 Fuzzy segmentation by modified Gath–Geva clustering

A crisp c-segmentation with the variance as cost minimizes

cost(ST c) = ∑ i=1c ∑ k=si−1+1si ‖xk −vix‖ 2 = ∑ i=1c ∑ k=1Nβ i(tk)D2(x k,vix), βi(tk) = { 1si−1 < k ≤si
(9.1)

which is the k-means functional with clusters restricted to time intervals instead of Voronoi cells. Fuzzy segments replace the indicator by normalized Gaussian membership functions in time,

Ai(tk) = exp ⁡ ( − 1 2 (tk −vit)2 σi,t2 ),βi(tk) = Ai(tk) ∑ j=1cAj(tk),
(9.2)

whose centers vit and widths σi,t are identified by the clustering. The algorithm minimizes the usual functional J = ∑ ⁡ i ∑ kμikmD2(zk,ηi) under the partition constraints, with a Gath–Geva-type distance that is the inverse of a probability density (fig. 9.1, bottom):

1 D2(zk,ηi) = αi 1 2πσi,t 2 exp ⁡ ( − 1 2 (tk −vit)2 σi,t2 ) × 1 (2π)r∕2det ⁡ A i exp ⁡ ( − 1 2(xk −vix)TA i−1(x k −vix) ).
(9.3)

Within a segment, time is treated as independent of the observations, so the density factorizes into the prior αi, a Gaussian in time and a Gaussian in the feature space with covariance Ai of rank r. For m = 2 the memberships are the posterior probabilities p(ηi∣zk) of this mixture, and the alternating optimization is a fuzzy relative of the EM identification of the mixture, which would weight the prototype updates by μik instead of μikm [21, 96].

The feature-space model. Choosing Ai = Fi, the fuzzy covariance matrix, gives Gath–Geva clustering of the extended samples; when the variables are strongly correlated, Fi is ill-conditioned, and regularizing it [19] hides exactly the low-dimensional structure one wants to detect. The journal version of the method therefore uses probabilistic PCA [125]: the observations of a segment are xk = Wiyik + vix + 𝜀 with q latent variables and isotropic noise, so that

Ai = σi,x2I + W iWiT,
(9.4)

a full-rank covariance (r = n) whose q large eigen-directions span the hyperplane of the segment and whose remaining n −q eigenvalues all equal σi,x2. The maximum-likelihood solution is known in closed form: with Fi = UiΛiUiT (eigenvalues in decreasing order),

Wi = Ui,q (Λi,q −σi,x2I )1∕2R i,σi,x2 = 1 n −q∑ j=q+1nλ i,j,
(9.5)

with an arbitrary rotation Ri. The journal version instead interleaves one EM step of PPCA with every clustering iteration: with Mi = σi,x2I + WiTWi and the latent expectations ⟨yik⟩= Mi−1WiT(xk −vix),

W~i = FiWi (σi,x2I+M i−1W iTF iWi )−1,σ i,x2 = 1 ntr ⁡ (Fi−FiWiMi−1W~ iT ),
(9.6)

where the center vix = ∑ ⁡ kμikm(xk −Wi⟨yik⟩)∕∑ kμikm and the fuzzy covariance Fi around it are computed with the weights μikm. Both routes have the same fixed point; fuzzyclust offers the EM step (pca_update="em") and the eigen-solution ("eig"). The noise variance in (9.6) carries the factor 1∕n of the EM algorithm of Tipping and Bishop [125]; the segmentation paper prints 1∕q there, which the book and the code correct. The prior and the time part are updated by

αi = 1 N∑ k=1Nμ ik,vit = ∑ kμikmtk ∑ kμikm ,σi,t2 = ∑ kμikm(tk −vit)2 ∑ kμikm ,
(9.7)

and the partition by μik = 1∕∑ ⁡ j(Dik∕Djk)2∕(m−1).

Two older variants. The conference version [115] restricted the feature-space Gaussian to a subspace of the PCA model and used a pseudo-inverse and pseudo-determinant in (9.3). The fuzzy-PCA-Q method keeps the n −q smallest eigen-directions, so the exponent is the reconstruction error Qik = ‖(I −Ui,qUi,qT)(xk −vix)‖2 with every residual direction divided by its eigenvalue: it detects changes of the correlation structure but is blind to displacements inside the hyperplane. The fuzzy-PCA-T2 method keeps the q largest, so the exponent is the Hotelling statistic Tik2 = yikTΛi,q−1yik of the projection: it detects shifts of the operating point but not rotations of the hyperplane. Both are sensitive to q (with q →n the reconstruction error vanishes everywhere; the T2 variant needs a q defined by a required accuracy so that all segments keep comparable models). The PPCA covariance (9.4) covers both subspaces and is insensitive to q; the two statistics remain available as diagnostics (hotelling_t2, q_reconstruction_error).

Number of components. The eigenvalues of the covariance matrices of the initial segments—a uniform partition into c intervals—are inspected in a scree plot, or q is chosen as the smallest number of components that explains a required fraction of the variance in every initial segment,

∑ j=1q−1λ i,j / ∑ j=1nλ i,j < accuracy ≤∑ j=1qλ i,j / ∑ j=1nλ i,j.
(9.8)

Number of segments by compatible cluster merging. Clustering starts from a deliberately large number of segments (ten in the paper) and merges adjacent segments that are compatible, re-clustering after every merge, in the spirit of the bottom-up algorithm and of compatible cluster merging for fuzzy modeling [40]. Two criteria are evaluated for every pair: the similarity of the PCA models by Krzanowski’s factor [126],

SPCAij = 1 q∑ a=1q ∑ b=1q cos ⁡ 2𝜃 ab = 1 qtr ⁡ (Ui,qTU j,qUj,qTU i,q ),
(9.9)

the mean squared cosine between the principal directions of one segment and the principal subspace of the other, and the distance of the centers D(vix,vjx) = ‖vix −vjx‖, because a change of the mean alone leaves SPCA = 1. Each criterion is turned into a degree of fulfillment by a triangular membership function: parallelism μij1 rises from 0 at ν1 to 1 at SPCA = 1, and closeness μij2 falls from 1 at distance 0 to 0 at ν2. The knots are the averages of the criteria over all pairs,

ν1 = 1 c(c −1)∑ i ∑ j≠iSPCAij,ν2 = 1 c(c −1)∑ i ∑ j≠iD(vix,v jx),
(9.10)

and the two degrees are aggregated to the compatibility

Oij = [1 2 ((μij1)2 + (μ ij2)2 ) ]1∕2.
(9.11)

The most compatible adjacent pair is merged whenever Oi,i+1 exceeds a threshold γ (0.3–0.75 in the paper, depending on the homogeneity of the series). Kelly’s formulas [41] give the parameters of the merged cluster from those of its parts, with Ni = ∑ ⁡ kμik and Ni∗ = Ni + Ni+1:

vi∗x = Ni Ni∗vix + Ni+1 Ni∗ vi+1x, Fi∗ = Ni −1 Ni∗−1Fi + Ni+1 −1 Ni∗−1 Fi+1 + NiNi+1 Ni∗(Ni∗−1)(vix −v i+1x)(v ix −v i+1x)T,
(9.12)

and analogous formulas merge the time center and variance; the priors add, αi∗ = αi + αi+1, and the PPCA model of the new segment follows from the eigen-decomposition of Fi∗ by (9.5). Two segments with identical PCA models but different means have μ1 = 1 and O = (1 + (μ2 )2 )∕2 ≥1∕2 ≈0.71, so the threshold has to be raised above the compatibility of the smallest mean shift that should survive; this is how γ encodes how different two regimes must be. The compatibility matrix of all pairs, adjacent or not, is informative in itself: repeated regimes show up as compatible nonadjacent segments. (fuzzyclust adds a safeguard, min_segment_weight, that absorbs a segment with a negligible prior into its more compatible neighbor regardless of γ; such slivers arise between regimes when the initial number of segments is far above the true one.)

Algorithm

In a nutshell: Fuzzy segmentation

  • Segmentation is clustering of zk = [tkxkT]T with a prototype made of a Gaussian in time (contiguity) and a probabilistic PCA model in the feature space (homogeneity); the distance is the inverse joint density.
  • Detects changes of the mean, the variance and the correlation structure of multivariate series; for m = 2 the memberships are the posteriors of a mixture of PPCA models, and the alternating optimization is a fuzzy relative of its EM algorithm.
  • q from the scree plot or an accuracy on the initial segments; the number of segments by merging compatible adjacent segments (PCA similarity and center distance, threshold γ) from a large initial number.
  • Fuzzy borders, posterior memberships and a PCA model per segment for process monitoring; Q and T2 remain available as diagnostics.

9.2.2 Bottom-up segmentation with PCA models

The classical competitor is the bottom-up algorithm [112], extended to multivariate data by using one PCA model per segment [114]. The series is cut into short pieces; for every pair of adjacent segments the cost of their union is computed; the cheapest pair is merged, and its merge costs with its two neighbors are updated; the loop stops when the cheapest merge would cost more than a tolerance or when the wanted number of segments is reached. For a segment Si = {ai,…,bi} and a PCA model with p components, the cost is either the mean reconstruction error or the mean Hotelling statistic,

costQ(Si) = 1 bi −ai + 1∑ k=aibi Qi,k = ∑ j>pλi,j, costT2(Si) = 1 bi −ai + 1∑ k=aibi Ti,k2 = ∑ j≤pλi,j2,
(9.13)

where the right-hand sides hold for centered data, with T2 computed as in the paper from the scores yk = Λp1∕2UpTxk. The cost measures the level of the model error of the merged segment, not its increase, so the natural stopping rule is a maximal error. Each cost is blind to one kind of change, Q to displacements along the hyperplane and T2 to rotations of it, and a greedy merge made early is never revised. This is the baseline against which the fuzzy segmentation is judged.

Algorithm

In a nutshell: Bottom-up segmentation

  • Greedy merging of adjacent pieces by the PCA cost of the union; fast and simple, the multivariate counterpart of piecewise-linear approximation.
  • The Q cost finds changes of the correlation structure, the T2 cost shifts of the operating point; neither finds both, and the Q cost depends strongly on p.
  • Stop by a maximal error (the jump of the merge-cost curve) or by a given number of segments; useful as a first look and to validate the fuzzy result.

9.2.3 Model order by false nearest neighbors with cluster-based thresholds

Let yk = f(xk) with the NARX regression vector xk = [yk−1,…,yk−na,uk−1,…,uk−nb]T. If the regressors carry all the information about yk and f is smooth, close regression vectors have close outputs: by a first-order Taylor expansion and the Cauchy–Schwarz inequality,

yk −yj = df(xk)T(x k −xj) + O( ‖xk −xj‖ 2)⟹ |yk −yj| ‖xk −xj‖ ≲ ‖df(xk)‖,
(9.14)

where df is the gradient (Jacobian) of f; the bound holds up to a term of order ‖xk −xj‖, that is, approximately for close neighbors. The FNN algorithm [116, 117] finds for every xk its nearest neighbor xj in the regression space, declares the neighbor false when the ratio exceeds a threshold R, and tabulates the percentage J(na,nb) of false neighbors over the orders. The percentage is 100 for the empty regressor, stays high while a regressor is missing (points that are close in the incomplete space have different outputs because they differ in the missing coordinate; see fig. 9.2), and drops to zero, or to a small, flat level when the data are noisy, as soon as the regression vector is complete. The smallest order in the corner of the table where this happens is the model order. For a scalar time series (u absent, regressors yk−τ,…,yk−naτ) the same test gives the embedding dimension, the problem for which it was introduced [116].

Figure 9.2

Figure 9.2. The false-nearest-neighbor idea and its clustering-based threshold. Top left: with a regressor missing, the output is not a function of the regression vector, so points that are neighbors in the regression space can have very different outputs. Top right: with the complete regression vector the output is a smooth function and the ratio |yk −yj| ∕ ‖xk −xj‖ is bounded by the local gradient. Bottom: Gath–Geva clusters of the regression data are flat ellipsoids whose normal, the eigenvector of the smallest eigenvalue, gives the local slope, and the membership-weighted slopes give a threshold that follows the nonlinearity.

The difficulty is the threshold. Heuristic values (10 ≤R ≤50, after Kennel et al. [116]) work for some systems and not for others [118], and the exact bound R = max ⁡ k ‖df(xk)‖ requires a nonlinear model of the unknown function [117]—the very thing the order selection is supposed to precede. Feil, Abonyi and Szeifert [119, 120] observe that when the regression vector is adequate, Gath–Geva clusters of the joint data zk = [xkTyk]T approximate the regression surface piecewise linearly (fig. 9.2, bottom): the smallest eigenvalue of Fi is much smaller than the others and its eigenvector ti = [(tix)Ttiy]T is the normal of the local hyperplane, so that

(ti)T(z k −vi) = 0⟹yk = −1 tiy (tix)T⏟ aiTxk + 1 tiytiTv i⏟ bi,
(9.15)

the total-least-squares estimate of a local linear model. The gradient at xk is approximated by the membership-weighted average of the local slopes, which gives a point-wise threshold,

df(xk) ≈∑ i=1cμ ikai,Rk = ‖∑ i=1cμ ik −1 tiy tix ‖ 2,
(9.16)

so that neighbor j of k is false when |yk −yj| ∕ ‖xk −xj‖ > Rk. The threshold adapts to the nonlinearity, large where the surface is steep and small where it is flat, and the only remaining parameter, the number of clusters, has little influence. Gath–Geva clustering, initialized by fuzzy c-means, is preferred to Gustafson–Kessel because the clusters may have different volumes. Regressors and output are standardized first so that the ratio and Rk are dimensionless.

Algorithm

In a nutshell: FNN model-order selection

  • Geometric, model-free test: a regression vector is complete when neighbors in the regression space have neighboring outputs.
  • The threshold of the test is the local gradient norm; Gath–Geva clusters of the regression data supply it point-wise as the norm of the membership-weighted local slopes.
  • Read the order off the corner of the J(na,nb) table where the percentage collapses; the number of clusters hardly matters, a constant threshold does.
  • With u absent and a lag τ the same function estimates the embedding dimension of a scalar series.

9.2.4 State-space reconstruction and prediction of chaotic series

Let the state sk ∈M of a deterministic system evolve as sk+1 = f(sk) and be observed through a smooth scalar function yk = g(sk). Takens’ theorem [121] states that, if M is a compact manifold of dimension dM, then for a generic observation the delay vectors

yk = [yk,yk−τ,…,yk−τ(de−1)]T
(9.17)

embed M when de ≥2dM + 1. Sauer, Yorke and Casdagli [122] replaced the manifold by the attractor itself: if its box-counting dimension is dA, almost every delay map is one-to-one on the attractor when de > 2dA. In practice de ≥dl + 1 often suffices, where dl is the local dimension of the attractor, the dimension of the surface on which the trajectory lies. The lag τ is taken as the first zero of the autocorrelation or the first minimum of the mutual information [127]. In the reconstructed space the dynamics is a smooth map yk+1 = fr(yk), and since the data are typically confined to a dl-dimensional surface of the de-dimensional space, local linear models [128, 129] are the natural approximators (fig. 9.3).

Figure 9.3

Figure 9.3. State-space reconstruction by delay embedding and clustering. Top left: three samples of the scalar series spaced by the lag τ form one delay vector. Bottom: the delay vectors trace the attractor in the reconstructed space; the clusters of the pairs (yk,yk+1) are operating regimes with local linear maps, flat because the trajectory lives on a low-dimensional surface. Top right: the one-step prediction error of the model saturates at the embedding dimension, and the prior-weighted smallest eigenvalue of the cluster covariances collapses one dimension above the local dimension.

The operating-regime model of [123] is the MIMO Takagi–Sugeno model of chapter 8 on the delay vectors,

y^k+1 = ∑ i=1cβ i(yk) (Aiyk + bi ) = ∑ i=1cβ i(yk)[ykT1]𝜃 i, βi(y) = exp ⁡ ( − 1 2(y −vi)TFi−1(y −vi) ) ∑ j=1c exp ⁡ ( − 1 2(y −vj)TFj−1(y −vj) ),
(9.18)

whose Gaussian regimes and local models are identified simultaneously by clustering the pairs (yk,yk+1) with the distance

1 Dik2 = p(ηi)exp ⁡ ( − 1 2(yk −vi)TFi−1(yk −vi) ) (2π)de∕2det ⁡ F i exp ⁡ ( − 1 2eikTPi−1eik ) (2π)p∕2det ⁡ P i , eik = yk+1 −[ykT1]𝜃 i,
(9.19)

the product of the prior, the Gaussian domain of influence and the Gaussian likelihood of the p-dimensional local prediction error with covariance Pi. The alternating optimization updates vi and Fi as the μikm-weighted mean and covariance of the delay vectors, the local models by weighted least squares 𝜃i = (YTBiY)−1YTBiY(+1) with Bi = diag ⁡ (μi1,… ⁡ ,μiN) (local estimation, which keeps the interpretation as a linear parameter-varying system), the error covariances Pi = ∑ ⁡ kμikmeikeikT∕∑ kμikm, the priors p(ηi) = 1 N ∑ ⁡ kμik and the partition by the usual formula. Since all but the first component of yk+1 are past samples, which a free-run simulation simply shifts along, fuzzyclust by default identifies only the map to the next sample yk+1 (p = 1, target="scalar"). The full MIMO map is available as target="full"; with τ = 1 its components copied from yk make Pi singular unless it is regularized.

Three results come out of this clustering. (i) Embedding dimension: the model is identified for de = 1,2,… and the one-step prediction errors on test data are compared; the error decreases as long as a coordinate is missing and stops improving at the right de, where the ratio of consecutive errors approaches one. (ii) Local dimension: the clusters approximate the tangent space of the attractor, so their smallest eigenvalues λi,min ⁡ are orders of magnitude below the others once de exceeds the dimension of the surface the trajectory lives on; the prior-weighted index

Jde = ∑ i=1cp(η i)λi,min ⁡
(9.20)

drops sharply at de = dl + 1. The integer dl is complemented by the fractal correlation dimension of Grassberger and Procaccia [130], the slope of log ⁡ C(r) against log ⁡ r for the correlation sum C(r) of the reconstructed vectors, which the fuzzy Sammon paper [51] uses to confirm the clustering-based estimate. (iii) Prediction: the model predicts one step ahead or, fed with its own outputs, simulates the series in free run; because the system is chaotic, the simulated trajectory leaves the measured one after a horizon set by the largest Lyapunov exponent, but it stays on (a model of) the attractor. The regimes of the reconstructed space are de-dimensional ellipsoids with Mahalanobis geometry; the fuzzy Sammon mapping of section 5.2.3 draws them as compact groups in the plane and shows how the trajectory wanders from regime to regime [51].

Algorithm

In a nutshell: Chaotic series by clustering in the reconstructed space

  • Delay vectors reconstruct the state space (Takens); the dynamics is identified as an operating-regime model with Gaussian regimes and local linear maps by modified Gath–Geva clustering of (yk,yk+1).
  • Clustering over a range of de gives the embedding dimension (saturation of the one-step error), the local dimension (collapse of the prior-weighted smallest eigenvalue) and a predictor.
  • Free-run simulation reproduces the attractor but diverges from the measured trajectory with the horizon, as it must for a chaotic system.
  • Parameters: lag τ, number of regimes c (10–20), regularization of Fi and Pi; visualize the regimes with the fuzzy Sammon mapping.

9.2.5 Structure selection with mixed discrete and continuous inputs

Suppose every candidate input xj takes values in a finite set Aj = {aj1,…,ajcj}. For a subset U of the inputs the data decompose into segments—one for every combination of values aU ∈×j∈UAj—and if U contains the inputs that drive the output, y varies little inside each segment. The variance of y within the segments, summed over the segments, is therefore a model-free measure of how well the subset explains the output, as in a (discrete) analysis of variance. There are ns = ∏ ⁡ j∈Ucj segments, so only subsets up to a maximal cardinality are enumerated; exhaustive enumeration up to that size is feasible for up to about fifteen candidate inputs.

Continuous inputs do not take finitely many values, and quantizing them into crisp bins introduces an arbitrary choice of levels. Girimonte, Babuška and Abonyi [124] fuzzify the decomposition: every continuous input xj is clustered on its own by fuzzy c-means into cj fuzzy sets (cj fixed or chosen by the Xie–Beni index [31]), giving a membership matrix Uj ∈[0,1]cj×N, and a discrete input gets one crisp set per value. The fuzzy segments of a structure U are the product-space conjunctions of the sets of its inputs,

βik = ∏ j∈Uμijkj,i = (i 1,…,ini) ∈×j∈U{1,…,cj},γik = βik ∑ i′βi′k,
(9.21)

(because the memberships of every input sum to one for each sample, the βik already sum to one over the segments), every segment is represented by the membership-weighted mean of the output, and the total fuzzy variance is the sum of squared errors of the singleton fuzzy model that the segments define:

bi = ∑ kγikyk ∑ kγik ,σt = ∑ k=1N (y k −∑ iγikbi )2.
(9.22)

Structures are ranked by increasing σt. An irrelevant input only splits every segment into cj smaller ones; it does not increase σt and usually lowers it a little, so the structures at the top of the list tend to contain the relevant inputs plus one or two dummies. The variance–complexity trade-off

V CT = σtni
(9.23)

penalizes the number of inputs ni and separates structures of similar variance: plotted along the ranking it shows a clear dip at the structure with the relevant inputs only. The paper compares the VCT only among structures of similar σt, and fuzzyclust follows this reading: it recommends the structure with the smallest VCT among those whose σt lies within a relative tolerance of the smallest one. The method is a screening tool: it returns a ranked list, and the final choice is made by fitting models for a few top candidates, since the eventual validation criterion (e.g. free-run simulation error) differs from the one used in the selection.

Algorithm

In a nutshell: Structure selection with mixed inputs

  • Fuzzy c-means turns continuous inputs into fuzzy values, so discrete and continuous inputs are treated alike and no model is fitted.
  • Every subset of inputs is scored by the total fuzzy variance of the output over its product-space segments; the VCT separates structures of similar variance by their size.
  • Exhaustive search up to a maximal cardinality (about 15 candidate inputs at most); the result is a ranked list to be confirmed by modeling.
  • Parameters: sets per input (3 is a good default; many sets need many samples), maximal cardinality, tolerance for “similar variance”.

9.3 Using it in fuzzyclust

All methods of this chapter are in fuzzyclust.timeseries. The segmentation is a BaseFuzzyClusterer whose fit accepts an optional time axis t; the other methods are functions or small estimators with their own signatures, because most of them take sequences rather than sample matrices. Data generators reproduce the benchmarks of the papers, and plot helpers draw the typical figures. Note that the merging threshold γ of section 9.2.1 is the parameter merge_threshold; the parameter gamma of FuzzySegmentation and ChaoticPredictor is the covariance shrinkage of section 3.2.4.

fuzzyclust.timeseries.FuzzySegmentation

n_segments=5, m=2.0, n_components=None|int|accuracy, distance="ppca"| "q"|"t2", pca_update="em"|"eig", merge=False, merge_threshold=0.75, merge_every=100, min_segment_weight=0.02, gamma=0.0, beta=1e15, tol, max_iter, init="uniform"|"random"|"kmeans++"|array, n_init=1, random_state, verbose.
fit(X, y=None, t=None); attributes boundaries_ (crisp borders), time_membership_ (βi(tk)), membership_ (posteriors), labels_, n_segments_, n_components_, segment_centers_, segment_variances_, cluster_centers_, covariances_, pca_loadings_, noise_variances_, norm_matrices_, eigenvalues_, eigenvectors_, local_pca_, priors_. Methods predict(X, t=None), predict_proba(X, t=None), transform(X, t=None), compatibility_matrix() (O, SPCA, center distances), merge_compatible_segments(threshold, max_merges), hotelling_t2(X), q_reconstruction_error(X).

fuzzyclust.timeseries.bottom_up_segmentation(X, n_components=2,  max_error=None, n_segments=None, cost="q"|"t2", init_length=10,  center=True)

Returns a Bunch with labels, boundaries, segments, merge_costs, n_segments; pca_segment_cost(X, n_components, cost) is the cost of one segment.

fuzzyclust.timeseries.fnn_model_order(y, u=None, max_na=4,  max_nb=0, n_clusters=6, threshold=None, fnn_tol=5.0, m=2.0,  scale=True, delay=1, random_state=None)

Returns a Bunch with table (DataFrame of percentages, rows na, columns nb), the selected n_a and n_b, and thresholds (the point-wise Rk of every order); threshold= replaces Rk by a constant, delay= is the embedding lag for a scalar series. select_model_order(...) returns only (n_a, n_b), false_nearest_neighbors(y,  u, max_na, max_nb, R_tol, A_tol, scale, delay) is the classical test of Kennel et al., and cluster_based_threshold(Phi, target, n_clusters) returns the thresholds of one order and the fitted GG model.

fuzzyclust.timeseries.ChaoticPredictor

dim=3, delay=1, n_clusters=10, m=2.0, target="scalar"|"full", gamma=0.0, beta=1e8, tol, max_iter, init="fcm"|"random"|array, random_state, verbose.
fit(y) on a scalar series; predict(Y) for delay vectors, predict_series(y), one_step_error(y), simulate(y_history, n_steps), multi_step_error(y,  horizons), regime_membership(Y) (= predict_proba), transform(Y) (Mahalanobis distances, for FuzzySammon); attributes embedding_, membership_, cluster_centers_, covariances_, local_models_, error_covariances_, priors_, eigenvalues_, local_dimension_index_. Helpers: delay_embedding(y,  dim, delay), select_delay(y, max_lag, method), embedding_scan(y, dims,  delay, n_clusters, train_fraction), select_embedding_dimension(table,  ratio_tol), correlation_dimension(Y).

fuzzyclust.timeseries.MixedInputStructureSelection

n_clusters=3|"xie-beni"|sequence, max_inputs=None, m=2.0, vct_tolerance=0.2, random_state.
fit(X, y, discrete=None, feature_names=None); ranking_ (DataFrame with inputs, n_inputs, sigma_t, vct, indexed by rank), best_structure_, memberships_, centers_, transform_segments(inputs). select_structure_mixed(X, y,  discrete, ...) returns the ranking directly; fuzzy_variance(memberships, y) is σt of one structure.

data generators and plot helpers

make_piecewise_timeseries (hidden regime changes of kind mean / correlation / both), make_nonlinear_io_system (the polymerization reactor), make_mackey_glass, make_lorenz, make_rossler, make_mixed_input_system; plot_segmentation(model, X), plot_fnn_table(table), plot_embedding_scan(table), plot_phase_space(Y,  labels), plot_structure_ranking(ranking).

A series is segmented and its borders are read off in a few lines, and the number of segments is found by merging from a large initial number:

fs = FuzzySegmentation(n_segments=4, n_components=2).fit(X) 
print("segment borders:", fs.boundaries_) 
print("time centers   :", np.round(fs.segment_centers_)) 
print("time std       :", np.round(np.sqrt(fs.segment_variances_), 1))
   
fs10 = FuzzySegmentation(n_segments=10, n_components=2, merge=True, merge_threshold=0.75).fit(X) 
print("segments after merging:", fs10.n_segments_, "borders:", fs10.boundaries_)
   

The bottom-up baseline and the model-order selection are single calls:

bu_q = bottom_up_segmentation(X, n_components=2, n_segments=4, cost="q", init_length=20) 
bu_t2 = bottom_up_segmentation(X, n_components=2, n_segments=4, cost="t2", init_length=20) 
fuzzy = FuzzySegmentation(n_segments=4, n_components=2).fit(X) 
print("bottom-up, Q   :", bu_q.boundaries) 
print("bottom-up, T^2 :", bu_t2.boundaries) 
print("fuzzy          :", fuzzy.boundaries_)
   
res = fnn_model_order(y, u, max_na=3, max_nb=3, n_clusters=6, random_state=0) 
print(res.table.round(2)) 
print("selected order: n_a =", res.n_a, " n_b =", res.n_b)
   

For a chaotic series the lag is chosen, the embedding dimension is scanned and the model is identified and simulated:

states = make_rossler(n_samples=2200, dt=0.05) 
x = states[:, 0]  # the only measured variable 
tau = select_delay(x, max_lag=60, method="mutual_information") 
n_train = 1500 
print("lag from the mutual information:", tau)
   
table = embedding_scan(x, dims=(1, 2, 3, 4, 5), delay=tau, n_clusters=8, train_fraction=n_train / x.size, 
                       random_state=0) 
choice = select_embedding_dimension(table, ratio_tol=1.3) 
print(table.round(5)) 
print(f"embedding dimension d_e = {choice.embedding_dimension}, local dimension d_l = {choice.local_dimension}")
   
model = ChaoticPredictor(dim=3, delay=tau, n_clusters=12, random_state=0).fit(x[:n_train]) 
print(f"one-step test MSE: {model.one_step_error(x[n_train:]):.4f}  (variance of x: {x.var():.2f})") 
simulated = model.simulate(x[:n_train], n_steps=x.size - n_train)
   

The structure selection ranks all small subsets of inputs:

X, y, discrete = make_mixed_input_system(n_samples=1000, noise=0.1, n_dummy=2, random_state=0) 
sel = MixedInputStructureSelection(n_clusters=3, max_inputs=5, random_state=0).fit(X, y, discrete=discrete) 
print(sel.ranking_.head(8).to_string()) 
print("recommended structure:", sel.best_structure_)
   

9.4 Examples

9.4.1 Fuzzy segmentation of a multivariate series

Two hidden variables generate six observed ones through a mixing matrix that changes at t = 500 (correlation change), while their mean jumps at t = 1000 and both change at t = 1500 (fig. 9.4); the first change leaves every mean in place and is invisible in any single variable. The scree plot of ten uniform initial segments (fig. 9.5) shows two dominant eigenvalues followed by four small ones at the noise level (0.152 ≈0.02), so q = 2; inside one regime the two components explain 85–88% of the variance, so an accuracy of 95% in (9.8) would ask for more components. With four segments the borders are found at 498, 1001 and 1500 (fig. 9.6). The Gaussian segments in time overlap only around the borders, and the posteriors are almost crisp inside the segments because the PCA models of neighboring regimes explain each other’s data badly. The PCA similarity factors of the adjacent models are 0.28, 1.00 and 0.58, small where the correlation structure changed and one where only the mean moved, as in the paper. Figure 9.7 varies the two structural parameters. With fewer than four segments, borders are sacrificed: three segments keep the correlation change (found at 539) and the change at 1500 but drop the mean shift at 1000, and two segments keep only the mean shift at 1000. With more than four segments a regime is split, and the surplus borders fall inside the regimes or next to the true ones. The number of components hardly matters for the PPCA distance: q = 1 moves one border by sixty samples, and from q = 2 on the result is stable. The printed comparison of the distance measures confirms the discussion of section 9.2.1: Q works with q = 2 and fails with q = 5, T2 fails with q = 2 and works with the q given by an accuracy of 99 %, and PPCA works with both. Finally, merging from ten segments with γ = 0.75 (fig. 9.8) reduces the number of segments to four with the right borders. The compatibility matrix of the initial segments shows blocks of mutually compatible surplus segments inside each regime, and the printed scan of γ shows that a lower threshold (0.5–0.65) merges the two regimes that differ only in their mean (and moves the first border to 539), whereas 0.75 and 0.85 keep all four.

Figure 9.4

Figure 9.4. The six observed variables of the synthetic series change regime at the dashed lines; the first change alters only the correlation and is visible in no single variable.

Open in ColabExample plot_01_fuzzy_segmentation.py in the gallery

Figure 9.5

Figure 9.5. The scree plot (left) and the cumulative fraction of variance (right) of the ten initial segments show two dominant components above a noise floor; the dashed line marks an accuracy of 95 %, which two components reach only in the segment dominated by a mean shift.

Figure 9.6

Figure 9.6. Two variables colored by the hard segment, the Gaussian segments in time βi(tk) and the posterior memberships show the fuzzy segmentation with four segments; dashed lines mark the crisp borders.

Figure 9.7

Figure 9.7. The borders found for different numbers of segments (left, q = 2) and of components (right, c = 4) are compared with the true change points (dashed lines).

Figure 9.8

Figure 9.8. The compatibility matrix of the ten initial segments is shown on the left, the fuzzy segments after merging to four with γ = 0.75 on the right.

9.4.2 Bottom-up baseline versus fuzzy segmentation

On the same series the bottom-up algorithm with the Q cost finds the two correlation changes and misses the mean shift, with the T2 cost it finds the two mean shifts and misses the correlation change, and the fuzzy segmentation finds all three (fig. 9.9); each cost also places one spurious border because it has to deliver four segments. The merge-cost curves (fig. 9.10) jump when pieces of different regimes have to be joined, and for both costs the knee is at three segments, the number of regimes each cost can see. The parameter scan printed by the script shows that the Q cost depends strongly on p (with p = 1 the displacement of a mean shift leaves the one-dimensional model and is detected by accident; with p = 5 the residual is noise), that the T2 cost is insensitive to p but blind to the correlation change, and that a long initial piece coarsens the borders. The fuzzy segmentation with q = 1,2,3,5 finds the three borders every time, with q = 1 one of them sixty samples off.

Figure 9.9

Figure 9.9. The borders found by the bottom-up algorithm with the Q cost, by the bottom-up algorithm with the T2 cost and by the fuzzy segmentation, all with four segments, are compared with the true change points (gray dashed lines).

Open in ColabExample plot_02_bottom_up_vs_fuzzy.py in the gallery

Figure 9.10

Figure 9.10. The cost of every merge of the bottom-up algorithm with the Q cost (left) and the T2 cost (right) is plotted against the number of segments left; the jump marks the merge of two different regimes.

9.4.3 Model order of the polymerization reactor

Six hundred samples of the reactor under a random initiator flow (fig. 9.11) are analyzed for orders up to na = nb = 3. With the cluster-based threshold (fig. 9.12) the percentage of false neighbors collapses in the corner na ≥1, nb ≥2, and the smallest order there, (1,2), is the one reported in the paper. The point-wise thresholds of that order (fig. 9.13) differ by more than 60 % between the six operating regions found by the clusters, so no constant threshold fits everywhere. Figure 9.14 shows how a constant threshold moves the corner. A strict constant (R = 0.5, below every local slope) keeps flagging more than a third of the neighbors at every order, so no corner appears; R = 1 happens to give the right order; a loose constant (R = 3, above every local slope) also passes wrong orders of the same size, (0,3) and (2,1), and selects (0,3). Kennel’s two-criterion test is looser still and accepts models that are too small, (0,2) and (1,1). The selected order is the same for 3, 6 and 10 clusters. A model-based check with linear ARX models of all orders (fig. 9.15) agrees: the normalized error drops sharply up to (1,2) and then flattens.

Figure 9.11

Figure 9.11. The polymerization reactor benchmark is driven by a random initiator flow (top) and observed through the molecular weight (bottom).

Open in ColabExample plot_03_fnn_model_order.py in the gallery

Figure 9.12

Figure 9.12. The table gives the percentage of false nearest neighbors over the orders with the cluster-based threshold; the frame marks the selected order (na,nb) = (1,2).

Figure 9.13

Figure 9.13. The point-wise thresholds Rk of the order (1,2) are plotted along the lagged input and colored by cluster (left), and their distribution is shown on the right.

Figure 9.14

Figure 9.14. The percentage of false nearest neighbors with the cluster-based threshold, with three constant thresholds and with the classical test of Kennel et al. shows that the corner moves with the constant.

Figure 9.15

Figure 9.15. The normalized one-step error of linear ARX models over the orders confirms the selected order with a model-based check.

9.4.4 Reconstruction and prediction of the Rössler series

The Rössler system is observed through x1 (fig. 9.16); the first minimum of the mutual information gives a lag of 15 samples. The embedding scan with eight regimes (fig. 9.17) shows the one-step test error dropping by a factor of nine from de = 1 to 2 and by 1.8 to de = 3, after which it fluctuates around a floor, so de = 3. The prior-weighted smallest eigenvalue drops by a factor of three at de = 3 (from 1.26 to 0.41) and keeps falling, because the clusters are flat from three dimensions on, so dl = 2, which reflects the well-known band structure of the Rössler attractor. The FNN test with the cluster-based threshold on the same series collapses at de = 3 as well, and the correlation dimension of the reconstructed vectors is 1.92. With twelve regimes the model tiles the reconstructed attractor (fig. 9.18, left); its free-run simulation keeps spiraling on a Rössler-like band but visits the outer part more often than the system does (right). In time (fig. 9.19) the simulation follows the measured series for about two and a half cycles (some 280 samples) before the chaotic divergence takes over, and the multi-step error grows with the horizon from 3 ⋅10−4 of the variance one step ahead to 0.4 of the variance after 80 steps. The fuzzy Sammon mapping (fig. 9.20) shows the twelve regimes as compact groups arranged in the cyclic order in which the trajectory visits them, whereas the PCA projection of the same vectors overlaps the clusters that differ in the third coordinate. The parameter scan printed by the script shows that more regimes lower both the one- and the ten-step error at the lags 5 and 15, that a very short lag gives small one-step errors (consecutive samples are almost collinear) but a stretched attractor, and that a long lag (30 samples, about a third of the mean cycle) folds the attractor and raises the errors. The three systems compared at the end have correlation dimensions close to two (1.97, 1.90 and 2.00); the percentage of false neighbors of the classical test falls below the tolerance of 5% at de = 3 for the Rössler and Mackey–Glass series and already at de = 2 (3.9%) for the Lorenz series.

Figure 9.16

Figure 9.16. The Rössler system is observed through x1 (left); its true attractor is shown in the (x1,x2) plane (right).

Open in ColabExample plot_04_chaotic_reconstruction.py in the gallery

Figure 9.17

Figure 9.17. The embedding scan plots the one-step training and test errors (top) and the prior-weighted smallest eigenvalue Jde (bottom) against the embedding dimension and marks the selected de = 3 and dl = 2.

Figure 9.18

Figure 9.18. The reconstructed state space is shown with the twelve regimes and their centers (left) and with the free-run simulation of the test part (right).

Figure 9.19

Figure 9.19. The free-run prediction of the test part is compared with the measured series in time (left), and its error is plotted against the horizon (right).

Figure 9.20

Figure 9.20. The delay vectors and the regime centers are projected to the plane by PCA (left) and by the fuzzy Sammon mapping (right).

9.4.5 Structure selection with a switching input

The output switches between x12 and x42 + x3 according to the binary input x2, and two irrelevant inputs are added. With three fuzzy sets per continuous input and structures of up to five inputs, the three best structures by σt all contain the four true inputs; the two with a dummy have a marginally smaller variance but a larger VCT, and {x1,x2,x3,x4} is the first dip of the VCT curve (fig. 9.21), as in the paper. Figure 9.22 shows the fuzzy sets of x1 and the crisp sets of x2 behind the decomposition. The parameter scan printed by the script shows the trade-off in the number of sets. Two sets resolve the quadratic terms poorly and drop x1 under strong noise; five sets spread the thousand samples over the 250 segments of the true structure and let a dummy input in; three sets are the best choice for a thousand samples, although with 300 samples a dummy enters there too. On the Friedman function with five relevant and five irrelevant inputs (fig. 9.23) the six best structures by σt are the true one and the true one plus each dummy, the VCT singles out the true one, and x3 is the first relevant input to be dropped further down the list, as in Table I of the paper.

Figure 9.21

Figure 9.21. The variance–complexity trade-off is plotted for the 30 best structures of the mixed-input problem; the framed dip is the recommended structure {x1,x2,x3,x4}.

Open in ColabExample plot_05_mixed_input_structure.py in the gallery

Figure 9.22

Figure 9.22. Fuzzy c-means gives three fuzzy sets of the continuous input x1 (left), and the binary input x2 has two crisp sets (right).

Figure 9.23

Figure 9.23. The variance–complexity trade-off is plotted for the 70 best structures of the Friedman function with five dummy inputs; the dip at structure six is the true set of inputs.

9.5 Further reading

The fuzzy segmentation was published in [114]; its conference precursor with the Q and T2 variants is [115]. The method builds on Gath–Geva clustering [21], on the modified Gath–Geva algorithm of chapter 8 [96], on probabilistic PCA and its mixtures [125], on Krzanowski’s similarity of principal components [126], on compatible cluster merging [40] with Kelly’s merging formulas [41], and on the covariance regularization of [19]. The bottom-up algorithm and its relatives are described in [112, 113]. The false-nearest-neighbor test originates in [116], its input–output version in [117, 118] and the Lipschitz-quotient idea in [131]; the cluster-based threshold was proposed in [119] and published in journal form in [120], the polymerization benchmark comes from [132], and model-order selection for linear systems is covered by [133]. State-space reconstruction rests on [121, 122], the choice of the lag on [127], embedding-dimension methods on [116, 134, 135], local prediction on [128, 129], operating-regime modeling on [7, 136], and the correlation dimension on [130]; the clustering-based method was proposed in [123] and its visualization by fuzzy Sammon mapping in [51]. The benchmark systems are those of Mackey and Glass [137], Lorenz [138] and Rössler [139]. The structure selection with mixed inputs was proposed in [124], which uses the Xie–Beni index [31] and the Friedman function of [140]. The c-means functional behind all these methods is Bezdek’s [3].