altx.altx#

Implementation of the altx algorithm.

class altx.altx.Altx(train_set, train_classes, train_length=None, R=None, L=5, K=1, device='cpu')[source]#

Bases: object

Implement the Adaptive Law-Based Transformation.

Find the preserved quantities of the time series and use them to transform the test instances and prepare them for future classification and/or anomaly detection.

train_set#

The linear laws are based on this time series database.

Type:

torch.Tensor

train_classes#

Contains the predefined class labels.

Type:

torch.Tensor

train_length#

Length of train instances. Used when the length varies.

Type:

torch.Tensor

noc#

The number of unique classes.

Type:

int

class_labels#

The list of unique class labels.

Type:

torch.Tensor

RLK#

Two-dimensional tuple for storing the used r-l-k triplets, where r is the length of the analyzed time window (always a multiple of 2*l-1), l is the dimension of the extracted laws, and k is the step of the time window.

Type:

tuple

Ps#

Contains the laws for r-l-k triplets, and a tensor that indicates which law belongs to the specific classes.

Type:

dict

tau#

Number of training instances. (Positive in each case.)

Type:

int

m#

Number of channels. (Positive in each case.)

Type:

int

device#

Device where the operations will be carried out. When cuda, results may need to be moved to the cpu for further work.

Type:

torch.device

_embed(instance_index, sensor_index, rlk, t=0)[source]#

Embed the given time-window in a real, symmetric matrix.

_get_law(S)[source]#

Return the eigenvector for the smallest absolute eigenvalue.

_get_P(rlk)[source]#

Extract and store the laws for an embedding size in tensor P.

_nol(r, k)[source]#

Calculate the number of laws for a given r-k pair.

train()[source]#

Store tensors into a dictionary for each rlk triplet.

save(save_file_name)[source]#

Save the trained model with pickle into the given file.

load(load_file_name)[source]#

Load a previously trained and saved model.

transform(z, extr_methods)[source]#

Transform one instance into features with the given methods.

transform_set(test_set, extr_method, save_file_name,

save_file_mode, test_classes)

Transform a whole set by iterating the transform function.

_save_features(extr_methods, features, test_classes,

save_file_name, save_file_mode)

Save features to a CSV file.

_generate_header(extr_methods)[source]#

Generate the header columns for the feature save file.

_multiply(z, rlk)[source]#

Embed and multiply an instance with the P matrix for the rlk.

_extract_features(M, extr_methods)[source]#

Extract features from the result of the multiply function.

plot(z, rlk, zoom)#

Transform one instance and plot the resulting matrix values.

plot_anomalies(z)#

Not implemented yet. Will be used for anomaly detection.

print_number_of_laws()[source]#

Print the number of laws.

Notes

One instance contains m number of time series.

static load(load_file_name)[source]#

Load a previously trained and saved model.

Parameters:

load_file_name (str) – Path of the save file.

Returns:

The trained model instance.

Return type:

Altx

Notes

The save file does not contain the training data, so further training is not possible after loading.

Examples

>>> import torch, tempfile, os
>>> from altx import ALT as Altx
>>> _ = torch.manual_seed(0)
>>> model = Altx(
...     torch.randn(6, 50),
...     torch.tensor([0, 0, 0, 1, 1, 1]),
...     L=3, K=1,
... )
>>> model.train()
>>> path = tempfile.mktemp(suffix=".pkl")
>>> model.save(path)
>>> loaded = Altx.load(path)
>>> loaded.device = model.device
>>> print(loaded.noc)
2
>>> print(loaded.RLK)
((5, 3, 1),)
>>> os.unlink(path)
multiply_only(z, rlk, normalize_data=True)[source]#

Multiplies an instance with the generated laws.

Parameters:
  • z (Tensor | ndarray) – An instance of time series.

  • rlk (tuple[int, int, int]) – The (r, l, k) triplet.

  • normalize_data (bool) – Normalize the embedded time series to unit length for each time step.

Returns:

A tensor of the results.

Return type:

Tensor

print_number_of_laws()[source]#

Print the number of laws for each class and (r, l, k) triplet.

Raises:

RuntimeError – If called before training.

Return type:

None

Notes

Only usable after training.

save(save_file_name)[source]#

Save the trained model to a file.

