scvi.external.ContrastiveVI#

class scvi.external.ContrastiveVI(adata, n_hidden=128, n_background_latent=10, n_salient_latent=10, n_layers=1, dropout_rate=0.1, use_observed_lib_size=True, wasserstein_penalty=0)[source]#

contrastive variational inference [Weinberger et al., 2023].

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

  • n_hidden (int (default: 128)) – Number of nodes per hidden layer.

  • n_background_latent (int (default: 10)) – Dimensionality of the background shared latent space.

  • n_salient_latent (int (default: 10)) – Dimensionality of the salient latent space.

  • n_layers (int (default: 1)) – Number of hidden layers used for encoder and decoder NNs.

  • dropout_rate (float (default: 0.1)) – Dropout rate for neural networks.

  • use_observed_lib_size (bool (default: True)) – Use observed library size for RNA as scaling factor in mean of conditional distribution.

  • wasserstein_penalty (float (default: 0)) – Weight of the Wasserstein distance loss that further discourages background shared variations from leaking into the salient latent space.

Notes

See further usage examples in the following tutorial:

  1. Isolating perturbation-induced variations with contrastiveVI

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.

history

Returns computed metrics during training.

is_trained

Whether the model has been trained.

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#

convert_legacy_save(dir_path, output_dir_path)

Converts a legacy saved model (<v0.15.0) to the updated save format.

deregister_manager([adata])

Deregisters the AnnDataManager instance associated with adata.

differential_expression([adata, groupby, ...])

Performs differential expression analysis.

get_anndata_manager(adata[, required])

Retrieves the AnnDataManager for a given AnnData object.

get_from_registry(adata, registry_key)

Returns the object in AnnData associated with the key in the data registry.

get_latent_library_size([adata, indices, ...])

Returns the latent library size for each cell.

get_latent_representation([adata, indices, ...])

Returns the background or salient latent representation for each cell.

get_normalized_expression([adata, indices, ...])

Returns the normalized (decoded) gene expression.

get_salient_normalized_expression([adata, ...])

Returns the normalized (decoded) gene expression.

get_specific_normalized_expression([adata, ...])

Returns the normalized (decoded) gene expression.

load(dir_path[, adata, accelerator, device, ...])

Instantiate a model from the saved output.

load_registry(dir_path[, prefix])

Return the full registry saved with the model.

register_manager(adata_manager)

Registers an AnnDataManager instance with this model class.

save(dir_path[, prefix, overwrite, ...])

Save the state of the model.

setup_anndata(adata[, layer, batch_key, ...])

Sets up the AnnData object for this model.

to_device(device)

Move model to device.

train(background_indices, target_indices[, ...])

Train the model.

view_anndata_setup([adata, ...])

Print summary of the setup for the initial AnnData or a given AnnData object.

view_setup_args(dir_path[, prefix])

Print args used to setup a saved model.

Attributes#

ContrastiveVI.adata[source]#

Data attached to model instance.

ContrastiveVI.adata_manager[source]#

Manager instance associated with self.adata.

ContrastiveVI.device[source]#

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

ContrastiveVI.history[source]#

Returns computed metrics during training.

ContrastiveVI.is_trained[source]#

Whether the model has been trained.

ContrastiveVI.summary_string[source]#

Summary string of the model.

ContrastiveVI.test_indices[source]#

Observations that are in test set.

ContrastiveVI.train_indices[source]#

Observations that are in train set.

ContrastiveVI.validation_indices[source]#

Observations that are in validation set.

Methods#

classmethod ContrastiveVI.convert_legacy_save(dir_path, output_dir_path, overwrite=False, prefix=None, **save_kwargs)[source]#

Converts a legacy saved 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. If False and directory already exists at output_dir_path, error will be raised.

  • prefix (str | None (default: None)) – Prefix of saved file names.

  • **save_kwargs – Keyword arguments passed into save().

Return type:

None

ContrastiveVI.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.

