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,ArchesMixinMultigrate multimodal integration model.
- Parameters:
adata (
AnnData) – AnnData object that has been registered viasetup_anndata().integrate_on (
str|None(default:None)) – One of the categorical covariates refistered withsetup_anndata()to integrate on. The latent space then will be disentangled from this covariate. IfNone, no integration is performed.condition_encoders (
bool(default:True)) – Whether to concatentate covariate embeddings to the first layer of the encoders. Default isTrue.condition_decoders (
bool(default:True)) – Whether to concatentate covariate embeddings to the first layer of the decoders. Default isTrue.normalization (
Literal['layer','batch',None] (default:'layer')) – What normalization to use; has to be one ofbatchorlayer. Default islayer.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 isMSEfor 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 isgaussian.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 issigm.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 isNone.alignment_type (
Literal['latent','marginal','both'] (default:'latent')) – Which alignment type to use, one of [‘latent’, ‘marginal’, ‘both’]. Default islatent.activation (
Optional[Literal['leaky_relu','tanh']] (default:'leaky_relu')) – Activation function to use. Default isleaky_relu.initialization (
Optional[Literal['xavier','kaiming']] (default:None)) – Initialization method to use. Default isNone.ignore_covariates (
list[str] |None(default:None)) – List of covariates to ignore. Needed for query-to-reference mapping. Default isNone.mix (
Literal['product','mixture'] (default:'product')) – How to mix the distributions to get the joint, one of [‘product’, ‘mixture’]. Default isproduct.
Attributes table#
Data attached to model instance. |
|
Manager instance associated with self.adata. |
|
The current device that the module's params are on. |
|
What the get normalized functions name is |
|
Returns computed metrics during training. |
|
Whether the model has been trained. |
|
Data attached to model instance. |
|
Returns the run id of the model. |
|
Returns the run name of the model. |
|
Summary string of the model. |
|
Observations that are in test set. |
|
Observations that are in train set. |
|
Observations that are in validation set. |
Methods table#
|
Save the latent representation in the adata object. |
|
Impute missing values in the adata object. |
|
Online update of a reference model with scArches algorithm # TODO cite. |
|
Plot losses. |
|
Set up |
|
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. IfNone, 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 isFalse.save_unimodal_latent (default:
False) – Whether to save the unimodal latent representation. Default isFalse.
- 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. IfNone, 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 theregistry.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 isNone.
- Return type:
- 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
AnnDataobject.A mapping will be created between data fields used by
scvito 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 inadata.obscontaining the size factor. IfNone, 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 calculatelibary_size.categorical_covariate_keys (
list[str] |None(default:None)) – Keys inadata.obsthat correspond to categorical data.continuous_covariate_keys (
list[str] |None(default:None)) – Keys inadata.obsthat 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. IfNone, defaults to 1 -train_size. Iftrain_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, unlessearly_stoppingisTrue. 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. Overridesn_steps_kl_warmupwhen both are notNone. Default is 1/3 ofmax_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 whenn_epochs_kl_warmupis set to None. IfNone, defaults tofloor(0.75 * adata.n_obs).adversarial_mixing (
bool(default:False)) – Whether to use adversarial mixing. Default isFalse.plan_kwargs (
dict|None(default:None)) – Keyword args forTrainingPlan. Keyword arguments passed totrain()will overwrite values present inplan_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_epochsis notNone.kwargs – Additional keyword arguments for
TrainRunner.
- Returns:
Trainer object.