TICC#
TICC – Toeplitz Inverse Covariance-based Clustering.
Description#
TICC simultaneously segments and clusters multivariate time series by modelling
each cluster as a Markov Random Field (MRF) defined over a short window of
length window_size. The MRF is characterised by a block-Toeplitz inverse
covariance matrix that captures temporal and cross-variable partial correlations.
The algorithm alternates between:
Assignment step – dynamic programming assigns each window to a cluster, minimising the negative log-likelihood of the windows plus a switching penalty \(\beta\) for each change of cluster.
Update step – ADMM updates the Toeplitz inverse covariance of each cluster subject to a sparsity penalty \(\lambda\).
The label of time point t is that of the window of points t to
t + window_size − 1. All n - window_size + 1 complete windows enter
training, assignment and likelihood calculations, so the final observations
are included. The final window_size - 1 point labels repeat the label of
the last window. This corrects the reference solver’s truncated, zero-padded
windows and omitted tail costs; fitted outputs and BIC-selected state counts
can change when window_size > 1. Earlier TICC scores need to be recomputed.
The start-aligned labeling convention differs from the paper’s window ending
at t and is retained. predict on a series other than the one given to fit
labels it with a new fit, with a warning (see the Notes of
TiccDetector).
Without n_states, the number of states is selected by the Bayesian
information criterion (BIC), as the paper recommends: TICC is fitted for each
number of states from 1 to max_states, and the fit with the lowest BIC is
kept (see TiccDetector).
n_states=None, BIC) or semi-supervised
(n_states given)n_states and w is window_size: each stacked window
(dimension \(d\,w\)) is scored under the precision matrix of each state.
Without n_states, one fit per number of states up to max_states.Parameters#
Name |
Type |
Default |
Description |
|---|---|---|---|
|
int |
|
Number of consecutive time points stacked into each window. |
|
int / None |
|
Number of states (clusters); |
|
int |
|
Largest number of states tried when |
|
float |
|
Weight of the \(\ell_1\) penalty on the inverse covariances. |
|
float |
|
Switching penalty (temporal consistency); twice the \(\beta\) of the paper. |
|
int |
|
Maximum number of iterations (update and assignment steps). |
|
float |
|
No effect: the solver never reads it. |
|
int |
|
Number of processes for the update steps; the output does not depend on it. |
|
int |
|
Time axis. |
Usage#
from tsseg.algorithms import TiccDetector
detector = TiccDetector(n_states=4, window_size=10, beta=200)
states = detector.fit_predict(X)
# number of states chosen by BIC
detector = TiccDetector(window_size=10, beta=200, max_states=6)
states = detector.fit_predict(X)
detector.n_states_, detector.bic_
Implementation: Adapted from the original TICC code by Hallac et al.
Reference: Hallac, Vare, Boyd & Leskovec (2017), Toeplitz Inverse Covariance-Based Clustering of Multivariate Time Series Data, KDD.
API reference#
TICC detector, a wrapper of tsseg.algorithms.ticc.ticc.
- class TiccDetector(*, window_size=10, n_states=None, lambda_parameter=0.11, beta=400, maxIters=100, threshold=2e-05, num_proc=1, max_states=8, axis=0)[source]#
Bases:
BaseSegmenterTICC: Toeplitz inverse covariance-based clustering of time series windows.
Each state is a Gaussian model of the windows of
window_sizeconsecutive time points, whose precision (inverse covariance) matrix is sparse and block Toeplitz: the dependency between two channels at a given lag is the same everywhere in the window. TICC alternates between estimating the precision matrix of each state (Toeplitz graphical lasso, solved by ADMM) and assigning the windows to the states by dynamic programming, with a penaltybetafor each change of state between consecutive windows [1].- Parameters:
window_size (int, default=10) – Number \(w\) of consecutive time points stacked into each window; the window of time point
tholds the pointsttot + w - 1. Must be smaller than the length of the series.n_states (int or None, default=None) – The number of states (clusters) to find;
1labels every time point with the same state.Noneselects it by the Bayesian information criterion among1, ..., max_states(see Notes).lambda_parameter (float, default=11e-2) – Weight \(\lambda\) of the \(\ell_1\) penalty on every entry of the precision matrix of each state, diagonal included. It is not divided by the number of windows of the state: the paper absorbs this factor into \(\lambda\) [1].
beta (float, default=400) – Switching penalty: cost of each change of state between two consecutive windows. The assignment step weighs it against \((X_t - \mu)^\top \Theta (X_t - \mu) - \log\det\Theta\), twice the negative log-likelihood of a window up to a constant, so
betais twice the \(\beta\) of the paper. With0, each window takes its most likely state.maxIters (int, default=100) – Maximum number of iterations (update step, then assignment step); the iterations stop earlier when the assignment no longer changes.
threshold (float, default=2e-5) – No effect: the solver stores it but never reads it (the tolerances of the ADMM are fixed at
1e-6).num_proc (int, default=1) – Number of processes that solve the update steps of the states in parallel (
multiprocessing.Pool); the output does not depend on it.max_states (int, default=8) – Largest number of states tried when
n_statesisNone.axis (
int) – Axis of the time points in a 2D input:0for an array of shape(n_timepoints, n_channels),1for(n_channels, n_timepoints).
- bic_#
BIC of each candidate number of states (only when
n_states=None);inffor a number of states the solver failed to fit.- Type:
Notes
Windows.
fitstacks the complete windows that start att = 0, ..., n - w: the label of time pointtis that of the pointsttot + w - 1(the paper labels the window that ends att). Every observation enters a window, and alln - w + 1windows contribute to fitting, assignment costs and the likelihood. The detector gives the lastw - 1time points the label of the window starting atn - w. The reference code instead truncates the final windows and pads them with zeros, omitting the final observations and their costs; this port corrects that behavior, so fitted outputs can differ.Solver. A Gaussian mixture with full covariances, fitted on the stacked windows, gives the initial states. The update step solves, for each state with at least two windows, the Toeplitz graphical lasso (Problem (4) of [1]) on the unbiased empirical covariance of its windows, by ADMM (\(\rho = 1\), at most 1000 iterations, tolerances
1e-6). The assignment step solves Problem (3) of [1], with \(\beta\) =beta / 2, by dynamic programming over the windows. From the second iteration on, a state left without windows after the assignment step receives 20 consecutive windows of another state. The solver draws from its own generator, seeded with 102: the output is the same at every run, and the detector has norandom_state.TICC labels the time points of the series given to
fit:predict(X)returns those labels whenXhas the same values, and otherwise labelsXwith a new fit, with a warning, leaving the fitted attributes unchanged.Every state needs two windows to estimate its covariance. With
n_statesgiven,fitraisesValueErrorwhen the series has fewer than2 * n_stateswindows (n_timepoints - window_size + 1), or when the initial Gaussian mixture gives a state fewer than two windows (for instance to a single window of outliers); withn_states=None, such a number of states gets an infinite BIC.Number of states. The paper selects the number of clusters \(K\) by BIC [1] (Sec. 3, “Selecting the Number of Clusters”, and Sec. 7, where BIC picks \(K = 5\)). With
n_states=None, TICC is fitted for each \(K\) in1, ..., max_statesand the fit with the lowest\[\mathrm{BIC}(K) = -\frac{2}{w} \sum_t \ell\ell(X_t, \Theta_{c(t)}) + \Big(\sum_{i=1}^{K} (p_i + d) + s\Big) \log T\]is kept, where \(\ell\ell\) is the Gaussian log-likelihood of the stacked window \(X_t\) under the precision \(\Theta_{c(t)}\) of its cluster (Eq. 2), \(p_i\) the number of free entries of the block Toeplitz \(\Theta_i\) above
2e-5in absolute value, \(d\) the number of channels (the mean), \(s\) the number of switches between clusters and \(T\) the number of time points. A time point belongs to up to \(w\) =window_sizeoverlapping windows (fewer near the ends). The sum of the window log-likelihoods is divided by \(w\) (a composite likelihood). This costsmax_statesfits of TICC.On univariate series, the log-likelihood of the fitted model often does not increase with the number of states, and BIC then selects a single state.
The solver,
tsseg.algorithms.ticc.ticc, is the code of the reference implementation (davidhallac/TICC, BSD 2-Clause licence); the changes listed at the top of that module leave its output unchanged.References
- set_fit_request(*, axis='$UNCHANGED$')#
Configure whether metadata should be requested to be passed to the
fitmethod.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 tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.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.
- set_predict_request(*, axis='$UNCHANGED$')#
Configure whether metadata should be requested to be passed to the
predictmethod.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 topredictif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it topredict.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.
Core solver of TICC (Toeplitz inverse covariance-based clustering).
- class ADMMSolver(lamb, num_stacked, size_blocks, rho, S, rho_update_func=None)[source]#
Bases:
objectADMM for the Toeplitz graphical lasso, the update step of TICC.
Solves
\[\min_{\Theta} \; -\log\det\Theta + \mathrm{tr}(S\Theta) + \|\lambda \circ \Theta\|_1\]over the symmetric block Toeplitz matrices \(\Theta\) (Problem (4) of Hallac et al., 2017, with the factor \(1/|P_i|\) absorbed into \(\lambda\)). The variable
xtakes the log-determinant step, its copyzthe block Toeplitz constraint and the \(\ell_1\) penalty, anduis the scaled dual variable. All three hold the entries on and above the diagonal, row by row.- Parameters:
lamb (np.ndarray) – Penalty weights \(\lambda\), of shape
(p, p)withp = num_stacked * size_blocks.num_stacked (int) – Number of blocks \(w\) (the window size).
size_blocks (int) – Size \(d\) of each block (the number of channels).
rho (float) – Penalty parameter \(\rho\) of the augmented Lagrangian.
S (np.ndarray) – Empirical covariance, of shape
(p, p).rho_update_func (callable or None, default=None) – Called after each iteration from the second on, as
rho_update_func(rho, res_pri, e_pri, res_dual, e_dual), to give a new \(\rho\). As in the reference code, onlyuis rescaled byrho / new_rho:rhoitself keeps its value. TICC passesNone.
- x, z, u
The ADMM variables, of length
p * (p + 1) / 2.- Type:
np.ndarray
- status#
"Optimal"when the stopping criterion was met,"Incomplete: max iterations reached"otherwise.- Type:
- ADMM_z(index_penalty=1)[source]#
Soft-threshold the mean of each group of tied entries of
x + u.Each free entry of the block Toeplitz matrix gets the mean of its occurrences in
x + u, soft-thresholded at the mean of their weights inlambdivided byrho;zrepeats it at every occurrence.- Parameters:
index_penalty (int, default=1) – Unused.
- CheckConvergence(z_old, e_abs, e_rel, verbose)[source]#
Stopping criterion of the ADMM, from the primal and dual residuals.
The primal residual is \(\|x - z\|\), the dual residual \(\|\rho (z - z_{old})\|\); their thresholds are \(\sqrt{L} e_{abs} + e_{rel} \max(\|x\|, \|z\|) + 10^{-4}\) and \(\sqrt{L} e_{abs} + e_{rel} \|\rho u\| + 10^{-4}\), with \(L\) the length of the variables.
- Parameters:
- Returns:
(stop, res_pri, e_pri, res_dual, e_dual): whether both residuals are at most their thresholds, then the primal residual and threshold, and the dual residual and threshold.- Return type:
- Prox_logdet(S, A, eta)[source]#
Log-determinant step of the ADMM, in closed form.
Minimises \(-\log\det X + \mathrm{tr}(SX) + \frac{\eta}{2}\|X - A\|_F^2\) from the eigendecomposition \(Q D Q^\top\) of \(\eta A - S\): \(X = Q \, \frac{D + \sqrt{D^2 + 4\eta}}{2\eta} \, Q^\top\).
- Parameters:
S (np.ndarray) – Empirical covariance, of shape
(p, p).A (np.ndarray) – Symmetric matrix of shape
(p, p), herez - u.eta (float) – Weight of the quadratic term, here \(\rho\).
- Returns:
Entries of \(X\) on and above the diagonal, row by row.
- Return type:
np.ndarray
- class TICC(window_size=10, number_of_clusters=5, lambda_parameter=0.11, beta=400, maxIters=1000, threshold=2e-05, write_out_file=False, prefix_string='', num_proc=1, compute_BIC=False, cluster_reassignment=20, biased=False)[source]#
Bases:
objectTICC solver: alternate update and assignment steps on stacked windows.
- Parameters:
window_size (int, default=10) – Number \(w\) of consecutive time points stacked into each window.
number_of_clusters (int, default=5) – Number of states.
lambda_parameter (float, default=11e-2) – Weight of the \(\ell_1\) penalty on every entry of the precision matrix of each state, diagonal included.
beta (float, default=400) – Switching penalty of the assignment step, stored as
switch_penalty.maxIters (int, default=1000) – Maximum number of iterations;
fit_transformraisesValueErrorif it is not positive.threshold (float, default=2e-5) – Stored, never read.
write_out_file (bool, default=False) – Unused, kept for compatibility.
prefix_string (str, default="") – Unused, kept for compatibility.
num_proc (int, default=1) – Number of processes of the pool that solves the update steps;
1solves them in the calling process.compute_BIC (bool, default=False) – Whether
fit_transformalso returns the value ofcomputeBIC.cluster_reassignment (int, default=20) – Number of consecutive windows moved to a state left without windows.
biased (bool, default=False) – Whether the empirical covariances divide by the number of windows of the state (
True) or by that number minus one (False).
- clustered_points_#
State of each window after the last iteration, set by
fit_transform.- Type:
np.ndarray
- trained_model#
Means, covariances and stacked windows read by
predict_clustersandlog_likelihood.- Type:
- fit_transform(series)[source]#
Fit the model and return the state of each window.
- Parameters:
series (np.ndarray) – The time series, of shape
(n_timepoints, n_channels).- Returns:
clustered_points (np.ndarray) – State of each of the
n_timepoints - window_size + 1windows, as floats. Windowtholds the pointsttot + window_size - 1. Every window is complete and contributes to the model update and assignment steps.train_cluster_inverse (dict) – Precision matrix of each state, of shape
(window_size * n_channels,) * 2.bic (float) – Only when
compute_BICis true: the value ofcomputeBIC.
- Raises:
ValueError – If
maxItersis not positive, if the series has fewer than two windows per state, or if the initial Gaussian mixture gives a state fewer than two windows: the update step needs two windows to estimate the covariance of a state.
- log_likelihood()[source]#
Gaussian log-likelihood of the stacked windows under the fitted model.
Sum over the windows of Eq. (2) of the paper, each window under the precision matrix and the mean of the cluster it is assigned to after the last iteration. Every complete training window contributes.
- Returns:
The log-likelihood.
- Return type:
- optimize_clusters(computed_covariance, len_train_clusters, log_det_values, optRes, train_cluster_inverse)[source]#
Store the precision and covariance matrices computed by the ADMM.
For each state whose update step ran, the vector returned by the ADMM becomes the precision matrix
train_cluster_inverse[state], its inverse the covariancecomputed_covariance[number_of_clusters, state]and the log-determinant of that covariancelog_det_values[number_of_clusters, state]. States skipped bytrain_clusterskeep their previous values.- Parameters:
computed_covariance (dict) – Covariance of each state; updated in place.
len_train_clusters (dict) – Unused.
log_det_values (dict) – Log-determinant of the covariance of each state; updated in place.
optRes (list) – Output of
train_clusters: for each state, the result of its solver (an object with agetmethod), orNone.train_cluster_inverse (dict) – Precision matrix of each state; updated in place.
- predict_clusters(test_data=None)[source]#
Assignment step: state of each window under the current model.
- Parameters:
test_data (np.ndarray or None, default=None) – Stacked windows, of shape
(n_windows, window_size * n_channels)as returned bystack_training_data, not the raw series;Noneuses the training windows. Every row is scored.- Returns:
State of each window, as floats (see
updateClusters).- Return type:
np.ndarray
- Raises:
TypeError – If
test_datais given and is not a NumPy array.
- smoothen_clusters(cluster_mean_info, computed_covariance, cluster_mean_stacked_info, complete_D_train, n)[source]#
Cost of each window under each state, for the assignment step.
- Parameters:
cluster_mean_info (dict) – Unused.
computed_covariance (dict) – Covariance \(\Sigma = \Theta^{-1}\) of each state, keyed by
(number_of_clusters, state).cluster_mean_stacked_info (dict) – Mean window \(\mu\) of each state, with the same keys.
complete_D_train (np.ndarray) – Stacked windows, of shape
(n_windows, window_size * n).n (int) – Number of channels.
- Returns:
Array of shape
(n_windows, number_of_clusters)holding \((X_t - \mu)^\top \Sigma^{-1} (X_t - \mu) + \log\det\Sigma\), twice the negative Gaussian log-likelihood of each complete window \(X_t\) up to a constant.- Return type:
np.ndarray
- Raises:
KeyError – If a state has no covariance yet, i.e. if it had fewer than two windows at the first iteration.
- stack_training_data(Data, n, num_train_points, training_indices)[source]#
Stack the windows of the series.
- Parameters:
- Returns:
Array of shape
(num_train_points, window_size * n): rowiconcatenates the pointstraining_indices[i] + kfork = 0, ..., window_size - 1. Training indices are starts of complete windows; no input observations are replaced with padding.- Return type:
np.ndarray
- train_clusters(cluster_mean_info, cluster_mean_stacked_info, complete_D_train, empirical_covariances, len_train_clusters, n, pool, train_clusters_arr)[source]#
Start the update step of every state with at least two windows.
For each such state, store its mean window, the mean of its last block and the empirical covariance of its windows, then submit to
poolanADMMSolverwith \(\lambda\) =lambda_parameterfor every entry and \(\rho = 1\), run for at most 1000 iterations with tolerances1e-6.- Parameters:
cluster_mean_info (dict) – Mean of the last block of the windows of each state, of shape
(1, n), keyed by(number_of_clusters, state); updated in place.cluster_mean_stacked_info (dict) – Mean window of each state, with the same keys; updated in place.
complete_D_train (np.ndarray) – Stacked windows, of shape
(n_windows, window_size * n).empirical_covariances (dict) – Empirical covariance of the windows of each state; updated in place.
len_train_clusters (dict) – Number of windows of each state.
n (int) – Number of channels.
pool (multiprocessing.pool.Pool or _SerialPool) – Runs the solvers.
train_clusters_arr (dict) – Indices of the windows of each state.
- Returns:
For each state, the result of its solver (an object with a
getmethod), orNonewhen the state has fewer than two windows.- Return type:
- computeBIC(K, T, clustered_points, inverse_covariances, empirical_covariances)[source]#
BIC of the reference implementation, not used by
TiccDetector.- Parameters:
- Returns:
\(k \log T - 2 L\), where \(L\) sums \(\log\det\Theta - \mathrm{tr}(S\Theta)\) over the states of
inverse_covariances, without weighting them by their numbers of windows, and \(k\) adds the number of entries of \(\Theta\) above2e-5in absolute value once for each run of consecutive windows in the same state.- Return type:
- getTrainTestSplit(m, num_blocks, num_stacked, rng=None)[source]#
Compute the training indices for the TICC model.
The training fraction is fixed at 1: with
num_blocks = num_stacked + 1, as TICC calls it, the indices are all of0, ..., m - num_stacked, and the random draw only advancesrng.
- n_free_parameters(theta, window_size, n_channels, threshold=2e-05)[source]#
Number of free entries of a block Toeplitz precision above a threshold.
A symmetric block Toeplitz matrix is defined by its diagonal block \(A^{(0)}\) (symmetric, \(d(d+1)/2\) free entries) and the blocks \(A^{(1)}, \dots, A^{(w-1)}\) below it (\(d^2\) each). The ADMM returns the dense variable of the splitting, whose entries are never exactly zero: an entry counts when its absolute value exceeds
threshold(the threshold ofcomputeBIC).- Parameters:
- Returns:
Number of free entries above the threshold.
- Return type:
- updateClusters(LLE_node_vals, switch_penalty=1)[source]#
Assignment step: the sequence of states of least total cost.
Dynamic programming (Problem (3) of Hallac et al., 2017): a backward pass computes, for each window and state, the least cost of the windows that follow; a forward pass then picks the states. Ties go to the smallest state index.
- Parameters:
LLE_node_vals (np.ndarray) – Cost of each window under each state, of shape
(n_windows, n_states). TICC passes twice the negative log-likelihood up to a constant (seeTICC.smoothen_clusters), not the log-likelihood.switch_penalty (float, default=1) – Cost added each time two consecutive windows are in different states.
- Returns:
State of each window, of shape
(n_windows,), as floats.- Return type:
np.ndarray
- upperToFull(a, eps=0)[source]#
Symmetric matrix from the vector of its upper triangle.
- Parameters:
a (np.ndarray) – Entries on and above the diagonal of a symmetric
n x nmatrix, row by row (the order ofnp.triu_indices(n)), of lengthn * (n + 1) / 2. Modified in place by the thresholding.eps (float, default=0) – Entries of absolute value below
epsare set to 0.
- Returns:
The symmetric matrix, of shape
(n, n).- Return type:
np.ndarray