ContrastiveVI.differential_expression(adata=None, groupby=None, group1=None, group2=None, idx1=None, idx2=None, mode='change', delta=0.25, batch_size=None, all_stats=True, batch_correction=False, batchid1=None, batchid2=None, fdr_target=0.05, silent=False, target_idx=None, n_samples=1, **kwargs)[source]#

Performs differential expression analysis.

Parameters:
  • adata (AnnData | None (default: None)) – AnnData object with equivalent structure to initial AnnData. If None, defaults to the AnnData object used to initialize the model.

  • groupby (str | None (default: None)) – The key of the observations grouping to consider.

  • group1 (Iterable[str] | None (default: None)) – Subset of groups, e.g. [“g1”, “g2”, “g3”], to which comparison shall be restricted, or all groups in groupby (default).

  • group2 (str | None (default: None)) – If None, compare each group in group1 to the union of the rest of the groups in groupby. If a group identifier, compare with respect to this group.

  • idx1 (Sequence[int] | Sequence[bool] | str | None (default: None)) – idx1 and idx2 can be used as an alternative to the AnnData keys. Custom identifier for group1 that can be of three sorts: (1) a boolean mask, (2) indices, or (3) a string. If it is a string, then it will query indices that verifies conditions on adata.obs, as described in pandas.DataFrame.query(). If idx1 is not None, this option overrides group1 and group2.

  • idx2 (Sequence[int] | Sequence[bool] | str | None (default: None)) – Custom identifier for group2 that has the same properties as idx1. By default, includes all cells not specified in idx1.

  • mode (str (default: 'change')) – Method for differential expression. See https://docs.scvi-tools.org/en/0.14.1/user_guide/background/differential_expression.html for more details.

  • delta (float (default: 0.25)) – Specific case of region inducing differential expression. In this case, we suppose that R[-delta, delta] does not induce differential expression (change model default case).

  • batch_size (int | None (default: None)) – Mini-batch size for data loading into model. Defaults to scvi.settings.batch_size.

  • all_stats (bool (default: True)) – Concatenate count statistics (e.g., mean expression group 1) to DE results.

  • batch_correction (bool (default: False)) – Whether to correct for batch effects in DE inference.

  • batchid1 (Iterable[str] | None (default: None)) – Subset of categories from batch_key registered in setup_anndata, e.g. [“batch1”, “batch2”, “batch3”], for group1. Only used if batch_correction is True, and by default all categories are used.

  • batchid2 (Iterable[str] | None (default: None)) – Same as batchid1 for group2. batchid2 must either have null intersection with batchid1, or be exactly equal to batchid1. When the two sets are exactly equal, cells are compared by decoding on the same batch. When sets have null intersection, cells from group1 and group2 are decoded on each group in group1 and group2, respectively.

  • fdr_target (float (default: 0.05)) – Tag features as DE based on posterior expected false discovery rate.

  • silent (bool (default: False)) – If True, disables the progress bar. Default: False.

  • target_idx (Sequence[int] | None (default: None)) – If not None, a boolean or integer identifier should be used for cells in the contrastive target group. Normalized expression values derived from both salient and background latent embeddings are used when {group1, group2} is a subset of the target group, otherwise background normalized expression values are used.

  • kwargs (Keyword args for) – scvi.model.base.DifferentialComputation.get_bayes_factors.

Return type:

DataFrame

Returns:

Differential expression DataFrame.

ContrastiveVI.get_anndata_manager(adata, required=False)[source]#

Retrieves the AnnDataManager for a given AnnData object.

Requires self.id has been set. Checks for an AnnDataManager specific to this model instance.

Parameters:
  • adata (Union[AnnData, MuData]) – AnnData object to find manager instance for.

  • required (bool (default: False)) – If True, errors on missing manager. Otherwise, returns None when manager is missing.

Return type:

AnnDataManager | None

ContrastiveVI.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.

Parameters:
  • registry_key (str) – key of object to get from data registry.

  • adata (Union[AnnData, MuData]) – AnnData to pull data from.

Return type:

ndarray

