multigrate.model.MultiVAE#

class multigrate.model.MultiVAE(adata, integrate_on=None, condition_encoders=True, condition_decoders=True, normalization='layer', z_dim=16, losses=None, dropout=0.2, cond_dim=16, kernel_type='gaussian', loss_coefs=None, cont_cov_type='sigm', n_layers_cont_embed=1, n_layers_encoders=None, n_layers_decoders=None, n_hidden_cont_embed=32, n_hidden_encoders=None, n_hidden_decoders=None, modality_alignment=None, alignment_type='latent', activation='leaky_relu', initialization=None, ignore_covariates=None, mix='product')#

Bases: BaseModelClass, ArchesMixin

Multigrate multimodal integration model.

Parameters:
  • adata (AnnData) – AnnData object that has been registered via setup_anndata().

  • integrate_on (str | None (default: None)) – One of the categorical covariates refistered with setup_anndata() to integrate on. The latent space then will be disentangled from this covariate. If None, no integration is performed.

  • condition_encoders (bool (default: True)) – Whether to concatentate covariate embeddings to the first layer of the encoders. Default is True.

  • condition_decoders (bool (default: True)) – Whether to concatentate covariate embeddings to the first layer of the decoders. Default is True.

  • normalization (Literal['layer', 'batch', None] (default: 'layer')) – What normalization to use; has to be one of batch or layer. Default is layer.

  • z_dim (int (default: 16)) – Dimensionality of the latent space. Default is 16.

  • losses (list[str] | None (default: None)) – Which losses to use for each modality. Has to be the same length as the number of modalities. Default is MSE for all modalities.

  • dropout (float (default: 0.2)) – Dropout rate. Default is 0.2.

  • cond_dim (int (default: 16)) – Dimensionality of the covariate embeddings. Default is 16.

  • kernel_type (Literal['gaussian', 'not gaussian', None] (default: 'gaussian')) – Type of kernel to use for the MMD loss. Default is gaussian.

  • loss_coefs (dict[str, float] | None (default: None)) – Loss coeficients for the different losses in the model.

  • cont_cov_type (Literal['logsigm', 'sigm', None] (default: 'sigm')) – How to calculate embeddings for continuous covariates. Default is sigm.

  • n_layers_cont_embed (int (default: 1)) – Number of layers for the continuous covariate embedding calculation. Default is 1.

  • n_layers_encoders (list[int] | None (default: None)) – Number of layers for each encoder. Default is 2 for all modalities. Has to be the same length as the number of modalities.

  • n_layers_decoders (list[int] | None (default: None)) – Number of layers for each decoder. Default is 2 for all modalities. Has to be the same length as the number of modalities.

  • n_hidden_cont_embed (int (default: 32)) – Number of nodes for each hidden layer in the continuous covariate embedding calculation. Default is 32.

  • n_hidden_encoders (list[int] | None (default: None)) – Number of nodes for each hidden layer in the encoders. Default is 32.

  • n_hidden_decoders (list[int] | None (default: None)) – Number of nodes for each hidden layer in the decoders. Default is 32.

  • modality_alignment (Literal['MMD', 'Jeffreys', None] (default: None)) – Whether to align the modalities, one of [‘MMD’, ‘Jeffreys’, None]. Default is None.

  • alignment_type (Literal['latent', 'marginal', 'both'] (default: 'latent')) – Which alignment type to use, one of [‘latent’, ‘marginal’, ‘both’]. Default is latent.

  • activation (Optional[Literal['leaky_relu', 'tanh']] (default: 'leaky_relu')) – Activation function to use. Default is leaky_relu.

  • initialization (Optional[Literal['xavier', 'kaiming']] (default: None)) – Initialization method to use. Default is None.

  • ignore_covariates (list[str] | None (default: None)) – List of covariates to ignore. Needed for query-to-reference mapping. Default is None.

  • mix (Literal['product', 'mixture'] (default: 'product')) – How to mix the distributions to get the joint, one of [‘product’, ‘mixture’]. Default is product.

