pypots.classification

pypots.classification.saits

The package of the partially-observed time-series classification model SAITS.

Refer to the paper Wenjie Du, David Cote, and Yan Liu. SAITS: Self-Attention-based Imputation for Time Series. Expert Systems with Applications, 219:119619, 2023.

Notes

This implementation is inspired by the official one https://github.com/WenjieDu/SAITS

class pypots.classification.saits.SAITS(n_steps, n_features, n_classes, n_layers, d_model, n_heads, d_k, d_v, d_ffn, dropout=0, attn_dropout=0, diagonal_attention_mask=True, batch_size=32, epochs=100, patience=None, training_loss=<class 'pypots.nn.modules.loss.CrossEntropy'>, validation_metric=<class 'pypots.nn.modules.loss.CrossEntropy'>, optimizer=<class 'pypots.optim.adam.Adam'>, num_workers=0, device=None, saving_path=None, model_saving_strategy='best', verbose=True)[source]

Bases: BaseNNClassifier

The PyTorch implementation of the SAITS classification model [1].

Parameters:
  • n_steps (int) – The number of time steps in the time-series data sample.

  • n_features (int) – The number of features in the time-series data sample.

  • n_classes (int) – The number of classes in the classification task.

  • n_layers (int) – The number of layers in the 1st and 2nd DMSA blocks in the SAITS model.

  • d_model (int) – The dimension of the model’s backbone. It is the input dimension of the multi-head DMSA layers.

  • n_heads (int) – The number of heads in the multi-head DMSA mechanism. d_model must be divisible by n_heads, and the result should be equal to d_k.

  • d_k (int) – The dimension of the keys (K) and the queries (Q) in the DMSA mechanism. d_k should be the result of d_model divided by n_heads. Although d_k can be directly calculated with given d_model and n_heads, we want it be explicitly given together with d_v by users to ensure users be aware of them and to avoid any potential mistakes.

  • d_v (int) – The dimension of the values (V) in the DMSA mechanism.

  • d_ffn (int) – The dimension of the layer in the Feed-Forward Networks (FFN).

  • dropout (float) – The dropout rate for all fully-connected layers in the model.

  • attn_dropout (float) – The dropout rate for DMSA.

  • diagonal_attention_mask (bool) – Whether to apply a diagonal attention mask to the self-attention mechanism. If so, the attention layers will use DMSA. Otherwise, the attention layers will use the original.

  • batch_size (int) – The batch size for training and evaluating the model.

  • epochs (int) – The number of epochs for training the model.

  • patience (Optional[int]) – The patience for the early-stopping mechanism. Given a positive integer, the training process will be stopped when the model does not perform better after that number of epochs. Leaving it default as None will disable the early-stopping.

  • training_loss (Union[Criterion, type]) – The customized loss function designed by users for training the model. If not given, will use the default loss as claimed in the original paper.

  • validation_metric (Union[Criterion, type]) – The customized metric function designed by users for validating the model. If not given, will use the default loss from the original paper as the metric.

  • optimizer (Union[Optimizer, type]) – The optimizer for model training. If not given, will use a default Adam optimizer.

  • num_workers (int) – The number of subprocesses to use for data loading. 0 means data loading will be in the main process, i.e. there won’t be subprocesses.

  • device (Union[str, device, list, None]) – The device for the model to run on. It can be a string, a torch.device object, or a list of them. If not given, will try to use CUDA devices first (will use the default CUDA device if there are multiple), then CPUs, considering CUDA and CPU are so far the main devices for people to train ML models. If given a list of devices, e.g. [‘cuda:0’, ‘cuda:1’], or [torch.device(‘cuda:0’), torch.device(‘cuda:1’)] , the model will be parallely trained on the multiple devices (so far only support parallel training on CUDA devices). Other devices like Google TPU and Apple Silicon accelerator MPS may be added in the future.

  • saving_path (Optional[str]) – The path for automatically saving model checkpoints and tensorboard files (i.e. loss values recorded during training into a tensorboard file). Will not save if not given.

  • model_saving_strategy (Optional[str]) – The strategy to save model checkpoints. It has to be one of [None, “best”, “better”, “all”]. No model will be saved when it is set as None. The “best” strategy will only automatically save the best model after the training finished. The “better” strategy will automatically save the model during training whenever the model performs better than in previous epochs. The “all” strategy will save every model after each epoch training.

  • verbose (bool) – Whether to print out the training logs during the training process.

classify(test_set, file_type='hdf5', **kwargs)

Classify the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The data samples for testing, should be array-like with shape [n_samples, n_steps, n_features], or a path string locating a data file, e.g. h5 file.

  • file_type (str) – The type of the given file if X is a path string.

Returns:

Classification results of the given samples.

Return type:

results

fit(train_set, val_set=None, file_type='hdf5')

Train the classifier on the given data.

Parameters:
  • train_set (Union[dict, str]) – The dataset for model training, should be a dictionary including keys as ‘X’ and ‘y’, or a path string locating a data file. If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is time-series data for training, can contain missing values, and y should be array-like of shape [n_samples], which is classification labels of X. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include keys as ‘X’ and ‘y’.

  • val_set (Union[dict, str, None]) – The dataset for model validating, should be a dictionary including keys as ‘X’ and ‘y’, or a path string locating a data file. If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is time-series data for validating, can contain missing values, and y should be array-like of shape [n_samples], which is classification labels of X. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include keys as ‘X’ and ‘y’.

  • file_type (str) – The type of the given file if train_set and val_set are path strings.

Return type:

None

load(path)

Load the saved model from a disk file.

Parameters:

path (str) – The local path to a disk file saving the trained model.

Return type:

None

Notes

If the training environment and the deploying/test environment use the same type of device (GPU/CPU), you can load the model directly with torch.load(model_path).

On PyTorch versions that support it, PyPOTS loads checkpoint files with weights_only=True so deserializing model state does not execute arbitrary pickle payloads from untrusted files.

predict(test_set, file_type='hdf5', **kwargs)

Make predictions for the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The test dataset for model to process, should be a dictionary including keys as ‘X’, or a path string locating a data file supported by PyPOTS (e.g. h5 file). If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is the time-series data for processing. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include ‘X’ key.

  • file_type (str) – The type of the given file if test_set is a path string.

Returns:

The dictionary containing the classification results as key ‘classification’ and latent variables if necessary.

Return type:

result_dict

predict_proba(test_set, file_type='hdf5', **kwargs)

Predict the classification probabilities of the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The data samples for testing, should be array-like with shape [n_samples, n_steps, n_features], or a path string locating a data file, e.g. h5 file.

  • file_type (str) – The type of the given file if X is a path string.

Returns:

Classification probabilities of the given samples.

Return type:

results

save(saving_path, overwrite=False)

Save the model with current parameters to a disk file.

A .pypots extension will be appended to the filename if it does not already have one. Please note that such an extension is not necessary, but to indicate the saved model is from PyPOTS framework so people can distinguish.

Parameters:
  • saving_path (str) – The given path to save the model. The directory will be created if it does not exist.

  • overwrite (bool) – Whether to overwrite the model file if the path already exists.

Return type:

None

to(device)

Move the model to the given device.

Parameters:

device (Union[str, device]) – The device to move the model to. It can be a string or a torch.device object.

Return type:

None

pypots.classification.tefn

The implementation of TEFN for the partially-observed time-series classification task.

Refer to the paper Tianxiang Zhan, Yuanpeng He, Yong Deng, Zhen Li, Wenjie Du, and Qingsong Wen. Time Evidence Fusion Network: Multi-source View in Long-Term Time Series Forecasting. IEEE TPAMI. 2025.

Notes

This implementation is transferred from the official one https://github.com/ztxtech/Time-Evidence-Fusion-Network

class pypots.classification.tefn.TEFN(n_steps, n_features, n_classes, n_fod, dropout=0, batch_size=32, epochs=100, patience=None, training_loss=<class 'pypots.nn.modules.loss.CrossEntropy'>, validation_metric=<class 'pypots.nn.modules.loss.CrossEntropy'>, optimizer=<pypots.optim.adam.Adam object>, num_workers=0, device=None, saving_path=None, model_saving_strategy='best', verbose=True)[source]

Bases: BaseNNClassifier

The PyTorch implementation of the TEFN classification model [6].

Parameters:
  • n_steps (int) – The number of time steps in the time-series data sample.

  • n_features (int) – The number of features in the time-series data sample.

  • n_classes (int) – The number of classes in the classification task.

  • n_fod (int) – The number of FOD (frame of discernment) in the TEFN model.

  • dropout (float) – The dropout rate for the model.

  • batch_size (int) – The batch size for training and evaluating the model.

  • epochs (int) – The number of epochs for training the model.

  • patience (Optional[int]) – The patience for the early-stopping mechanism. Given a positive integer, the training process will be stopped when the model does not perform better after that number of epochs. Leaving it default as None will disable the early-stopping.

  • training_loss (Union[Criterion, type]) – The customized loss function designed by users for training the model. If not given, will use the default loss as claimed in the original paper.

  • validation_metric (Union[Criterion, type]) – The customized metric function designed by users for validating the model. If not given, will use the default loss from the original paper as the metric.

  • optimizer (Optimizer) – The optimizer for model training. If not given, will use a default Adam optimizer.

  • num_workers (int) – The number of subprocesses to use for data loading. 0 means data loading will be in the main process, i.e. there won’t be subprocesses.

  • device (Union[str, device, list, None]) – The device for the model to run on. It can be a string, a torch.device object, or a list of them. If not given, will try to use CUDA devices first (will use the default CUDA device if there are multiple), then CPUs, considering CUDA and CPU are so far the main devices for people to train ML models. If given a list of devices, e.g. [‘cuda:0’, ‘cuda:1’], or [torch.device(‘cuda:0’), torch.device(‘cuda:1’)] , the model will be parallely trained on the multiple devices (so far only support parallel training on CUDA devices). Other devices like Google TPU and Apple Silicon accelerator MPS may be added in the future.

  • saving_path (Optional[str]) – The path for automatically saving model checkpoints and tensorboard files (i.e. loss values recorded during training into a tensorboard file). Will not save if not given.

  • model_saving_strategy (Optional[str]) – The strategy to save model checkpoints. It has to be one of [None, “best”, “better”, “all”]. No model will be saved when it is set as None. The “best” strategy will only automatically save the best model after the training finished. The “better” strategy will automatically save the model during training whenever the model performs better than in previous epochs. The “all” strategy will save every model after each epoch training.

  • verbose (bool) – Whether to print out the training logs during the training process.

