E2USD#

E2USD – Efficient-yet-Effective Unsupervised State Detection.

Description#

E2USD combines two key ideas for scalable, accurate unsupervised state detection in multivariate time series:

  1. DDEM (Decomposed Dual-view Embedding Module) – a lightweight encoder that compresses sliding windows into low-dimensional representations using FFT-based compression and a decomposed contrastive learning objective.

  2. DPGMM clustering – a Dirichlet Process Gaussian Mixture Model that automatically determines the number of states from the learned embeddings.

A False Negative Cancellation Contrastive Learning method (FNCCLearning) is used to counteract false negatives and produce cluster-friendly embedding spaces.

Each window gets one state, so window_size sets the time resolution: a window that straddles a change point can be embedded next to either of the two segments, not always the one that covers more of it. Keep the window well below the length of the shortest segment; the authors’ experiments use windows of 128 to 512 points. On a 1000-point series of three Gaussian segments of 300, 400 and 300 points, only 5 of the 15 windows of the default 256 points lie inside a single segment, and the adjusted Rand index is 0.45 with n_states=3 (0.28 to 0.52 over five seeds); it is 0.83 to 0.95 with window_size=32, step=32, and 0.90 to 0.91 with the default window when the segments are ten times longer.

Type: state detection
Supervision: unsupervised or semi-supervised
Scope: univariate and multivariate
Complexity: \(O(d\,n\,\ell\log\ell)\) per pass over the sliding windows, where \(\ell\) is window_size
Requires: PyTorch

Parameters#

Name

Type

Default

Description

window_size

int

256

Size of the sliding window; must be even.

step

int

50

Step size of the sliding window.

n_states

int

20

Upper bound on the number of states (DPGMM components).

alpha

float

1e3

Concentration parameter for DPGMM.

batch_size

int

1

No effect: the training set is one sample, the whole series.

nb_steps

int

20

Number of optimisation steps.

lr

float

0.003

Learning rate.

depth

int

1

No effect: the encoder network does not use it.

out_channels

int

4

Number of output channels of the encoder.

reduced_size

int

80

Dimension of the CNN output before the final linear layer.

kernel_size

int

3

Kernel size of the two convolutions; at most min(window_size, 64).

use_gpu

bool / None

None

Run on CUDA device 0 (None: when available).

random_state

int / None

None

Random seed.

axis

int

0

Time axis.

Usage#

from tsseg.algorithms import E2USDDetector

detector = E2USDDetector(window_size=256, n_states=10, nb_steps=20)
states = detector.fit_predict(X)

Implementation: Adapted from AI4CTS/E2Usd. No licence found in original repository. Two parts come from projects with a published licence: the Dataset class from the code of Franceschi et al. (2019), White-Link/UnsupervisedScalableRepresentationLearningTimeSeries, Apache License 2.0, and the moving_avg and series_decomp blocks from thuml/Autoformer, MIT licence. The LICENSE file of tsseg/algorithms/e2usd holds these two licences and covers these parts only.

Reference: Lai, Li, Zhang, Zhao, Qian & Jensen (2024), E2Usd: Efficient-yet-effective Unsupervised State Detection for Multivariate Time Series, Proceedings of the ACM Web Conference 2024 (WWW), pp. 3010–3021, doi:10.1145/3589334.3645593.

API reference#

E2USD state detector: a wrapper around the reference implementation.

class E2USDDetector(*, window_size=256, step=50, n_states=20, alpha=1000.0, batch_size=1, nb_steps=20, lr=0.003, depth=1, out_channels=4, reduced_size=80, kernel_size=3, use_gpu=None, random_state=None, axis=0)[source]#

Bases: BaseSegmenter

E2USD: unsupervised state detection from decomposed window embeddings.

An encoder trained without labels on the series itself maps sliding windows to embeddings; a Dirichlet process Gaussian mixture (DPGMM) clusters the embeddings; each time point then takes the state that most windows covering it received [1].