Parameters:

save_file_name (str) – Path of the save file.

Return type:

None

Examples

>>> import torch, tempfile, os
>>> from altx import ALT as Altx
>>> _ = torch.manual_seed(0)
>>> model = Altx(
...     torch.randn(6, 50),
...     torch.tensor([0, 0, 0, 1, 1, 1]),
...     L=3, K=1,
... )
>>> model.train()
>>> path = tempfile.mktemp(suffix=".pkl")
>>> model.save(path)
>>> print(os.path.exists(path))
True
>>> os.unlink(path)
train(cleanup=False)[source]#

Train the model by extracting laws from the training data.

Extract and store the patterns (laws) for each (r, l, k) triplet.

Parameters:

cleanup (bool) – Whether to delete the training data after training to free memory. Default is False.

Raises:

RuntimeError – If training is attempted without training data.

Return type:

None

Examples

>>> import torch
>>> from altx import ALT as Altx
>>> _ = torch.manual_seed(0)
>>> model = Altx(
...     torch.randn(6, 50),
...     torch.tensor([0, 0, 0, 1, 1, 1]),
...     L=3, K=1,
... )
>>> model.train()
>>> print((5, 3, 1) in model.Ps)
True
>>> _, P = model.Ps[(5, 3, 1)]
>>> print(P.shape)
torch.Size([3, 276, 1])
transform(z, extr_methods)[source]#

Transform one instance into features using the given methods.

Parameters:
  • z (Tensor | ndarray) – The input time series instance.

  • extr_methods (list[list[str] | list[str | float]]) – Each element is either a one-element list [method] or a two-element list [method, percentile]. If the percentile is omitted, 0.05 is used by default.

Returns:

A one-dimensional tensor of the calculated features.

Return type:

Tensor

Raises:

ValueError – If the given extraction method is not implemented.

Examples

>>> import torch
>>> from altx import ALT as Altx
>>> _ = torch.manual_seed(0)
>>> model = Altx(
...     torch.randn(6, 50),
...     torch.tensor([0, 0, 0, 1, 1, 1]),
...     L=3, K=1,
... )
>>> model.train()
>>> _ = torch.manual_seed(0)
>>> z = torch.randn(50)
>>> features = model.transform(z, [["mean", 0.05]])
>>> print(features.shape)
torch.Size([2])
>>> features = model.transform(z, [["mean", 0.05], ["var", 0.1]])
>>> print(features.shape)
torch.Size([4])
transform_set(test_set, extr_methods, test_length=None, save_file_name=None, save_file_mode=None, test_classes=None)[source]#

Transform a whole set of instances by iterating transform.

Save the features in CSV format if save parameters are given.

Parameters:
  • test_set (Tensor | ndarray) – The set of instances to transform (same dimensions as train_set).

  • extr_methods (list[list[str] | list[str | float]]) – Each element is either a one-element list [method] or a two-element list [method, percentile]. If the percentile is omitted, 0.05 is used by default.

  • test_length (Tensor | None) – The useful length of each instance in the set. Default is None, which uses the training set length.

  • save_file_name (str | None) – The path for the save file. Default is None (no saving).

  • save_file_mode (str | None) – Saving mode: “New file”, “Append feature”, or “Append instance”. Ignored if save_file_name is None or the file does not exist.

  • test_classes (Tensor | None) – The class labels for the transformed set. Required when saving.

Returns:

The results in a two-dimensional tensor.

Return type:

Tensor

Raises:
  • ValueError – If the given extraction method is not implemented.

  • TypeError – If save_file_name is given but test_classes is None.

Examples

>>> import torch
>>> from altx import ALT as Altx
>>> _ = torch.manual_seed(0)
>>> model = Altx(
...     torch.randn(6, 50),
...     torch.tensor([0, 0, 0, 1, 1, 1]),
...     L=3, K=1,
... )
>>> model.train()
>>> _ = torch.manual_seed(0)
>>> test_set = torch.randn(3, 50)
>>> features = model.transform_set(test_set, [["mean", 0.05]])
>>> print(features.shape)
torch.Size([3, 2])
>>> print(features)
tensor([[0.0077, 0.0113],
        [0.0122, 0.0163],
        [0.0077, 0.0104]])