classify(test_set, file_type='hdf5', **kwargs)

Classify the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The data samples for testing, should be array-like with shape [n_samples, n_steps, n_features], or a path string locating a data file, e.g. h5 file.

  • file_type (str) – The type of the given file if X is a path string.

Returns:

Classification results of the given samples.

Return type:

results

fit(train_set, val_set=None, file_type='hdf5')

Train the classifier on the given data.

Parameters:
  • train_set (Union[dict, str]) – The dataset for model training, should be a dictionary including keys as ‘X’ and ‘y’, or a path string locating a data file. If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is time-series data for training, can contain missing values, and y should be array-like of shape [n_samples], which is classification labels of X. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include keys as ‘X’ and ‘y’.

  • val_set (Union[dict, str, None]) – The dataset for model validating, should be a dictionary including keys as ‘X’ and ‘y’, or a path string locating a data file. If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is time-series data for validating, can contain missing values, and y should be array-like of shape [n_samples], which is classification labels of X. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include keys as ‘X’ and ‘y’.

  • file_type (str) – The type of the given file if train_set and val_set are path strings.

Return type:

None

load(path)

Load the saved model from a disk file.

Parameters:

path (str) – The local path to a disk file saving the trained model.

Return type:

None

Notes

If the training environment and the deploying/test environment use the same type of device (GPU/CPU), you can load the model directly with torch.load(model_path).

On PyTorch versions that support it, PyPOTS loads checkpoint files with weights_only=True so deserializing model state does not execute arbitrary pickle payloads from untrusted files.

predict(test_set, file_type='hdf5', **kwargs)

Make predictions for the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The test dataset for model to process, should be a dictionary including keys as ‘X’, or a path string locating a data file supported by PyPOTS (e.g. h5 file). If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is the time-series data for processing. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include ‘X’ key.

  • file_type (str) – The type of the given file if test_set is a path string.

Returns:

The dictionary containing the classification results as key ‘classification’ and latent variables if necessary.

Return type:

result_dict

predict_proba(test_set, file_type='hdf5', **kwargs)

Predict the classification probabilities of the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The data samples for testing, should be array-like with shape [n_samples, n_steps, n_features], or a path string locating a data file, e.g. h5 file.

  • file_type (str) – The type of the given file if X is a path string.

Returns:

Classification probabilities of the given samples.

Return type:

results

save(saving_path, overwrite=False)

Save the model with current parameters to a disk file.

A .pypots extension will be appended to the filename if it does not already have one. Please note that such an extension is not necessary, but to indicate the saved model is from PyPOTS framework so people can distinguish.

Parameters:
  • saving_path (str) – The given path to save the model. The directory will be created if it does not exist.

  • overwrite (bool) – Whether to overwrite the model file if the path already exists.

Return type:

None

to(device)

Move the model to the given device.

Parameters:

device (Union[str, device]) – The device to move the model to. It can be a string or a torch.device object.

Return type:

None

pypots.classification.brits

The package of the partially-observed time-series classification model BRITS.

Refer to the paper Wei Cao, Dong Wang, Jian Li, Hao Zhou, Lei Li, and Yitan Li. BRITS: Bidirectional recurrent imputation for time series. In Advances in Neural Information Processing Systems, volume 31. Curran Associates, Inc., 2018.

Notes

This implementation is inspired by the official one https://github.com/caow13/BRITS. The bugs in the original implementation are fixed here.

class pypots.classification.brits.BRITS(n_steps, n_features, n_classes, rnn_hidden_size, classification_weight=1, reconstruction_weight=1, batch_size=32, epochs=100, patience=None, training_loss=<class 'pypots.nn.modules.loss.CrossEntropy'>, validation_metric=<class 'pypots.nn.modules.loss.CrossEntropy'>, optimizer=<class 'pypots.optim.adam.Adam'>, num_workers=0, device=None, saving_path=None, model_saving_strategy='best', verbose=True)[source]

Bases: BaseNNClassifier

The PyTorch implementation of the BRITS model [48].

Parameters:
  • n_steps (int) – The number of time steps in the time-series data sample.

  • n_features (int) – The number of features in the time-series data sample.

  • n_classes (int) – The number of classes in the classification task.

  • rnn_hidden_size (int) – The size of the RNN hidden state.

  • classification_weight (float) – The loss weight for the classification task.

  • reconstruction_weight (float) – The loss weight for the reconstruction task.

  • batch_size (int) – The batch size for training and evaluating the model.

  • epochs (int) – The number of epochs for training the model.

  • patience (Optional[int]) – The patience for the early-stopping mechanism. Given a positive integer, the training process will be stopped when the model does not perform better after that number of epochs. Leaving it default as None will disable the early-stopping.

  • training_loss (Union[Criterion, type]) – The customized loss function designed by users for training the model. If not given, will use the default loss as claimed in the original paper.

  • validation_metric (Union[Criterion, type]) – The customized metric function designed by users for validating the model. If not given, will use the default loss from the original paper as the metric.

  • optimizer (Union[Optimizer, type]) – The optimizer for model training. If not given, will use a default Adam optimizer.

  • num_workers (int) – The number of subprocesses to use for data loading. 0 means data loading will be in the main process, i.e. there won’t be subprocesses.

  • device (Union[str, device, list, None]) – The device for the model to run on. It can be a string, a torch.device object, or a list of them. If not given, will try to use CUDA devices first (will use the default CUDA device if there are multiple), then CPUs, considering CUDA and CPU are so far the main devices for people to train ML models. If given a list of devices, e.g. [‘cuda:0’, ‘cuda:1’], or [torch.device(‘cuda:0’), torch.device(‘cuda:1’)] , the model will be parallely trained on the multiple devices (so far only support parallel training on CUDA devices). Other devices like Google TPU and Apple Silicon accelerator MPS may be added in the future.

  • saving_path (Optional[str]) – The path for automatically saving model checkpoints and tensorboard files (i.e. loss values recorded during training into a tensorboard file). Will not save if not given.

  • model_saving_strategy (Optional[str]) – The strategy to save model checkpoints. It has to be one of [None, “best”, “better”, “all”]. No model will be saved when it is set as None. The “best” strategy will only automatically save the best model after the training finished. The “better” strategy will automatically save the model during training whenever the model performs better than in previous epochs. The “all” strategy will save every model after each epoch training.

  • verbose (bool) – Whether to print out the training logs during the training process.

fit(train_set, val_set=None, file_type='hdf5')[source]

Train the classifier on the given data.

Parameters:
  • train_set (Union[dict, str]) – The dataset for model training, should be a dictionary including keys as ‘X’ and ‘y’, or a path string locating a data file. If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is time-series data for training, can contain missing values, and y should be array-like of shape [n_samples], which is classification labels of X. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include keys as ‘X’ and ‘y’.

  • val_set (Union[dict, str, None]) – The dataset for model validating, should be a dictionary including keys as ‘X’ and ‘y’, or a path string locating a data file. If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is time-series data for validating, can contain missing values, and y should be array-like of shape [n_samples], which is classification labels of X. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include keys as ‘X’ and ‘y’.

  • file_type (str) – The type of the given file if train_set and val_set are path strings.

Return type:

None

classify(test_set, file_type='hdf5', **kwargs)

Classify the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The data samples for testing, should be array-like with shape [n_samples, n_steps, n_features], or a path string locating a data file, e.g. h5 file.

  • file_type (str) – The type of the given file if X is a path string.

Returns:

Classification results of the given samples.

Return type:

results

load(path)

Load the saved model from a disk file.

Parameters:

path (str) – The local path to a disk file saving the trained model.

Return type:

None

Notes

If the training environment and the deploying/test environment use the same type of device (GPU/CPU), you can load the model directly with torch.load(model_path).

On PyTorch versions that support it, PyPOTS loads checkpoint files with weights_only=True so deserializing model state does not execute arbitrary pickle payloads from untrusted files.

predict(test_set, file_type='hdf5')[source]

Make predictions for the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The test dataset for model to process, should be a dictionary including keys as ‘X’, or a path string locating a data file supported by PyPOTS (e.g. h5 file). If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is the time-series data for processing. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include ‘X’ key.

  • file_type (str) – The type of the given file if test_set is a path string.

Returns:

The dictionary containing the classification results as key ‘classification’ and latent variables if necessary.

Return type:

result_dict

predict_proba(test_set, file_type='hdf5', **kwargs)

Predict the classification probabilities of the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The data samples for testing, should be array-like with shape [n_samples, n_steps, n_features], or a path string locating a data file, e.g. h5 file.

  • file_type (str) – The type of the given file if X is a path string.

Returns:

Classification probabilities of the given samples.

Return type:

results

save(saving_path, overwrite=False)

Save the model with current parameters to a disk file.

A .pypots extension will be appended to the filename if it does not already have one. Please note that such an extension is not necessary, but to indicate the saved model is from PyPOTS framework so people can distinguish.

Parameters:
  • saving_path (str) – The given path to save the model. The directory will be created if it does not exist.

  • overwrite (bool) – Whether to overwrite the model file if the path already exists.

Return type:

None

to(device)

Move the model to the given device.

Parameters:

device (Union[str, device]) – The device to move the model to. It can be a string or a torch.device object.

Return type:

None

pypots.classification.itransformer

The package of the partially-observed time-series classification model iTransformer.

