TS-CP2#

TS-CP² – change point detection with contrastive predictive coding.

Description#

TS-CP² learns temporal representations using a Temporal Convolutional Network (TCN) trained with a contrastive predictive coding (CPC) objective. Pairs of consecutive windows are encoded; if their embeddings are similar the boundary between them is unlikely to be a change point, while dissimilar embeddings signal a regime change.

The contrastive loss (configurable: NCE, debiased CL, focal CL, hard-negative CL) encourages the encoder to capture the distributional structure of each segment. A similarity curve is built from all adjacent-window pairs. A change point lowers the similarity of every pair centred less than one window from it, so one change point is kept per dip: the pair centres are visited from the least similar, and a centre less than one window from a change point already kept is skipped. The candidates are all the centres when the number of change points is given (the first n_cps kept), and the centres below the similarity threshold otherwise.

Type: change point detection
Supervision: unsupervised or semi-supervised
Scope: univariate and multivariate
Complexity: \(O(n\,\ell\,F\,(d + F + \ell)/s)\) per training epoch, where \(\ell\) is window_size, s stride and F nb_filters (kernel size and depth of the TCN fixed): the encoder runs on both windows of the \(n/s\) window pairs, and its first dense layer maps the \(\ell\,F\) outputs of the TCN to about \(\ell\) units (default dense_units). Prediction costs one such pass. On a CPU, the time hardly grows with \(\ell\) up to 128 or with d up to 64, and is about proportional to the number of batches: 5 to 8 s per epoch for 4,000 points (14 cores)
Requires: TensorFlow and tcn

Parameters#

Name

Type

Default

Description

window_size

int

128

Sliding window size for building window pairs.

n_cps

int / None

None

Number of change points, at least one window apart when the series leaves room for them (None = use the similarity threshold).

similarity_threshold

float / None

None

Similarity below which a pair centre is a candidate change point (None = learned by fit and stored in threshold_).

stride

int

5

Step between successive window pairs.

code_size

int

32

Dimension of the learned representation.

nb_filters

int

64

Number of TCN filters.

kernel_size

int

4

TCN kernel size.

dilations

tuple

(1,2,4,8)

Dilation factors for TCN layers.

nb_stacks

int

2

Number of TCN stacks.

dropout_rate

float

0.0

Dropout rate.

batch_size

int

64

Training batch size.

epochs

int

100

Training epochs.

learning_rate

float

1e-3

Optimiser learning rate.

loss

str

"nce"

Contrastive loss ("nce", "dcl", "fc", "harddcl").

temperature

float

0.1

Temperature for contrastive logits.

similarity

str

"cosine"

Similarity function.

random_state

int / None

None

Seed of the weight initialisation, the shuffling of the training windows and the dropout masks (None = a different model at each fit). Reseeds the global Python, NumPy and TensorFlow generators.

axis

int

0

Time axis.

Usage#

from tsseg.algorithms import TSCP2Detector

detector = TSCP2Detector(window_size=128, n_cps=5, epochs=50)
change_points = detector.fit_predict(X)

Implementation: TensorFlow reimplementation adapted from original code by Deldari et al.

Reference: Deldari, Smith, Xue & Salim (2021), Time Series Change Point Detection with Self-Supervised Contrastive Predictive Coding, WWW.

API reference#

TensorFlow reimplementation of the TS-CP2 contrastive change point detector.

class TSCP2Detector(*, window_size=128, n_cps=None, similarity_threshold=None, stride=5, code_size=32, nb_filters=64, kernel_size=4, dilations=(1, 2, 4, 8), nb_stacks=2, dropout_rate=0.0, dense_units=None, batch_size=64, epochs=100, learning_rate=0.001, loss='nce', temperature=0.1, tau=0.1, beta=0.1, similarity='cosine', refit_on_predict=False, random_state=None, axis=0)[source]#

Bases: BaseSegmenter

Time Series Change Point Detection with contrastive predictive coding.

