scvi.external.DIAGVI#
- class scvi.external.DIAGVI(adatas, guidance_graph=None, mapping_df=None, n_latent=50, n_hidden=256, n_layers=2, dropout_rate=0.1, **model_kwargs)[source]#
Diagonal Multi-Modal Integration Variational Inference (DIAGVI) model.
Integrates multi-modal single-cell data using a guidance graph and supports semi-supervised learning and GMM priors.
The model architecture is inspired by GLUE (Cao & Gao, 2022). This scvi-tools implementation is based on GimVI. Handling of continuous data in decoder is inspired by CytoVI.
- Parameters:
- adatas
dict[str,AnnData] |MuData Dictionary mapping input names to AnnData objects.
- guidance_graph
Data|None(default:None) Precomputed guidance graph. If None, it will be constructed from the data by using overlapping feature names.
- mapping_df
DataFrame|None(default:None) DataFrame specifying feature correspondences between modalities (used to compute the guidance graph).
- n_latent
int(default:50) Dimensionality of the latent space.
- n_hidden
int(default:256) Number of nodes per hidden layer.
- n_layers
int(default:2) Number of hidden layers used for encoder and decoder NNs.
- dropout_rate
float(default:0.1) Dropout rate for neural networks.
- **model_kwargs
Additional keyword arguments for
DIAGVAE.
- adatas
Examples
>>> adatas = {"rna_data": adata_rna, "protein_data": adata_protein} >>> model = DIAGVI(adatas) >>> model.train()
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#
|
Constructs a custom guidance graph defined by the mapping_df. |
|
Converts a legacy saved model (<v0.15.0) to the updated save format. |
|
Returns the object in AnnData associated with the key in the data registry. |
|
Deregisters the |
|
Not implemented for this model class. |
|
Compute the aggregated posterior over 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 a given query modality. |
|
Return the latent space embedding for each dataset. |
|
Compute the marginal log-likehood of the data. |
|
Not implemented for this model class. |
|
Compute the reconstruction error on the data. |
|
Returns the string provided to setup of a specific setup_arg. |
|
Returns the state registry for the AnnDataField registered with this instance. |
|
Variable names of input data. |
|
Load a saved DIAGVI model from disk. |
|
Return the full registry saved with the model. |
|
Generate posterior predictive samples for each modality. |
|
Predict cell type labels using a trained classifier. |
|
Registers an |
|
Save the DIAGVI model and optionally the AnnData objects. |
|
Set up a model from on-disk AnnData files via the annbatch streaming loader. |
|
Sets up the |
|
Register a MuData object for use with DIAGVI. |
|
Move the model to the device. |
|
Train the DIAGVI model. |
|
Transfer fields from a model to an AnnData object. |
|
Update setup method args. |
|
Print summary of the setup for the initial AnnData or a given AnnData object. |
|
Prints summary of the registry. |
|
Print args used to setup a saved model. |
Prints setup kwargs used to produce a given registry. |
Attributes#
- DIAGVI.adata#
Data attached to model instance.
- DIAGVI.adata_manager#
Manager instance associated with self.adata.
- DIAGVI.device#
The current device that the module’s params are on.
- DIAGVI.get_normalized_function_name#
What the get normalized functions name is
- DIAGVI.history#
Returns computed metrics during training.
- DIAGVI.is_trained#
Whether the model has been trained.
- DIAGVI.registry#
Data attached to model instance.
- DIAGVI.run_id#
Returns the run id of the model. Used in MLFlow
- DIAGVI.run_name#
Returns the run name of the model. Used in MLFlow
- DIAGVI.summary_string#
Summary string of the model.
- DIAGVI.test_indices#
Observations that are in test set.
- DIAGVI.train_indices#
Observations that are in train set.
- DIAGVI.validation_indices#
Observations that are in validation set.
Methods#
- static DIAGVI.construct_custom_guidance_graph(input_dict, mapping_df, weight=1.0, sign=1.0)[source]#
Constructs a custom guidance graph defined by the mapping_df.
- Parameters:
- input_dict
dict[str,AnnData] Dictionary mapping modality names (e.g., “scRNAseq”, “seqFISH”) to their respective AnnData objects. The keys in this dictionary must match the column names in
mapping_df.- mapping_df
DataFrame DataFrame specifying feature correspondences between modalities. Each column should correspond to a modality name in input_dict, and each row defines a feature pair.
- weight
float(default:1.0) Edge weight assigned to cross-modality edges.
- sign
float(default:1.0) Edge sign assigned to cross-modality edges.
- input_dict
- Return type:
- Returns:
A PyTorch Geometric Data object representing the guidance graph, including node features, edge indices, edge weights, edge signs, and modality-specific feature indices.
Notes
Features are renamed to include the modality name as a suffix.
Self-loops are added for all features with weight=1.0 and sign=1.0.
Missing features in the mapping are silently skipped.
- classmethod DIAGVI.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 the directory where the legacy model is saved.
- output_dir_path
str Path to save converted save files.
- overwrite
bool(default:False) Overwrite existing data or not. If
Falseand directory already exists atoutput_dir_path, an error will be raised.- prefix
str|None(default:None) Prefix of saved file names.
- **save_kwargs
Keyword arguments passed into
save().
- dir_path
- Return type:
- DIAGVI.data_registry(registry_key)[source]#
Returns the object in AnnData associated with the key in the data registry.
- DIAGVI.deregister_manager(adata=None)[source]#
Deregisters the
AnnDataManagerinstance associated withadata.If
adataisNone, deregisters allAnnDataManagerinstances in both the class and instance-specific manager stores, except for the one associated with this model instance.
- DIAGVI.differential_abundance(*args, **kwargs)[source]#
Not implemented for this model class.
Available in models that inherit from
VAEMixin.- Raises:
- DIAGVI.get_aggregated_posterior(adata=None, indices=None, batch_size=None, dof=3.0)[source]#
Compute the aggregated posterior over the
ulatent representations.- Parameters:
- adata
AnnData|MuData|None(default:None) AnnData object to use. Defaults to the AnnData object used to initialize the model.
- indices
Sequence[int] |None(default:None) Indices of cells to use.
- batch_size
int|None(default:None) Batch size to use for computing the latent representation.
- dof
float|None(default:3.0) Degrees of freedom for the Student’s t-distribution components. If
None, components are Normal.
- adata
- Return type:
- Returns:
A mixture distribution of the aggregated posterior.
- DIAGVI.get_anndata_manager(adata, required=False)[source]#
Retrieves the
AnnDataManagerfor a given AnnData object.Requires
self.idhas been set. Checks for anAnnDataManagerspecific to this model instance.- Parameters:
- Return type:
- DIAGVI.get_elbo(adata=None, indices=None, batch_size=None, dataloader=None, return_mean=True, data_loader_kwargs=None, **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.AnnData |
None(default:None) AnnDataobject withvar_namesin the same order as the ones used to train the model. IfNoneanddataloaderis alsoNone, it defaults to the object used to initialize the model.- indices
Sequence[int] |None(default:None) Indices of observations in
adatato use. IfNone, defaults to all observations. Ignored ifdataloaderis notNone.- batch_size
int|None(default:None) Minibatch size for the forward pass. If
None, defaults toscvi.settings.batch_size. Ignored ifdataloaderis notNone.- dataloader
Iterator[dict[str, torch.Tensor |None]] |None(default:None) An iterator over minibatches of data on which to compute the metric. The minibatches should be formatted as a dictionary of
Tensorwith 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.
- data_loader_kwargs
dict|None(default:None) Keyword args for data loader, in dict form.
- **kwargs
Additional keyword arguments to pass into the forward method of the module.
- adata anndata.AnnData |
- Return type:
- Returns:
Evidence lower bound (ELBO) of the data.
Notes
This is not the negative ELBO, so higher is better.
- DIAGVI.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_anndatamethod.
- DIAGVI.get_imputed_values(query_name, query_adata=None, indices=None, deterministic=True, batch_size=2048, reference_batch=None, reference_libsize=None)[source]#
Return imputed values for a given query modality.
- Parameters:
- query_name
str Name of the query modality.
- query_adata anndata.AnnData |
None(default:None) AnnData object for the query modality. If None, uses the registered AnnData.
- indices
Sequence[int] |None(default:None) Indices of cells to use. If
None, all cells are used.- deterministic
bool(default:True) Whether to use deterministic inference (posterior mean).
- batch_size
int(default:2048) Minibatch size for data loading.
- reference_batch
int|str|ndarray|None(default:None) Reference batch index or array for imputation. Can be a scalar, a length-1 array, or an array with length equal to the number of queried cells.
- reference_libsize
float|ndarray|None(default:None) Reference library size(s) for imputation. Can be a scalar, a length-1 array, or an array with length equal to the number of queried cells.
- query_name
- Return type:
- Returns:
Imputed values.
- DIAGVI.get_latent_representation(adatas=None, indices=None, batch_size=1024)[source]#
Return the latent space embedding for each dataset.
- Parameters:
- adatas
dict[str,AnnData] |list[AnnData] |None(default:None) Modalities to compute embeddings for. If None, uses all modalities.
- indices
dict[str,Sequence[int]] |None(default:None) Dictionary mapping modality names to indices of cells to use. If
None, all cells are used for each modality.- batch_size
int(default:1024) Minibatch size for data loading.
- adatas
- Return type:
- Returns:
Dictionary mapping modality names to latent embeddings.
- DIAGVI.get_marginal_ll(adata=None, indices=None, n_mc_samples=1000, batch_size=None, return_mean=True, dataloader=None, data_loader_kwargs=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.AnnData |
None(default:None) AnnDataobject withvar_namesin the same order as the ones used to train the model. IfNoneanddataloaderis alsoNone, it defaults to the object used to initialize the model.- indices
Sequence[int] |None(default:None) Indices of observations in
adatato use. IfNone, defaults to all observations. Ignored ifdataloaderis notNone.- n_mc_samples
int(default:1000) Number of Monte Carlo samples to use for the estimator. Passed into the module’s
marginal_llmethod.- batch_size
int|None(default:None) Minibatch size for the forward pass. If
None, defaults toscvi.settings.batch_size. Ignored ifdataloaderis 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, torch.Tensor |None]] (default:None) An iterator over minibatches of data on which to compute the metric. The minibatches should be formatted as a dictionary of
Tensorwith keys as expected by the model. IfNone, a dataloader is created fromadata.- data_loader_kwargs
dict|None(default:None) Keyword args for data loader, in dict form.
- **kwargs
Additional keyword arguments to pass into the module’s
marginal_llmethod.
- adata anndata.AnnData |
- Return type:
float| torch.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.
- DIAGVI.get_normalized_expression(*args, **kwargs)[source]#
Not implemented for this model class.
Available in RNA models that inherit from
RNASeqMixin.- Raises:
- DIAGVI.get_reconstruction_error(adata=None, indices=None, batch_size=None, dataloader=None, return_mean=True, data_loader_kwargs=None, **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.AnnData |
None(default:None) AnnDataobject withvar_namesin the same order as the ones used to train the model. IfNoneanddataloaderis alsoNone, it defaults to the object used to initialize the model.- indices
Sequence[int] |None(default:None) Indices of observations in
adatato use. IfNone, defaults to all observations. Ignored ifdataloaderis notNone- batch_size
int|None(default:None) Minibatch size for the forward pass. If
None, defaults toscvi.settings.batch_size. Ignored ifdataloaderis notNone- dataloader
Iterator[dict[str, torch.Tensor |None]] |None(default:None) An iterator over minibatches of data on which to compute the metric. The minibatches should be formatted as a dictionary of
Tensorwith 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.
- data_loader_kwargs
dict|None(default:None) Keyword args for data loader, in dict form.
- **kwargs
Additional keyword arguments to pass into the forward method of the module.
- adata anndata.AnnData |
- Return type:
- Returns:
Reconstruction error for the data.
Notes
This is not the negative reconstruction error, so higher is better.
- DIAGVI.get_setup_arg(setup_arg)[source]#
Returns the string provided to setup of a specific setup_arg.
- Return type:
- DIAGVI.get_state_registry(registry_key)[source]#
Returns the state registry for the AnnDataField registered with this instance.
- Return type:
- DIAGVI.get_var_names(legacy_mudata_format=False)[source]#
Variable names of input data.
- Return type:
- classmethod DIAGVI.load(dir_path, adatas=None, accelerator='auto', device='auto', prefix=None, backup_url=None)[source]#
Load a saved DIAGVI model from disk.
- Parameters:
- dir_path
str Directory path where the model was saved.
- adatas
dict[str,AnnData] |None(default:None) Dictionary mapping modality names to AnnData objects. Required when the model was saved with
save_anndata=False.- 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 (
intorstr) or"auto"for automatic selection based on the chosen accelerator. If set to"auto"andacceleratoris not determined to be"cpu", thendevicewill be set to the first available device.- prefix
str|None(default:None) Prefix used when saving the model.
- backup_url
str|None(default:None) URL to download the model from if not found locally.
- dir_path
- Return type:
- Returns:
Loaded DIAGVI model instance.
- Raises:
ValueError – If the saved model is from a different class or missing setup inputs.
- static DIAGVI.load_registry(dir_path, prefix=None)[source]#
Return the full registry saved with the model.
- DIAGVI.posterior_predictive_sample(adatas=None, indices=None, n_samples=1, batch_size=None)[source]#
Generate posterior predictive samples for each modality.
This method generates samples from the posterior predictive distribution p(x̂|x) for each modality, which can be used for model criticism via
PosteriorPredictiveCheck.- Parameters:
- adatas
dict[str,AnnData] |None(default:None) Dictionary mapping modality names to AnnData objects. If
None, defaults to the AnnData objects used to initialize the model.- indices
dict[str,Sequence[int]] |None(default:None) Dictionary mapping modality names to indices of cells to use. If
None, all cells are used for each modality.- n_samples
int(default:1) Number of posterior predictive samples to generate per cell.
- batch_size
int|None(default:None) Minibatch size for data loading. Defaults to
scvi.settings.batch_size.
- adatas
- Return type:
- Returns:
Dictionary mapping modality names to arrays of shape
(n_cells, n_features, n_samples)ifn_samples > 1, else(n_cells, n_features).
- DIAGVI.predict_celltype(labeled_modality, target_modality=None, target_adata=None, indices=None, batch_size=2048, deterministic=True)[source]#
Predict cell type labels using a trained classifier.
- Parameters:
- labeled_modality
str Name of the modality for which the classifier was trained. A classifier must have been trained for this modality (i.e., labels_key must have been provided during setup_anndata for this modality).
- target_modality
str|None(default:None) Name of the modality to predict cell types for. If None, defaults to the other modality (not labeled_modality) for cross-modal label transfer.
- target_adata anndata.AnnData |
None(default:None) AnnData object for the target modality. If None, uses the registered AnnData.
- indices
Sequence[int] |None(default:None) Indices of cells to predict. If
None, all cells are used.- batch_size
int(default:2048) Minibatch size for data loading.
- labeled_modality
- Return type:
- Returns:
Dictionary with keys: - “predictions”: Array of predicted label categories (strings) - “probabilities”: Array of class probabilities (n_cells, n_classes) - “confidence”: Array of maximum probability for each cell
- Raises:
ValueError – If labeled_modality is not a valid modality name. If target_modality is not a valid modality name. If no classifier was trained for the labeled modality.
- classmethod DIAGVI.register_manager(adata_manager)[source]#
Registers an
AnnDataManagerinstance with this model class.Stores the
AnnDataManagerreference in a class-specific manager store. Intended for use in thesetup_anndata()class method followed up by retrieval of theAnnDataManagervia the_get_most_recent_anndata_manager()method in the model init method.Notes
Subsequent calls to this method with an
AnnDataManagerinstance referring to the same underlying AnnData object will overwrite the reference to previousAnnDataManager.
- DIAGVI.save(dir_path, prefix=None, overwrite=False, save_anndata=False, save_kwargs=None)[source]#
Save the DIAGVI model and optionally the AnnData objects.
- Parameters:
- dir_path
str Directory path to save the model and AnnData objects.
- prefix
str|None(default:None) Prefix for the saved model file name.
- overwrite
bool(default:False) Whether to overwrite the directory if it already exists.
- save_anndata
bool(default:False) Whether to save the AnnData objects used to train the model.
- save_kwargs
dict|None(default:None) Additional keyword arguments for torch.save.
- dir_path
- Raises:
ValueError – If dir_path exists and overwrite is False.
- classmethod DIAGVI.setup_annbatch(collection_path=None, paths=None, batch_key=None, labels_key=None, sample_key=None, unlabeled_category='Unknown', layer=None, categorical_covariate_keys=None, continuous_covariate_keys=None, rebuild=True, batch_size=4096, chunk_size=256, preload_nchunks=32, preload_to_gpu=True, dataset_size='20GB', shuffle=False, var_subset=None, merge=None, adatas=None, use_class_sampler=False, class_sampler_key=None, class_weights=None)[source]#
Set up a model from on-disk AnnData files via the annbatch streaming loader.
Builds (or reuses) a zarr-backed
DatasetCollectionfrom the supplied h5ad file paths, then wraps it in aAnnbatchDataModuleready for training.- Parameters:
- collection_path
str|None(default:None) Directory where the zarr collection is written (or already exists). If
None(default), a path is auto-generated as"./{ModelName}_annbatch.zarr"in the current working directory.- paths
list[str] |None(default:None) Paths to h5ad files that make up the training dataset. If
None, an existing collection atcollection_pathis opened without rebuilding — useful when the zarr store was created by a previous call. Must be provided when the store does not exist yet.- batch_key
str|None(default:None) Column in
obsto use as the batch variable.- labels_key
str|None(default:None) Column in
obsto use as the cell-type / label variable.- sample_key
str|None(default:None) Column in
obsto use as the sample variable. Used by models like MrVI.- unlabeled_category
str(default:'Unknown') Value used to mark unlabeled cells in
labels_key. Required by semi-supervised models such as SCANVI. Defaults to"Unknown".- layer
str|None(default:None) Layer in the h5ad files to use as the count matrix.
Noneusesadata.X(falling back toadata.raw.Xwhen a raw slot exists).- categorical_covariate_keys
list[str] |None(default:None) Additional categorical covariate columns in
obs.- continuous_covariate_keys
list[str] |None(default:None) Additional continuous covariate columns in
obs.- rebuild
bool(default:True) If
True, always rebuild the zarr collection even if it already exists on disk. IfFalse(default), reuse an existing collection and skip the (potentially expensive)add_adatasstep.- batch_size
int(default:4096) Number of cells per batch yielded by the
Loader.- chunk_size
int(default:256) Number of cells loaded from disk contiguously per read.
- preload_nchunks
int(default:32) Number of chunks to preload and shuffle in memory.
- preload_to_gpu
bool(default:True) Whether the loader should move data to GPU before yielding.
- dataset_size
int|str(default:'20GB') Number of observations to load into memory for shuffling / pre-processing when building the collection, or annbatch’s human-readable size strings, e.g.
"20GB".- shuffle
bool(default:False) Whether to pre-shuffle cells when building the collection.
- var_subset
list[str] |None(default:None) Optional list of gene names to restrict the collection to (passed as
var_subsettoadd_adatas).- merge
Literal['same','unique','first','only'] |None(default:None) How annbatch should merge
varmetadata across inputs. Passed through toannbatch.DatasetCollection.add_adatas().
- collection_path
- Returns:
AnnbatchDataModuleA configured datamodule whoseregistrycan be passed directly to the model constructor, e.g.model = SCVI(registry=dm.registry).
Notes
After training, saving and reloading the model requires reconstructing the datamodule manually and passing it to
load()via thedatamoduleargument — the same pattern used by all custom datamodules.
- classmethod DIAGVI.setup_anndata(adata, layer=None, batch_key=None, labels_key=None, likelihood='nb', normalize_lib=True, gmm_prior=False, n_mixture_components=10, unlabeled_category='unknown', **kwargs)[source]#
Sets up the
AnnDataobject 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 to register.
- batch_key
str|None(default:None) key in
adata.obsfor batch information. Categories will automatically be converted into integer categories and saved toadata.obs['_scvi_batch']. IfNone, assigns the same batch to all the data.- labels_key
str|None(default:None) key in
adata.obsfor label information. Categories will automatically be converted into integer categories and saved toadata.obs['_scvi_labels']. IfNone, assigns the same label to all the data.- layer
str|None(default:None) if not
None, uses this as the key inadata.layersfor raw count data.- likelihood
Literal['nb','zinb','nbmixture','normal','log1pnormal','ziln','zig'] (default:'nb') Likelihood model for this modality (default: ‘nb’). One of: - ‘nb’ : Negative Binomial - ‘zinb’ : Zero-Inflated Negative Binomial - ‘nbmixture’ : Negative Binomial Mixture (for protein data with background/foreground) - ‘normal’ : Normal distribution - ‘log1pnormal’ : Log1p Normal distribution - ‘ziln’ : Zero-Inflated Log Normal distribution - ‘zig’ : Zero-Inflated Gamma distribution
- normalize_lib
bool(default:True) Whether to normalize counts with library size in the model.
- gmm_prior
bool(default:False) Whether to use a GMM prior for this modality.
- n_mixture_components
int(default:10) Number of mixture components for the GMM prior. If labels_key is provided, this parameter is ignored and set to the number of unique labels in labels_key.
- unlabeled_category
str(default:'unknown') Category for unlabeled cells in labels_key.
- **kwargs
Additional keyword arguments.
- adata
- classmethod DIAGVI.setup_mudata(mdata, modalities, batch_key=None, labels_key=None, layer=None, likelihood='nb', normalize_lib=True, gmm_prior=False, n_mixture_components=10, unlabeled_category='unknown', **kwargs)[source]#
Register a MuData object for use with DIAGVI.
- Parameters:
- mdata
MuData MuData object containing multiple modalities.
- modalities
list[str] List of two modality names from mdata.mod to use.
- batch_key
dict[str,str] |str|None(default:None) Key(s) in adata.obs for batch annotation. Can be a single string (applied to all modalities) or a dict mapping modality names to keys.
- labels_key
dict[str,str] |str|None(default:None) Key(s) in adata.obs for cell type labels.
- layer
dict[str,str|None] |str|None(default:None) Layer(s) in adata to use as input.
- likelihood
dict[str,Literal['nb','zinb','nbmixture','normal']] |str(default:'nb') Likelihood model(s) for each modality. Options: ‘nb’, ‘zinb’, ‘nbmixture’, ‘normal’. Default is ‘nb’.
- normalize_lib
dict[str,bool] |bool(default:True) Whether to normalize counts with library size in the model for each modality.
- gmm_prior
dict[str,bool] |bool(default:False) Whether to use GMM prior for each modality. Default is False.
- n_mixture_components
dict[str,int] |int(default:10) Number of mixture components for the GMM prior for each modality. If labels_key is provided, this parameter is ignored and set to the number of unique labels in labels_key.
- unlabeled_category
dict[str,str] |str(default:'unknown') Category name for unlabeled cells. Default is ‘unknown’.
- **kwargs
Additional keyword arguments passed to setup_anndata.
- mdata
- DIAGVI.to_device(device)[source]#
Move the model to the device.
- Parameters:
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
- DIAGVI.train(max_epochs=None, lr=0.001, batch_size=256, train_size=0.9, accelerator='auto', devices='auto', shuffle_set_split=True, datasplitter_kwargs=None, plan_kwargs=None, **kwargs)[source]#
Train the DIAGVI model.
- Parameters:
- max_epochs
int|None(default:None) Maximum number of training epochs. If None, a heuristic is used.
- lr
float(default:0.001) Learning rate for optimization.
- batch_size
int(default:256) Minibatch size for training.
- 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 (
intorstr), a sequence of device indices (listor comma-separatedstr), the value-1to indicate all available devices, or"auto"for automatic selection based on the chosenaccelerator. If set to"auto"andacceleratoris not determined to be"cpu", thendeviceswill be set to the first available device.- train_size
float(default:0.9) Proportion of data to use for training (rest for validation).
- shuffle_set_split
bool(default:True) Whether to shuffle data before splitting into train/validation.
- datasplitter_kwargs
dict|None(default:None) Additional keyword arguments for the DataSplitter and DataLoaders. Can be either:
A dict of shared kwargs applied to all modalities
A nested dict mapping modality names to their specific kwargs, e.g.,
{"rna": {"external_indexing": [train, val, test]}, "protein": {...}}
- plan_kwargs
dict|None(default:None) Additional keyword arguments for the training plan.
- **kwargs
Additional keyword arguments for the Trainer.
- max_epochs
- DIAGVI.transfer_fields(adata, **kwargs)[source]#
Transfer fields from a model to an AnnData object.
- Return type:
- DIAGVI.update_setup_method_args(setup_method_args)[source]#
Update setup method args.
- Parameters:
- setup_method_args
dict This is a bit of a misnomer, this is a dict representing kwargs of the setup method that will be used to update the existing values in the registry of this instance.
- setup_method_args
- DIAGVI.view_anndata_setup(adata=None, hide_state_registries=False)[source]#
Print summary of the setup for the initial AnnData or a given AnnData object.