scvi.external.GIMVI#
- class scvi.external.GIMVI(adata_seq, adata_spatial, generative_distributions=None, model_library_size=None, n_latent=10, **model_kwargs)[source]#
Joint VAE for imputing missing genes in spatial data [Lopez et al., 2019].
- Parameters:
adata_seq (
AnnData
) – AnnData object that has been registered viasetup_anndata()
and contains RNA-seq data.adata_spatial (
AnnData
) – AnnData object that has been registered viasetup_anndata()
and contains spatial data.n_hidden – Number of nodes per hidden layer.
generative_distributions (
list
[str
] |None
(default:None
)) – List of generative distribution for adata_seq data and adata_spatial data. Defaults to [‘zinb’, ‘nb’].model_library_size (
list
[bool
] |None
(default:None
)) – List of bool of whether to model library size for adata_seq and adata_spatial. Defaults to [True, False].n_latent (
int
(default:10
)) – Dimensionality of the latent space.**model_kwargs – Keyword args for
JVAE
Examples
>>> adata_seq = anndata.read_h5ad(path_to_anndata_seq) >>> adata_spatial = anndata.read_h5ad(path_to_anndata_spatial) >>> scvi.external.GIMVI.setup_anndata(adata_seq) >>> scvi.external.GIMVI.setup_anndata(adata_spatial) >>> vae = scvi.model.GIMVI(adata_seq, adata_spatial) >>> vae.train(n_epochs=400)
Notes
See further usage examples in the following tutorials:
Attributes table#
Data attached to model instance. |
|
Manager instance associated with self.adata. |
|
The current device that the module's params are on. |
|
Returns computed metrics during training. |
|
Whether the model has been trained. |
|
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#
|
Converts a legacy saved GIMVI model (<v0.15.0) to the updated save format. |
|
Deregisters the |
|
Retrieves the |
|
Compute the evidence lower bound (ELBO) on the data. |
|
Returns the object in AnnData associated with the key in the data registry. |
|
Return imputed values for all genes for each dataset. |
|
Return the latent space embedding for each dataset. |
|
Compute the marginal log-likehood of the data. |
|
Compute the reconstruction error on the data. |
|
Instantiate a model from the saved output. |
|
Return the full registry saved with the model. |
|
Registers an |
|
Save the state of the model. |
|
Sets up the |
|
Move model to device. |
|
Train the model. |
|
Print summary of the setup for the initial AnnData or a given AnnData object. |
|
Print args used to setup a saved model. |
Attributes#
Methods#
- classmethod GIMVI.convert_legacy_save(dir_path, output_dir_path, overwrite=False, prefix=None, **save_kwargs)[source]#
Converts a legacy saved GIMVI model (<v0.15.0) to the updated save format.
- Parameters:
dir_path (
str
) – Path to directory where legacy model is saved.output_dir_path (
str
) – Path to save converted save files.overwrite (
bool
(default:False
)) – Overwrite existing data or not. IfFalse
and directory already exists atoutput_dir_path
, error will be raised.prefix (
str
|None
(default:None
)) – Prefix of saved file names.
- Return type:
- **save_kwargs
Keyword arguments passed into
save()
.
- GIMVI.deregister_manager(adata=None)[source]#
Deregisters the
AnnDataManager
instance associated with adata.If adata is None, deregisters all
AnnDataManager
instances in both the class and instance-specific manager stores, except for the one associated with this model instance.
- GIMVI.get_anndata_manager(adata, required=False)[source]#
Retrieves the
AnnDataManager
for a given AnnData object.Requires
self.id
has been set. Checks for anAnnDataManager
specific to this model instance.- Parameters:
- Return type:
- GIMVI.get_elbo(adata=None, indices=None, batch_size=None, dataloader=None, return_mean=True, **kwargs)[source]#
Compute the evidence lower bound (ELBO) on the data.
The ELBO is the reconstruction error plus the Kullback-Leibler (KL) divergences between the variational distributions and the priors. It is different from the marginal log-likelihood; specifically, it is a lower bound on the marginal log-likelihood plus a term that is constant with respect to the variational distribution. It still gives good insights on the modeling of the data and is fast to compute.
- Parameters:
adata (
AnnData
|None
(default:None
)) –AnnData
object withvar_names
in the same order as the ones used to train the model. IfNone
anddataloader
is alsoNone
, it defaults to the object used to initialize the model.indices (
Sequence
[int
] |None
(default:None
)) – Indices of observations inadata
to use. IfNone
, defaults to all observations. Ignored ifdataloader
is notNone
.batch_size (
int
|None
(default:None
)) – Minibatch size for the forward pass. IfNone
, defaults toscvi.settings.batch_size
. Ignored ifdataloader
is notNone
.dataloader (
Iterator
[dict
[str
,Tensor
|None
]] (default:None
)) – An iterator over minibatches of data on which to compute the metric. The minibatches should be formatted as a dictionary ofTensor
with keys as expected by the model. IfNone
, a dataloader is created fromadata
.return_mean (
bool
(default:True
)) – Whether to return the mean of the ELBO or the ELBO for each observation.**kwargs – Additional keyword arguments to pass into the forward method of the module.
- Return type:
- Returns:
Evidence lower bound (ELBO) of the data.
Notes
This is not the negative ELBO, so higher is better.
- GIMVI.get_from_registry(adata, registry_key)[source]#
Returns the object in AnnData associated with the key in the data registry.
AnnData object should be registered with the model prior to calling this function via the
self._validate_anndata
method.
- GIMVI.get_imputed_values(adatas=None, deterministic=True, normalized=True, decode_mode=None, batch_size=128)[source]#
Return imputed values for all genes for each dataset.
- Parameters:
adatas (
list
[AnnData
] (default:None
)) – List of adata seq and adata spatialdeterministic (
bool
(default:True
)) – If true, use the mean of the encoder instead of a Gaussian sample for the latent vector.normalized (
bool
(default:True
)) – Return imputed normalized values or not.decode_mode (
int
|None
(default:None
)) – If a decode_mode is given, use the encoder specific to each dataset as usual but use the decoder of the dataset of id decode_mode to impute values.batch_size (
int
(default:128
)) – Minibatch size for data loading into model.
- Return type:
- GIMVI.get_latent_representation(adatas=None, deterministic=True, batch_size=128)[source]#
Return the latent space embedding for each dataset.
- Parameters:
- Return type:
- GIMVI.get_marginal_ll(adata=None, indices=None, n_mc_samples=1000, batch_size=None, return_mean=True, dataloader=None, **kwargs)[source]#
Compute the marginal log-likehood of the data.
The computation here is a biased estimator of the marginal log-likelihood of the data.
- Parameters:
adata (
AnnData
|None
(default:None
)) –AnnData
object withvar_names
in the same order as the ones used to train the model. IfNone
anddataloader
is alsoNone
, it defaults to the object used to initialize the model.indices (
Sequence
[int
] |None
(default:None
)) – Indices of observations inadata
to use. IfNone
, defaults to all observations. Ignored ifdataloader
is notNone
.n_mc_samples (
int
(default:1000
)) – Number of Monte Carlo samples to use for the estimator. Passed into the module’smarginal_ll
method.batch_size (
int
|None
(default:None
)) – Minibatch size for the forward pass. IfNone
, defaults toscvi.settings.batch_size
. Ignored ifdataloader
is notNone
.return_mean (
bool
(default:True
)) – Whether to return the mean of the marginal log-likelihood or the marginal-log likelihood for each observation.dataloader (
Iterator
[dict
[str
,Tensor
|None
]] (default:None
)) – An iterator over minibatches of data on which to compute the metric. The minibatches should be formatted as a dictionary ofTensor
with keys as expected by the model. IfNone
, a dataloader is created fromadata
.**kwargs – Additional keyword arguments to pass into the module’s
marginal_ll
method.
- Return type:
float
|Tensor
- Returns:
If
True
, returns the mean marginal log-likelihood. Otherwise returns a tensor of shape(n_obs,)
with the marginal log-likelihood for each observation.
Notes
This is not the negative log-likelihood, so higher is better.
- GIMVI.get_reconstruction_error(adata=None, indices=None, batch_size=None, dataloader=None, return_mean=True, **kwargs)[source]#
Compute the reconstruction error on the data.
The reconstruction error is the negative log likelihood of the data given the latent variables. It is different from the marginal log-likelihood, but still gives good insights on the modeling of the data and is fast to compute. This is typically written as \(p(x \mid z)\), the likelihood term given one posterior sample.
- Parameters:
adata (
AnnData
|None
(default:None
)) –AnnData
object withvar_names
in the same order as the ones used to train the model. IfNone
anddataloader
is alsoNone
, it defaults to the object used to initialize the model.indices (
Sequence
[int
] |None
(default:None
)) – Indices of observations inadata
to use. IfNone
, defaults to all observations. Ignored ifdataloader
is notNone
batch_size (
int
|None
(default:None
)) – Minibatch size for the forward pass. IfNone
, defaults toscvi.settings.batch_size
. Ignored ifdataloader
is notNone
dataloader (
Iterator
[dict
[str
,Tensor
|None
]] (default:None
)) – An iterator over minibatches of data on which to compute the metric. The minibatches should be formatted as a dictionary ofTensor
with keys as expected by the model. IfNone
, a dataloader is created fromadata
.return_mean (
bool
(default:True
)) – Whether to return the mean reconstruction loss or the reconstruction loss for each observation.**kwargs – Additional keyword arguments to pass into the forward method of the module.
- Return type:
- Returns:
Reconstruction error for the data.
Notes
This is not the negative reconstruction error, so higher is better.
- classmethod GIMVI.load(dir_path, adata_seq=None, adata_spatial=None, accelerator='auto', device='auto', prefix=None, backup_url=None)[source]#
Instantiate a model from the saved output.
- Parameters:
dir_path (
str
) – Path to saved outputs.adata_seq (
AnnData
|None
(default:None
)) – AnnData organized in the same way as data used to train model. It is not necessary to runsetup_anndata()
, as AnnData is validated against the saved scvi setup dictionary. AnnData must be registered viasetup_anndata()
.adata_spatial (
AnnData
|None
(default:None
)) – AnnData organized in the same way as data used to train model. If None, will check for and load anndata saved with the model.accelerator (
str
(default:'auto'
)) – Supports passing different accelerator types (“cpu”, “gpu”, “tpu”, “ipu”, “hpu”, “mps, “auto”) as well as custom accelerator instances.device (
int
|str
(default:'auto'
)) – The device to use. Can be set to a non-negative index (int or str) or “auto” for automatic selection based on the chosen accelerator. If set to “auto” and accelerator is not determined to be “cpu”, then device will be set to the first available device.prefix (
str
|None
(default:None
)) – Prefix of saved file names.backup_url (
str
|None
(default:None
)) – URL to retrieve saved outputs from if not present on disk.
- Returns:
Model with loaded state dictionaries.
Examples
>>> vae = GIMVI.load(adata_seq, adata_spatial, save_path) >>> vae.get_latent_representation()
- static GIMVI.load_registry(dir_path, prefix=None)[source]#
Return the full registry saved with the model.
- classmethod GIMVI.register_manager(adata_manager)[source]#
Registers an
AnnDataManager
instance with this model class.Stores the
AnnDataManager
reference in a class-specific manager store. Intended for use in thesetup_anndata()
class method followed up by retrieval of theAnnDataManager
via the_get_most_recent_anndata_manager()
method in the model init method.Notes
Subsequent calls to this method with an
AnnDataManager
instance referring to the same underlying AnnData object will overwrite the reference to previousAnnDataManager
.
- GIMVI.save(dir_path, prefix=None, overwrite=False, save_anndata=False, save_kwargs=None, **anndata_write_kwargs)[source]#
Save the state of the model.
Neither the trainer optimizer state nor the trainer history are saved. Model files are not expected to be reproducibly saved and loaded across versions until we reach version 1.0.
- Parameters:
dir_path (
str
) – Path to a directory.prefix (
str
|None
(default:None
)) – Prefix to prepend to saved file names.overwrite (
bool
(default:False
)) – Overwrite existing data or not. If False and directory already exists at dir_path, error will be raised.save_anndata (
bool
(default:False
)) – If True, also saves the anndatasave_kwargs (
dict
|None
(default:None
)) – Keyword arguments passed intosave()
.anndata_write_kwargs – Kwargs for anndata write function
- classmethod GIMVI.setup_anndata(adata, batch_key=None, labels_key=None, layer=None, **kwargs)[source]#
Sets up the
AnnData
object for this model.A mapping will be created between data fields used by this model to their respective locations in adata. None of the data in adata are modified. Only adds fields to adata.
- Parameters:
batch_key (
str
|None
(default:None
)) – key in adata.obs for batch information. Categories will automatically be converted into integer categories and saved to adata.obs[‘_scvi_batch’]. If None, assigns the same batch to all the data.labels_key (
str
|None
(default:None
)) – key in adata.obs for label information. Categories will automatically be converted into integer categories and saved to adata.obs[‘_scvi_labels’]. If None, assigns the same label to all the data.layer (
str
|None
(default:None
)) – if not None, uses this as the key in adata.layers for raw count data.
- GIMVI.to_device(device)[source]#
Move model to device.
- Parameters:
device (
str
|int
) – Device to move model to. Options: ‘cpu’ for CPU, integer GPU index (eg. 0), or ‘cuda:X’ where X is the GPU index (eg. ‘cuda:0’). See torch.device for more info.
Examples
>>> adata = scvi.data.synthetic_iid() >>> model = scvi.model.SCVI(adata) >>> model.to_device("cpu") # moves model to CPU >>> model.to_device("cuda:0") # moves model to GPU 0 >>> model.to_device(0) # also moves model to GPU 0
- GIMVI.train(max_epochs=200, accelerator='auto', devices='auto', kappa=5, train_size=0.9, validation_size=None, shuffle_set_split=True, batch_size=128, datasplitter_kwargs=None, plan_kwargs=None, **kwargs)[source]#
Train the model.
- Parameters:
max_epochs (
int
(default:200
)) – Number of passes through the dataset. If None, defaults to np.min([round((20000 / n_cells) * 400), 400])accelerator (
str
(default:'auto'
)) – Supports passing different accelerator types (“cpu”, “gpu”, “tpu”, “ipu”, “hpu”, “mps, “auto”) as well as custom accelerator instances.devices (
int
|list
[int
] |str
(default:'auto'
)) – The devices 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 based on the chosen accelerator. If set to “auto” and accelerator is not determined to be “cpu”, then devices will be set to the first available device.kappa (
int
(default:5
)) – Scaling parameter for the discriminator loss.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.shuffle_set_split (
bool
(default:True
)) – Whether to shuffle indices before splitting. If False, the val, train, and test set are split in the sequential order of the data according to validation_size and train_size percentages.batch_size (
int
(default:128
)) – Minibatch size to use during training.datasplitter_kwargs (
dict
|None
(default:None
)) – Additional keyword arguments passed intoDataSplitter
.plan_kwargs (
dict
|None
(default:None
)) – Keyword args for model-specific Pytorch Lightning task. Keyword arguments passed to train() will overwrite values present in plan_kwargs, when appropriate.**kwargs – Other keyword args for
Trainer
.