pypots.clustering package#

pypots.clustering.crli#

The package of the partially-observed time-series clustering model CRLI.

Refer to the paper Qianli Ma, Chuxin Chen, Sen Li, and Garrison W. Cottrell. Learning Representations for Incomplete Time Series Clustering. In AAAI, 35(10):8837–8846, May 2021.

Notes

This implementation is inspired by the official one https://github.com/qianlima-lab/CRLI

class pypots.clustering.crli.CRLI(n_steps, n_features, n_clusters, n_generator_layers, rnn_hidden_size, rnn_cell_type='GRU', lambda_kmeans=1, decoder_fcn_output_dims=None, G_steps=1, D_steps=1, batch_size=32, epochs=100, patience=None, G_optimizer=<pypots.optim.adam.Adam object>, D_optimizer=<pypots.optim.adam.Adam object>, num_workers=0, device=None, saving_path=None, model_saving_strategy='best')[source]#

Bases: BaseNNClusterer

The PyTorch implementation of the CRLI 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_clusters (int) – The number of clusters in the clustering task.

  • n_generator_layers (int) – The number of layers in the generator.

  • rnn_hidden_size (int) – The size of the RNN hidden state, also the number of hidden units in the RNN cell.

  • rnn_cell_type (str) – The type of RNN cell to use. Can be either “GRU” or “LSTM”.

  • decoder_fcn_output_dims (Optional[list]) – The output dimensions of each layer in the FCN (fully-connected network) of the decoder.

  • lambda_kmeans (float) – The weight of the k-means loss, i.e. the item \lambda ahead of \mathcal{L}_{k-means} in Eq.13 of the original paper.

  • G_steps (int) – The number of steps to train the generator in each iteration.

  • D_steps (int) – The number of steps to train the discriminator in each iteration.

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

  • G_optimizer (Optional[Optimizer]) – The optimizer for the generator training. If not given, will use a default Adam optimizer.

  • D_optimizer (Optional[Optimizer]) – The optimizer for the discriminator 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 cluster.

Parameters:
  • train_set (Union[dict, str]) – The dataset for model training, should be a dictionary including the key ‘X’, 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. 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 the key ‘X’.

  • 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', return_latent_vars=False)[source]#

Make predictions for the input data with the trained model.

Parameters:
  • test_set (dict or 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.

  • return_latent_vars (bool) – Whether to return the latent variables in CRLI, e.g. latent representation from the fully connected network in CRLI, etc.

Returns:

The dictionary containing the clustering results and latent variables if necessary.

Return type:

file_type

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

Cluster the input 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:

Clustering results.

Return type:

array-like,

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.clustering.vader#

The package of the partially-observed time-series clustering model VaDER.

Refer to the paper Johann de Jong, Mohammad Asif Emon, Ping Wu, Reagon Karki, Meemansa Sood, Patrice Godard, Ashar Ahmad, Henri Vrooman, Martin Hofmann-Apitius, and Holger Fröhlich. Deep learning for clustering of multivariate clinical patient trajectories with missing values. GigaScience, 8(11):giz134, November 2019.

Notes

This implementation is inspired by the official one https://github.com/johanndejong/VaDER

class pypots.clustering.vader.VaDER(n_steps, n_features, n_clusters, rnn_hidden_size, d_mu_stddev, batch_size=32, epochs=100, pretrain_epochs=10, patience=None, optimizer=<pypots.optim.adam.Adam object>, num_workers=0, device=None, saving_path=None, model_saving_strategy='best')[source]#

Bases: BaseNNClusterer

The PyTorch implementation of the VaDER model [25].

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_clusters (int) – The number of clusters in the clustering task.

  • rnn_hidden_size (int) – The size of the RNN hidden state, also the number of hidden units in the RNN cell.

  • d_mu_stddev (int) – The dimension of the mean and standard deviation of the Gaussian distribution.

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

  • pretrain_epochs (int) – The number of epochs for pretraining 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. If not given, will try to use CUDA devices first (will use the GPU with device number 0 only by default), then CPUs, considering CUDA and CPU are so far the main devices for people to train ML models. 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 cluster.

Parameters:
  • train_set (Union[dict, str]) – The dataset for model training, should be a dictionary including the key ‘X’, 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. 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 the key ‘X’.

  • 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', return_latent_vars=False)[source]#

Make predictions for the input data with the trained model.

Parameters:
  • test_set (dict or 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.

  • return_latent_vars (bool) – Whether to return the latent variables in VaDER, e.g. mu and phi, etc.

Returns:

The dictionary containing the clustering results and latent variables if necessary.

Return type:

file_type

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

Cluster the input 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:

Clustering results.

Return type:

array-like,

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