Parameters:
  • axis (int) – Axis along which to segment if passed a multivariate series (2D input). If axis is 0, it is assumed each column is a time series and each row is a timepoint. i.e. the shape of the data is (n_timepoints,n_channels). axis == 1 indicates the time series are in rows, i.e. the shape of the data is (n_channels, n_timepoints).

  • window_size (int, default=256) – Length of the sliding windows, in time points. Must be even: fit raises ValueError on an odd value. Each window gets one state: keep it well below the length of the shortest segment (see Notes).

  • step (int, default=50) – Distance between the starts of consecutive windows, at most window_size.

  • n_states (int, default=20) – Upper bound on the number of states: the number of components of the DPGMM, capped at the number of windows. The DPGMM can leave components empty, so fewer states may be returned.

  • alpha (float, default=1e3) – Weight concentration prior of the Dirichlet process (weight_concentration_prior of sklearn.mixture.BayesianGaussianMixture); larger values favour more states.

  • batch_size (int, default=1) – Batch size of the training data loader. The training set is a single sample, the whole series, so this value has no effect.

  • nb_steps (int, default=20) – Number of optimisation steps of the encoder.

  • lr (float, default=0.003) – Learning rate of the Adam optimiser.

  • depth (int, default=1) – Passed to the encoder network, which does not use it: this value has no effect.

  • out_channels (int, default=4) – Dimension of the window embeddings.

  • reduced_size (int, default=80) – Number of output channels of each of the two convolutions of the encoder (one for the trend, one for the seasonal part), max-pooled over time before the linear layers.

  • kernel_size (int, default=3) – Kernel size of the two convolutions of the encoder. At most min(window_size, 64), the length of a window after the low-pass filter of the encoder: fit raises ValueError on a larger value.

  • use_gpu (bool, optional) – Whether to run the encoder on CUDA device 0. None uses it when available; True without CUDA falls back to the CPU. The attribute stores the resolved boolean.

  • random_state (int, optional) – Seed of PyTorch and of NumPy’s global generator, set at the start of fit. The DPGMM of predict draws from NumPy’s global generator without its own seed: fit_predict with a seed is reproducible on one machine, but two predict calls after one fit can differ.

Notes

fit and predict z-normalise the series with one mean and one variance computed over all channels together; a series of zero variance is only centred (the reference implementation returns NaN), so a constant series is labelled as one state. fit then trains the encoder for nb_steps steps.

The encoder (DDEM, decomposed dual-view embedding module [1]) keeps the 33 lowest frequencies of the Fourier transform of each window, which resamples a window of 64 points or more to 64 points, then splits it into a trend (moving average over 5 points) and a seasonal part (the residual). Each part goes through its own convolution, a max pooling over time and a linear layer; a last linear layer combines the two. The convolutions keep their random initial weights: only the linear layers are trained. At each step, the loss (FNCC, false negative cancellation contrastive learning [1]) draws 20 random positions and, at each position, 4 windows shifted by one point. It pulls together the embeddings of the windows of a position. Among the pairs of windows from different positions, it pushes apart the half with the lowest product of their trend and seasonal similarities, and leaves out the other half as likely false negatives (windows of the same state). The positions are drawn among the first n_timepoints - 2 * window_size + 1 points, so the last window_size - 3 points never enter a training window.

predict embeds the (n_timepoints - window_size) // step + 1 windows of the series, fits the DPGMM (full covariances, k-means initialisation) on these embeddings and numbers the window labels in order of first appearance. Each window votes for its label on the points it covers, and each point takes the label with the most votes (the smallest label on a tie). The last points of the series, fewer than step, lie in no window: they take the label of the last window (the reference implementation gives them label 0).

Each window gets one label, so window_size sets the time resolution: only the windows that lie inside a segment see it alone, and the encoder can embed a window that straddles a change point next to either of the two segments, not always the one that covers more of it. The window should be well below the length of the shortest segment; the authors’ experiments use windows of 128 to 512 points. On a series of 1000 points made of three Gaussian segments of 300, 400 and 300 points, 5 of the 15 windows of the default 256 points lie inside a single segment, and the adjusted Rand index is 0.45 with n_states=3 and random_state=0 (0.28 to 0.52 over five seeds). Labelling each window with the segment that covers most of it would give 0.96 after the vote: what fails is the embedding of the windows that straddle a change point. The index is 0.83 to 0.95 over five seeds with window_size=32, step=32, and 0.90 to 0.91 with the default window when the three segments are ten times longer; more training (nb_steps=200) does not raise it.