Refer to the papers Liu, Yong, Tengge Hu, Haoran Zhang, Haixu Wu, Shiyu Wang, Lintao Ma, and Mingsheng Long. “iTransformer: Inverted transformers are effective for time series forecasting.” ICLR 2024.

Notes

This implementation is inspired by the official one https://github.com/thuml/iTransformer

class pypots.classification.itransformer.iTransformer(n_steps, n_features, n_classes, n_layers, d_model, n_heads, d_k, d_v, d_ffn, dropout=0, attn_dropout=0, batch_size=32, epochs=100, patience=None, training_loss=<class 'pypots.nn.modules.loss.CrossEntropy'>, validation_metric=<class 'pypots.nn.modules.loss.CrossEntropy'>, optimizer=<pypots.optim.adam.Adam object>, num_workers=0, device=None, saving_path=None, model_saving_strategy='best', verbose=True)[source]

Bases: BaseNNClassifier

The PyTorch implementation of the iTransformer classification model [13].

Parameters:
  • n_steps (int) – The number of time steps in the time-series data sample.

  • n_features (int) – The number of features in the time-series data sample.

  • n_classes (int) – The number of classes in the classification task.

  • n_layers (int) – The number of layers in the iTransformer model.

  • d_model (int) – The dimension of the model’s backbone. It is the input dimension of the multi-head self-attention layers.

  • n_heads (int) – The number of heads in the multi-head self-attention mechanism. d_model must be divisible by n_heads, and the result should be equal to d_k.

  • d_k (int) – The dimension of the keys (K) and the queries (Q) in the DMSA mechanism. d_k should be the result of d_model divided by n_heads. Although d_k can be directly calculated with given d_model and n_heads, we want it be explicitly given together with d_v by users to ensure users be aware of them and to avoid any potential mistakes.

  • d_v (int) – The dimension of the values (V) in the DMSA mechanism.

  • d_ffn (int) – The dimension of the layer in the Feed-Forward Networks (FFN).

  • dropout (float) – The dropout rate for all fully-connected layers in the model.

  • attn_dropout (float) – The dropout rate for DMSA.

  • batch_size (int) – The batch size for training and evaluating the model.

  • epochs (int) – The number of epochs for training the model.

  • patience (Optional[int]) – The patience for the early-stopping mechanism. Given a positive integer, the training process will be stopped when the model does not perform better after that number of epochs. Leaving it default as None will disable the early-stopping.

  • training_loss (Union[Criterion, type]) – The customized loss function designed by users for training the model. If not given, will use the default loss as claimed in the original paper.

  • validation_metric (Union[Criterion, type]) – The customized metric function designed by users for validating the model. If not given, will use the default loss from the original paper as the metric.

  • optimizer (Optimizer) – The optimizer for model training. If not given, will use a default Adam optimizer.

  • num_workers (int) – The number of subprocesses to use for data loading. 0 means data loading will be in the main process, i.e. there won’t be subprocesses.

  • device (Union[str, device, list, None]) – The device for the model to run on. It can be a string, a torch.device object, or a list of them. If not given, will try to use CUDA devices first (will use the default CUDA device if there are multiple), then CPUs, considering CUDA and CPU are so far the main devices for people to train ML models. If given a list of devices, e.g. [‘cuda:0’, ‘cuda:1’], or [torch.device(‘cuda:0’), torch.device(‘cuda:1’)] , the model will be parallely trained on the multiple devices (so far only support parallel training on CUDA devices). Other devices like Google TPU and Apple Silicon accelerator MPS may be added in the future.

  • saving_path (Optional[str]) – The path for automatically saving model checkpoints and tensorboard files (i.e. loss values recorded during training into a tensorboard file). Will not save if not given.

  • model_saving_strategy (Optional[str]) – The strategy to save model checkpoints. It has to be one of [None, “best”, “better”, “all”]. No model will be saved when it is set as None. The “best” strategy will only automatically save the best model after the training finished. The “better” strategy will automatically save the model during training whenever the model performs better than in previous epochs. The “all” strategy will save every model after each epoch training.

  • verbose (bool) – Whether to print out the training logs during the training process.

classify(test_set, file_type='hdf5', **kwargs)

Classify the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The data samples for testing, should be array-like with shape [n_samples, n_steps, n_features], or a path string locating a data file, e.g. h5 file.

  • file_type (str) – The type of the given file if X is a path string.

Returns:

Classification results of the given samples.

Return type:

results

fit(train_set, val_set=None, file_type='hdf5')

Train the classifier on the given data.

Parameters:
  • train_set (Union[dict, str]) – The dataset for model training, should be a dictionary including keys as ‘X’ and ‘y’, or a path string locating a data file. If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is time-series data for training, can contain missing values, and y should be array-like of shape [n_samples], which is classification labels of X. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include keys as ‘X’ and ‘y’.

  • val_set (Union[dict, str, None]) – The dataset for model validating, should be a dictionary including keys as ‘X’ and ‘y’, or a path string locating a data file. If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is time-series data for validating, can contain missing values, and y should be array-like of shape [n_samples], which is classification labels of X. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include keys as ‘X’ and ‘y’.

  • file_type (str) – The type of the given file if train_set and val_set are path strings.

Return type:

None

load(path)

Load the saved model from a disk file.

Parameters:

path (str) – The local path to a disk file saving the trained model.

Return type:

None

Notes

If the training environment and the deploying/test environment use the same type of device (GPU/CPU), you can load the model directly with torch.load(model_path).

On PyTorch versions that support it, PyPOTS loads checkpoint files with weights_only=True so deserializing model state does not execute arbitrary pickle payloads from untrusted files.

predict(test_set, file_type='hdf5', **kwargs)

Make predictions for the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The test dataset for model to process, should be a dictionary including keys as ‘X’, or a path string locating a data file supported by PyPOTS (e.g. h5 file). If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is the time-series data for processing. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include ‘X’ key.

  • file_type (str) – The type of the given file if test_set is a path string.

Returns:

The dictionary containing the classification results as key ‘classification’ and latent variables if necessary.

Return type:

result_dict

predict_proba(test_set, file_type='hdf5', **kwargs)

Predict the classification probabilities of the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The data samples for testing, should be array-like with shape [n_samples, n_steps, n_features], or a path string locating a data file, e.g. h5 file.

  • file_type (str) – The type of the given file if X is a path string.

Returns:

Classification probabilities of the given samples.

Return type:

results

save(saving_path, overwrite=False)

Save the model with current parameters to a disk file.

A .pypots extension will be appended to the filename if it does not already have one. Please note that such an extension is not necessary, but to indicate the saved model is from PyPOTS framework so people can distinguish.

Parameters:
  • saving_path (str) – The given path to save the model. The directory will be created if it does not exist.

  • overwrite (bool) – Whether to overwrite the model file if the path already exists.

Return type:

None

to(device)

Move the model to the given device.

Parameters:

device (Union[str, device]) – The device to move the model to. It can be a string or a torch.device object.

Return type:

None

pypots.classification.patchtst

The package of the partially-observed time-series classification model PatchTST.

Refer to the paper Yuqi Nie, Nam H Nguyen, Phanwadee Sinthong, and Jayant Kalagnanam. A time series is worth 64 words: Long-term forecasting with transformers. In ICLR, 2023.

Notes

This implementation is inspired by the official one https://github.com/yuqinie98/PatchTST

class pypots.classification.patchtst.PatchTST(n_steps, n_features, n_classes, patch_size, patch_stride, n_layers, d_model, n_heads, d_k, d_v, d_ffn, dropout, attn_dropout, batch_size=32, epochs=100, patience=None, training_loss=<class 'pypots.nn.modules.loss.CrossEntropy'>, validation_metric=<class 'pypots.nn.modules.loss.CrossEntropy'>, optimizer=<pypots.optim.adam.Adam object>, num_workers=0, device=None, saving_path=None, model_saving_strategy='best', verbose=True)[source]

Bases: BaseNNClassifier

The PyTorch implementation of the PatchTST classification model [23].

Parameters:
  • n_steps (int) – The number of time steps in the time-series data sample.

  • n_features (int) – The number of features in the time-series data sample.

  • n_classes (int) – The number of classes in the classification task.

  • patch_size (int) – The patch length for patch embedding.

  • patch_stride (int) – The stride for patch embedding.

  • n_layers (int) – The number of layers in the PatchTST model.

  • d_model (int) – The dimension of the model.

  • n_heads (int) – The number of heads in each layer of PatchTST.

  • d_k (int) – The dimension of the keys (K) and the queries (Q) in the DMSA mechanism. d_k should be the result of d_model divided by n_heads. Although d_k can be directly calculated with given d_model and n_heads, we want it be explicitly given together with d_v by users to ensure users be aware of them and to avoid any potential mistakes.

  • d_v (int) – The dimension of the values (V) in the DMSA mechanism.

  • d_ffn (int) – The dimension of the feed-forward network.

  • dropout (float) – The dropout rate for the model.

  • attn_dropout (float) – The dropout rate for the attention mechanism in the model.

  • batch_size (int) – The batch size for training and evaluating the model.

  • epochs (int) – The number of epochs for training the model.

  • patience (Optional[int]) – The patience for the early-stopping mechanism. Given a positive integer, the training process will be stopped when the model does not perform better after that number of epochs. Leaving it default as None will disable the early-stopping.

  • training_loss (Union[Criterion, type]) – The customized loss function designed by users for training the model. If not given, will use the default loss as claimed in the original paper.

  • validation_metric (Union[Criterion, type]) – The customized metric function designed by users for validating the model. If not given, will use the default loss from the original paper as the metric.

  • optimizer (Optimizer) – The optimizer for model training. If not given, will use a default Adam optimizer.

  • num_workers (int) – The number of subprocesses to use for data loading. 0 means data loading will be in the main process, i.e. there won’t be subprocesses.

  • device (Union[str, device, list, None]) – The device for the model to run on. It can be a string, a torch.device object, or a list of them. If not given, will try to use CUDA devices first (will use the default CUDA device if there are multiple), then CPUs, considering CUDA and CPU are so far the main devices for people to train ML models. If given a list of devices, e.g. [‘cuda:0’, ‘cuda:1’], or [torch.device(‘cuda:0’), torch.device(‘cuda:1’)] , the model will be parallely trained on the multiple devices (so far only support parallel training on CUDA devices). Other devices like Google TPU and Apple Silicon accelerator MPS may be added in the future.

  • saving_path (Optional[str]) – The path for automatically saving model checkpoints and tensorboard files (i.e. loss values recorded during training into a tensorboard file). Will not save if not given.

  • model_saving_strategy (Optional[str]) – The strategy to save model checkpoints. It has to be one of [None, “best”, “better”, “all”]. No model will be saved when it is set as None. The “best” strategy will only automatically save the best model after the training finished. The “better” strategy will automatically save the model during training whenever the model performs better than in previous epochs. The “all” strategy will save every model after each epoch training.

  • verbose (bool) – Whether to print out the training logs during the training process.