This implementation mirrors the original TensorFlow TS-CP2 reference (Deldari et al., WWW’21, https://doi.org/10.1145/3442381.3449903).

Each window pair (history, future) of 2 * window_size points is encoded by a temporal convolutional network (TCN); the change score at the centre of the pair is one minus the similarity of the two codes.

Parameters:
  • window_size (int) – Length of the history and of the future window. fit needs at least 2 * window_size points. A series of exactly that many points holds a single window pair: fit then trains on windows of window_size // 2 points, with a UserWarning; window_size itself is left unchanged. predict uses the window of fit and needs at least twice as many points, unless refit_on_predict is set (the window is then halved as often as the series requires).

  • n_cps (int | None) – Number of change points: the centres of the window pairs with the highest change score, at least one window apart (see Notes); when the series is too short for n_cps such centres, the highest-scoring closer ones complete the set. Takes precedence over similarity_threshold. 0 returns no change point (the encoder is still trained by fit).

  • similarity_threshold (float | None) – The pair centres whose similarity is below this value are the candidate change points; of those less than one window apart, only the highest-scoring one is kept (see Notes). With neither n_cps nor similarity_threshold, fit learns the threshold from the last training batch, pos - (pos - neg) / 3, with pos and neg the mean similarities of positive and negative pairs, and stores it in threshold_: the parameter stays None, so the next fit (or a clone) learns its own.

  • stride (int) – Step between consecutive window pairs, hence between candidate change points.

  • code_size (int) – Dimension of the learned representation.

  • nb_filters (int) – Number of filters of the TCN.

  • kernel_size (int) – Kernel size of the TCN.

  • dilations (tuple[int, ...] | None) – Dilation factors of the TCN layers; None means (1, 2, 4, 8).

  • nb_stacks (int) – Number of stacks of residual blocks of the TCN.

  • dropout_rate (float) – Dropout rate of the TCN.

  • dense_units (tuple[int, ...] | None) – Units of the ReLU dense layers between the TCN and the final linear projection to code_size. None means (2 * (w // 2), w // 2), with w the window trained on (window_size but on a short series).

  • batch_size (int) – Training batch size; the last incomplete batch is dropped when there are at least batch_size window pairs.

  • epochs (int) – Number of training epochs.

  • learning_rate (float) – Learning rate of the Adam optimiser.

  • loss (str) – Contrastive loss: "nce" or its alias "info_nce" (InfoNCE), "dcl" (debiased), "fc" (focal, which drops the hardest negatives) or "harddcl" (hard negatives).

  • temperature (float) – Temperature of the contrastive loss.

  • tau (float) – Class prior tau_plus of the "dcl" and "harddcl" losses.

  • beta (float) – Weight of the reweighting of the negatives by their similarity in the "harddcl" loss (0: no reweighting); for "fc", the fraction of the hardest negatives that is dropped (clipped to [0, 0.5]).

  • similarity (str) – Similarity of two codes, used by the loss and by the change score: "cosine", "dot", "euclidean" or "edit".

  • refit_on_predict (bool) – Retrain the encoder on X when predict receives a series other than the one seen by fit.

  • random_state (int | None) – Seed of the encoder’s weight initialisation, the shuffling of the training windows and the dropout masks. None gives a different model at each fit. An integer makes fit reproducible on a given machine and TensorFlow build: every fit (including the refit done by refit_on_predict) calls tf.keras.utils.set_random_seed, which reseeds the global Python, NumPy and TensorFlow generators.

  • axis (int) – The time axis of X: 0 if time points are rows.

threshold_#

Similarity threshold used by predict: similarity_threshold when given, else the one learned by fit; None when n_cps is set.

Type:

float or None

Notes

A change point at t lies inside both windows of every pair centred less than one window from t: the change score rises over that whole neighbourhood, not at t alone. One change point is kept per peak: the candidates are visited by decreasing change score, and one less than one window from a change point already kept is skipped. The paper looks for the peaks of the dissimilarity, and the reference code counts each run of consecutive pairs below the threshold as one detection. The window is window_size, or the shorter window that fit trains on when the series is short.

set_fit_request(*, axis='$UNCHANGED$')#

Configure whether metadata should be requested to be passed to the fit 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 fit 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 fit.

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

axis (Union[bool, None, str]) – Metadata routing for axis parameter in fit.

Returns:

self – The updated object.

Return type:

TSCP2Detector

set_predict_request(*, axis='$UNCHANGED$')#

Configure whether metadata should be requested to be passed to the predict 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 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.

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

axis (Union[bool, None, str]) – Metadata routing for axis parameter in predict.

Returns:

self – The updated object.

Return type:

TSCP2Detector

Loss utilities adapted from the original TensorFlow TS-CP2 implementation.

cosine_similarity_dim1(x, y)#

Cosine similarity for aligned pairs (shape: [batch]).

Return type:

Tensor

cosine_similarity_dim2(x, y)#

Cosine similarity matrix between two batches (shape: [batch, batch]).

Return type:

Tensor

cosine_similarity_matrix(x, y)[source]#

Cosine similarity matrix between two batches (shape: [batch, batch]).

Return type:

Tensor

cosine_similarity_vector(x, y)[source]#

Cosine similarity for aligned pairs (shape: [batch]).

Return type:

Tensor

debiased_contrastive_loss(history, future, similarity, *, temperature=0.1, tau_plus=0.1)[source]#

Debiased contrastive loss (DCL).

Return type:

tuple[Tensor, Tensor, Tensor]

dot_similarity_dim1(x, y)#
Return type:

Tensor

dot_similarity_dim2(x, y)#
Return type:

Tensor

dot_similarity_matrix(x, y)[source]#
Return type:

Tensor

dot_similarity_vector(x, y)[source]#
Return type:

Tensor

edit_similarity_dim1(x, y)#
Return type:

Tensor

edit_similarity_dim2(x, y)#
Return type:

Tensor

edit_similarity_matrix(x, y)#
Return type:

Tensor

edit_similarity_vector(x, y)#
Return type:

Tensor

euclidean_similarity_dim1(x, y)#
Return type:

Tensor

euclidean_similarity_dim2(x, y)#
Return type:

Tensor

euclidean_similarity_matrix(x, y)[source]#
Return type:

Tensor

euclidean_similarity_vector(x, y)[source]#
Return type:

Tensor

focal_contrastive_loss(history, future, similarity, *, temperature=0.1, elimination_topk=0.1)[source]#

Focal contrastive loss that removes the hardest negatives.

Return type:

tuple[Tensor, Tensor, Tensor]

hard_contrastive_loss(history, future, similarity, *, temperature=0.1, tau_plus=0.1, beta=0.1)[source]#

Hard negative debiased contrastive loss.

Return type:

tuple[Tensor, Tensor, Tensor]

info_nce_loss(history, future, similarity, *, temperature=0.1)[source]#

InfoNCE loss mirroring the original TensorFlow implementation.

Return type:

tuple[Tensor, Tensor, Tensor]

TensorFlow encoder building blocks for the TS-CP2 detector.

class TemporalEncoder(*, input_features, window_size, code_size, nb_filters=64, kernel_size=4, dilations=(1, 2, 4, 8), nb_stacks=2, dropout_rate=0.0, padding='causal', use_skip_connections=True, dense_units=None)[source]#

Bases: Model

Temporal convolutional encoder mirroring the original TS-CP2 design.

call(inputs, training=False)[source]#
Return type:

Tensor