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 is a sequence of observations labeled by time points . 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 -segmentation splits into 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 and distances of section 9.2.1). They cluster the extended samples 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.
Model order. Before a nonlinear dynamic model can be identified, the regression vector 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 can be reconstructed from the delay vectors [121, 122]. Choosing the embedding dimension , 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 are local linear models of the map whose prediction error decides 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: with rows , memberships in the matrix (stored transposed in the code), prototypes with index , samples with index . Time stamps are , the extended sample is , delay vectors are , and denotes cluster 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 -segmentation with the variance as cost minimizes
|
| (9.1) |
which is the -means functional with clusters restricted to time intervals instead of Voronoi cells. Fuzzy segments replace the indicator by normalized Gaussian membership functions in time,
|
| (9.2) |
whose centers and widths are identified by the clustering. The algorithm minimizes the usual functional under the partition constraints, with a Gath–Geva-type distance that is the inverse of a probability density (fig. 9.1, bottom):
|
| (9.3) |
Within a segment, time is treated as independent of the observations, so the density factorizes into the prior , a Gaussian in time and a Gaussian in the feature space with covariance of rank . For the memberships are the posterior probabilities 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 instead of [21, 96].
The feature-space model. Choosing , the fuzzy covariance matrix, gives Gath–Geva clustering of the extended samples; when the variables are strongly correlated, 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 with latent variables and isotropic noise, so that
|
| (9.4) |
a full-rank covariance () whose large eigen-directions span the hyperplane of the segment and whose remaining eigenvalues all equal . The maximum-likelihood solution is known in closed form: with (eigenvalues in decreasing order),
|
| (9.5) |
with an arbitrary rotation . The journal version instead interleaves one EM step of PPCA with every clustering iteration: with and the latent expectations ,
|
| (9.6) |
where the center and
the fuzzy covariance
around it are computed with the weights
. 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
of
the EM algorithm of Tipping and Bishop [125]; the segmentation paper prints
there,
which the book and the code correct. The prior and the time part are updated by
|
| (9.7) |
and the partition by .
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-
method keeps the
smallest eigen-directions, so the exponent is the reconstruction error
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-
method keeps the
largest, so the exponent is the Hotelling statistic
of the
projection: it detects shifts of the operating point but not rotations of the hyperplane. Both
are sensitive to
(with
the reconstruction error vanishes everywhere; the
variant
needs a
defined by a required accuracy so that all segments keep comparable models).
The PPCA covariance (9.4) covers both subspaces and is insensitive to
; 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 intervals—are inspected in a scree plot, or is chosen as the smallest number of components that explains a required fraction of the variance in every initial segment,
|
| (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],
|
| (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 , because a change of the mean alone leaves . Each criterion is turned into a degree of fulfillment by a triangular membership function: parallelism rises from at to at , and closeness falls from at distance to at . The knots are the averages of the criteria over all pairs,
|
| (9.10) |
and the two degrees are aggregated to the compatibility
|
| (9.11) |
The most compatible adjacent pair is merged whenever 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 and :
|
| (9.12) |
and analogous formulas merge the time center and variance; the priors add,
, and
the PPCA model of the new segment follows from the eigen-decomposition of
by
(9.5). Two segments with identical PCA models but different means have
and
, 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.)
In a nutshell: Fuzzy segmentation
- Segmentation is clustering of 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 the memberships are the posteriors of a mixture of PPCA models, and the alternating optimization is a fuzzy relative of its EM algorithm.
- 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; and 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 and a PCA model with components, the cost is either the mean reconstruction error or the mean Hotelling statistic,
|
| (9.13) |
where the right-hand sides hold for centered data, with computed as in the paper from the scores . 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, to displacements along the hyperplane and to rotations of it, and a greedy merge made early is never revised. This is the baseline against which the fuzzy segmentation is judged.
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 cost finds changes of the correlation structure, the cost shifts of the operating point; neither finds both, and the cost depends strongly on .
- 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 with the NARX regression vector . If the regressors carry all the information about and is smooth, close regression vectors have close outputs: by a first-order Taylor expansion and the Cauchy–Schwarz inequality,
|
| (9.14) |
where is the gradient (Jacobian) of ; the bound holds up to a term of order , that is, approximately for close neighbors. The FNN algorithm [116, 117] finds for every its nearest neighbor in the regression space, declares the neighbor false when the ratio exceeds a threshold , and tabulates the percentage 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 ( absent, regressors ) the same test gives the embedding dimension, the problem for which it was introduced [116].
The difficulty is the threshold. Heuristic values (, after Kennel et al. [116]) work for some systems and not for others [118], and the exact bound 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 approximate the regression surface piecewise linearly (fig. 9.2, bottom): the smallest eigenvalue of is much smaller than the others and its eigenvector is the normal of the local hyperplane, so that
|
| (9.15) |
the total-least-squares estimate of a local linear model. The gradient at is approximated by the membership-weighted average of the local slopes, which gives a point-wise threshold,
|
| (9.16) |
so that neighbor of is false when . 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 are dimensionless.
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 table where the percentage collapses; the number of clusters hardly matters, a constant threshold does.
- With 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 of a deterministic system evolve as and be observed through a smooth scalar function . Takens’ theorem [121] states that, if is a compact manifold of dimension , then for a generic observation the delay vectors
|
| (9.17) |
embed when . Sauer, Yorke and Casdagli [122] replaced the manifold by the attractor itself: if its box-counting dimension is , almost every delay map is one-to-one on the attractor when . In practice often suffices, where 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 , and since the data are typically confined to a -dimensional surface of the -dimensional space, local linear models [128, 129] are the natural approximators (fig. 9.3).
The operating-regime model of [123] is the MIMO Takagi–Sugeno model of chapter 8 on the delay vectors,
|
| (9.18) |
whose Gaussian regimes and local models are identified simultaneously by clustering the pairs with the distance
|
| (9.19) |
the product of the prior, the Gaussian domain of influence and the Gaussian likelihood of the
-dimensional local prediction
error with covariance . The
alternating optimization updates
and as the
-weighted
mean and covariance of the delay vectors, the local models by weighted least squares
with
(local
estimation, which keeps the interpretation as a linear parameter-varying system), the error
covariances ,
the priors
and the partition by the usual formula. Since all but the first component of
are past samples, which a free-run simulation simply shifts along,
fuzzyclust by default identifies only the map to the next sample
(,
target="scalar"). The full MIMO map is available as target="full"; with
its components
copied from
make
singular unless it is regularized.
Three results come out of this clustering. (i) Embedding dimension: the model is identified for 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 , where the ratio of consecutive errors approaches one. (ii) Local dimension: the clusters approximate the tangent space of the attractor, so their smallest eigenvalues are orders of magnitude below the others once exceeds the dimension of the surface the trajectory lives on; the prior-weighted index
|
| (9.20) |
drops sharply at . The integer is complemented by the fractal correlation dimension of Grassberger and Procaccia [130], the slope of against for the correlation sum 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 -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].
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 .
- Clustering over a range of 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 (10–20), regularization of and ; visualize the regimes with the fuzzy Sammon mapping.
9.2.5 Structure selection with mixed discrete and continuous inputs
Suppose every candidate input takes values in a finite set . For a subset of the inputs the data decompose into segments—one for every combination of values —and if contains the inputs that drive the output, varies little inside each segment. The variance of 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 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 is clustered on its own by fuzzy c-means into fuzzy sets ( fixed or chosen by the Xie–Beni index [31]), giving a membership matrix , and a discrete input gets one crisp set per value. The fuzzy segments of a structure are the product-space conjunctions of the sets of its inputs,
|
| (9.21) |
(because the memberships of every input sum to one for each sample, the 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:
|
| (9.22) |
Structures are ranked by increasing . An irrelevant input only splits every segment into smaller ones; it does not increase 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
|
| (9.23) |
penalizes the number of inputs 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 , and fuzzyclust follows this reading: it recommends the structure with the smallest VCT among those whose 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.
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_
(),
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()
(,
,
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 , columns ), the selected n_a and n_b, and thresholds (the point-wise of every order); threshold= replaces 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 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 (correlation change), while their mean jumps at and both change at (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 (), so ; inside one regime the two components explain – of the variance, so an accuracy of 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 , and , 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: moves one border by sixty samples, and from on the result is stable. The printed comparison of the distance measures confirms the discussion of section 9.2.1: works with and fails with , fails with and works with the given by an accuracy of 99 %, and PPCA works with both. Finally, merging from ten segments with (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 and keep all four.
Open in ColabExample plot_01_fuzzy_segmentation.py in the gallery
9.4.2 Bottom-up baseline versus fuzzy segmentation
On the same series the bottom-up algorithm with the cost finds the two correlation changes and misses the mean shift, with the 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 cost depends strongly on (with the displacement of a mean shift leaves the one-dimensional model and is detected by accident; with the residual is noise), that the cost is insensitive to but blind to the correlation change, and that a long initial piece coarsens the borders. The fuzzy segmentation with finds the three borders every time, with one of them sixty samples off.
Open in ColabExample plot_02_bottom_up_vs_fuzzy.py in the gallery
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 . With the cluster-based threshold (fig. 9.12) the percentage of false neighbors collapses in the corner , , and the smallest order there, , 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 (, below every local slope) keeps flagging more than a third of the neighbors at every order, so no corner appears; happens to give the right order; a loose constant (, above every local slope) also passes wrong orders of the same size, and , and selects . Kennel’s two-criterion test is looser still and accepts models that are too small, and . 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 and then flattens.
Open in ColabExample plot_03_fnn_model_order.py in the gallery
9.4.4 Reconstruction and prediction of the Rössler series
The Rössler system is observed through (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 to and by to , after which it fluctuates around a floor, so . The prior-weighted smallest eigenvalue drops by a factor of three at (from to ) and keeps falling, because the clusters are flat from three dimensions on, so , 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 as well, and the correlation dimension of the reconstructed vectors is . 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 of the variance one step ahead to 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 (, and ); the percentage of false neighbors of the classical test falls below the tolerance of at for the Rössler and Mackey–Glass series and already at () for the Lorenz series.
Open in ColabExample plot_04_chaotic_reconstruction.py in the gallery
9.4.5 Structure selection with a switching input
The output switches between and according to the binary input , 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 all contain the four true inputs; the two with a dummy have a marginally smaller variance but a larger VCT, and is the first dip of the VCT curve (fig. 9.21), as in the paper. Figure 9.22 shows the fuzzy sets of and the crisp sets of 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 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 are the true one and the true one plus each dummy, the VCT singles out the true one, and is the first relevant input to be dropped further down the list, as in Table I of the paper.
Open in ColabExample plot_05_mixed_input_structure.py in the gallery
9.5 Further reading
The fuzzy segmentation was published in [114]; its conference precursor with the and 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].