Returns:

The requested data as a NumPy array.

ContrastiveVI.get_latent_library_size(adata=None, indices=None, give_mean=True, batch_size=None)[source]#

Returns the latent library size for each cell.

This is denoted as \(\ell_n\) in the scVI paper.

Parameters:
  • adata (AnnData | None (default: None)) – AnnData object with equivalent structure to initial AnnData. If None, defaults to the AnnData object used to initialize the model.

  • indices (Sequence[int] | None (default: None)) – Indices of cells in adata to use. If None, all cells are used.

  • give_mean (bool (default: True)) – Return the mean or a sample from the posterior distribution.

  • batch_size (int | None (default: None)) – Minibatch size for data loading into model. Defaults to scvi.settings.batch_size.

Return type:

ndarray

ContrastiveVI.get_latent_representation(adata=None, indices=None, give_mean=True, batch_size=None, representation_kind='salient')[source]#

Returns the background or salient latent representation for each cell.

Parameters:
  • adata (AnnData | None (default: None)) – AnnData object with equivalent structure to initial AnnData. If None, defaults to the AnnData object used to initialize the model.

  • indices (Sequence[int] | None (default: None)) – Indices of cells in adata to use. If None, all cells are used.

  • give_mean (bool (default: True)) – Give mean of distribution or sample from it.

  • batch_size (int | None (default: None)) – Mini-batch size for data loading into model. Defaults to scvi.settings.batch_size.

  • representation_kind (str (default: 'salient')) – Either “background” or “salient” for the corresponding representation kind.

Return type:

ndarray

Returns:

A numpy array with shape (n_cells, n_latent).

ContrastiveVI.get_normalized_expression(adata=None, indices=None, transform_batch=None, gene_list=None, library_size=1.0, n_samples=1, n_samples_overall=None, batch_size=None, return_mean=True, return_numpy=None)[source]#

Returns the normalized (decoded) gene expression.

Parameters:
  • adata (AnnData | None (default: None)) – AnnData object with equivalent structure to initial AnnData. If None, defaults to the AnnData object used to initialize the model.

  • indices (Sequence[int] | None (default: None)) – Indices of cells in adata to use. If None, all cells are used.

  • transform_batch (Sequence[Union[int, float, str]] | None (default: None)) – Batch to condition on. If transform_batch is: - None, then real observed batch is used. - int, then batch transform_batch is used.

  • gene_list (Sequence[str] | None (default: None)) – Return frequencies of expression for a subset of genes. This can save memory when working with large datasets and few genes are of interest.

  • library_size (float | str (default: 1.0)) – Scale the expression frequencies to a common library size. This allows gene expression levels to be interpreted on a common scale of relevant magnitude. If set to “latent”, use the latent library size.

  • n_samples (int (default: 1)) – Number of posterior samples to use for estimation.

  • n_samples_overall (int | None (default: None)) – The number of random samples in adata to use.

  • batch_size (int | None (default: None)) – Mini-batch size for data loading into model. Defaults to scvi.settings.batch_size.

  • return_mean (bool (default: True)) – Whether to return the mean of the samples.

  • return_numpy (bool | None (default: None)) – Return a numpy.ndarray instead of a pandas.DataFrame. DataFrame includes gene names as columns. If either n_samples=1 or return_mean=True, defaults to False. Otherwise, it defaults to True.

Return type:

dict[str, ndarray | DataFrame]

Returns:

A dictionary with keys “background” and “salient”, with value as follows. If n_samples > 1 and return_mean is False, then the shape is (samples, cells, genes). Otherwise, shape is (cells, genes). In this case, return type is pandas.DataFrame unless return_numpy is True.

ContrastiveVI.get_salient_normalized_expression(adata=None, indices=None, transform_batch=None, gene_list=None, library_size=1.0, n_samples=1, n_samples_overall=None, batch_size=None, return_mean=True, return_numpy=None)[source]#

Returns the normalized (decoded) gene expression.

Gene expressions are decoded from both the background and salient latent space.