classify(test_set, file_type='hdf5', **kwargs)

Classify the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The data samples for testing, should be array-like with shape [n_samples, n_steps, n_features], or a path string locating a data file, e.g. h5 file.

  • file_type (str) – The type of the given file if X is a path string.

Returns:

Classification results of the given samples.

Return type:

results

fit(train_set, val_set=None, file_type='hdf5')

Train the classifier on the given data.

Parameters:
  • train_set (Union[dict, str]) – The dataset for model training, should be a dictionary including keys as ‘X’ and ‘y’, or a path string locating a data file. If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is time-series data for training, can contain missing values, and y should be array-like of shape [n_samples], which is classification labels of X. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include keys as ‘X’ and ‘y’.

  • val_set (Union[dict, str, None]) – The dataset for model validating, should be a dictionary including keys as ‘X’ and ‘y’, or a path string locating a data file. If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is time-series data for validating, can contain missing values, and y should be array-like of shape [n_samples], which is classification labels of X. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include keys as ‘X’ and ‘y’.

  • file_type (str) – The type of the given file if train_set and val_set are path strings.

Return type:

None

load(path)

Load the saved model from a disk file.

Parameters:

path (str) – The local path to a disk file saving the trained model.

Return type:

None

Notes

If the training environment and the deploying/test environment use the same type of device (GPU/CPU), you can load the model directly with torch.load(model_path).

On PyTorch versions that support it, PyPOTS loads checkpoint files with weights_only=True so deserializing model state does not execute arbitrary pickle payloads from untrusted files.

predict(test_set, file_type='hdf5', **kwargs)

Make predictions for the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The test dataset for model to process, should be a dictionary including keys as ‘X’, or a path string locating a data file supported by PyPOTS (e.g. h5 file). If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is the time-series data for processing. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include ‘X’ key.

  • file_type (str) – The type of the given file if test_set is a path string.

Returns:

The dictionary containing the classification results as key ‘classification’ and latent variables if necessary.

Return type:

result_dict

predict_proba(test_set, file_type='hdf5', **kwargs)

Predict the classification probabilities of the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The data samples for testing, should be array-like with shape [n_samples, n_steps, n_features], or a path string locating a data file, e.g. h5 file.

  • file_type (str) – The type of the given file if X is a path string.

Returns:

Classification probabilities of the given samples.

Return type:

results

save(saving_path, overwrite=False)

Save the model with current parameters to a disk file.

A .pypots extension will be appended to the filename if it does not already have one. Please note that such an extension is not necessary, but to indicate the saved model is from PyPOTS framework so people can distinguish.

Parameters:
  • saving_path (str) – The given path to save the model. The directory will be created if it does not exist.

  • overwrite (bool) – Whether to overwrite the model file if the path already exists.

Return type:

None

to(device)

Move the model to the given device.

Parameters:

device (Union[str, device]) – The device to move the model to. It can be a string or a torch.device object.

Return type:

None

pypots.classification.csai

The package including the modules of CSAI.

Refer to the paper Linglong Qian, Zina Ibrahim, Hugh Logan Ellis, Ao Zhang, Yuezhou Zhang, Tao Wang, Richard Dobson. Knowledge Enhanced Conditional Imputation for Healthcare Time-series. In Arxiv, 2024.

Notes

This implementation is inspired by the official one the official implementation https://github.com/LinglongQian/CSAI.

class pypots.classification.csai.CSAI(n_steps, n_features, rnn_hidden_size, imputation_weight, consistency_weight, classification_weight, n_classes, removal_percent, increase_factor, step_channels, dropout=0.5, batch_size=32, epochs=100, patience=None, training_loss=<class 'pypots.nn.modules.loss.CrossEntropy'>, validation_metric=<class 'pypots.nn.modules.loss.CrossEntropy'>, optimizer=<class 'pypots.optim.adam.Adam'>, num_workers=0, device=None, saving_path=None, model_saving_strategy='best', verbose=True)[source]

Bases: BaseNNClassifier

The PyTorch implementation of the CSAI model.

Parameters

n_steps : The number of time steps in the time-series data sample.

n_features : The number of features in the time-series data sample.

rnn_hidden_size : The size of the RNN hidden state.

imputation_weight : The loss weight for the imputation task.

consistency_weight : The loss weight for the consistency task.

classification_weight : The loss weight for the classification task.

n_classes : The number of classes in the classification task.

removal_percent : The percentage of data to be removed during training for simulating missingness.

increase_factor : The factor to increase the frequency of missing value occurrences.

step_channels : The number of step channels for the model.

batch_size : The batch size for training and evaluating the model.

epochs :

The number of epochs for training the model.

patience :

The patience for the early-stopping mechanism. Given a positive integer, the training process will be stopped when the model does not perform better after that number of epochs. Leaving it default as None will disable the early-stopping.

training_loss:

The customized loss function designed by users for training the model. If not given, will use the default loss as claimed in the original paper.

validation_metric:

The customized metric function designed by users for validating the model. If not given, will use the default loss from the original paper as the metric.

optimizer :

The optimizer for model training. If not given, will use a default Adam optimizer.

num_workers :

The number of subprocesses to use for data loading. 0 means data loading will be in the main process, i.e. there won’t be subprocesses.

device :

The device for the model to run on. It can be a string, a torch.device object, or a list of them. If not given, will try to use CUDA devices first (will use the default CUDA device if there are multiple), then CPUs, considering CUDA and CPU are so far the main devices for people to train ML models. If given a list of devices, e.g. [‘cuda:0’, ‘cuda:1’], or [torch.device(‘cuda:0’), torch.device(‘cuda:1’)] , the model will be parallely trained on the multiple devices (so far only support parallel training on CUDA devices). Other devices like Google TPU and Apple Silicon accelerator MPS may be added in the future.

saving_path :

The path for automatically saving model checkpoints and tensorboard files (i.e. loss values recorded during training into a tensorboard file). Will not save if not given.

model_saving_strategy :

The strategy to save model checkpoints. It has to be one of [None, “best”, “better”, “all”]. No model will be saved when it is set as None. The “best” strategy will only automatically save the best model after the training finished. The “better” strategy will automatically save the model during training whenever the model performs better than in previous epochs. The “all” strategy will save every model after each epoch training.

verbose :

Whether to print out the training logs during the training process.

fit(train_set, val_set=None, file_type='hdf5')[source]

Train the classifier on the given data.

Parameters:
  • train_set – The dataset for model training, should be a dictionary including keys as ‘X’ and ‘y’, or a path string locating a data file. If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is time-series data for training, can contain missing values, and y should be array-like of shape [n_samples], which is classification labels of X. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include keys as ‘X’ and ‘y’.

  • val_set – The dataset for model validating, should be a dictionary including keys as ‘X’ and ‘y’, or a path string locating a data file. If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is time-series data for validating, can contain missing values, and y should be array-like of shape [n_samples], which is classification labels of X. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include keys as ‘X’ and ‘y’.

  • file_type (str) – The type of the given file if train_set and val_set are path strings.

Return type:

None

classify(test_set, file_type='hdf5', **kwargs)

Classify the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The data samples for testing, should be array-like with shape [n_samples, n_steps, n_features], or a path string locating a data file, e.g. h5 file.

  • file_type (str) – The type of the given file if X is a path string.

Returns:

Classification results of the given samples.

Return type:

results

load(path)

Load the saved model from a disk file.

Parameters:

path (str) – The local path to a disk file saving the trained model.

Return type:

None

Notes

If the training environment and the deploying/test environment use the same type of device (GPU/CPU), you can load the model directly with torch.load(model_path).

On PyTorch versions that support it, PyPOTS loads checkpoint files with weights_only=True so deserializing model state does not execute arbitrary pickle payloads from untrusted files.

predict(test_set, file_type='hdf5')[source]

Make predictions for the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The test dataset for model to process, should be a dictionary including keys as ‘X’, or a path string locating a data file supported by PyPOTS (e.g. h5 file). If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is the time-series data for processing. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include ‘X’ key.

  • file_type (str) – The type of the given file if test_set is a path string.

Returns:

The dictionary containing the classification results as key ‘classification’ and latent variables if necessary.

Return type:

result_dict

predict_proba(test_set, file_type='hdf5', **kwargs)

Predict the classification probabilities of the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The data samples for testing, should be array-like with shape [n_samples, n_steps, n_features], or a path string locating a data file, e.g. h5 file.

  • file_type (str) – The type of the given file if X is a path string.

Returns:

Classification probabilities of the given samples.

Return type:

results

save(saving_path, overwrite=False)

Save the model with current parameters to a disk file.

A .pypots extension will be appended to the filename if it does not already have one. Please note that such an extension is not necessary, but to indicate the saved model is from PyPOTS framework so people can distinguish.

