tsseg.algorithms.tscp2 package

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 and thresholded (or top-K peaks selected) to produce change points.

Type: change point detection
Supervision: unsupervised or semi-supervised
Scope: univariate and multivariate
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 (None = auto-threshold).

similarity_threshold

float / None

None

Custom similarity threshold for detecting CPs.

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.

axis

int

0

Time axis.

Usage

from tsseg.algorithms import TSCP2Detector

detector = TSCP2Detector(window_size=128, n_cps=5, epochs=50)
labels = 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.

Submodules

tsseg.algorithms.tscp2.detector module

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

class tsseg.algorithms.tscp2.detector.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, 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).

set_fit_request(*, axis: bool | None | str = '$UNCHANGED$') TSCP2Detector

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 (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for axis parameter in fit.

Returns:

self – The updated object.

Return type:

object

set_predict_request(*, axis: bool | None | str = '$UNCHANGED$') TSCP2Detector

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 (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for axis parameter in predict.

Returns:

self – The updated object.

Return type:

object

tsseg.algorithms.tscp2.losses module

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

tsseg.algorithms.tscp2.losses.cosine_similarity_dim1(x, y)

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

Return type:

Tensor

tsseg.algorithms.tscp2.losses.cosine_similarity_dim2(x, y)

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

Return type:

Tensor

tsseg.algorithms.tscp2.losses.cosine_similarity_matrix(x, y)[source]

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

Return type:

Tensor

tsseg.algorithms.tscp2.losses.cosine_similarity_vector(x, y)[source]

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

Return type:

Tensor

tsseg.algorithms.tscp2.losses.debiased_contrastive_loss(history, future, similarity, *, temperature=0.1, tau_plus=0.1)[source]

Debiased contrastive loss (DCL).

Return type:

tuple[Tensor, Tensor, Tensor]

tsseg.algorithms.tscp2.losses.dot_similarity_dim1(x, y)
Return type:

Tensor

tsseg.algorithms.tscp2.losses.dot_similarity_dim2(x, y)
Return type:

Tensor

tsseg.algorithms.tscp2.losses.dot_similarity_matrix(x, y)[source]
Return type:

Tensor

tsseg.algorithms.tscp2.losses.dot_similarity_vector(x, y)[source]
Return type:

Tensor

tsseg.algorithms.tscp2.losses.edit_similarity_dim1(x, y)
Return type:

Tensor

tsseg.algorithms.tscp2.losses.edit_similarity_dim2(x, y)
Return type:

Tensor

tsseg.algorithms.tscp2.losses.edit_similarity_matrix(x, y)
Return type:

Tensor

tsseg.algorithms.tscp2.losses.edit_similarity_vector(x, y)
Return type:

Tensor

tsseg.algorithms.tscp2.losses.euclidean_similarity_dim1(x, y)
Return type:

Tensor

tsseg.algorithms.tscp2.losses.euclidean_similarity_dim2(x, y)
Return type:

Tensor

tsseg.algorithms.tscp2.losses.euclidean_similarity_matrix(x, y)[source]
Return type:

Tensor

tsseg.algorithms.tscp2.losses.euclidean_similarity_vector(x, y)[source]
Return type:

Tensor

tsseg.algorithms.tscp2.losses.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]

tsseg.algorithms.tscp2.losses.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]

tsseg.algorithms.tscp2.losses.info_nce_loss(history, future, similarity, *, temperature=0.1)[source]

InfoNCE loss mirroring the original TensorFlow implementation.

Return type:

tuple[Tensor, Tensor, Tensor]

tsseg.algorithms.tscp2.network module

TensorFlow encoder building blocks for the TS-CP2 detector.

class tsseg.algorithms.tscp2.network.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

Module contents

TensorFlow TSCP2 change point detector.