Parameters:
  • adata (AnnData | None (default: None)) – AnnData object with equivalent structure to initial AnnData. If None, defaults to the AnnData object used to initialize the model.

  • indices (Sequence[int] | None (default: None)) – Indices of cells in adata to use. If None, all cells are used.

  • transform_batch (Sequence[Union[int, float, str]] | None (default: None)) – Batch to condition on. If transform_batch is: - None, then real observed batch is used. - int, then batch transform_batch is used.

  • gene_list (Sequence[str] | None (default: None)) – Return frequencies of expression for a subset of genes. This can save memory when working with large datasets and few genes are of interest.

  • library_size (float | str (default: 1.0)) – Scale the expression frequencies to a common library size. This allows gene expression levels to be interpreted on a common scale of relevant magnitude. If set to “latent”, use the latent library size.

  • n_samples (int (default: 1)) – Number of posterior samples to use for estimation.

  • n_samples_overall (int | None (default: None)) – The number of random samples in adata to use.

  • batch_size (int | None (default: None)) – Mini-batch size for data loading into model. Defaults to scvi.settings.batch_size.

  • return_mean (bool (default: True)) – Whether to return the mean of the samples.

  • return_numpy (bool | None (default: None)) – Return a numpy.ndarray instead of a pandas.DataFrame. DataFrame includes gene names as columns. If either n_samples=1 or return_mean=True, defaults to False. Otherwise, it defaults to True.

Return type:

ndarray | DataFrame

Returns:

If n_samples > 1 and return_mean is False, then the shape is (samples, cells, genes). Otherwise, shape is (cells, genes). In this case, return type is pandas.DataFrame unless return_numpy is True.

ContrastiveVI.get_specific_normalized_expression(adata=None, indices=None, transform_batch=None, gene_list=None, library_size=1, n_samples=1, n_samples_overall=None, batch_size=None, return_mean=True, return_numpy=None, expression_type=None, indices_to_return_salient=None)[source]#

Returns the normalized (decoded) gene expression.

Gene expressions are decoded from either the background or salient latent space. One of expression_type or indices_to_return_salient should have an input argument.

Parameters:
  • adata (AnnData | None (default: None)) – AnnData object with equivalent structure to initial AnnData. If None, defaults to the AnnData object used to initialize the model.

  • indices (Sequence[int] | None (default: None)) – Indices of cells in adata to use. If None, all cells are used.

  • transform_batch (Sequence[Union[int, float, str]] | None (default: None)) – Batch to condition on. If transform_batch is: - None, then real observed batch is used. - int, then batch transform_batch is used.

  • gene_list (Sequence[str] | None (default: None)) – Return frequencies of expression for a subset of genes. This can save memory when working with large datasets and few genes are of interest.

  • library_size (float | str (default: 1)) – Scale the expression frequencies to a common library size. This allows gene expression levels to be interpreted on a common scale of relevant magnitude. If set to “latent”, use the latent library size.

  • n_samples (int (default: 1)) – Number of posterior samples to use for estimation.

  • n_samples_overall (int | None (default: None)) – The number of random samples in adata to use.

  • batch_size (int | None (default: None)) – Mini-batch size for data loading into model. Defaults to scvi.settings.batch_size.

  • return_mean (bool (default: True)) – Whether to return the mean of the samples.

  • return_numpy (bool | None (default: None)) – Return a numpy.ndarray instead of a pandas.DataFrame. DataFrame includes gene names as columns. If either n_samples=1 or return_mean=True, defaults to False. Otherwise, it defaults to True.

  • expression_type (str | None (default: None)) – One of {“salient”, “background”} to specify the type of normalized expression to return.

  • indices_to_return_salient (Sequence[int] | None (default: None)) – If indices is a subset of indices_to_return_salient, normalized expressions derived from background and salient latent embeddings are returned. If indices is not None and is not a subset of indices_to_return_salient, normalized expressions derived only from background latent embeddings are returned.

Returns:

