sispca
Submodules
Classes
Custom data class for variable used as supervision. |
|
Custom dataset for supervised independent subspace PCA (sisPCA). |
|
The supervised independent subspace PCA (sisPCA) model. |
|
A wrapper class for sisPCA for fitting with multiple lambda_contrast values. |
Package Contents
- class sispca.Supervision(target_data, target_type, target_name=None, target_kernel_K=None, target_kernel_Q=None)
Custom data class for variable used as supervision.
- Parameters:
target_data (2D tensor or ndarray) – (n_sample, n_dim_target). The target data used as supervision.
target_type (str) – One of [‘continuous’, ‘categorical’, ‘custom’]. The type of the target data. If ‘custom’, the target_kernel should be provided.
target_name (str) – The name of the target data.
target_kernel_K (2D tensor) – (n_sample, n_sample). Optional. The kernel matrix of the target data. Once provided, the target_data will be ignored.
target_kernel_Q (2D tensor) – (n_sample, n_rank). Optional. The decomposed kernel matrix. K = Q @ Q.T. Will be overriden by target_kernel_K if both are provided.
- target_data
- target_type
- target_name = None
- _target_kernel_K = None
- _target_kernel_Q = None
- target_kernel
- n_sample
- _sanity_check()
- class sispca.SISPCADataset(data, target_supervision_list: List[Supervision])
Bases:
torch.utils.data.DatasetCustom dataset for supervised independent subspace PCA (sisPCA).
- Parameters:
data (2D tensor) – (n_sample, n_feature). Data to run sisPCA on.
target_supervision_list (list of Supervision) – List of Supervision objects.
- x
- n_sample
- n_feature
- target_supervision_list
- n_target
- target_data_list
- target_kernel_list
- target_name_list
- __len__()
- __getitem__(idx)
- class sispca.SISPCA(dataset: sispca.data.SISPCADataset, n_latent_sub=[10, 10], lambda_contrast=1.0, kernel_subspace='linear', solver='eig')
Bases:
PCAThe supervised independent subspace PCA (sisPCA) model.
- Parameters:
dataset (SISPCADataset) – The dataset with supervision for sisPCA.
n_latent_sub (list of int) – Number of PCs in each subspace.
lambda_contrast (float) – Weight for the contrastive loss.
kernel_subspace (str) – The HSIC kernel for the contrastive loss between subspaces. Can be ‘linear’ or ‘gaussian’.
solver (str) – Can be ‘eig’ or ‘gd’.
- n_sample
- n_latent_sub = [10, 10]
- n_subspace
- lambda_contrast = 1.0
- kernel_subspace = 'linear'
- lr = 1.0
- automatic_optimization
If set to
Falseyou are responsible for calling.backward(),.step(),.zero_grad().
- U
- _dataset
- n_target
- target_name_list
- target_kernel_list
- _extract_batch_inputs(batch)
Helper function to extract batched inputs for training.
- loss(batch)
Calculate the loss function.
- _get_U_subspace_list()
Split U into subspaces.
- _reorthogonalize_U()
Reorthogonalize U per subspace.
- configure_optimizers()
Choose what optimizers and learning-rate schedulers to use in your optimization. Normally you’d need one. But in the case of GANs or similar you might have multiple. Optimization with multiple optimizers only works in the manual optimization mode.
- Returns:
Any of these 6 options.
Single optimizer.
List or Tuple of optimizers.
Two lists - The first list has multiple optimizers, and the second has multiple LR schedulers (or multiple
lr_scheduler_config).Dictionary, with an
"optimizer"key, and (optionally) a"lr_scheduler"key whose value is a single LR scheduler orlr_scheduler_config.None - Fit will run without any optimizer.
The
lr_scheduler_configis a dictionary which contains the scheduler and its associated configuration. The default configuration is shown below.lr_scheduler_config = { # REQUIRED: The scheduler instance "scheduler": lr_scheduler, # The unit of the scheduler's step size, could also be 'step'. # 'epoch' updates the scheduler on epoch end whereas 'step' # updates it after a optimizer update. "interval": "epoch", # How many epochs/steps should pass between calls to # `scheduler.step()`. 1 corresponds to updating the learning # rate after every epoch/step. "frequency": 1, # Metric to to monitor for schedulers like `ReduceLROnPlateau` "monitor": "val_loss", # If set to `True`, will enforce that the value specified 'monitor' # is available when the scheduler is updated, thus stopping # training if not found. If set to `False`, it will only produce a warning "strict": True, # If using the `LearningRateMonitor` callback to monitor the # learning rate progress, this keyword can be used to specify # a custom logged name "name": None, }
When there are schedulers in which the
.step()method is conditioned on a value, such as thetorch.optim.lr_scheduler.ReduceLROnPlateauscheduler, Lightning requires that thelr_scheduler_configcontains the keyword"monitor"set to the metric name that the scheduler should be conditioned on.# The ReduceLROnPlateau scheduler requires a monitor def configure_optimizers(self): optimizer = Adam(...) return { "optimizer": optimizer, "lr_scheduler": { "scheduler": ReduceLROnPlateau(optimizer, ...), "monitor": "metric_to_track", "frequency": "indicates how often the metric is updated", # If "monitor" references validation metrics, then "frequency" should be set to a # multiple of "trainer.check_val_every_n_epoch". }, } # In the case of two optimizers, only one using the ReduceLROnPlateau scheduler def configure_optimizers(self): optimizer1 = Adam(...) optimizer2 = SGD(...) scheduler1 = ReduceLROnPlateau(optimizer1, ...) scheduler2 = LambdaLR(optimizer2, ...) return ( { "optimizer": optimizer1, "lr_scheduler": { "scheduler": scheduler1, "monitor": "metric_to_track", }, }, {"optimizer": optimizer2, "lr_scheduler": scheduler2}, )
Metrics can be made available to monitor by simply logging it using
self.log('metric_to_track', metric_val)in yourLightningModule.Note
Some things to know:
Lightning calls
.backward()and.step()automatically in case of automatic optimization.If a learning rate scheduler is specified in
configure_optimizers()with key"interval"(default “epoch”) in the scheduler configuration, Lightning will call the scheduler’s.step()method automatically in case of automatic optimization.If you use 16-bit precision (
precision=16), Lightning will automatically handle the optimizer.If you use
torch.optim.LBFGS, Lightning handles the closure function automatically for you.If you use multiple optimizers, you will have to switch to ‘manual optimization’ mode and step them yourself.
If you need to control how often the optimizer steps, override the
optimizer_step()hook.
- training_step(batch, batch_idx)
Training step for sisPCA.
- on_train_epoch_end()
At the end of each epoch, reorthogonalize U (for gradient descent).
- fit(batch_size=-1, shuffle=True, max_epochs=100, early_stopping_patience=5, accelerator='cpu', deterministic=True, lr=None, **kwargs)
Fit the sisPCA model.
- get_latent_representation()
Get the latent representation.
- class sispca.SISPCAAuto(dataset, n_latent_sub, max_log_lambda_c, n_lambda, n_lambda_clu, target_sdim_list=None, **kwargs)
A wrapper class for sisPCA for fitting with multiple lambda_contrast values.
Adapted from contrastive PCA. Abid et al. (2018). https://github.com/abidlabs/contrastive/blob/master/contrastive/__init__.py
- Parameters:
dataset (SISPCADataset) – The dataset with supervision for sisPCA.
n_latent_sub (list of int) – Number of PCs in each subspace.
max_log_lambda_c (float) – Maximum log10 lambda_contrast value.
n_lambda (int) – Number of lambda_contrast values to search.
n_lambda_clu (int) – Number of lambda_contrast clusters to return.
target_sdim_list (list of int) – Effective dimension of each target space. If None, will re-compute the rank of the target kernel.
**kwargs – Additional keyword arguments for sisPCA
- dataset
- n_latent_sub
- n_subspace
- kwargs
- max_log_lambda_c
- n_lambda
- n_lambda_clu
- lambda_contrast_list
- models = []
- target_sdim_list
- find_best_update_order()
- fit(**kwargs)
- create_affinity_matrix(affinity_metric='determinant')
Compute the pairwise affinity matrix between results of varying lambda_contrast.
- affinity_metric: str, the metric to compute the pairwise subspace affinity on the Grassmann manifold.
Can be ‘determinant’ (Fubini-Study), ‘asimov’, or ‘geodesic’. See https://uqpyproject.readthedocs.io/en/stable/utilities/distances/grassmann_distances.html.
- find_spectral_lambdas()
Aggregate solutions using spectral clustering.
- get_latent_representation(affinity_metric='determinant', exemplar_method='smallest')