sispca ====== .. py:module:: sispca Submodules ---------- .. toctree:: :maxdepth: 1 /autoapi/sispca/data/index /autoapi/sispca/hcv_vi/index /autoapi/sispca/model/index /autoapi/sispca/utils/index Classes ------- .. autoapisummary:: sispca.Supervision sispca.SISPCADataset sispca.SISPCA sispca.SISPCAAuto Package Contents ---------------- .. py:class:: Supervision(target_data, target_type, target_name=None, target_kernel=None) Custom data class for variable used as supervision. :param target_data: (n_sample, n_dim_target). The target data used as supervision. :type target_data: 2D tensor or ndarray :param target_type: One of ['continuous', 'categorical', 'custom']. The type of the target data. If 'custom', the target_kernel should be provided. :type target_type: str :param target_name: The name of the target data. :type target_name: str :param target_kernel: (n_sample, n_sample). Optional. The kernel matrix of the target data. Once provided, the target_data will be ignored. :type target_kernel: 2D tensor .. py:attribute:: target_data .. py:attribute:: target_type .. py:attribute:: target_name :value: None .. py:attribute:: target_kernel :value: None .. py:attribute:: n_sample .. py:method:: _sanity_check() .. py:method:: _calc_kernel() Calculate the kernel matrix of the target data. .. py:class:: SISPCADataset(data, target_supervision_list: List[Supervision]) Bases: :py:obj:`torch.utils.data.Dataset` Custom dataset for supervised independent subspace PCA (sisPCA). :param data: (n_sample, n_feature). Data to run sisPCA on. :type data: 2D tensor :param target_supervision_list: List of Supervision objects. :type target_supervision_list: list of Supervision .. py:attribute:: x .. py:attribute:: n_sample .. py:attribute:: n_feature .. py:attribute:: target_supervision_list .. py:attribute:: n_target .. py:attribute:: target_data_list .. py:attribute:: target_kernel_list .. py:attribute:: target_name_list .. py:method:: __len__() .. py:method:: __getitem__(idx) .. py:class:: SISPCA(dataset: sispca.data.SISPCADataset, n_latent_sub=[10, 10], lambda_contrast=1.0, kernel_subspace='linear', solver='eig') Bases: :py:obj:`PCA` The supervised independent subspace PCA (sisPCA) model. :param dataset: The dataset with supervision for sisPCA. :type dataset: SISPCADataset :param n_latent_sub: Number of PCs in each subspace. :type n_latent_sub: list of int :param lambda_contrast: Weight for the contrastive loss. :type lambda_contrast: float :param kernel_subspace: The HSIC kernel for the contrastive loss between subspaces. Can be 'linear' or 'gaussian'. :type kernel_subspace: str :param solver: Can be 'eig' or 'gd'. :type solver: str .. py:attribute:: n_sample .. py:attribute:: n_latent_sub :value: [10, 10] .. py:attribute:: n_subspace .. py:attribute:: lambda_contrast :value: 1.0 .. py:attribute:: kernel_subspace :value: 'linear' .. py:attribute:: lr :value: 1.0 .. py:attribute:: automatic_optimization If set to ``False`` you are responsible for calling ``.backward()``, ``.step()``, ``.zero_grad()``. .. py:attribute:: U .. py:attribute:: _dataset .. py:attribute:: n_target .. py:attribute:: target_name_list .. py:attribute:: target_kernel_list .. py:method:: _extract_batch_inputs(batch) Helper function to extract batched inputs for training. .. py:method:: loss(batch) Calculate the loss function. .. py:method:: _get_U_subspace_list() Split U into subspaces. .. py:method:: _reorthogonalize_U() Reorthogonalize U per subspace. .. py:method:: 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. .. code-block:: python 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 :class:`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. .. testcode:: # 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 :class:`~lightning.pytorch.core.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 :class:`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 :meth:`optimizer_step` hook. .. py:method:: training_step(batch, batch_idx) Training step for sisPCA. .. py:method:: on_train_epoch_end() At the end of each epoch, reorthogonalize U (for gradient descent). .. py:method:: fit(batch_size=-1, shuffle=True, max_epochs=100, early_stopping_patience=5, accelerator='cpu', deterministic=True, lr=None, **kwargs) Fit the sisPCA model. .. py:method:: get_latent_representation() Get the latent representation. .. py:class:: 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 :param dataset: The dataset with supervision for sisPCA. :type dataset: SISPCADataset :param n_latent_sub: Number of PCs in each subspace. :type n_latent_sub: list of int :param max_log_lambda_c: Maximum log10 lambda_contrast value. :type max_log_lambda_c: float :param n_lambda: Number of lambda_contrast values to search. :type n_lambda: int :param n_lambda_clu: Number of lambda_contrast clusters to return. :type n_lambda_clu: int :param target_sdim_list: Effective dimension of each target space. If None, will re-compute the rank of the target kernel. :type target_sdim_list: list of int :param \*\*kwargs: Additional keyword arguments for sisPCA .. py:attribute:: dataset .. py:attribute:: n_latent_sub .. py:attribute:: n_subspace .. py:attribute:: kwargs .. py:attribute:: max_log_lambda_c .. py:attribute:: n_lambda .. py:attribute:: n_lambda_clu .. py:attribute:: lambda_contrast_list .. py:attribute:: models :value: [] .. py:attribute:: target_sdim_list .. py:method:: find_best_update_order() .. py:method:: fit(**kwargs) .. py:method:: 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. .. py:method:: find_spectral_lambdas() Aggregate solutions using spectral clustering. .. py:method:: get_latent_representation(affinity_metric='determinant', exemplar_method='smallest')