Time2State#
Time2State – unsupervised latent state inference.
Description#
Time2State infers latent states in time series data using a Causal CNN-based encoder and a novel unsupervised loss function (LSE-Loss). A sliding window extracts subsequences; the encoder maps them to a low-dimensional latent space where a Dirichlet Process Gaussian Mixture Model (DPGMM) clusters the embeddings into states without requiring the number of states a priori.
The framework drastically reduces computational cost compared to operating on raw time series by compressing the representation before clustering.
Each window gets one state, so window_size sets the time resolution, and
the encoder does not always embed a window that straddles a change point next
to the segment 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.22 to 0.40 over five seeds
with n_states=3. Labelling each window with the segment that covers most
of it would give 0.96: what fails is the embedding of the windows that
straddle a change point. The index is 0.90 to 0.95 with
window_size=32, step=32, and 0.91 to 0.92 with the default window when
the segments are ten times longer.
window_sizeParameters#
Name |
Type |
Default |
Description |
|---|---|---|---|
|
int |
|
Sliding window size; must be even. |
|
int |
|
Step size of the sliding window. |
|
int |
|
Upper bound on the number of states (DPGMM components). |
|
float |
|
DPGMM concentration parameter. |
|
int |
|
No effect: the training set is one sample, the whole series. |
|
int |
|
Training optimisation steps. |
|
float |
|
Learning rate. |
|
int |
|
Depth of the Causal CNN. |
|
int |
|
Encoder output channels. |
|
int |
|
CNN output dimension before the linear layer. |
|
int |
|
Convolution kernel size; at least 2. |
|
bool / None |
|
Run on CUDA device 0 ( |
|
int / None |
|
Random seed. |
|
int |
|
Time axis. |
Usage#
from tsseg.algorithms import Time2StateDetector
detector = Time2StateDetector(window_size=128, n_states=10)
states = detector.fit_predict(X)
Implementation: Adapted from Lab-ANT/Time2State, MIT licence. Its causal CNN encoder
and Dataset class come from the code of Franceschi et al. (2019),
White-Link/UnsupervisedScalableRepresentationLearningTimeSeries,
Apache License 2.0, and partly from locuslab/TCN, MIT licence. The LICENSE file of
tsseg/algorithms/time2state holds the three licences.
Reference: Wang, Wu, Zhou & Cai (2023), Time2State: An Unsupervised Framework for Inferring the Latent States in Time Series Data, SIGMOD.
API reference#
Time2State state detector: a wrapper around the reference implementation.
- class Time2StateDetector(*, window_size=256, step=50, n_states=20, alpha=1000.0, batch_size=1, nb_steps=20, lr=0.003, depth=10, out_channels=4, reduced_size=80, kernel_size=3, use_gpu=None, random_state=None, axis=0)[source]#
Bases:
BaseSegmenterTime2State: unsupervised state detection from learned window embeddings.
A causal CNN encoder, trained without labels on the series itself with the LSE loss, 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 == 1indicates 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:
fitraisesValueErroron 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_priorofsklearn.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=10) – Number of causal convolution blocks before the last one; the dilation doubles from one block to the next.
out_channels (int, default=4) – Dimension of the window embeddings.
reduced_size (int, default=80) – Number of channels output by the causal CNN, max-pooled over time before the final linear layer.
kernel_size (int, default=3) – Kernel size of the convolutions of the causal CNN. Must be at least 2:
fitraisesValueErroron 1.use_gpu (bool, optional) – Whether to run the encoder on CUDA device 0.
Noneuses it when available;Truewithout 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 ofpredictdraws from NumPy’s global generator without its own seed:fit_predictwith a seed is reproducible on one machine, but twopredictcalls after onefitcan differ.
Notes
fitandpredictz-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.fitthen trains the encoder fornb_stepssteps. At each step, the LSE loss draws 10 random positions and, at each position, 4 windows shifted by one point; it pulls the embeddings of the windows of a position together and pushes the mean embeddings of different positions apart [1]. As in the reference implementation, the positions are drawn among the firstn_timepoints - 2 * window_size + 1points, so the lastwindow_size - 3points of the series lie in no training window.predictembeds the(n_timepoints - window_size) // step + 1windows 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 thanstep, 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_sizesets the time resolution: only the windows that lie inside a segment see it alone, and the encoder does not always embed a window that straddles a change point next to the segment 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.22 withn_states=3andrandom_state=0(0.22 to 0.40 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. Withrandom_state=0, the windows that straddle the first change point share the state of the third segment, whose mean lies between those of the first two, and those that straddle the second get the state of the second segment, even where the third covers 80% of them. The index is 0.90 to 0.95 over five seeds withwindow_size=32, step=32, and 0.91 to 0.92 with the default window when the three segments are ten times longer.fitraisesValueErroron a series of fewer than2 * window_sizepoints. A series of at most2 * window_sizepoints is not encoded: if it is the one given tofit, or the one given topredict,predictlabels every point 0.The wrapped code is that of the reference implementation (Lab-ANT/Time2State, MIT licence), whose causal CNN encoder comes from the code of Franceschi et al. (2019) (Apache License 2.0, partly from locuslab/TCN, MIT licence); the
LICENSEfile oftsseg/algorithms/time2stateholds the three licences.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.
Time2State encoder, loss and clustering, from the reference implementation.
Taken from Lab-ANT/Time2State (MIT licence). The causal
CNN encoder (Chomp1d to CausalCNNEncoder) and
Dataset come from the code of Franceschi et al. (2019),
White-Link/UnsupervisedScalableRepresentationLearningTimeSeries,
on which Time2State builds (Apache License 2.0); Chomp1d and
CausalConvolutionBlock are there partly taken from
locuslab/TCN (MIT licence). The three 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.Time2StateDetector, which uses
CausalConv_LSE_Adaper, DPGMM and Time2State.
Tensors and arrays follow the PyTorch layout (batch, channels, length),
except where a docstring says otherwise.
- class BasicClusteringClass(params)[source]#
Bases:
objectInterface of the clustering component of
Time2State.- Parameters:
params (object) – Ignored.
- class BasicEncoder[source]#
Bases:
objectBase class of
CausalConv_LSE; its methods do nothing.- encode(X)[source]#
Do nothing; overridden by
CausalConv_LSE.encode().
- class BasicEncoderClass(params)[source]#
Bases:
objectInterface of the encoder component of
Time2State.- Parameters:
params (dict) – Hyperparameters, passed to
_set_parmas.
- class CausalCNN(*args: Any, **kwargs: Any)[source]#
Bases:
ModuleCausal CNN, composed of a sequence of causal convolution blocks.
Takes as input a three-dimensional tensor (B, C, L) where B is the batch size, C is the number of input channels, and L is the length of the input. Outputs a three-dimensional tensor (B, C_out, L).
- Parameters:
in_channels (int) – Number of input channels.
channels (int) – Number of channels output by each of the first
depthblocks.depth (int) – Number of blocks before the last one, of dilations 1, 2, …,
2 ** (depth - 1); the last block has dilation2 ** depth.out_channels (int) – Number of output channels (C_out), those of the last block.
kernel_size (int) – Kernel size of the applied non-residual convolutions.
- class CausalCNNEncoder(*args: Any, **kwargs: Any)[source]#
Bases:
ModuleEncoder of a time series using a causal CNN: the computed representation is the output of a fully connected layer applied to the output of an adaptive max pooling layer applied on top of the causal CNN, which reduces the length of the time series to one (a maximum over time per channel).
Takes as input a three-dimensional tensor (B, C, L) where B is the batch size, C is the number of input channels, and L is the length of the input. Outputs a two-dimensional tensor (B,
out_channels).- Parameters:
in_channels (int) – Number of input channels.
channels (int) – Number of channels manipulated in the causal CNN.
reduced_size (int) – Number of channels output by the causal CNN, hence the input size of the fully connected layer. The source docstring described it as the length kept by the pooling layer, which always keeps one step.
out_channels (int) – Dimension of the representation.
kernel_size (int) – Kernel size of the applied non-residual convolutions.
- class CausalConv_LSE(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:
BasicEncoderCausal CNN encoder trained with the LSE loss.
The network is a
CausalCNNEncoderin double precision, on CUDA devicegpuifcudais true, optimised by Adam.- Parameters:
batch_size (int) – Batch size of the training data loader.
nb_steps (int) – Number of optimisation steps.
lr (float) – Learning rate of Adam.
channels (int) – Number of channels of the hidden causal convolution blocks.
reduced_size (int) – Number of channels output by the causal CNN.
out_channels (int) – Dimension of the embeddings.
kernel_size (int) – Kernel size of the convolutions, at least 2.
in_channels (int) – Number of channels of the series.
cuda (bool) – Whether to run on a CUDA device.
gpu (int) – Index of the CUDA device.
M (int) – Numbers of positions and of windows per position of
LSELoss.N (int) – Numbers of positions and of windows per position of
LSELoss.win_type ({"rect", "hanning"}) – Taper of the windows (see
LSELossandencode_window()).
- encode(X, batch_size=500)[source]#
Outputs the representations associated to the input by the encoder.
- Parameters:
X (numpy.ndarray of shape (n_windows, channels, length)) – Testing set.
batch_size (int, default=500) – Size of batches used for splitting the test data to avoid out of memory errors when using CUDA. Ignored if the testing set contains time series of unequal lengths.
- Returns:
One representation per input series.
- Return type:
numpy.ndarray of shape (n_windows, out_channels)
- encode_window(X, win_size=128, batch_size=500, window_batch_size=10000, step=10)[source]#
Outputs the representations associated to the input by the encoder, for each subseries of the input of the given size (sliding window representations).
- Parameters:
X (numpy.ndarray) – Testing set.
win_size (int, default=128) – Size of the sliding window.
batch_size (int, default=500) – Size of batches used for splitting the test data to avoid out-of-memory errors when using CUDA.
window_batch_size (int, default=10000) – Number of windows processed per batch when calling
encodeto save RAM.step (int, default=10) – Step length of the sliding window.
- Returns:
Representations of the windows of the first series of
X, which start at0, step, ..., (n_windows - 1) * step, withn_windows = (length - win_size) // step + 1. Withwin_type="hanning", the windows are tapered first.- Return type:
numpy.ndarray of shape (n_windows, out_channels)
- fit(X, y=None, save_memory=False, verbose=False)[source]#
Train the network for
nb_stepssteps of the LSE loss.- Parameters:
X (np.ndarray of shape (n_series, channels, length)) – Training series, iterated over in shuffled batches until
nb_stepssteps are done; the loss uses the first series of each batch.Time2Statepasses a single series.y (None) – Not used.
save_memory (bool, default=False) – Passed to the loss, which ignores it.
verbose (bool, default=False) – Print the epoch number at the start of each epoch.
- Returns:
The trained network.
- Return type:
torch.nn.Module
- set_params(compared_length, batch_size, nb_steps, lr, channels, depth, reduced_size, out_channels, kernel_size, in_channels, cuda, gpu)[source]#
Re-initialise the encoder (broken, unused by tsseg).
Calls
__init__without itsM,Nandwin_typearguments, so it raisesTypeError. Kept as in the source.
- class CausalConv_LSE_Adaper(params)[source]#
Bases:
BasicEncoderClassAdapter from time-major arrays to
CausalConv_LSE.Both methods take a series of shape (n_timepoints, n_channels), convert it to float, reshape it to (1, n_channels, n_timepoints) and z-normalise it with the mean and the variance of all its values (one pair for all channels; a constant series gives NaN).
- Parameters:
params (dict) – Keyword arguments of
CausalConv_LSE(seeparams_LSE).
- class CausalConvolutionBlock(*args: Any, **kwargs: Any)[source]#
Bases:
ModuleCausal convolution block, composed sequentially of two causal convolutions (with leaky ReLU activation functions), and a parallel residual connection.
Takes as input a three-dimensional tensor (B, C, L) where B is the batch size, C is the number of input channels, and L is the length of the input. Outputs a three-dimensional tensor (B, C_out, L), where C_out is
out_channels.- Parameters:
in_channels (int) – Number of input channels.
out_channels (int) – Number of output channels.
kernel_size (int) – Kernel size of the applied non-residual convolutions. With
kernel_size=1, the causal truncation removes every time step and the block fails.dilation (int) – Dilation parameter of non-residual convolutions.
final (bool, default=False) – If
True, adds a leaky ReLU after the sum of the two branches. The source docstring said the opposite (“disables the last activation”).
- class Chomp1d(*args: Any, **kwargs: Any)[source]#
Bases:
ModuleRemoves the last elements of a time series.
Takes as input a three-dimensional tensor (B, C, L) where B is the batch size, C is the number of input channels, and L is the length of the input. Outputs a three-dimensional tensor (B, C, L - s) where s is the number of elements to remove.
- Parameters:
chomp_size (int) – Number of elements to remove.
- class DPGMM(n_states, alpha=1000.0)[source]#
Bases:
BasicClusteringClassDirichlet process Gaussian mixture on the window embeddings.
- Parameters:
- fit(X)[source]#
Fit a new mixture to
Xand return the component of each row.Uses
sklearn.mixture.BayesianGaussianMixturewithmin(n_states, n_windows)components, full covariances, k-means initialisation, a Dirichlet process prior of concentrationalpha, at most 1000 iterations and norandom_state(NumPy’s global generator).- Parameters:
X (np.ndarray of shape (n_windows, n_features)) – Window embeddings.
- Returns:
Index of the most probable component of each row. Indices need not be contiguous.
- Return type:
np.ndarray of shape (n_windows,)
- class Dataset(*args: Any, **kwargs: Any)[source]#
Bases:
DatasetPyTorch wrapper for a numpy dataset.
- Parameters:
dataset (numpy.ndarray) – Array representing the dataset.
- class LSELoss(*args: Any, **kwargs: Any)[source]#
Bases:
_LossLSE loss (latent state encoding) of Time2State.
At each call, the loss draws
Mrandom positions in the series and, at each position,Nwindows ofwin_sizepoints shifted by one point. Windows of the same position are assumed to share a state: the loss pulls their embeddings together (-log sigmoidof their dot products) and pushes the mean embeddings of different positions apart (-log sigmoidof minus their dot products), each term averaged over its pairs.- Parameters:
win_size (int) – Length of the sampled windows.
M (int) – Number of random positions (inter-state samples), at least 2.
N (int) – Number of windows per position (intra-state samples), at least 2.
win_type ({"rect", "hanning"}) –
"hanning"tapers the sampled windows withhanning_tensor()before encoding them.
- forward(batch, encoder, save_memory=False)[source]#
Compute the loss on the first series of a batch.
Positions are drawn with NumPy’s global generator.
- Parameters:
batch (torch.Tensor of shape (batch, channels, length)) – Training series; only
batch[0]is used.lengthmust be at least2 * win_size.encoder (torch.nn.Module) – Maps a tensor of shape (n_windows, channels, win_size) to embeddings of shape (n_windows, n_features).
save_memory (bool, default=False) – Ignored.
- Returns:
Scalar loss.
- Return type:
torch.Tensor
- class SqueezeChannels(*args: Any, **kwargs: Any)[source]#
Bases:
ModuleSqueezes, in a three-dimensional tensor, the third dimension.
- class Time2State(win_size, step, encoder, clustering_component, verbose=False)[source]#
Bases:
objectTime2State pipeline: encode windows, cluster them, label time points.
Time2StateDetectorbuilds one at eachpredictand calls its private steps directly, with the encoder trained infit.- Parameters:
win_size (int) – Window length, even. The label assignment gives each window a vote on
win_sizepoints.step (int) – Distance between the starts of consecutive windows, used by the label assignment.
encoder (BasicEncoderClass) – Encoder, e.g.
CausalConv_LSE_Adaper.clustering_component (BasicClusteringClass) – Clustering of the embeddings, e.g.
DPGMM.verbose (bool, default=False) – Ignored.
- Raises:
ValueError – If
win_sizeis odd.
Notes
The label assignment lets each window vote, with weight 1, for its cluster on the
win_sizepoints it covers; each point takes the cluster with the most votes, the smallest on a tie. Points covered by no window, at moststep - 1at the end of the series, take the label of the last window; the reference implementation gives them label 0.- property change_points#
reading it raises
AttributeError.- Type:
Never set
- property embedding_label#
cluster of each window.
Numbered from 0 in order of first appearance.
- Type:
np.ndarray of shape (n_windows,)
- property embeddings#
window embeddings.
- Type:
np.ndarray of shape (n_windows, n_features)
- fit(X, win_size, step)[source]#
Train the encoder on
X, then labelX.- Parameters:
- Returns:
self – With
embeddings,embedding_labelandstate_seqset.- Return type:
- predict(X, win_size, step)[source]#
Label
Xwith the current encoder, refitting the clustering.- Parameters:
- Returns:
self – With
embeddings,embedding_labelandstate_seqset.- Return type:
- predict_without_encode(X, win_size, step)[source]#
Recluster the stored embeddings and relabel; return
self.X,win_sizeandstepare ignored: the embeddings and the series length are those of the lastfitorpredict.
- property state_seq#
state label of each point.
- Type:
np.ndarray of shape (n_timepoints,)
- property velocity#
reading it raises
AttributeError.- Type:
Never set
- hanning_numpy(X)[source]#
NumPy version of
hanning_tensor().- Parameters:
X (np.ndarray of shape (n_windows, channels, length)) – Windows to taper.
- Returns:
Xtimes(1 - cos(2 pi t / length)) / 2along the last axis.- Return type:
np.ndarray of shape (n_windows, channels, length)
- hanning_tensor(X)[source]#
Multiply a tensor by a Hann window along its last axis.
- Parameters:
X (torch.Tensor of shape (batch, channels, length)) – Windows to taper.
- Returns:
Xtimes(1 - cos(2 pi t / length)) / 2, on the device ofX.- Return type:
torch.Tensor of shape (batch, channels, length)
- params_LSE = {'M': 10, 'N': 4, 'batch_size': 1, 'channels': 30, 'cuda': torch.cuda.is_available, 'depth': 10, '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
CausalConv_LSE, keyed by its argument names.Time2StateDetectoroverrides all of them butchannels(30),win_type("rect"),M(10) andN(4)."cuda"is evaluated once, at import.