Parameters:
  • saving_path (str) – The given path to save the model. The directory will be created if it does not exist.

  • overwrite (bool) – Whether to overwrite the model file if the path already exists.

Return type:

None

to(device)

Move the model to the given device.

Parameters:

device (Union[str, device]) – The device to move the model to. It can be a string or a torch.device object.

Return type:

None

pypots.classification.timesnet

The package of the partially-observed time-series classification model TimesNet.

Refer to the paper Haixu Wu, Tengge Hu, Yong Liu, Hang Zhou, Jianmin Wang, and Mingsheng Long. TimesNet: Temporal 2D-Variation Modeling for General Time Series Analysis. In ICLR, 2023.

Notes

This implementation is inspired by the official one https://github.com/thuml/Time-Series-Library

class pypots.classification.timesnet.TimesNet(n_steps, n_features, n_classes, n_layers, top_k, d_model, d_ffn, n_kernels, dropout=0, batch_size=32, epochs=100, patience=None, training_loss=<class 'pypots.nn.modules.loss.CrossEntropy'>, validation_metric=<class 'pypots.nn.modules.loss.CrossEntropy'>, optimizer=<pypots.optim.adam.Adam object>, num_workers=0, device=None, saving_path=None, model_saving_strategy='best', verbose=True)[source]

Bases: BaseNNClassifier

The PyTorch implementation of the TimesNet classification model [22].

Parameters:
  • n_steps (int) – The number of time steps in the time-series data sample.

  • n_features (int) – The number of features in the time-series data sample.

  • n_classes (int) – The number of classes in the classification task.

  • n_layers (int) – The number of layers in the TimesNet model.

  • top_k (int) – The number of top-k amplitude values to be selected to obtain the most significant frequencies.

  • d_model (int) – The dimension of the model.

  • d_ffn (int) – The dimension of the feed-forward network.

  • n_kernels (int) – The number of 2D kernels (2D convolutional layers) to use in the submodule InceptionBlockV1.

  • dropout (float) – The dropout rate for the model.

  • batch_size (int) – The batch size for training and evaluating the model.

  • epochs (int) – The number of epochs for training the model.

  • patience (Optional[int]) – The patience for the early-stopping mechanism. Given a positive integer, the training process will be stopped when the model does not perform better after that number of epochs. Leaving it default as None will disable the early-stopping.

  • training_loss (Union[Criterion, type]) – The customized loss function designed by users for training the model. If not given, will use the default loss as claimed in the original paper.

  • validation_metric (Union[Criterion, type]) – The customized metric function designed by users for validating the model. If not given, will use the default loss from the original paper as the metric.

  • optimizer (Optimizer) – The optimizer for model training. If not given, will use a default Adam optimizer.

  • num_workers (int) – The number of subprocesses to use for data loading. 0 means data loading will be in the main process, i.e. there won’t be subprocesses.

  • device (Union[str, device, list, None]) – The device for the model to run on. It can be a string, a torch.device object, or a list of them. If not given, will try to use CUDA devices first (will use the default CUDA device if there are multiple), then CPUs, considering CUDA and CPU are so far the main devices for people to train ML models. If given a list of devices, e.g. [‘cuda:0’, ‘cuda:1’], or [torch.device(‘cuda:0’), torch.device(‘cuda:1’)] , the model will be parallely trained on the multiple devices (so far only support parallel training on CUDA devices). Other devices like Google TPU and Apple Silicon accelerator MPS may be added in the future.

  • saving_path (Optional[str]) – The path for automatically saving model checkpoints and tensorboard files (i.e. loss values recorded during training into a tensorboard file). Will not save if not given.

  • model_saving_strategy (Optional[str]) – The strategy to save model checkpoints. It has to be one of [None, “best”, “better”, “all”]. No model will be saved when it is set as None. The “best” strategy will only automatically save the best model after the training finished. The “better” strategy will automatically save the model during training whenever the model performs better than in previous epochs. The “all” strategy will save every model after each epoch training.

  • verbose (bool) – Whether to print out the training logs during the training process.

classify(test_set, file_type='hdf5', **kwargs)

Classify the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The data samples for testing, should be array-like with shape [n_samples, n_steps, n_features], or a path string locating a data file, e.g. h5 file.

  • file_type (str) – The type of the given file if X is a path string.

Returns:

Classification results of the given samples.

Return type:

results

fit(train_set, val_set=None, file_type='hdf5')

Train the classifier on the given data.

Parameters:
  • train_set (Union[dict, str]) – The dataset for model training, should be a dictionary including keys as ‘X’ and ‘y’, or a path string locating a data file. If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is time-series data for training, can contain missing values, and y should be array-like of shape [n_samples], which is classification labels of X. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include keys as ‘X’ and ‘y’.

  • val_set (Union[dict, str, None]) – The dataset for model validating, should be a dictionary including keys as ‘X’ and ‘y’, or a path string locating a data file. If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is time-series data for validating, can contain missing values, and y should be array-like of shape [n_samples], which is classification labels of X. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include keys as ‘X’ and ‘y’.

  • file_type (str) – The type of the given file if train_set and val_set are path strings.

Return type:

None

load(path)

Load the saved model from a disk file.

Parameters:

path (str) – The local path to a disk file saving the trained model.

Return type:

None

Notes

If the training environment and the deploying/test environment use the same type of device (GPU/CPU), you can load the model directly with torch.load(model_path).

On PyTorch versions that support it, PyPOTS loads checkpoint files with weights_only=True so deserializing model state does not execute arbitrary pickle payloads from untrusted files.

predict(test_set, file_type='hdf5', **kwargs)

Make predictions for the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The test dataset for model to process, should be a dictionary including keys as ‘X’, or a path string locating a data file supported by PyPOTS (e.g. h5 file). If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is the time-series data for processing. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include ‘X’ key.

  • file_type (str) – The type of the given file if test_set is a path string.

Returns:

The dictionary containing the classification results as key ‘classification’ and latent variables if necessary.

Return type:

result_dict

predict_proba(test_set, file_type='hdf5', **kwargs)

Predict the classification probabilities of the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The data samples for testing, should be array-like with shape [n_samples, n_steps, n_features], or a path string locating a data file, e.g. h5 file.

  • file_type (str) – The type of the given file if X is a path string.

Returns:

Classification probabilities of the given samples.

Return type:

results

save(saving_path, overwrite=False)

Save the model with current parameters to a disk file.

A .pypots extension will be appended to the filename if it does not already have one. Please note that such an extension is not necessary, but to indicate the saved model is from PyPOTS framework so people can distinguish.

Parameters:
  • saving_path (str) – The given path to save the model. The directory will be created if it does not exist.

  • overwrite (bool) – Whether to overwrite the model file if the path already exists.

Return type:

None

to(device)

Move the model to the given device.

Parameters:

device (Union[str, device]) – The device to move the model to. It can be a string or a torch.device object.

Return type:

None

pypots.classification.autoformer

The package of the partially-observed time-series classification model Autoformer.

Refer to the paper Haixu Wu, Jiehui Xu, Jianmin Wang, and Mingsheng Long. Autoformer: Decomposition transformers with autocorrelation for long-term series forecasting. In Advances in Neural Information Processing Systems, volume 34, pages 22419–22430. Curran Associates, Inc., 2021.

Notes

This implementation is inspired by the official one https://github.com/thuml/Autoformer

class pypots.classification.autoformer.Autoformer(n_steps, n_features, n_classes, n_layers, d_model, n_heads, d_ffn, factor, moving_avg_window_size, dropout=0, batch_size=32, epochs=100, patience=None, training_loss=<class 'pypots.nn.modules.loss.CrossEntropy'>, validation_metric=<class 'pypots.nn.modules.loss.CrossEntropy'>, optimizer=<pypots.optim.adam.Adam object>, num_workers=0, device=None, saving_path=None, model_saving_strategy='best', verbose=True)[source]

Bases: BaseNNClassifier

The PyTorch implementation of the Autoformer classification model [36].

Parameters:
  • n_steps (int) – The number of time steps in the time-series data sample.

  • n_features (int) – The number of features in the time-series data sample.

  • n_classes (int) – The number of classes in the classification task.

  • n_layers (int) – The number of layers in the Autoformer model.

  • d_model (int) – The dimension of the model.

  • n_heads (int) – The number of heads in each layer of Autoformer.

  • d_ffn (int) – The dimension of the feed-forward network.

  • factor (int) – The factor of the auto correlation mechanism for the Autoformer model.

  • moving_avg_window_size (int) – The window size of moving average.

  • dropout (float) – The dropout rate for the model.

batch_size :

The batch size for training and evaluating the model.

epochs :

The number of epochs for training the model.

patience :

The patience for the early-stopping mechanism. Given a positive integer, the training process will be stopped when the model does not perform better after that number of epochs. Leaving it default as None will disable the early-stopping.

training_loss:

The customized loss function designed by users for training the model. If not given, will use the default loss as claimed in the original paper.

validation_metric:

The customized metric function designed by users for validating the model. If not given, will use the default loss from the original paper as the metric.

optimizer :

The optimizer for model training. If not given, will use a default Adam optimizer.

num_workers :

The number of subprocesses to use for data loading. 0 means data loading will be in the main process, i.e. there won’t be subprocesses.

device :

The device for the model to run on. It can be a string, a torch.device object, or a list of them. If not given, will try to use CUDA devices first (will use the default CUDA device if there are multiple), then CPUs, considering CUDA and CPU are so far the main devices for people to train ML models. If given a list of devices, e.g. [‘cuda:0’, ‘cuda:1’], or [torch.device(‘cuda:0’), torch.device(‘cuda:1’)] , the model will be parallely trained on the multiple devices (so far only support parallel training on CUDA devices). Other devices like Google TPU and Apple Silicon accelerator MPS may be added in the future.

saving_path :

The path for automatically saving model checkpoints and tensorboard files (i.e. loss values recorded during training into a tensorboard file). Will not save if not given.

model_saving_strategy :

