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.
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)tcnParameters#
Name |
Type |
Default |
Description |
|---|---|---|---|
|
int |
|
Sliding window size for building window pairs. |
|
int / None |
|
Number of change points, at least one window apart when the series
leaves room for them ( |
|
float / None |
|
Similarity below which a pair centre is a candidate change point
( |
|
int |
|
Step between successive window pairs. |
|
int |
|
Dimension of the learned representation. |
|
int |
|
Number of TCN filters. |
|
int |
|
TCN kernel size. |
|
tuple |
|
Dilation factors for TCN layers. |
|
int |
|
Number of TCN stacks. |
|
float |
|
Dropout rate. |
|
int |
|
Training batch size. |
|
int |
|
Training epochs. |
|
float |
|
Optimiser learning rate. |
|
str |
|
Contrastive loss ( |
|
float |
|
Temperature for contrastive logits. |
|
str |
|
Similarity function. |
|
int / None |
|
Seed of the weight initialisation, the shuffling of the training
windows and the dropout masks ( |
|
int |
|
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:
BaseSegmenterTime 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_sizepoints 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.fitneeds at least2 * window_sizepoints. A series of exactly that many points holds a single window pair:fitthen trains on windows ofwindow_size // 2points, with aUserWarning;window_sizeitself is left unchanged.predictuses the window offitand needs at least twice as many points, unlessrefit_on_predictis 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 forn_cpssuch centres, the highest-scoring closer ones complete the set. Takes precedence oversimilarity_threshold.0returns no change point (the encoder is still trained byfit).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 neithern_cpsnorsimilarity_threshold,fitlearns the threshold from the last training batch,pos - (pos - neg) / 3, withposandnegthe mean similarities of positive and negative pairs, and stores it inthreshold_: the parameter staysNone, so the nextfit(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;Nonemeans(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 tocode_size.Nonemeans(2 * (w // 2), w // 2), withwthe window trained on (window_sizebut on a short series).batch_size (
int) – Training batch size; the last incomplete batch is dropped when there are at leastbatch_sizewindow 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 priortau_plusof 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 onXwhenpredictreceives a series other than the one seen byfit.random_state (
int|None) – Seed of the encoder’s weight initialisation, the shuffling of the training windows and the dropout masks.Nonegives a different model at each fit. An integer makesfitreproducible on a given machine and TensorFlow build: every fit (including the refit done byrefit_on_predict) callstf.keras.utils.set_random_seed, which reseeds the global Python, NumPy and TensorFlow generators.axis (
int) – The time axis ofX:0if time points are rows.
- threshold_#
Similarity threshold used by
predict:similarity_thresholdwhen given, else the one learned byfit;Nonewhenn_cpsis set.- Type:
float or None
Notes
A change point at
tlies inside both windows of every pair centred less than one window fromt: the change score rises over that whole neighbourhood, not attalone. 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 iswindow_size, or the shorter window thatfittrains on when the series is short.- 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.
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
- 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
- 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:
ModelTemporal convolutional encoder mirroring the original TS-CP2 design.