If n_samples > 1 and return_mean is False, then the shape is (samples, cells, genes). Otherwise, shape is (cells, genes). In this case, return type is pandas.DataFrame unless return_numpy is True.

classmethod ContrastiveVI.load(dir_path, adata=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 (Union[AnnData, MuData, None] (default: None)) – 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 saved scvi setup dictionary. 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

>>> model = ModelClass.load(save_path, adata)
>>> model.get_....
static ContrastiveVI.load_registry(dir_path, prefix=None)[source]#

Return the full registry saved with the model.

Parameters:
  • dir_path (str) – Path to saved outputs.

  • prefix (str | None (default: None)) – Prefix of saved file names.

Return type:

dict

Returns:

The full registry saved with the model

classmethod ContrastiveVI.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 the setup_anndata() class method followed up by retrieval of the AnnDataManager 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 previous AnnDataManager.

ContrastiveVI.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 anndata

  • save_kwargs (dict | None (default: None)) – Keyword arguments passed into save().

  • anndata_write_kwargs – Kwargs for write()

classmethod ContrastiveVI.setup_anndata(adata, layer=None, batch_key=None, labels_key=None, size_factor_key=None, categorical_covariate_keys=None, continuous_covariate_keys=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:
  • adata (AnnData) – AnnData object. Rows represent cells, columns represent features.

  • layer (str | None (default: None)) – if not None, uses this as the key in adata.layers for raw count data.

  • 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.

  • size_factor_key (str | None (default: None)) – key in adata.obs for size factor information. Instead of using library size as a size factor, the provided size factor column will be used as offset in the mean of the likelihood. Assumed to be on linear scale.

  • categorical_covariate_keys (list[str] | None (default: None)) – keys in adata.obs that correspond to categorical data. These covariates can be added in addition to the batch covariate and are also treated as nuisance factors (i.e., the model tries to minimize their effects on the latent space). Thus, these should not be used for biologically-relevant factors that you do _not_ want to correct for.

  • continuous_covariate_keys (list[str] | None (default: None)) – keys in adata.obs that correspond to continuous data. These covariates can be added in addition to the batch covariate and are also treated as nuisance factors (i.e., the model tries to minimize their effects on the latent space). Thus, these should not be used for biologically-relevant factors that you do _not_ want to correct for.

ContrastiveVI.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
ContrastiveVI.train(background_indices, target_indices, max_epochs=None, accelerator='auto', devices='auto', train_size=0.9, validation_size=None, shuffle_set_split=True, load_sparse_tensor=False, batch_size=128, early_stopping=False, datasplitter_kwargs=None, plan_kwargs=None, **trainer_kwargs)[source]#

Train the model.

Parameters:
  • max_epochs (int | None (default: None)) – 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.

  • 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.

  • load_sparse_tensor (bool (default: False)) – EXPERIMENTAL If True, loads data with sparse CSR or CSC layout as a Tensor with the same layout. Can lead to speedups in data transfers to GPUs, depending on the sparsity of the data.

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

  • early_stopping (bool (default: False)) – Perform early stopping. Additional arguments can be passed in **kwargs. See Trainer for further options.

  • datasplitter_kwargs (dict | None (default: None)) – Additional keyword arguments passed into ContrastiveDataSplitter.

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

  • **trainer_kwargs – Other keyword args for Trainer.

ContrastiveVI.view_anndata_setup(adata=None, hide_state_registries=False)[source]#

Print summary of the setup for the initial AnnData or a given AnnData object.

Parameters:
  • adata (Union[AnnData, MuData, None] (default: None)) – AnnData object setup with setup_anndata or transfer_fields().

  • hide_state_registries (bool (default: False)) – If True, prints a shortened summary without details of each state registry.

Return type:

None

static ContrastiveVI.view_setup_args(dir_path, prefix=None)[source]#

Print args used to setup a saved model.

Parameters:
  • dir_path (str) – Path to saved outputs.

  • prefix (str | None (default: None)) – Prefix of saved file names.

Return type:

None