The strategy to save model checkpoints. It has to be one of [None, “best”, “better”, “all”]. No model will be saved when it is set as None. The “best” strategy will only automatically save the best model after the training finished. The “better” strategy will automatically save the model during training whenever the model performs better than in previous epochs. The “all” strategy will save every model after each epoch training.

verbose :

Whether to print out the training logs during the training process.

classify(test_set, file_type='hdf5', **kwargs)

Classify the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The data samples for testing, should be array-like with shape [n_samples, n_steps, n_features], or a path string locating a data file, e.g. h5 file.

  • file_type (str) – The type of the given file if X is a path string.

Returns:

Classification results of the given samples.

Return type:

results

fit(train_set, val_set=None, file_type='hdf5')

Train the classifier on the given data.

Parameters:
  • train_set (Union[dict, str]) – The dataset for model training, should be a dictionary including keys as ‘X’ and ‘y’, or a path string locating a data file. If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is time-series data for training, can contain missing values, and y should be array-like of shape [n_samples], which is classification labels of X. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include keys as ‘X’ and ‘y’.

  • val_set (Union[dict, str, None]) – The dataset for model validating, should be a dictionary including keys as ‘X’ and ‘y’, or a path string locating a data file. If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is time-series data for validating, can contain missing values, and y should be array-like of shape [n_samples], which is classification labels of X. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include keys as ‘X’ and ‘y’.

  • file_type (str) – The type of the given file if train_set and val_set are path strings.

Return type:

None

load(path)

Load the saved model from a disk file.

Parameters:

path (str) – The local path to a disk file saving the trained model.

Return type:

None

Notes

If the training environment and the deploying/test environment use the same type of device (GPU/CPU), you can load the model directly with torch.load(model_path).

On PyTorch versions that support it, PyPOTS loads checkpoint files with weights_only=True so deserializing model state does not execute arbitrary pickle payloads from untrusted files.

predict(test_set, file_type='hdf5', **kwargs)

Make predictions for the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The test dataset for model to process, should be a dictionary including keys as ‘X’, or a path string locating a data file supported by PyPOTS (e.g. h5 file). If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is the time-series data for processing. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include ‘X’ key.

  • file_type (str) – The type of the given file if test_set is a path string.

Returns:

The dictionary containing the classification results as key ‘classification’ and latent variables if necessary.

Return type:

result_dict

predict_proba(test_set, file_type='hdf5', **kwargs)

Predict the classification probabilities of the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The data samples for testing, should be array-like with shape [n_samples, n_steps, n_features], or a path string locating a data file, e.g. h5 file.

  • file_type (str) – The type of the given file if X is a path string.

Returns:

Classification probabilities of the given samples.

Return type:

results

save(saving_path, overwrite=False)

Save the model with current parameters to a disk file.

A .pypots extension will be appended to the filename if it does not already have one. Please note that such an extension is not necessary, but to indicate the saved model is from PyPOTS framework so people can distinguish.

Parameters:
  • saving_path (str) – The given path to save the model. The directory will be created if it does not exist.

  • overwrite (bool) – Whether to overwrite the model file if the path already exists.

Return type:

None

to(device)

Move the model to the given device.

Parameters:

device (Union[str, device]) – The device to move the model to. It can be a string or a torch.device object.

Return type:

None

pypots.classification.ts2vec

The package of the partially-observed time-series classification model TS2Vec.

Refer to the paper Zhihan Yue, Yujing Wang, Juanyong Duan, Tianmeng Yang, Congrui Huang, Yunhai Tong, Bixiong Xu. “TS2Vec: Towards Universal Representation of Time Series”. In AAAI 2022.

Notes

This implementation is inspired by the official one https://github.com/zhihanyue/ts2vec

class pypots.classification.ts2vec.TS2Vec(n_steps, n_features, n_classes, n_output_dims, d_hidden, n_layers, mask_mode='binomial', batch_size=32, epochs=100, patience=None, optimizer=<class 'pypots.optim.adam.Adam'>, num_workers=0, device=None, saving_path=None, model_saving_strategy='best', verbose=True)[source]

Bases: BaseNNClassifier

The PyTorch implementation of the TS2Vec model [2].

Parameters:
  • n_steps (int) – The number of time steps in the time-series data sample.

  • n_features (int) – The number of features in the time-series data sample.

  • n_classes (int) – The number of classes in the classification task.

  • n_output_dims (int) – The number of output dimensions for the vectorization of the time-series data sample.

  • d_hidden (int) – The number of hidden dimensions for the TS2VEC encoder.

  • n_layers (int) – The number of layers for the TS2VEC encoder.

  • mask_mode (str) – The mode for generating the mask for the TS2VEC encoder. It has to be one of [‘binomial’, ‘continuous’, ‘all_true’, ‘all_false’, ‘mask_last’].

  • batch_size (int) – The batch size for training and evaluating the model.

  • epochs (int) – The number of epochs for training the model.

  • patience (Optional[int]) – The patience for the early-stopping mechanism. Given a positive integer, the training process will be stopped when the model does not perform better after that number of epochs. Leaving it default as None will disable the early-stopping.

  • optimizer (Union[Optimizer, type]) – The optimizer for model training. If not given, will use a default Adam optimizer.

  • num_workers (int) – The number of subprocesses to use for data loading. 0 means data loading will be in the main process, i.e. there won’t be subprocesses.

  • device (Union[str, device, list, None]) – The device for the model to run on. It can be a string, a torch.device object, or a list of them. If not given, will try to use CUDA devices first (will use the default CUDA device if there are multiple), then CPUs, considering CUDA and CPU are so far the main devices for people to train ML models. If given a list of devices, e.g. [‘cuda:0’, ‘cuda:1’], or [torch.device(‘cuda:0’), torch.device(‘cuda:1’)] , the model will be parallely trained on the multiple devices (so far only support parallel training on CUDA devices). Other devices like Google TPU and Apple Silicon accelerator MPS may be added in the future.

  • saving_path (Optional[str]) – The path for automatically saving model checkpoints and tensorboard files (i.e. loss values recorded during training into a tensorboard file). Will not save if not given.

  • model_saving_strategy (Optional[str]) – The strategy to save model checkpoints. It has to be one of [None, “best”, “better”, “all”]. No model will be saved when it is set as None. The “best” strategy will only automatically save the best model after the training finished. The “better” strategy will automatically save the model during training whenever the model performs better than in previous epochs. The “all” strategy will save every model after each epoch training.

  • verbose (bool) – Whether to print out the training logs during the training process.

fit(train_set, val_set=None, file_type='hdf5')[source]

Train the classifier on the given data.

Parameters:
  • train_set (Union[dict, str]) – The dataset for model training, should be a dictionary including keys as ‘X’ and ‘y’, or a path string locating a data file. If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is time-series data for training, can contain missing values, and y should be array-like of shape [n_samples], which is classification labels of X. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include keys as ‘X’ and ‘y’.

  • val_set (Union[dict, str, None]) – The dataset for model validating, should be a dictionary including keys as ‘X’ and ‘y’, or a path string locating a data file. If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is time-series data for validating, can contain missing values, and y should be array-like of shape [n_samples], which is classification labels of X. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include keys as ‘X’ and ‘y’.

  • file_type (str) – The type of the given file if train_set and val_set are path strings.

Return type:

None

predict(test_set, file_type='hdf5', classifier_type='svm')[source]

Make predictions for the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The test dataset for model to process, should be a dictionary including keys as ‘X’, or a path string locating a data file supported by PyPOTS (e.g. h5 file). If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is the time-series data for processing. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include ‘X’ key.

  • file_type (str) – The type of the given file if test_set is a path string.

  • classifier_type (str) – The type of classifier to use for the classification task. It has to be one of [‘lr’, ‘svm’, ‘knn’].

Returns:

The dictionary containing the classification results as key ‘classification’ and latent variables if necessary.

Return type:

result_dict

predict_proba(test_set, file_type='hdf5', classifier_type='svm')[source]

Predict the classification probabilities of the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The data samples for testing, should be array-like with shape [n_samples, n_steps, n_features], or a path string locating a data file, e.g. h5 file.

  • file_type (str) – The type of the given file if X is a path string.

  • classifier_type (str) – The type of classifier to use for the classification task. It has to be one of [‘lr’, ‘svm’, ‘knn’].

Returns:

Classification probabilities of the given samples.

Return type:

results

classify(test_set, file_type='hdf5', classifier_type='svm')[source]

Classify the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The test dataset for model to process, should be a dictionary including keys as ‘X’, or a path string locating a data file supported by PyPOTS (e.g. h5 file). If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is the time-series data for processing. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include ‘X’ key.

  • file_type (str) – The type of the given file if test_set is a path string.

  • classifier_type (str) – The type of classifier to use for the classification task. It has to be one of [‘lr’, ‘svm’, ‘knn’].

Returns:

Classification results of the given samples.

Return type:

results

load(path)

Load the saved model from a disk file.

Parameters:

path (str) – The local path to a disk file saving the trained model.

Return type:

None

Notes

If the training environment and the deploying/test environment use the same type of device (GPU/CPU), you can load the model directly with torch.load(model_path).

On PyTorch versions that support it, PyPOTS loads checkpoint files with weights_only=True so deserializing model state does not execute arbitrary pickle payloads from untrusted files.

save(saving_path, overwrite=False)

Save the model with current parameters to a disk file.

A .pypots extension will be appended to the filename if it does not already have one. Please note that such an extension is not necessary, but to indicate the saved model is from PyPOTS framework so people can distinguish.

Parameters:
  • saving_path (str) – The given path to save the model. The directory will be created if it does not exist.

  • overwrite (bool) – Whether to overwrite the model file if the path already exists.

Return type:

None

to(device)

Move the model to the given device.

Parameters:

device (Union[str, device]) – The device to move the model to. It can be a string or a torch.device object.

Return type:

None

pypots.classification.grud

The package of the partially-observed time-series classification model GRU-D.