Attributes table#

adata

Data attached to model instance.

adata_manager

Manager instance associated with self.adata.

device

The current device that the module's params are on.

get_normalized_function_name

What the get normalized functions name is

history

Returns computed metrics during training.

is_trained

Whether the model has been trained.

registry

Data attached to model instance.

run_id

Returns the run id of the model.

run_name

Returns the run name of the model.

summary_string

Summary string of the model.

test_indices

Observations that are in test set.

train_indices

Observations that are in train set.

validation_indices

Observations that are in validation set.

Methods table#

get_model_output([adata, batch_size, ...])

Save the latent representation in the adata object.

impute([adata, batch_size])

Impute missing values in the adata object.

load_query_data(adata, reference_model[, ...])

Online update of a reference model with scArches algorithm # TODO cite.

plot_losses([save])

Plot losses.

setup_anndata(adata[, size_factor_key, ...])

Set up AnnData object.

train([max_epochs, lr, accelerator, ...])

Train the model using amortized variational inference.

Attributes#

MultiVAE.adata#

Data attached to model instance.

MultiVAE.adata_manager#

Manager instance associated with self.adata.

MultiVAE.device#

The current device that the module’s params are on.

MultiVAE.get_normalized_function_name#

What the get normalized functions name is

MultiVAE.history#

Returns computed metrics during training.

MultiVAE.is_trained#

Whether the model has been trained.

MultiVAE.registry#

Data attached to model instance.

MultiVAE.run_id#

Returns the run id of the model. Used in MLFlow

MultiVAE.run_name#

Returns the run name of the model. Used in MLFlow

MultiVAE.summary_string#

Summary string of the model.

MultiVAE.test_indices#

Observations that are in test set.

MultiVAE.train_indices#

Observations that are in train set.

MultiVAE.validation_indices#

Observations that are in validation set.

Methods#

MultiVAE.get_model_output(adata=None, batch_size=256, save_unimodal_params=False, save_unimodal_latent=False)#

Save the latent representation in the adata object.

Parameters:
  • adata (default: None) – AnnData object to run the model on. If None, the model’s AnnData object is used.

  • batch_size (default: 256) – Minibatch size to use. Default is 256.

  • save_unimodal_params (default: False) – Whether to save the unimodal parameters. Default is False.

  • save_unimodal_latent (default: False) – Whether to save the unimodal latent representation. Default is False.

MultiVAE.impute(adata=None, batch_size=256)#

Impute missing values in the adata object. Modifies adata in-place, returns None.

Parameters:
  • adata (default: None) – AnnData object to run the model on. If None, the model’s AnnData object is used.

  • batch_size (default: 256) – Minibatch size to use. Default is 256.

classmethod MultiVAE.load_query_data(adata, reference_model, accelerator='auto', device='auto', freeze=True, ignore_covariates=None)#

Online update of a reference model with scArches algorithm # TODO cite.

Parameters:
  • adata (AnnData) – AnnData organized in the same way as data used to train model. It is not necessary to run setup_anndata, as AnnData is validated against the registry.

  • reference_model (BaseModelClass) – Already instantiated model of the same class.

  • accelerator (str (default: 'auto')) – Supports passing different accelerator types (“cpu”, “gpu”, “tpu”, “auto”).

  • device (int | str (default: 'auto')) – The device to use. Can be a string (“auto”, “cpu”, “cuda”), an integer (GPU index), or “auto” to automatically select.

  • freeze (bool (default: True)) – Whether to freeze the encoders and decoders and only train the new weights.

  • ignore_covariates (list[str] | None (default: None)) – List of covariates to ignore. Needed for query-to-reference mapping. Default is None.

Return type:

BaseModelClass

Returns:

Model with updated architecture and weights.

MultiVAE.plot_losses(save=None)#

Plot losses.

Parameters:

