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: BaseFuzzyClusterer

Fuzzy 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_segmentsint, default=5

Initial number of segments \(c\). With merge=True this is an upper bound; the paper starts from ten segments.

mfloat, default=2.0

Fuzziness exponent \(m>1\).

n_componentsint, float or None, 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. None uses an accuracy of 0.95. 0 gives 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_thresholdfloat, 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_everyint, default=100

Merging is evaluated after this many iterations and at convergence.

min_segment_weightfloat, 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. 0 disables it.

gammafloat, default=0.0

Shrinkage of the fuzzy covariance matrices toward a scaled identity (see GK).

betafloat, default=1e15

Condition-number bound of the fuzzy covariance matrices.

tolfloat, default=1e-4
max_iterint, 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++”} or ndarray, default=”uniform”

"uniform" splits the series into n_segments equal intervals (the initialization of the paper); the other options are those of BaseFuzzyClusterer applied to \(\mathbf{z}_k\).

n_initint, 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_stateint, RandomState instance or None, default=None
verboseint, default=0
Attributes:
membership_ndarray of shape (n_samples, n_segments_)

Fuzzy partition \(p(\eta_i|\mathbf{z}_k)\); segments are ordered in time.

labels_ndarray of shape (n_samples,)
boundaries_ndarray of int

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 posterior membership_, 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_ndarray of shape (n_segments_,)

Time centers \(v^t_i\).

segment_variances_ndarray of shape (n_segments_,)

Time variances \(\sigma^2_{i,t}\).

time_membership_ndarray of shape (n_samples, n_segments_)

Normalized Gaussian memberships in time, \(\beta_i(t_k)\) of eq. (4).

cluster_centers_ndarray of shape (n_segments_, n_features)

Observation centers \(\mathbf{v}^x_i\).

covariances_ndarray of shape (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_ndarray of shape (n_segments_, n_features, n_components_)

PPCA loading matrices \(\mathbf{W}_i\).

noise_variances_ndarray of shape (n_segments_,)

PPCA noise variances \(\sigma^2_{i,x}\).

norm_matrices_ndarray of shape (n_segments_, n_features, n_features)

\(\mathbf{A}_i\) of the observation distance.

local_pca_list of sklearn.utils.Bunch

Per segment: mean, components ((q, n), principal axes), explained_variance ((q,)), noise_variance.

priors_ndarray of shape (n_segments_,)

\(\alpha_i\).

time_ndarray of shape (n_samples,)

Time index used in fit.

objective_, objective_history_, n_iter_

See BaseFuzzyClusterer.

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/transform evaluate the fitted prototypes for given observations and time stamps; without t they 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]))
compatibility_matrix()[source]#

Compatibility \(O_{ij}\) of all pairs of segments (eqs. (22)–(26)).

Returns:
Ondarray of shape (c, c)
S_pcandarray of shape (c, c)

Krzanowski PCA similarity factors.

Dndarray of shape (c, c)

Euclidean distances between the observation centers.

fit(X, y=None, t=None)[source]#

Segment the series.

Parameters:
Xarray_like of shape (n_samples, n_features)

Observations in time order.

yIgnored
tarray_like of shape (n_samples,), optional

Time stamps (non-decreasing). Defaults to 0, 1, ..., n_samples-1.

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:
T2ndarray of shape (n_samples, n_segments_)
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) or max_merges merges were made.

Returns:
self
predict(X, t=None)[source]#

Hard segment labels of observations X at times t.

predict_proba(X, t=None)[source]#

Memberships of observations X at times t (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:
Qndarray of shape (n_samples, n_segments_)
score(X, y=None, t=None)[source]#

Negative objective \(-J\) on X (higher is better).

set_predict_proba_request(*, t='$UNCHANGED$')#

Configure whether metadata should be requested to be passed to the predict_proba method.

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 (see sklearn.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 to predict_proba if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to predict_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.

Parameters:
tstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for t parameter in predict_proba.

Returns:
selfobject

The updated object.

transform(X, t=None)[source]#

Distances \(D(\mathbf{z}_k,\eta_i)\) of observations at times t to the segments.

Examples using fuzzyclust.timeseries.FuzzySegmentation#

Fuzzy segmentation of a multivariate time series

Fuzzy segmentation of a multivariate time series

Bottom-up segmentation with PCA models versus fuzzy segmentation

Bottom-up segmentation with PCA models versus fuzzy segmentation