E2USD#
E2USD – Efficient-yet-Effective Unsupervised State Detection.
Description#
E2USD combines two key ideas for scalable, accurate unsupervised state detection in multivariate time series:
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.
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.
window_sizeParameters#
Name |
Type |
Default |
Description |
|---|---|---|---|
|
int |
|
Size of the sliding window; must be even. |
|
int |
|
Step size of the sliding window. |
|
int |
|
Upper bound on the number of states (DPGMM components). |
|
float |
|
Concentration parameter for DPGMM. |
|
int |
|
No effect: the training set is one sample, the whole series. |
|
int |
|
Number of optimisation steps. |
|
float |
|
Learning rate. |
|
int |
|
No effect: the encoder network does not use it. |
|
int |
|
Number of output channels of the encoder. |
|
int |
|
Dimension of the CNN output before the final linear layer. |
|
int |
|
Kernel size of the two convolutions; at most |
|
bool / None |
|
Run on CUDA device 0 ( |
|
int / None |
|
Random seed. |
|
int |
|
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:
BaseSegmenterE2USD: 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 == 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=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:fitraisesValueErroron a larger value.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.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 + 1points, so the lastwindow_size - 3points never enter a 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 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 withn_states=3andrandom_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 withwindow_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.fitraisesValueErroron a series of fewer than2 * window_sizepoints;predictlabels every point of such a series 0.yis ignored.The wrapped code is that of the reference implementation (AI4CTS/E2Usd), which publishes no licence. Its
Datasetclass comes from the code of Franceschi et al. (2019) (Apache License 2.0) and itsmoving_avgandseries_decompblocks from Autoformer (MIT licence); theLICENSEfile oftsseg/algorithms/e2usdholds 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
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.
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:
objectInterface of the clustering step of
E2USD.abc.abstractmethodis not enforced: the class has noABCMetametaclass.- Parameters:
params (object) – Ignored.
- class BasicEncoder[source]#
Bases:
objectBase class of
DDEM, whose methods do nothing.- encode(X)[source]#
Do nothing (overridden by
DDEM.encode()).
- class BasicEncoderClass(params)[source]#
Bases:
objectInterface of the encoders used by
E2USD.The constructor hands
paramsto_set_parmas(spelling of the reference code), which subclasses implement to build the encoder.abc.abstractmethodis not enforced: the class has noABCMetametaclass.- Parameters:
params (dict) – Hyperparameters of the encoder.
- 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:
BasicEncoderEncoder of E2USD: trains a
NetworkDDEMand 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:
- optimizer#
Optimiser of the trainable parameters of the network, those of its linear layers.
- Type:
torch.optim.Adam
- 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
Xhere; 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.
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 + 1windows of the first series, starting at0, 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_stepssteps.Each step evaluates the loss on random windows of the series (see
fncc_loss) and updates the linear layers.- Parameters:
- Returns:
The trained network.
- Return type:
- 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_lengthin the place ofwin_size, whereas it requires 15: any call raisesTypeError(M,Nandwin_typeare missing), as in the reference code.- Parameters:
compared_length (int) – The
win_sizeof 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:
- class DPGMM(n_states, alpha=1000.0)[source]#
Bases:
BasicClusteringClassDirichlet process Gaussian mixture on the window embeddings.
- Parameters:
- fit(X)[source]#
Fit the mixture on
Xand return the component of each row.sklearn.mixture.BayesianGaussianMixturewith full covariances, k-means initialisation, a Dirichlet process prior and at most 1000 iterations; it has norandom_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 emptyXgives an empty result.- Parameters:
X (array-like of shape (n_samples, n_features) or (n_samples,)) – The samples, without NaN (
ValueErrorotherwise).- 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:
DatasetPyTorch dataset whose samples are the entries of an array.
- Parameters:
dataset (np.ndarray) – The samples, along the first axis:
dataset[i]is samplei.
- class E2USD(win_size, step, encoder, clustering_component, verbose=False)[source]#
Bases:
objectE2USD 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 raisesValueErrorwhen the labels are assigned.step (int) – Distance between the starts of consecutive windows, as voted on.
encoder (BasicEncoderClass) – Object with
fit(X)andencode(X, win_size, step), such asE2USD_Adaper.clustering_component (BasicClusteringClass) – Object with
fit(embeddings)that returns one label per window, such asDPGMM.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.ndarrayof shape(n_windows,).
- property embeddings#
Embeddings of the windows of the last series encoded.
np.ndarrayof 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_sizeof the constructor: the two should be equal.step (int) – Distance between the windows embedded. The votes use the
stepof the constructor (or ofset_step()): the two should be equal.
- Returns:
self; the labels are instate_seq.- Return type:
- fit_encoder(X)[source]#
Train the encoder on
Xonly.- Parameters:
X (np.ndarray of shape (n_timepoints, n_channels)) – The series.
- Returns:
self.- Return type:
- predict(X, win_size, step)[source]#
Label the points of
Xwith the encoder as it is.- Parameters:
- Returns:
self; the labels are instate_seq.- Return type:
- predict_without_encode(X, win_size, step)[source]#
Cluster the embeddings of the last series encoded and vote again.
Raises
AttributeErrorif no series was encoded.- Parameters:
X – Unused.
win_size – Unused.
step – Unused.
- Returns:
self.- Return type:
- set_clustering_component(clustering_obj)[source]#
Replace the clustering component.
- Parameters:
clustering_obj (BasicClusteringClass) – The new clustering component.
- Returns:
self.- Return type:
- set_step(step)[source]#
Set the
stepused 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.ndarrayof shape(n_timepoints,).
- property velocity#
reading it raises
AttributeError.- Type:
Never set
- class E2USD_Adaper(params)[source]#
Bases:
BasicEncoderClassAdapter that gives a
DDEMthe interface used byE2USD.The class name keeps the spelling of the reference code.
- Parameters:
params (dict) – Keyword arguments of
DDEM, such asparams. A"compared_length"key is removed from the dict itself.
- encode(X, win_size, step)[source]#
Normalise a series with
all_normalize()and embed its windows.- Parameters:
- Returns:
The embeddings of the
(n_timepoints - win_size) // step + 1windows (seeDDEM.encode_window()).- 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_timepointsat least twice thewin_sizeof the encoder.
- class NetworkDDEM(*args: Any, **kwargs: Any)[source]#
Bases:
ModuleDecomposed dual-view embedding network (DDEM) of E2USD.
Named
DDEMin the reference code (networks/network.py); renamed here, whereDDEMis 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 = 33lowest frequencies of the real Fourier transform of each window and transforms back without a target length, scaling by33 / length: a window oflength >= 64points becomes 64 points; a shorter one keeps its length if even, and loses one point if odd.series_decompwith a moving average over 5 points splits it into a trend and a seasonal part (the residual). Each part goes through its ownConv1d(in_channelstoreduced_sizechannels, no padding), a max pooling over time and a linear layer toout_channels; a last linear layer maps the two concatenated embeddings toout_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.
- 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_tensoritself.- 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.
- 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:
- class fncc_loss(*args: Any, **kwargs: Any)[source]#
Bases:
_LossFalse negative cancellation contrastive loss (FNCC) of E2USD.
- Parameters:
Notes
Each call draws
Mpositionspuniformly in[0, length - 2 * win_size]from NumPy’s global generator and embeds, at each, theNwindows starting atp, ..., 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 attributestotalandtotal_conditionare 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.lengthmust be at least2 * 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:
ModuleMoving average along the last axis, with the edge values repeated.
- Parameters:
- forward(x)[source]#
Pad each end of
xwith its edge value, then average.Each end gets
(kernel_size - 1) // 2copies of its edge value.- Parameters:
x (torch.Tensor of shape (batch, channels, length)) – The series.
- Returns:
The averages. With
stride=1and an oddkernel_size,n_averagesislength.- 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.E2USDDetectoroverrides all of them butchannels(30) andwin_type("rect"), which have no effect,M(20) andN(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:
- 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
labelwhere 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:
ModuleSplit 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).