save (default: None) – If not None, save the plot to this location.

classmethod MultiVAE.setup_anndata(adata, size_factor_key=None, rna_indices_end=None, categorical_covariate_keys=None, continuous_covariate_keys=None, **kwargs)#

Set up AnnData object.

A mapping will be created between data fields used by scvi to their respective locations in adata. This method will also compute the log mean and log variance per batch for the library size prior. None of the data in adata are modified. Only adds fields to adata.

Parameters:
  • adata (AnnData) – AnnData object containing raw counts. Rows represent cells, columns represent features.

  • size_factor_key (str | None (default: None)) – Key in adata.obs containing the size factor. If None, will be calculated from the RNA counts.

  • rna_indices_end (int | None (default: None)) – Integer to indicate where RNA feature end in the AnnData object. Is used to calculate libary_size.

  • categorical_covariate_keys (list[str] | None (default: None)) – Keys in adata.obs that correspond to categorical data.

  • continuous_covariate_keys (list[str] | None (default: None)) – Keys in adata.obs that correspond to continuous data.

  • kwargs – Additional parameters to pass to register_fields() of AnnDataManager.

MultiVAE.train(max_epochs=200, lr=0.0005, accelerator='auto', devices='auto', train_size=0.9, validation_size=None, batch_size=256, weight_decay=0.001, eps=1e-08, early_stopping=True, early_stopping_patience=10, check_val_every_n_epoch=None, n_epochs_kl_warmup=None, n_steps_kl_warmup=None, adversarial_mixing=False, plan_kwargs=None, **kwargs)#

Train the model using amortized variational inference.

Parameters:
  • max_epochs (int (default: 200)) – Number of passes through the dataset.

  • lr (float (default: 0.0005)) – Learning rate for optimization.

  • accelerator (str (default: 'auto')) – Supports passing different accelerator types (“cpu”, “gpu”, “tpu”, “auto”).

  • devices (int | list[int] | str (default: 'auto')) – The device(s) to use. Can be set to a non-negative index (int or str), a sequence of device indices (list or comma-separated str), the value -1 to indicate all available devices, or “auto” for automatic selection.

  • train_size (float (default: 0.9)) – Size of training set in the range [0.0, 1.0].

  • validation_size (float | None (default: None)) – Size of the test set. If None, defaults to 1 - train_size. If train_size + validation_size < 1, the remaining cells belong to a test set.

  • batch_size (int (default: 256)) – Minibatch size to use during training.

  • weight_decay (float (default: 0.001)) – Weight decay regularization term for optimization.

  • eps (float (default: 1e-08)) – Optimizer eps.

  • early_stopping (bool (default: True)) – Whether to perform early stopping with respect to the validation set.

  • check_val_every_n_epoch (int | None (default: None)) – Check val every n train epochs. By default, val is not checked, unless early_stopping is True. If so, val is checked every epoch.

  • n_epochs_kl_warmup (int | None (default: None)) – Number of epochs to scale weight on KL divergences from 0 to 1. Overrides n_steps_kl_warmup when both are not None. Default is 1/3 of max_epochs.

  • n_steps_kl_warmup (int | None (default: None)) – Number of training steps (minibatches) to scale weight on KL divergences from 0 to 1. Only activated when n_epochs_kl_warmup is set to None. If None, defaults to floor(0.75 * adata.n_obs).

  • adversarial_mixing (bool (default: False)) – Whether to use adversarial mixing. Default is False.

  • plan_kwargs (dict | None (default: None)) – Keyword args for TrainingPlan. Keyword arguments passed to train() will overwrite values present in plan_kwargs, when appropriate.

  • save_checkpoint_every_n_epochs – Save a checkpoint every n epochs. If None, no checkpoints are saved.

  • path_to_checkpoints – Path to save checkpoints. Required if save_checkpoint_every_n_epochs is not None.

  • kwargs – Additional keyword arguments for TrainRunner.

Returns:

Trainer object.