fit raises ValueError on a series of fewer than 2 * window_size points; predict labels every point of such a series 0. y is ignored.

The wrapped code is that of the reference implementation (AI4CTS/E2Usd), which publishes no licence. Its Dataset class comes from the code of Franceschi et al. (2019) (Apache License 2.0) and its moving_avg and series_decomp blocks from Autoformer (MIT licence); the LICENSE file of tsseg/algorithms/e2usd holds these two licences and covers these parts only.

References

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:

E2USDDetector

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:

E2USDDetector

E2USD encoder, loss and clustering, from the reference implementation.

Taken from AI4CTS/E2Usd, which publishes no licence: the modules of its E2USD package are merged here, unchanged except where a docstring or a comment says otherwise. Dataset comes from the code of Franceschi et al. (2019), White-Link/UnsupervisedScalableRepresentationLearningTimeSeries (Apache License 2.0), and moving_avg and series_decomp from Autoformer, thuml/Autoformer (MIT licence); their licences, the NOTICE of Franceschi et al. and the changes made to their code are in LICENSE, in this directory. Public entry point: tsseg.algorithms.E2USDDetector, which uses E2USD_Adaper, DPGMM and E2USD.

Tensors and arrays follow the PyTorch layout (batch, channels, length), except where a docstring says otherwise.

class BasicClusteringClass(params)[source]#

Bases: object

Interface of the clustering step of E2USD.

abc.abstractmethod is not enforced: the class has no ABCMeta metaclass.

Parameters:

params (object) – Ignored.

abstractmethod fit(X)[source]#

Cluster the rows of X; does nothing here.

Parameters:

X (np.ndarray of shape (n_samples, n_features)) – The samples to cluster.

Returns:

Subclasses return the label of each row, an np.ndarray of shape (n_samples,).

Return type:

None

class BasicEncoder[source]#

Bases: object

Base class of DDEM, whose methods do nothing.

encode(X)[source]#

Do nothing (overridden by DDEM.encode()).

load(X)[source]#

Do nothing.

save(X)[source]#

Do nothing.

class BasicEncoderClass(params)[source]#

Bases: object

Interface of the encoders used by E2USD.

The constructor hands params to _set_parmas (spelling of the reference code), which subclasses implement to build the encoder. abc.abstractmethod is not enforced: the class has no ABCMeta metaclass.

Parameters:

params (dict) – Hyperparameters of the encoder.

abstractmethod encode(X, win_size, step)[source]#

Embed the sliding windows of X; does nothing here.

Parameters:
  • X (np.ndarray of shape (n_timepoints, n_channels)) – The series.

  • win_size (int) – Length of the windows.

  • step (int) – Distance between the starts of consecutive windows.

Returns:

Subclasses return one embedding per window, an np.ndarray of shape (n_windows, n_features).

Return type:

None

abstractmethod fit(X)[source]#

Train the encoder on the series X; does nothing here.

Parameters:

X (np.ndarray of shape (n_timepoints, n_channels)) – The training series.

class DDEM(win_size, batch_size, nb_steps, lr, channels, depth, reduced_size, out_channels, kernel_size, in_channels, cuda, gpu, M, N, win_type)[source]#

Bases: BasicEncoder

Encoder of E2USD: trains a NetworkDDEM and embeds windows.

Parameters:
  • win_size (int) – Length of the training windows of the loss.

  • batch_size (int) – Batch size of the training data loader. Training uses a single sample, the whole series, so this value has no effect.

  • nb_steps (int) – Number of optimisation steps.

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

  • channels (int) – Unused (passed to NetworkDDEM, which ignores it).

  • depth (int) – Unused (passed to NetworkDDEM, which ignores it).

  • reduced_size (int) – Number of output channels of the two convolutions of the network.

  • out_channels (int) – Dimension of the embeddings.

  • kernel_size (int) – Kernel size of the two convolutions of the network.

  • in_channels (int) – Number of channels of the series.

  • cuda (bool) – Whether to run on a CUDA device.

  • gpu (int) – Index of that device.

  • M (int) – Number of random positions of each step of the loss.

  • N (int) – Number of windows at each position.

  • win_type (str) – Stored, unused.

