sispca.model

Classes

LossHistoryCallback

Abstract base class used to build new callbacks.

PCA

The unsupervised PCA model.

SISPCA

The supervised independent subspace PCA (sisPCA) model.

SISPCAAuto

A wrapper class for sisPCA for fitting with multiple lambda_contrast values.

Module Contents

class sispca.model.LossHistoryCallback

Bases: lightning.Callback

Abstract base class used to build new callbacks.

Subclass this class and override any of the relevant hooks

loss_history
on_train_batch_end(trainer, pl_module, outputs, batch, batch_idx)

Called when the train batch ends.

Note

The value outputs["loss"] here will be the normalized value w.r.t accumulate_grad_batches of the loss returned from training_step.

on_train_epoch_end(trainer, pl_module)

Called when the train epoch ends.

To access all batch outputs at the end of the epoch, you can cache step outputs as an attribute of the lightning.pytorch.core.LightningModule and access them in this hook:

class MyLightningModule(L.LightningModule):
    def __init__(self):
        super().__init__()
        self.training_step_outputs = []

    def training_step(self):
        loss = ...
        self.training_step_outputs.append(loss)
        return loss


class MyCallback(L.Callback):
    def on_train_epoch_end(self, trainer, pl_module):
        # do something with all training_step outputs, for example:
        epoch_mean = torch.stack(pl_module.training_step_outputs).mean()
        pl_module.log("training_epoch_mean", epoch_mean)
        # free up the memory
        pl_module.training_step_outputs.clear()
class sispca.model.PCA(n_feature, n_latent: int = 10, lr: float = 1.0)

Bases: lightning.LightningModule

The unsupervised PCA model.

Parameters:
  • n_feature (int) – Number of features of the data.

  • n_latent (int) – Number of principal components to compute.

  • lr (float) – Learning rate for updating U.

n_latent = 10
n_feature
_data = None
automatic_optimization = False

If set to False you are responsible for calling .backward(), .step(), .zero_grad().

lr = 1.0
U
forward(x)

Project data to the latent PC space.

Parameters:

x (n_sample, n_feature) – Data to project.

loss(x)

Calculate the loss function.

training_step(batch, batch_idx)

Training step for PCA.

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 or lr_scheduler_config.

  • None - Fit will run without any optimizer.

The lr_scheduler_config is 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 the torch.optim.lr_scheduler.ReduceLROnPlateau scheduler, Lightning requires that the lr_scheduler_config contains 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 your LightningModule.

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.

class sispca.model.SISPCA(dataset: sispca.data.SISPCADataset, n_latent_sub=[10, 10], lambda_contrast=1.0, kernel_subspace='linear', solver='eig')

Bases: PCA

The 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 False you 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 or lr_scheduler_config.

  • None - Fit will run without any optimizer.

The lr_scheduler_config is 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 the torch.optim.lr_scheduler.ReduceLROnPlateau scheduler, Lightning requires that the lr_scheduler_config contains 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 your LightningModule.

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