Refer to the paper Zhengping Che, Sanjay Purushotham, Kyunghyun Cho, David Sontag, and Yan Liu. Recurrent Neural Networks for Multivariate Time Series with Missing Values. Scientific Reports, 8(1):6085, April 2018.

Notes

This implementation is inspired by the official one https://github.com/PeterChe1990/GRU-D

class pypots.classification.grud.GRUD(n_steps, n_features, n_classes, rnn_hidden_size, batch_size=32, epochs=100, patience=None, training_loss=<class 'pypots.nn.modules.loss.CrossEntropy'>, validation_metric=<class 'pypots.nn.modules.loss.CrossEntropy'>, optimizer=<class 'pypots.optim.adam.Adam'>, num_workers=0, device=None, saving_path=None, model_saving_strategy='best', verbose=True)[source]

Bases: BaseNNClassifier

The PyTorch implementation of the GRU-D model [49].

Parameters:
  • n_steps (int) – The number of time steps in the time-series data sample.

  • n_features (int) – The number of features in the time-series data sample.

  • n_classes (int) – The number of classes in the classification task.

  • rnn_hidden_size (int) – The size of the RNN hidden state.

  • batch_size (int) – The batch size for training and evaluating the model.

  • epochs (int) – The number of epochs for training the model.

  • patience (Optional[int]) – The patience for the early-stopping mechanism. Given a positive integer, the training process will be stopped when the model does not perform better after that number of epochs. Leaving it default as None will disable the early-stopping.

  • training_loss (Union[Criterion, type]) – The customized loss function designed by users for training the model. If not given, will use the default loss as claimed in the original paper.

  • validation_metric (Union[Criterion, type]) – The customized metric function designed by users for validating the model. If not given, will use the default loss from the original paper as the metric.

  • optimizer (Union[Optimizer, type]) – The optimizer for model training. If not given, will use a default Adam optimizer.

  • num_workers (int) – The number of subprocesses to use for data loading. 0 means data loading will be in the main process, i.e. there won’t be subprocesses.

  • device (Union[str, device, list, None]) – The device for the model to run on. It can be a string, a torch.device object, or a list of them. If not given, will try to use CUDA devices first (will use the default CUDA device if there are multiple), then CPUs, considering CUDA and CPU are so far the main devices for people to train ML models. If given a list of devices, e.g. [‘cuda:0’, ‘cuda:1’], or [torch.device(‘cuda:0’), torch.device(‘cuda:1’)] , the model will be parallely trained on the multiple devices (so far only support parallel training on CUDA devices). Other devices like Google TPU and Apple Silicon accelerator MPS may be added in the future.

  • saving_path (Optional[str]) – The path for automatically saving model checkpoints and tensorboard files (i.e. loss values recorded during training into a tensorboard file). Will not save if not given.

  • model_saving_strategy (Optional[str]) – The strategy to save model checkpoints. It has to be one of [None, “best”, “better”, “all”]. No model will be saved when it is set as None. The “best” strategy will only automatically save the best model after the training finished. The “better” strategy will automatically save the model during training whenever the model performs better than in previous epochs. The “all” strategy will save every model after each epoch training.

  • verbose (bool) – Whether to print out the training logs during the training process.

fit(train_set, val_set=None, file_type='hdf5')[source]

Train the classifier on the given data.

Parameters:
  • train_set (Union[dict, str]) – The dataset for model training, should be a dictionary including keys as ‘X’ and ‘y’, or a path string locating a data file. If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is time-series data for training, can contain missing values, and y should be array-like of shape [n_samples], which is classification labels of X. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include keys as ‘X’ and ‘y’.

  • val_set (Union[dict, str, None]) – The dataset for model validating, should be a dictionary including keys as ‘X’ and ‘y’, or a path string locating a data file. If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is time-series data for validating, can contain missing values, and y should be array-like of shape [n_samples], which is classification labels of X. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include keys as ‘X’ and ‘y’.

  • file_type (str) – The type of the given file if train_set and val_set are path strings.

Return type:

None

classify(test_set, file_type='hdf5', **kwargs)

Classify the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The data samples for testing, should be array-like with shape [n_samples, n_steps, n_features], or a path string locating a data file, e.g. h5 file.

  • file_type (str) – The type of the given file if X is a path string.

Returns:

Classification results of the given samples.

Return type:

results

load(path)

Load the saved model from a disk file.

Parameters:

path (str) – The local path to a disk file saving the trained model.

Return type:

None

Notes

If the training environment and the deploying/test environment use the same type of device (GPU/CPU), you can load the model directly with torch.load(model_path).

On PyTorch versions that support it, PyPOTS loads checkpoint files with weights_only=True so deserializing model state does not execute arbitrary pickle payloads from untrusted files.

predict(test_set, file_type='hdf5')[source]

Make predictions for the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The test dataset for model to process, should be a dictionary including keys as ‘X’, or a path string locating a data file supported by PyPOTS (e.g. h5 file). If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is the time-series data for processing. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include ‘X’ key.

  • file_type (str) – The type of the given file if test_set is a path string.

Returns:

The dictionary containing the classification results as key ‘classification’ and latent variables if necessary.

Return type:

result_dict

predict_proba(test_set, file_type='hdf5', **kwargs)

Predict the classification probabilities of the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The data samples for testing, should be array-like with shape [n_samples, n_steps, n_features], or a path string locating a data file, e.g. h5 file.

  • file_type (str) – The type of the given file if X is a path string.

Returns:

Classification probabilities of the given samples.

Return type:

results

save(saving_path, overwrite=False)

Save the model with current parameters to a disk file.

A .pypots extension will be appended to the filename if it does not already have one. Please note that such an extension is not necessary, but to indicate the saved model is from PyPOTS framework so people can distinguish.

Parameters:
  • saving_path (str) – The given path to save the model. The directory will be created if it does not exist.

  • overwrite (bool) – Whether to overwrite the model file if the path already exists.

Return type:

None

to(device)

Move the model to the given device.

Parameters:

device (Union[str, device]) – The device to move the model to. It can be a string or a torch.device object.

Return type:

None

pypots.classification.raindrop

The package of the partially-observed time-series classification model Raindrop.

Refer to the paper Xiang Zhang, Marko Zeman, Theodoros Tsiligkaridis, and Marinka Zitnik. Graph-guided network for irregularly sampled multivariate time series. In ICLR, 2022.

Notes

This implementation is inspired by the official one the official implementation https://github.com/mims-harvard/Raindrop

class pypots.classification.raindrop.Raindrop(n_steps, n_features, n_classes, n_layers, d_model, n_heads, d_ffn, dropout, d_static=0, aggregation='mean', sensor_wise_mask=False, static=False, batch_size=32, epochs=100, patience=None, training_loss=<class 'pypots.nn.modules.loss.CrossEntropy'>, validation_metric=<class 'pypots.nn.modules.loss.CrossEntropy'>, optimizer=<class 'pypots.optim.adam.Adam'>, num_workers=0, device=None, saving_path=None, model_saving_strategy='best', verbose=True)[source]

Bases: BaseNNClassifier

The PyTorch implementation of the Raindrop model [34].

Parameters:
  • n_steps – The number of time steps in the time-series data sample.

  • n_features – The number of features in the time-series data samples.

  • n_classes – The number of classes in the classification task.

  • n_layers – The number of layers in the Transformer encoder in the Raindrop model.

  • d_model – The dimension of the Transformer encoder backbone. It is the input dimension of the multi-head self-attention layers.

  • n_heads – The number of heads in the multi-head self-attention mechanism.

  • d_ffn – The dimension of the layer in the Feed-Forward Networks (FFN).

  • dropout – The dropout rate for all fully-connected layers in the model.

  • d_static – The dimension of the static features.

  • aggregation – The aggregation method for the Transformer encoder output.

  • sensor_wise_mask – Whether to apply the sensor-wise masking.

  • static – Whether to use the static features.

  • batch_size – The batch size for training and evaluating the model.

  • epochs – The number of epochs for training the model.

  • patience (Optional[int]) – The patience for the early-stopping mechanism. Given a positive integer, the training process will be stopped when the model does not perform better after that number of epochs. Leaving it default as None will disable the early-stopping.

  • training_loss (Union[Criterion, type]) – The customized loss function designed by users for training the model. If not given, will use the default loss as claimed in the original paper.

  • validation_metric (Union[Criterion, type]) – The customized metric function designed by users for validating the model. If not given, will use the default loss from the original paper as the metric.

  • optimizer (Union[Optimizer, type]) – The optimizer for model training. If not given, will use a default Adam optimizer.

  • num_workers (int) – The number of subprocesses to use for data loading. 0 means data loading will be in the main process, i.e. there won’t be subprocesses.

  • device (Union[str, device, list, None]) – The device for the model to run on. It can be a string, a torch.device object, or a list of them. If not given, will try to use CUDA devices first (will use the default CUDA device if there are multiple), then CPUs, considering CUDA and CPU are so far the main devices for people to train ML models. If given a list of devices, e.g. [‘cuda:0’, ‘cuda:1’], or [torch.device(‘cuda:0’), torch.device(‘cuda:1’)] , the model will be parallely trained on the multiple devices (so far only support parallel training on CUDA devices). Other devices like Google TPU and Apple Silicon accelerator MPS may be added in the future.

  • saving_path (Optional[str]) – The path for automatically saving model checkpoints and tensorboard files (i.e. loss values recorded during training into a tensorboard file). Will not save if not given.

  • model_saving_strategy (Optional[str]) – The strategy to save model checkpoints. It has to be one of [None, “best”, “better”, “all”]. No model will be saved when it is set as None. The “best” strategy will only automatically save the best model after the training finished. The “better” strategy will automatically save the model during training whenever the model performs better than in previous epochs. The “all” strategy will save every model after each epoch training.

  • verbose (bool) – Whether to print out the training logs during the training process.

fit(train_set, val_set=None, file_type='hdf5')[source]