network#

The network, in double precision.

Type:

NetworkDDEM

loss#

The training loss.

Type:

fncc_loss

optimizer#

Optimiser of the trainable parameters of the network, those of its linear layers.

Type:

torch.optim.Adam

loss_list#

Empty, never filled.

Type:

list

encode(X, batch_size=500)[source]#

Embed a set of windows, without gradients.

The network is put in evaluation mode. The reference code prints the shape of X here; this copy does not.

Parameters:
  • X (np.ndarray of shape (n_windows, in_channels, length)) – The windows, in float64, without NaN: with NaN the data loader uses batches of one window, but the rows of the result are still indexed by batches of batch_size.

  • batch_size (int, default=500) – Number of windows embedded at once.

Returns:

The embeddings.

Return type:

np.ndarray of shape (n_windows, out_channels)

encode_window(X, win_size=128, batch_size=500, window_batch_size=10000, step=10)[source]#

Embed the sliding windows of a series.

Parameters:
  • X (np.ndarray of shape (n_series, in_channels, n_timepoints)) – The series, in float64.

  • win_size (int, default=128) – Length of the windows.

  • batch_size (int, default=500) – Passed to encode().

  • window_batch_size (int, default=10000) – Number of windows cut out of the series at once.

  • step (int, default=10) – Distance between the starts of consecutive windows.

Returns:

The embeddings of the (n_timepoints - win_size) // step + 1 windows of the first series, starting at 0, step, 2 * step, and so on. The other series are embedded, then dropped.

Return type:

np.ndarray of shape (n_windows, out_channels)

fit(X, save_memory=False, verbose=False)[source]#

Train the network for nb_steps steps.

Each step evaluates the loss on random windows of the series (see fncc_loss) and updates the linear layers.

Parameters:
  • X (np.ndarray of shape (1, in_channels, n_timepoints)) – The training series, in float64, with n_timepoints at least 2 * win_size.

  • save_memory (bool, default=False) – Unused.

  • verbose (bool, default=False) – Unused.

Returns:

The trained network.

Return type:

NetworkDDEM

set_params(compared_length, batch_size, nb_steps, lr, channels, depth, reduced_size, out_channels, kernel_size, in_channels, cuda, gpu)[source]#

Rebuild the encoder with new hyperparameters (broken).

Calls __init__ with 12 positional arguments, compared_length in the place of win_size, whereas it requires 15: any call raises TypeError (M, N and win_type are missing), as in the reference code.

Parameters:
  • compared_length (int) – The win_size of the class.

  • batch_size – As the parameters of the class.

  • nb_steps – As the parameters of the class.

  • lr – As the parameters of the class.

  • channels – As the parameters of the class.

  • depth – As the parameters of the class.

  • reduced_size – As the parameters of the class.

  • out_channels – As the parameters of the class.

  • kernel_size – As the parameters of the class.

  • in_channels – As the parameters of the class.

  • cuda – As the parameters of the class.

  • gpu – As the parameters of the class.

Returns:

self, if the call succeeded.

Return type:

DDEM

class DPGMM(n_states, alpha=1000.0)[source]#

Bases: BasicClusteringClass

Dirichlet process Gaussian mixture on the window embeddings.

Parameters:
  • n_states (int or None) – Number of components of the mixture, an upper bound on the number of clusters; None means 20.

  • alpha (float, default=1e3) – Weight concentration prior of the Dirichlet process (weight_concentration_prior of sklearn.mixture.BayesianGaussianMixture).

fit(X)[source]#

Fit the mixture on X and return the component of each row.

sklearn.mixture.BayesianGaussianMixture with full covariances, k-means initialisation, a Dirichlet process prior and at most 1000 iterations; it has no random_state, so it draws from NumPy’s global generator. Changes from the reference code: the number of components is capped at the number of rows, and an empty X gives an empty result.

Parameters:

X (array-like of shape (n_samples, n_features) or (n_samples,)) – The samples, without NaN (ValueError otherwise).

Returns:

