fuzzyclust.timeseries.FuzzySegmentation#
- class fuzzyclust.timeseries.FuzzySegmentation(n_segments=5, m=2.0, n_components=None, distance='ppca', pca_update='em', merge=False, merge_threshold=0.75, merge_every=100, min_segment_weight=0.02, gamma=0.0, beta=1000000000000000.0, tol=0.0001, max_iter=300, init='uniform', n_init=1, random_state=None, verbose=0)[source]#
Bases:
BaseFuzzyClustererFuzzy segmentation of a multivariate time series (modified Gath–Geva clustering).
Segmentation is clustering with a time-ordered structure: the samples of a segment must be consecutive in time. The algorithm of Abonyi, Feil, Németh and Árva [1] clusters the extended samples \(\mathbf{z}_k=[t_k,\ \mathbf{x}_k^T]^T\) with a prototype that has two parts: a Gaussian membership function in time (center \(v^t_i\), variance \(\sigma^2_{i,t}\)) that makes the clusters contiguous, and a local probabilistic PCA (PPCA) model of the observations (center \(\mathbf{v}^x_i\), loading matrix \(\mathbf{W}_i\) with \(q\) columns and noise variance \(\sigma^2_{i,x}\)) that measures the homogeneity of the segment. Changes of the mean, of the variance and of the correlation structure of the variables are all detected, because the hyperplane of the local PCA model reacts to each of them. The number of segments can be reduced automatically by merging compatible adjacent clusters (a fuzzy decision based on the similarity of the PCA models and the distance of the centers).
- Parameters:
- n_segments
int, default=5 Initial number of segments \(c\). With
merge=Truethis is an upper bound; the paper starts from ten segments.- m
float, default=2.0 Fuzziness exponent \(m>1\).
- n_components
int,floatorNone, default=None Number of principal components \(q\) of the local PCA models. A float in
(0, 1)is the required accuracy (fraction of variance explained) of eq. (29) of [1]: \(q\) is the smallest number of components that explains at least this fraction in every segment of the initial uniform segmentation.Noneuses an accuracy of 0.95.0gives spherical (isotropic) Gaussian segments.- distance{“ppca”, “q”, “t2”}, default=”ppca”
Observation part of the distance.
"ppca"is the journal version: the Gaussian with covariance \(\mathbf{A}_i=\sigma^2_{i,x}\mathbf{I} +\mathbf{W}_i\mathbf{W}_i^T\)."q"and"t2"are the two variants of the conference version [2]: a Gaussian restricted to the residual subspace (reconstruction error \(Q\), sensitive to changes of the correlation structure) or to the principal subspace (Hotelling \(T^2\), sensitive to shifts of the operating point).- pca_update{“em”, “eig”}, default=”em”
How the PPCA parameters are updated in every iteration: by the EM step of eqs. (17)–(18) of [1] (as published) or by the closed-form eigen-solution of eqs. (11)–(12) (same fixed point, faster convergence).
- mergebool, default=False
Merge compatible adjacent segments during fitting (bottom-up reduction of the number of segments, Section 2.5 of [1]).
- merge_threshold
float, default=0.75 Threshold \(\gamma\) on the compatibility \(O_{i,i+1}\); the paper recommends values between 0.3 and 0.75. Note that two segments with identical PCA models but distant centers have \(O=1/\sqrt2\approx0.71\), so \(\gamma\) must exceed this value if shifts of the mean are to be preserved as separate segments.
- merge_every
int, default=100 Merging is evaluated after this many iterations and at convergence.
- min_segment_weight
float, default=0.02 Safeguard (not in the paper): during merging, a segment whose prior \(\alpha_i\) is below this fraction of the data is absorbed by its more compatible neighbor regardless of \(\gamma\). Such tiny “transition” clusters appear when the initial number of segments is much larger than the true one.
0disables it.- gamma
float, default=0.0 Shrinkage of the fuzzy covariance matrices toward a scaled identity (see
GK).- beta
float, default=1e15 Condition-number bound of the fuzzy covariance matrices.
- tol
float, default=1e-4 - max_iter
int, default=300 Maximum number of iterations per clustering stage (the counter is reset after every merge;
n_iter_is the total).- init{“uniform”, “random”, “kmeans++”}
orndarray, default=”uniform” "uniform"splits the series inton_segmentsequal intervals (the initialization of the paper); the other options are those ofBaseFuzzyClustererapplied to \(\mathbf{z}_k\).- n_init
int, default=1 Number of restarts for the random initializations (
"random","kmeans++"); the run with the lowest final objective is kept. Ignored for the deterministic"uniform"and array initializations.- random_state
int,RandomStateinstanceorNone, default=None - verbose
int, default=0
- n_segments
- Attributes:
- membership_
ndarrayofshape(n_samples,n_segments_) Fuzzy partition \(p(\eta_i|\mathbf{z}_k)\); segments are ordered in time.
- labels_
ndarrayofshape(n_samples,) - boundaries_
ndarrayofint Crisp change points: indices \(k\) where the segment of maximal time membership \(\beta_i(t_k)\) changes (the fuzzy segments in time are the Gaussians;
labels_is the argmax of the posteriormembership_, which also depends on the observations and may flicker around a boundary).- n_segments_
int Number of segments after merging.
- n_components_
int Number of principal components \(q\) used.
- segment_centers_
ndarrayofshape(n_segments_,) Time centers \(v^t_i\).
- segment_variances_
ndarrayofshape(n_segments_,) Time variances \(\sigma^2_{i,t}\).
- time_membership_
ndarrayofshape(n_samples,n_segments_) Normalized Gaussian memberships in time, \(\beta_i(t_k)\) of eq. (4).
- cluster_centers_
ndarrayofshape(n_segments_,n_features) Observation centers \(\mathbf{v}^x_i\).
- covariances_
ndarrayofshape(n_segments_,n_features,n_features) Fuzzy covariance matrices \(\mathbf{F}_i\).
- eigenvalues_, eigenvectors_
ndarrays Eigen-decomposition of \(\mathbf{F}_i\) in descending order (shapes
(c, n)and(c, n, n), eigenvectors in columns).- pca_loadings_
ndarrayofshape(n_segments_,n_features,n_components_) PPCA loading matrices \(\mathbf{W}_i\).
- noise_variances_
ndarrayofshape(n_segments_,) PPCA noise variances \(\sigma^2_{i,x}\).
- norm_matrices_
ndarrayofshape(n_segments_,n_features,n_features) \(\mathbf{A}_i\) of the observation distance.
- local_pca_
listofsklearn.utils.Bunch Per segment:
mean,components((q, n), principal axes),explained_variance((q,)),noise_variance.- priors_
ndarrayofshape(n_segments_,) \(\alpha_i\).
- time_
ndarrayofshape(n_samples,) Time index used in
fit.- objective_, objective_history_, n_iter_
See
BaseFuzzyClusterer.
- membership_
Notes
The objective is \(J=\sum_i\sum_k\mu_{ik}^m D^2(\mathbf{z}_k,\eta_i)\) with the distance defined through a probability (eq. (8) of [1]):
\[\frac{1}{D^2(\mathbf{z}_k,\eta_i)} = \alpha_i\; \frac{1}{\sqrt{2\pi\sigma^2_{i,t}}}\exp\!\Big(-\tfrac12\frac{(t_k-v^t_i)^2}{\sigma^2_{i,t}}\Big)\; \frac{1}{(2\pi)^{r/2}\sqrt{\det\mathbf{A}_i}} \exp\!\Big(-\tfrac12(\mathbf{x}_k-\mathbf{v}^x_i)^T\mathbf{A}_i^{-1}(\mathbf{x}_k-\mathbf{v}^x_i)\Big),\]where \(r\) is the rank of \(\mathbf{A}_i\) (\(n\) for the PPCA model, \(q\) and \(n-q\) for the
"t2"and"q"variants, with pseudo-determinant and pseudo-inverse). The alternating optimization updates\[\alpha_i=\frac1N\sum_k\mu_{ik},\qquad v^t_i=\frac{\sum_k\mu_{ik}^m t_k}{\sum_k\mu_{ik}^m},\qquad \sigma^2_{i,t}=\frac{\sum_k\mu_{ik}^m (t_k-v^t_i)^2}{\sum_k\mu_{ik}^m},\]the centers \(\mathbf{v}^x_i=\sum_k\mu_{ik}^m(\mathbf{x}_k-\mathbf{W}_i\langle\mathbf{y}_{ik}\rangle)/\sum_k\mu_{ik}^m\) with the latent expectations \(\langle\mathbf{y}_{ik}\rangle=\mathbf{M}_i^{-1}\mathbf{W}_i^T(\mathbf{x}_k-\mathbf{v}^x_i)\), \(\mathbf{M}_i=\sigma^2_{i,x}\mathbf{I}+\mathbf{W}_i^T\mathbf{W}_i\), the fuzzy covariance \(\mathbf{F}_i\), and the PPCA EM step
\[\tilde{\mathbf{W}}_i=\mathbf{F}_i\mathbf{W}_i\big(\sigma^2_{i,x}\mathbf{I}+\mathbf{M}_i^{-1}\mathbf{W}_i^T\mathbf{F}_i\mathbf{W}_i\big)^{-1},\qquad \sigma^2_{i,x}=\frac1n\tr\big(\mathbf{F}_i-\mathbf{F}_i\mathbf{W}_i\mathbf{M}_i^{-1}\tilde{\mathbf{W}}_i^T\big),\](Tipping & Bishop; eq. (18) of [1] prints the factor as \(1/q\)), followed by \(\mathbf{A}_i=\sigma^2_{i,x}\mathbf{I}+\tilde{\mathbf{W}}_i\tilde{\mathbf{W}}_i^T\) and the usual membership update \(\mu_{ik}=1/\sum_j (D_{ik}/D_{jk})^{2/(m-1)}\).
Compatible cluster merging. For every pair of segments the PCA similarity factor of Krzanowski \(S^{ij}_{PCA}=\frac1q\tr(\mathbf{U}_{i,q}^T\mathbf{U}_{j,q}\mathbf{U}_{j,q}^T\mathbf{U}_{i,q})\) and the distance of the centers \(\|\mathbf{v}^x_i-\mathbf{v}^x_j\|\) are evaluated, turned into degrees of parallelism and closeness by triangular membership functions whose knots are the averages \(\nu^1,\nu^2\) over all pairs, and aggregated to the compatibility \(O_{ij}=\sqrt{(\mu^1_{ij})^2+(\mu^2_{ij})^2)/2}\). The most compatible adjacent pair is merged (Kelly’s formulas for the merged mean and covariance) whenever \(O_{i,i+1}>\gamma\), the PPCA model of the new segment is computed from the eigen-decomposition of its covariance, and clustering continues.
predict/predict_proba/transformevaluate the fitted prototypes for given observations and time stamps; withouttthey assume the rows are the training series (or a series starting at time 0), because the time part of the prototype has no meaning for unordered new data.References
[1] (1,2,3,4,5,6)J. Abonyi, B. Feil, S. Németh, P. Árva, “Modified Gath–Geva clustering for fuzzy segmentation of multivariate time-series”, Fuzzy Sets and Systems 149 (2005) 39–56.
[2]J. Abonyi, B. Feil, S. Németh, P. Árva, “Fuzzy clustering based segmentation of time-series”, IDA 2003, LNCS 2810, 275–285.
[3]M. E. Tipping, C. M. Bishop, “Mixtures of probabilistic principal component analyzers”, Neural Computation 11 (1999) 443–482.
[4]W. J. Krzanowski, “Between-groups comparison of principal components”, J. Amer. Statist. Assoc. 74 (1979) 703–707.
Examples
>>> from fuzzyclust.timeseries import FuzzySegmentation, make_piecewise_timeseries >>> X, seg = make_piecewise_timeseries(n_samples=600, change_points=(200, 400), ... change_kinds=("mean", "mean"), random_state=0) >>> fs = FuzzySegmentation(n_segments=3, n_components=2).fit(X) >>> fs.membership_.shape, fs.boundaries_ ((600, 3), array([200, 400]))
- fit(X, y=None, t=None)[source]#
Segment the series.
- Parameters:
- Xarray_like
ofshape(n_samples,n_features) Observations in time order.
- y
Ignored - tarray_like
ofshape(n_samples,),optional Time stamps (non-decreasing). Defaults to
0, 1, ..., n_samples-1.
- Xarray_like
- hotelling_t2(X)[source]#
Hotelling \(T^2\) of every observation with respect to every local PCA model.
\[T^2_{ik} = \mathbf{y}_{ik}^T\boldsymbol{\Lambda}_{i,q}^{-1}\mathbf{y}_{ik},\qquad \mathbf{y}_{ik} = \mathbf{U}_{i,q}^T(\mathbf{x}_k-\mathbf{v}^x_i),\]the squared Mahalanobis distance of the projection inside the principal subspace (drift of the operating point).
- Returns:
- T2
ndarrayofshape(n_samples,n_segments_)
- T2
- merge_compatible_segments(threshold=None, max_merges=None)[source]#
Merge compatible adjacent segments of a fitted model and re-cluster.
Repeats merge the most compatible adjacent pair, run the alternating optimization to convergence until no adjacent pair has a compatibility \(O_{i,i+1}\) above
threshold(default:merge_threshold) ormax_mergesmerges were made.- Returns:
self
- predict_proba(X, t=None)[source]#
Memberships of observations
Xat timest(default: the training time axis).
- q_reconstruction_error(X)[source]#
Reconstruction error \(Q\) of every observation for every local PCA model.
\[Q_{ik} = \|(\mathbf{I}-\mathbf{U}_{i,q}\mathbf{U}_{i,q}^T)(\mathbf{x}_k-\mathbf{v}^x_i)\|^2,\]the squared distance from the hyperplane of the segment (change of the correlation structure).
- Returns:
- Q
ndarrayofshape(n_samples,n_segments_)
- Q
- set_predict_proba_request(*, t='$UNCHANGED$')#
Configure whether metadata should be requested to be passed to the
predict_probamethod.Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with
enable_metadata_routing=True(seesklearn.set_config()). Please check the User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed topredict_probaif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it topredict_proba.None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (
sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.Added in version 1.3.
Examples using fuzzyclust.timeseries.FuzzySegmentation#
Bottom-up segmentation with PCA models versus fuzzy segmentation