Train the classifier on the given data.

Parameters:
  • train_set (Union[dict, str]) – The dataset for model training, should be a dictionary including keys as ‘X’ and ‘y’, or a path string locating a data file. If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is time-series data for training, can contain missing values, and y should be array-like of shape [n_samples], which is classification labels of X. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include keys as ‘X’ and ‘y’.

  • val_set (Union[dict, str, None]) – The dataset for model validating, should be a dictionary including keys as ‘X’ and ‘y’, or a path string locating a data file. If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is time-series data for validating, can contain missing values, and y should be array-like of shape [n_samples], which is classification labels of X. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include keys as ‘X’ and ‘y’.

  • file_type (str) – The type of the given file if train_set and val_set are path strings.

Return type:

None

classify(test_set, file_type='hdf5', **kwargs)

Classify the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The data samples for testing, should be array-like with shape [n_samples, n_steps, n_features], or a path string locating a data file, e.g. h5 file.

  • file_type (str) – The type of the given file if X is a path string.

Returns:

Classification results of the given samples.

Return type:

results

load(path)

Load the saved model from a disk file.

Parameters:

path (str) – The local path to a disk file saving the trained model.

Return type:

None

Notes

If the training environment and the deploying/test environment use the same type of device (GPU/CPU), you can load the model directly with torch.load(model_path).

On PyTorch versions that support it, PyPOTS loads checkpoint files with weights_only=True so deserializing model state does not execute arbitrary pickle payloads from untrusted files.

predict(test_set, file_type='hdf5')[source]

Make predictions for the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The test dataset for model to process, should be a dictionary including keys as ‘X’, or a path string locating a data file supported by PyPOTS (e.g. h5 file). If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is the time-series data for processing. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include ‘X’ key.

  • file_type (str) – The type of the given file if test_set is a path string.

Returns:

The dictionary containing the classification results as key ‘classification’ and latent variables if necessary.

Return type:

result_dict

predict_proba(test_set, file_type='hdf5', **kwargs)

Predict the classification probabilities of the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The data samples for testing, should be array-like with shape [n_samples, n_steps, n_features], or a path string locating a data file, e.g. h5 file.

  • file_type (str) – The type of the given file if X is a path string.

Returns:

Classification probabilities of the given samples.

Return type:

results

save(saving_path, overwrite=False)

Save the model with current parameters to a disk file.

A .pypots extension will be appended to the filename if it does not already have one. Please note that such an extension is not necessary, but to indicate the saved model is from PyPOTS framework so people can distinguish.

Parameters:
  • saving_path (str) – The given path to save the model. The directory will be created if it does not exist.

  • overwrite (bool) – Whether to overwrite the model file if the path already exists.

Return type:

None

to(device)

Move the model to the given device.

Parameters:

device (Union[str, device]) – The device to move the model to. It can be a string or a torch.device object.

Return type:

None

pypots.classification.seft

The package of the partially-observed time-series classification model SeFT.

Refer to the paper Max Horn, Michael Moor, Christian Bock, Bastian Rieck, and Karsten Borgwardt. Set Functions for Time Series. In the 37th International Conference on Machine Learning, 2020.

Notes

This implementation is inspired by the official one https://github.com/BorgwardtLab/Set_Functions_for_Time_Series

class pypots.classification.seft.SeFT(n_steps, n_features, n_classes, n_layers, n_heads, d_model, d_ffn, n_seeds=4, dropout=0.0, max_timescale=100.0, batch_size=32, epochs=100, patience=None, training_loss=<class 'pypots.nn.modules.loss.CrossEntropy'>, validation_metric=<class 'pypots.nn.modules.loss.CrossEntropy'>, optimizer=<class 'pypots.optim.adam.Adam'>, num_workers=0, device=None, saving_path=None, model_saving_strategy='best', verbose=True)[source]

Bases: BaseNNClassifier

The PyTorch implementation of the SeFT model [43].

Parameters:
  • n_steps (int) – The number of time steps in the time-series data sample.

  • n_features (int) – The number of features in the time-series data sample.

  • n_classes (int) – The number of classes in the classification task.

  • n_layers (int) – The number of Set Attention Block (SAB) layers in the SeFT encoder.

  • n_heads (int) – The number of attention heads in each SAB and in the PMA pooling layer.

  • d_model (int) – The dimensionality of the set-function encoder. Must be divisible by n_heads for the multi-head attention to work correctly.

  • d_ffn (int) – The hidden dimensionality of the point-wise feed-forward networks inside each SAB and in the PMA layer.

  • n_seeds (int) – The number of seed vectors used by the PMA (Pooling by Multi-head Attention) aggregation layer. More seeds capture richer summary statistics at the cost of extra parameters.

  • dropout (float) – The dropout probability applied inside SAB and PMA layers.

  • max_timescale (float) – The maximum timescale for the sinusoidal time encoding. Larger values allow the model to distinguish time differences over a wider range.

  • batch_size (int) – The batch size for training and evaluating the model.

  • epochs (int) – The number of epochs for training the model.

  • patience (Optional[int]) – The patience for the early-stopping mechanism. Given a positive integer, the training process will be stopped when the model does not perform better after that number of epochs. Leaving it default as None will disable the early-stopping.

  • training_loss (Union[Criterion, type]) – The customized loss function designed by users for training the model. If not given, will use the default loss as claimed in the original paper.

  • validation_metric (Union[Criterion, type]) – The customized metric function designed by users for validating the model. If not given, will use the default loss from the original paper as the metric.

  • optimizer (Union[Optimizer, type]) – The optimizer for model training. If not given, will use a default Adam optimizer.

  • num_workers (int) – The number of subprocesses to use for data loading. 0 means data loading will be in the main process, i.e. there won’t be subprocesses.

  • device (Union[str, device, list, None]) – The device for the model to run on. It can be a string, a torch.device object, or a list of them. If not given, will try to use CUDA devices first (will use the default CUDA device if there are multiple), then CPUs, considering CUDA and CPU are so far the main devices for people to train ML models. If given a list of devices, e.g. [‘cuda:0’, ‘cuda:1’], or [torch.device(‘cuda:0’), torch.device(‘cuda:1’)] , the model will be parallely trained on the multiple devices (so far only support parallel training on CUDA devices). Other devices like Google TPU and Apple Silicon accelerator MPS may be added in the future.

  • saving_path (Optional[str]) – The path for automatically saving model checkpoints and tensorboard files (i.e. loss values recorded during training into a tensorboard file). Will not save if not given.

  • model_saving_strategy (Optional[str]) – The strategy to save model checkpoints. It has to be one of [None, “best”, “better”, “all”]. No model will be saved when it is set as None. The “best” strategy will only automatically save the best model after the training finished. The “better” strategy will automatically save the model during training whenever the model performs better than in previous epochs. The “all” strategy will save every model after each epoch training.

  • verbose (bool) – Whether to print out the training logs during the training process.

classify(test_set, file_type='hdf5', **kwargs)

Classify the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The data samples for testing, should be array-like with shape [n_samples, n_steps, n_features], or a path string locating a data file, e.g. h5 file.

  • file_type (str) – The type of the given file if X is a path string.

Returns:

Classification results of the given samples.

Return type:

results

fit(train_set, val_set=None, file_type='hdf5')

Train the classifier on the given data.

Parameters:
  • train_set (Union[dict, str]) – The dataset for model training, should be a dictionary including keys as ‘X’ and ‘y’, or a path string locating a data file. If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is time-series data for training, can contain missing values, and y should be array-like of shape [n_samples], which is classification labels of X. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include keys as ‘X’ and ‘y’.

  • val_set (Union[dict, str, None]) – The dataset for model validating, should be a dictionary including keys as ‘X’ and ‘y’, or a path string locating a data file. If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is time-series data for validating, can contain missing values, and y should be array-like of shape [n_samples], which is classification labels of X. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include keys as ‘X’ and ‘y’.

  • file_type (str) – The type of the given file if train_set and val_set are path strings.

Return type:

None

load(path)

Load the saved model from a disk file.

Parameters:

path (str) – The local path to a disk file saving the trained model.

Return type:

None

Notes

If the training environment and the deploying/test environment use the same type of device (GPU/CPU), you can load the model directly with torch.load(model_path).

On PyTorch versions that support it, PyPOTS loads checkpoint files with weights_only=True so deserializing model state does not execute arbitrary pickle payloads from untrusted files.

predict(test_set, file_type='hdf5', **kwargs)

Make predictions for the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The test dataset for model to process, should be a dictionary including keys as ‘X’, or a path string locating a data file supported by PyPOTS (e.g. h5 file). If it is a dict, X should be array-like with shape [n_samples, n_steps, n_features], which is the time-series data for processing. If it is a path string, the path should point to a data file, e.g. a h5 file, which contains key-value pairs like a dict, and it has to include ‘X’ key.

  • file_type (str) – The type of the given file if test_set is a path string.

Returns:

The dictionary containing the classification results as key ‘classification’ and latent variables if necessary.

Return type:

result_dict

predict_proba(test_set, file_type='hdf5', **kwargs)

Predict the classification probabilities of the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The data samples for testing, should be array-like with shape [n_samples, n_steps, n_features], or a path string locating a data file, e.g. h5 file.

  • file_type (str) – The type of the given file if X is a path string.

Returns:

Classification probabilities of the given samples.

Return type:

results

save(saving_path, overwrite=False)

Save the model with current parameters to a disk file.

A .pypots extension will be appended to the filename if it does not already have one. Please note that such an extension is not necessary, but to indicate the saved model is from PyPOTS framework so people can distinguish.

Parameters:
  • saving_path (str) – The given path to save the model. The directory will be created if it does not exist.

  • overwrite (bool) – Whether to overwrite the model file if the path already exists.

Return type:

None

to(device)

Move the model to the given device.

Parameters:

device (Union[str, device]) – The device to move the model to. It can be a string or a torch.device object.

Return type:

None