pypots.classification package#

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, optimizer=<pypots.optim.adam.Adam object>, num_workers=0, device=None, saving_path=None, model_saving_strategy='best')[source]#

Bases: BaseNNClassifier

The PyTorch implementation of the BRITS model [27].

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.

  • optimizer (Optional[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.

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 of shape [n_samples, sequence length (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 of shape [n_samples, sequence length (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')[source]#

Make predictions for the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The dataset for model validating, 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 of shape [n_samples, sequence length (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 test_set is a path string.

Returns:

Prediction results in a Python Dictionary for the given samples. It should be a dictionary including keys as ‘imputation’, ‘classification’, ‘clustering’, and ‘forecasting’. For sure, only the keys that relevant tasks are supported by the model will be returned.

Return type:

result_dict

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

Classify the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The data samples for testing, should be array-like of shape [n_samples, sequence length (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:

array-like, shape [n_samples],

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).

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

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, optimizer=<pypots.optim.adam.Adam object>, num_workers=0, device=None, saving_path=None, model_saving_strategy='best')[source]#

Bases: BaseNNClassifier

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

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.

  • optimizer (Optional[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.

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 of shape [n_samples, sequence length (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 of shape [n_samples, sequence length (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')[source]#

Make predictions for the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The dataset for model validating, 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 of shape [n_samples, sequence length (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 test_set is a path string.

Returns:

Prediction results in a Python Dictionary for the given samples. It should be a dictionary including keys as ‘imputation’, ‘classification’, ‘clustering’, and ‘forecasting’. For sure, only the keys that relevant tasks are supported by the model will be returned.

Return type:

result_dict

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

Classify the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The data samples for testing, should be array-like of shape [n_samples, sequence length (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:

array-like, shape [n_samples],

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).

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

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, optimizer=<pypots.optim.adam.Adam object>, num_workers=0, device=None, saving_path=None, model_saving_strategy='best')[source]#

Bases: BaseNNClassifier

The PyTorch implementation of the Raindrop model [16].

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.

  • optimizer (Optional[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.

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 of shape [n_samples, sequence length (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 of shape [n_samples, sequence length (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')[source]#

Make predictions for the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The dataset for model validating, 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 of shape [n_samples, sequence length (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 test_set is a path string.

Returns:

Prediction results in a Python Dictionary for the given samples. It should be a dictionary including keys as ‘imputation’, ‘classification’, ‘clustering’, and ‘forecasting’. For sure, only the keys that relevant tasks are supported by the model will be returned.

Return type:

result_dict

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

Classify the input data with the trained model.

Parameters:
  • test_set (Union[dict, str]) – The data samples for testing, should be array-like of shape [n_samples, sequence length (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:

array-like, shape [n_samples],

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).

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