The component of each sample, not renumbered: the values can skip integers.

Return type:

np.ndarray of shape (n_samples,)

class Dataset(*args: Any, **kwargs: Any)[source]#

Bases: Dataset

PyTorch dataset whose samples are the entries of an array.

Parameters:

dataset (np.ndarray) – The samples, along the first axis: dataset[i] is sample i.

class E2USD(win_size, step, encoder, clustering_component, verbose=False)[source]#

Bases: object

E2USD pipeline: embed sliding windows, cluster them, vote per point.

Parameters:
  • win_size (int) – Length of the windows, as voted on. Must be even: each window votes with a vector of 2 * (win_size // 2) ones, so an odd value raises ValueError when the labels are assigned.

  • step (int) – Distance between the starts of consecutive windows, as voted on.

  • encoder (BasicEncoderClass) – Object with fit(X) and encode(X, win_size, step), such as E2USD_Adaper.

  • clustering_component (BasicClusteringClass) – Object with fit(embeddings) that returns one label per window, such as DPGMM.

  • verbose (bool, default=False) – Unused.

Notes

The window labels are renumbered from 0 in order of first appearance. Each window adds one vote for its label to each point it covers, and each point takes the label with the most votes (the smallest label on a tie). Change from the reference code: the points after the last window, fewer than step, take the label of the last window instead of 0.

property change_points#

reading it raises AttributeError.

Type:

Never set

property embedding_label#

Label of each window, numbered from 0 in order of first appearance.

np.ndarray of shape (n_windows,).

property embeddings#

Embeddings of the windows of the last series encoded.

np.ndarray of shape (n_windows, out_channels).

fit(X, win_size, step)[source]#

Train the encoder on X, then label its points.

Parameters:
  • X (np.ndarray of shape (n_timepoints, n_channels)) – The series.

  • win_size (int) – Length of the windows embedded. The votes use the win_size of the constructor: the two should be equal.

  • step (int) – Distance between the windows embedded. The votes use the step of the constructor (or of set_step()): the two should be equal.

Returns:

self; the labels are in state_seq.

Return type:

E2USD

fit_encoder(X)[source]#

Train the encoder on X only.

Parameters:

X (np.ndarray of shape (n_timepoints, n_channels)) – The series.

Returns:

self.

Return type:

E2USD

load_encoder()[source]#

Do nothing.

load_result(path)[source]#

Do nothing; path is unused.

plot(path)[source]#

Do nothing; path is unused.

predict(X, win_size, step)[source]#

Label the points of X with the encoder as it is.

Parameters:
  • X (np.ndarray of shape (n_timepoints, n_channels)) – The series.

  • win_size (int) – Length of the windows embedded. The votes use the win_size of the constructor: the two should be equal.

  • step (int) – Distance between the windows, for the embedding and the votes.

Returns:

self; the labels are in state_seq.

Return type:

E2USD

predict_without_encode(X, win_size, step)[source]#

Cluster the embeddings of the last series encoded and vote again.

Raises AttributeError if no series was encoded.

Parameters:
  • X – Unused.

  • win_size – Unused.

  • step – Unused.

Returns:

self.

Return type:

E2USD

save_encoder()[source]#

Do nothing.

save_result(path)[source]#

Do nothing; path is unused.

set_clustering_component(clustering_obj)[source]#

Replace the clustering component.

Parameters:

clustering_obj (BasicClusteringClass) – The new clustering component.

Returns:

self.

Return type:

E2USD

set_step(step)[source]#

Set the step used by the votes.

Parameters:

step (int) – Distance between the starts of consecutive windows.

property state_seq#

Label of each point of the last series labelled, after the votes.

np.ndarray of shape (n_timepoints,).

property velocity#

reading it raises AttributeError.

Type:

Never set

class E2USD_Adaper(params)[source]#

Bases: BasicEncoderClass

Adapter that gives a DDEM the interface used by E2USD.

The class name keeps the spelling of the reference code.

Parameters:

params (dict) – Keyword arguments of DDEM, such as params. A "compared_length" key is removed from the dict itself.

hyperparameters#

params.

Type:

dict

encoder#

The encoder.

Type:

DDEM

encode(X, win_size, step)[source]#

Normalise a series with all_normalize() and embed its windows.

Parameters:
  • X (np.ndarray of shape (n_timepoints, n_channels)) – The series.

  • win_size (int) – Length of the windows.

  • step (int) – Distance between the starts of consecutive windows.

Returns:

The embeddings of the (n_timepoints - win_size) // step + 1 windows (see DDEM.encode_window()).

Return type:

np.ndarray of shape (n_windows, out_channels)

encode_one(X, win_size, step)[source]#

Same as encode().

Parameters:
  • X (np.ndarray of shape (n_timepoints, n_channels)) – The series.

  • win_size (int) – Length of the windows.

  • step (int) – Distance between the starts of consecutive windows.

Returns:

The embeddings of the windows.

Return type:

np.ndarray of shape (n_windows, out_channels)

fit(X)[source]#

Normalise a series with all_normalize() and train the encoder.

Parameters:

X (np.ndarray of shape (n_timepoints, n_channels)) – The training series, with n_timepoints at least twice the win_size of the encoder.

class NetworkDDEM(*args: Any, **kwargs: Any)[source]#

Bases: Module

Decomposed dual-view embedding network (DDEM) of E2USD.

Named DDEM in the reference code (networks/network.py); renamed here, where DDEM is the encoder that trains it.

Parameters:
  • in_channels (int) – Number of channels of the series.

  • channels (int) – Unused.

  • depth (int) – Unused.

  • reduced_size (int) – Number of output channels of each of the two convolutions.

  • out_channels (int) – Dimension of the embeddings.

  • kernel_size (int) – Kernel size of the two convolutions, at most the length of a window after the low-pass filter (see Notes).

Notes

The forward pass keeps the trade_off_freq = 33 lowest frequencies of the real Fourier transform of each window and transforms back without a target length, scaling by 33 / length: a window of length >= 64 points becomes 64 points; a shorter one keeps its length if even, and loses one point if odd. series_decomp with a moving average over 5 points splits it into a trend and a seasonal part (the residual). Each part goes through its own Conv1d (in_channels to reduced_size channels, no padding), a max pooling over time and a linear layer to out_channels; a last linear layer maps the two concatenated embeddings to out_channels. The two convolutions are frozen (requires_grad_(False)) at their random initial weights: only the linear layers are trained.

forward(x)[source]#

Embed a batch of windows.

Parameters:

x (torch.Tensor of shape (batch, in_channels, length)) – The windows.

Returns:

  • embedding (torch.Tensor of shape (batch, out_channels)) – The embeddings of the windows.

  • trend_x_embedding (torch.Tensor of shape (batch, out_channels)) – The embeddings of their trends.

  • seasonal_x_embedding (torch.Tensor of shape (batch, out_channels)) – The embeddings of their seasonal parts.

add_noise(data, mean=0, std=0.05)[source]#

Add Gaussian noise: data augmentation of the reference code, unused.

Parameters:
  • data (torch.Tensor) – The values.

  • mean (float, default=0) – Mean of the noise.

  • std (float, default=0.05) – Standard deviation of the noise, drawn from PyTorch’s global generator.

Returns:

data plus the noise, as a new tensor.

Return type:

torch.Tensor

all_normalize(data_tensor)[source]#

Z-normalise a series with one mean and one variance for all channels.

Parameters:

data_tensor (np.ndarray of shape (1, n_channels, n_timepoints)) – The series, normalised in place. The mean and the variance are those of all its values; a series of zero variance is only centred (the reference implementation divides by zero and returns NaN).

Returns:

data_tensor itself.

Return type:

np.ndarray

apply_scaling(data, mean=1.0, std=0.1)[source]#

Multiply by Gaussian factors: data augmentation of the reference code, unused.

Parameters:
  • data (torch.Tensor) – The values.

  • mean (float, default=1.0) – Mean of the factors.

  • std (float, default=0.1) – Standard deviation of the factors, drawn from PyTorch’s global generator.

Returns:

data times the factors, as a new tensor.

Return type:

torch.Tensor

compact(series)[source]#

Collapse each run of equal consecutive values into one value.

Parameters:

series (sequence) – A non-empty sequence of comparable values.

Returns:

The value of each run, in order: [3, 3, 1, 1, 3] gives [3, 1, 3].

Return type:

list

class fncc_loss(*args: Any, **kwargs: Any)[source]#

Bases: _Loss

False negative cancellation contrastive loss (FNCC) of E2USD.

Parameters:
  • win_size (int) – Length of the windows.

  • M (int) – Number of random positions drawn at each call.

  • N (int) – Number of windows at each position, shifted by one point.

  • win_type (str) – Stored, unused.

Notes

Each call draws M positions p uniformly in [0, length - 2 * win_size] from NumPy’s global generator and embeds, at each, the N windows starting at p, ..., p + N - 1. The first term is the mean, over the pairs of windows of the same position, of -log(sigmoid(<e_i, e_j>)), which pulls their embeddings together. For each pair of windows from two different positions, the product of the dot products of their trend and of their seasonal embeddings measures their similarity; the second term is the sum of the dot products <e_i, e_j> over the half of these pairs with the lowest similarity, divided by half the number of pairs (their mean when that number is even), which pushes them apart. The loss is the sum of the two terms. The other half, the pairs most likely to come from the same state (false negatives), is left out. The attributes total and total_condition are unused.

forward(batch, encoder, save_memory=False)[source]#

Compute the loss on random windows of a series.

Parameters:
  • batch (torch.Tensor of shape (batch, n_channels, length)) – The series; only batch[0] is used. length must be at least 2 * win_size.

  • encoder (torch.nn.Module) – The network that embeds the windows, such as NetworkDDEM: it returns the embeddings and the trend and seasonal embeddings.

  • save_memory (bool, default=False) – Unused.

Returns:

The loss, a scalar.

Return type:

torch.Tensor

class moving_avg(*args: Any, **kwargs: Any)[source]#

Bases: Module

Moving average along the last axis, with the edge values repeated.

Parameters:
  • kernel_size (int) – Number of points averaged.

  • stride (int) – Distance between the starts of consecutive averages.

forward(x)[source]#

Pad each end of x with its edge value, then average.

Each end gets (kernel_size - 1) // 2 copies of its edge value.

Parameters:

x (torch.Tensor of shape (batch, channels, length)) – The series.

Returns:

The averages. With stride=1 and an odd kernel_size, n_averages is length.

Return type:

torch.Tensor of shape (batch, channels, n_averages)

params = {'M': 20, 'N': 4, 'batch_size': 1, 'channels': 30, 'cuda': False, 'depth': 1, 'gpu': 0, 'in_channels': 1, 'kernel_size': 3, 'lr': 0.003, 'nb_steps': 20, 'out_channels': 4, 'reduced_size': 80, 'win_size': 256, 'win_type': 'rect'}#

Default hyperparameters of DDEM, keyed by its argument names. E2USDDetector overrides all of them but channels (30) and win_type ("rect"), which have no effect, M (20) and N (4).

remove_duplication(series)[source]#

Distinct values of a sequence, in order of first appearance.

Parameters:

series (sequence) – The values.

Returns:

Each value once: [3, 3, 1, 1, 3, 2] gives [3, 1, 2].

Return type:

list

reorder_label(label)[source]#

Renumber labels from 0 in order of first appearance.

Parameters:

label (array-like of int, shape (n,)) – The labels, non-empty.

Returns:

A copy of label where the first label is 0, the next new one 1, and so on: [3, 3, 1, 1, 3, 2] gives [0, 0, 1, 1, 0, 2].

Return type:

np.ndarray of shape (n,)

class series_decomp(*args: Any, **kwargs: Any)[source]#

Bases: Module

Split a series into a trend, its moving average, and the residual.

Parameters:

kernel_size (int) – Number of points of the moving average; odd, for the trend to have the length of the series.

forward(x)[source]#

Decompose x.

Parameters:

x (torch.Tensor of shape (batch, channels, length)) – The series.

Returns:

  • res (torch.Tensor of shape (batch, channels, length)) – The residual x - moving_mean (the seasonal part).

  • moving_mean (torch.Tensor of shape (batch, channels, length)) – The moving average of x (the trend).