scvi.external.RESOLVI#
- class scvi.external.RESOLVI(adata, n_hidden=32, n_hidden_encoder=128, n_latent=10, n_layers=2, dropout_rate=0.05, dispersion='gene', gene_likelihood='nb', background_ratio=None, median_distance=None, semisupervised=False, mixture_k=50, downsample_counts=True, **model_kwargs)[source]#
ResolVI addresses noise and bias in single-cell resolved spatial transcriptomics data.
- Parameters:
- adata
AnnData AnnData object that has been registered via
setup_anndata().- n_hidden
int(default:32) Number of nodes per hidden layer.
- n_latent
int(default:10) Dimensionality of the latent space.
- n_layers
int(default:2) Number of hidden layers used for encoder and decoder NNs.
- dropout_rate
float(default:0.05) Dropout rate for neural networks.
- dispersion
Literal['gene','gene-batch'] (default:'gene') One of the following:
'gene'- dispersion parameter of NB is constant per gene across cells'gene-batch'- dispersion can differ between different batches'gene-label'- dispersion can differ between different labels'gene-cell'- dispersion can differ for every gene in every cell
- gene_likelihood
Literal['nb','poisson'] (default:'nb') One of:
'nb'- Negative binomial distribution'zinb'- Zero-inflated negative binomial distribution'poisson'- Poisson distribution
- **model_kwargs
Keyword args for
RESOLVAE
- adata
Examples
>>> adata = anndata.read_h5ad(path_to_anndata) >>> scvi.external.RESOLVI.setup_anndata(adata, batch_key="batch") >>> resolvi = scvi.external.RESOLVI(adata) >>> resolvi.train() >>> adata.obsm["X_resolVI"] = resolvi.get_latent_representation() >>> adata.layers["X_normalized_resolVI"] = resolvi.get_normalized_expression()
Notes
See further usage examples in the following tutorial:
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#
|
Compute dataset-dependent prior parameters for the ResolVI model. |
|
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. |
|
A unified method for differential expression analysis. |
|
A unified method for niche differential abundance analysis. |
|
Retrieves the |
|
Returns the object in AnnData associated with the key in the data registry. |
|
Return the latent representation for each cell. |
|
Returns the abundance of cell-types within spatial proximity of center cells. |
|
Returns the normalized (decoded) gene expression. |
Returns the normalized (decoded) importance-sampled gene expression. |
|
|
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. |
|
Instantiate a model from the saved output. |
|
Online update of a reference model with scArches algorithm [Lotfollahi et al., 2021]. |
|
Return the full registry saved with the model. |
|
Return cell label predictions. |
|
Prepare data for query integration. |
|
Prepare multimodal dataset for query integration. |
|
Registers an |
|
Summarise posterior distribution. |
|
Save the state of the model. |
|
Set up a model from on-disk AnnData files via the annbatch streaming loader. |
|
Sets up the |
|
Move the model to the device. |
|
Trains the model using amortized variational inference. |
|
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#
- RESOLVI.adata#
Data attached to model instance.
- RESOLVI.adata_manager#
Manager instance associated with self.adata.
- RESOLVI.device#
The current device that the module’s params are on.
- RESOLVI.get_normalized_function_name#
What the get normalized functions name is
- RESOLVI.history#
Returns computed metrics during training.
- RESOLVI.is_trained#
Whether the model has been trained.
- RESOLVI.registry#
Data attached to model instance.
- RESOLVI.run_id#
Returns the run id of the model. Used in MLFlow
- RESOLVI.run_name#
Returns the run name of the model. Used in MLFlow
- RESOLVI.summary_string#
Summary string of the model.
- RESOLVI.test_indices#
Observations that are in test set.
- RESOLVI.train_indices#
Observations that are in train set.
- RESOLVI.validation_indices#
Observations that are in validation set.
Methods#
- RESOLVI.compute_dataset_dependent_priors(n_small_genes=None)[source]#
Compute dataset-dependent prior parameters for the ResolVI model.
Estimates background expression ratio and spatial kernel size from the data, which are used as priors during training.
- Parameters:
- n_small_genes default:
None Number of low-expressed genes used to estimate the background ratio. If
None, defaults ton_genes // 50.
- n_small_genes default:
- Returns:
dict with keys
"background_ratio","median_distance","mean_log_counts", and"std_log_counts".
- classmethod RESOLVI.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:
- RESOLVI.data_registry(registry_key)[source]#
Returns the object in AnnData associated with the key in the data registry.
- RESOLVI.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.
- RESOLVI.differential_abundance(*args, **kwargs)[source]#
Not implemented for this model class.
Available in models that inherit from
VAEMixin.- Raises:
- RESOLVI.differential_expression(adata=None, groupby=None, group1=None, group2=None, idx1=None, idx2=None, subset_idx=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, weights='uniform', filter_outlier_cells=False, n_samples=5, size_scaling=False, library_scaling=False, **kwargs)[source]#
A unified method for differential expression analysis.
Implements
"vanilla"DE [Lopez et al., 2018] and"change"mode DE [Boyeau et al., 2019].- Parameters:
- adata anndata.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 ingroupby(default).- group2
str|None(default:None) If
None, compare each group ingroup1to the union of the rest of the groups ingroupby. If a group identifier, compare with respect to this group.- idx1
Sequence[int] |Sequence[bool] |None(default:None) idx1andidx2can be used as an alternative to the AnnData keys. Custom identifier forgroup1that 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 onadata.obs, as described inpandas.DataFrame.query()Ifidx1is notNone, this option overridesgroup1andgroup2.- idx2
Sequence[int] |Sequence[bool] |None(default:None) Custom identifier for
group2that has the same properties asidx1. By default, includes all cells not specified inidx1.- subset_idx
Sequence[int] |None(default:None) Can be of three types. First, it can corresponds to a boolean mask that has the same shape as adata. It can also corresponds to a list of indices. Last, it can correspond to string query of adata.obs columns.
- mode
Literal['vanilla','change'] (default:'change') Method for differential expression. See user guide for full explanation.
- delta
float(default:0.25) specific case of region inducing differential expression. In this case, we suppose that \(R \setminus [-\delta, \delta]\) does not induce differential expression (change model default case).
- batch_size
int|None(default:None) Minibatch 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_keyregistered insetup_anndata, e.g. ['batch1','batch2','batch3'], forgroup1. Only used ifbatch_correctionisTrue, and by default all categories are used.- batchid2
Iterable[str] |None(default:None) Same as
batchid1for group2.batchid2must either have null intersection withbatchid1, or be exactly equal tobatchid1. When the two sets are exactly equal, cells are compared by decoding on the same batch. When sets have null intersection, cells fromgroup1andgroup2are decoded on each group ingroup1andgroup2, 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.
- weights
Literal['uniform','importance'] |None(default:'uniform') Precomputed weight for importance sampling. If
uniformno importance sampling is performed.- filter_outlier_cells
bool(default:False) Whether to filter outlier cells with
filter_outlier_cells()- n_samples
int(default:5) Number of posterior samples to use for estimation.
- size_scaling
bool(default:False) If True, will scale normalized expression by size factors (e.g. cell volume). This needs to be setup in
setup_anndata()withsize_factor_key. False by default.- library_scaling
bool(default:False) If True, will scale normalized expression to library size. This is useful for skewed gene panels if library size normalization is detrimental. False by default.
- **kwargs
Keyword args for
scvi.model.base.DifferentialComputation.get_bayes_factors()
- adata anndata.AnnData |
- Return type:
- Returns:
Differential expression DataFrame.
- RESOLVI.differential_niche_abundance(adata=None, groupby=None, group1=None, group2=None, neighbor_key=None, idx1=None, idx2=None, subset_idx=None, mode='change', delta=0.25, batch_size=None, fdr_target=0.05, silent=False, filter_outlier_cells=False, pseudocounts=0.001, **kwargs)[source]#
A unified method for niche differential abundance analysis.
Implements
"vanilla"DE [Lopez et al., 2018] and"change"mode DE [Boyeau et al., 2019].- Parameters:
- adata anndata.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 ingroupby(default).- group2
str|None(default:None) If
None, compare each group ingroup1to the union of the rest of the groups ingroupby. If a group identifier, compare with respect to this group.- neighbor_key
str|None(default:None) Obsm key containing the spatial neighbors of each cell.
- idx1
Sequence[int] |Sequence[bool] |None(default:None) idx1andidx2can be used as an alternative to the AnnData keys. Custom identifier forgroup1that 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 onadata.obs, as described inpandas.DataFrame.query()Ifidx1is notNone, this option overridesgroup1andgroup2.- idx2
Sequence[int] |Sequence[bool] |None(default:None) Custom identifier for
group2that has the same properties asidx1. By default, includes all cells not specified inidx1.- subset_idx
Sequence[int] |None(default:None) Can be of three types. First, it can corresponds to a boolean mask that has the same shape as adata. It can also corresponds to a list of indices. Last, it can correspond to string query of adata.obs columns.
- mode
Literal['vanilla','change'] (default:'change') Method for differential expression. See user guide for full explanation.
- delta
float(default:0.25) specific case of region inducing differential expression. In this case, we suppose that \(R \setminus [-\delta, \delta]\) does not induce differential expression (change model default case).
- batch_size
int|None(default:None) Minibatch size for data loading into model. Defaults to
scvi.settings.batch_size.- 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.
- filter_outlier_cells
bool(default:False) Whether to filter outlier cells with
filter_outlier_cells()- pseudocounts
float(default:0.001) pseudocount offset used for the mode
change. When None, observations from non-expressed genes are used to estimate its value.- **kwargs
Keyword args for
scvi.model.base.DifferentialComputation.get_bayes_factors()
- adata anndata.AnnData |
- Return type:
- Returns:
Differential expression DataFrame.
- RESOLVI.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:
- RESOLVI.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.
- RESOLVI.get_latent_representation(adata=None, indices=None, give_mean=True, mc_samples=1, batch_size=None, return_dist=False)[source]#
Return the latent representation for each cell.
This is denoted as \(z\) in RESOLVI.
- 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.
- mc_samples
int(default:1) For consistency with scVI, this parameter is ignored.
- batch_size
int|None(default:None) Minibatch size for data loading into model. Defaults to
scvi.settings.batch_size.- return_dist
bool(default:False) Return the distribution parameters of the latent variables rather than their sampled values. If
True, ignoresgive_meanandmc_samples.
- adata
- Return type:
- Returns:
Low-dimensional representation for each cell or a tuple containing its mean and variance.
- RESOLVI.get_neighbor_abundance(adata=None, indices=None, neighbor_key=None, n_samples=1, n_samples_overall=None, batch_size=None, summary_frequency=2, weights=None, return_mean=True, return_numpy=None, **kwargs)[source]#
Returns the abundance of cell-types within spatial proximity of center cells.
- 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.- neighbor_key
str|None(default:None) Obsm key containing the spatial neighbors of each cell.
- n_samples
int(default:1) Number of posterior samples to use for estimation.
- n_samples_overall
int(default:None) Number of posterior samples to use for estimation. Overrides
n_samples.- batch_size
int|None(default:None) Minibatch size for data loading into model. Defaults to
scvi.settings.batch_size.- summary_frequency
int(default:2) Compute summary_fn after summary_frequency batches. Reduces memory footprint.
- weights
str|None(default:None) Spatial weights for each neighbor. If
Noneperforms no spatial weighting. Needs to be of shapen_cellsbyn_neighbors.- return_mean
bool(default:True) Whether to return the mean of the samples.
- return_numpy
bool|None(default:None) Return a
ndarrayinstead of aDataFrame. DataFrame includes gene names as columns. If eithern_samples=1orreturn_mean=True, defaults toFalse. Otherwise, it defaults toTrue.- kwargs
Additional keyword arguments that have no effect and only serve for compatibility.
- adata
- Return type:
- Returns:
If
n_samplesis provided andreturn_meanis False, this method returns a 3d tensor of shape (n_samples, n_cells, n_celltypes). Ifn_samplesis provided andreturn_meanis True, it returns a 2d tensor of shape (n_cells, n_celltypes). In this case, return type isDataFrameunlessreturn_numpyis True. Otherwise, the method expectsn_samples_overallto be provided and returns a 2d tensor of shape (n_samples_overall, n_celltypes).
- RESOLVI.get_normalized_expression(adata=None, indices=None, transform_batch=None, gene_list=None, library_size=1, size_scaling=False, n_samples=1, n_samples_overall=None, batch_size=None, return_mean=True, return_numpy=None, silent=True, **kwargs)[source]#
Returns the normalized (decoded) gene expression.
This is denoted as \(\rho_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.- transform_batch
Sequence[int|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|None(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.
- size_scaling
bool(default:False) If
True, divides the decoded expression by the size factor (e.g. cell_area). Requires that a size factor key was provided insetup_anndata().- n_samples
int(default:1) Number of posterior samples to use for estimation.
- n_samples_overall
int(default:None) Number of posterior samples to use for estimation. Overrides
n_samples.- batch_size
int|None(default:None) Minibatch 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
ndarrayinstead of aDataFrame. DataFrame includes gene names as columns. If eithern_samples=1orreturn_mean=True, defaults toFalse. Otherwise, it defaults toTrue.- silent
bool(default:True) If True, disables the progress bar. Default: False.
- **kwargs
Additional keyword arguments passed
- adata
- Return type:
- Returns:
If
n_samplesis provided andreturn_meanis False, this method returns a 3d tensor of shape (n_samples, n_cells, n_genes). Ifn_samplesis provided andreturn_meanis True, it returns a 2d tensor of shape (n_cells, n_genes). In this case, return type isDataFrameunlessreturn_numpyis True. Otherwise, the method expectsn_samples_overallto be provided and returns a 2d tensor of shape (n_samples_overall, n_genes).
- RESOLVI.get_normalized_expression_importance(adata=None, indices=None, transform_batch=None, gene_list=None, library_size=1, n_samples=30, n_samples_overall=None, batch_size=None, weights=None, return_mean=True, return_numpy=None, library_scaling=False, size_scaling=False)[source]#
Returns the normalized (decoded) importance-sampled gene expression.
This is denoted as \(\rho_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.- transform_batch
Sequence[int|str] |None(default:None) Not supported. Here for consistency with other functions.
- 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|None(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.
- n_samples
int(default:30) Number of posterior samples to use for estimation.
- n_samples_overall
int(default:None) Number of posterior samples to use for estimation. Overrides
n_samples.- batch_size
int|None(default:None) Minibatch size for data loading into model. Defaults to
scvi.settings.batch_size.- weights
str|ndarray|None(default:None) Precomputed weight for importance sampling. If
uniformno importance sampling is performed.- return_mean
bool(default:True) Whether to return the mean of the samples.
- return_numpy
bool|None(default:None) Return a
ndarrayinstead of aDataFrame. DataFrame includes gene names as columns. If eithern_samples=1orreturn_mean=True, defaults toFalse. Otherwise, it defaults toTrue.- library_scaling
bool(default:False) If
True, multiplies the decoded expression by the library size.- size_scaling
bool(default:False) If
True, divides the decoded expression by the size factor (e.g. cell_area). Requires that a size factor key was provided insetup_anndata().- silent
If True, disables the progress bar. Default: False.
- adata
- Return type:
- Returns:
If
n_samplesis provided andreturn_meanis False, this method returns a 3d tensor of shape (n_samples, n_cells, n_genes). Ifn_samplesis provided andreturn_meanis True, it returns a 2d tensor of shape (n_cells, n_genes). In this case, return type isDataFrameunlessreturn_numpyis True. Otherwise, the method expectsn_samples_overallto be provided and returns a 2d tensor of shape (n_samples_overall, n_genes) sampled by importance.
- RESOLVI.get_setup_arg(setup_arg)[source]#
Returns the string provided to setup of a specific setup_arg.
- Return type:
- RESOLVI.get_state_registry(registry_key)[source]#
Returns the state registry for the AnnDataField registered with this instance.
- Return type:
- RESOLVI.get_var_names(legacy_mudata_format=False)[source]#
Variable names of input data.
- Return type:
- classmethod RESOLVI.load(dir_path, adata=None, accelerator='auto', device='auto', prefix=None, backup_url=None, datamodule=None, allowed_classes_names_list=None)[source]#
Instantiate a model from the saved output.
- Parameters:
- dir_path
str Path to saved outputs.
- adata
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
scvisetup dictionary. If None, will check for and load anndata saved with the model. If False, will load the model without AnnData.- 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 of saved file names.
- backup_url
str|None(default:None) URL to retrieve saved outputs from if not present on disk.
- datamodule
LightningDataModule|None(default:None) EXPERIMENTALALightningDataModuleinstance to use for training in place of the defaultDataSplitter. Can only be passed in if the model was not initialized withAnnData.- allowed_classes_names_list
list[str] |None(default:None) list of allowed classes names to be loaded (besides the original class name)
- dir_path
- Returns:
Model with loaded state dictionaries.
Examples
>>> model = ModelClass.load(save_path, adata) >>> model.get_....
- classmethod RESOLVI.load_query_data(adata=None, reference_model=None, registry=None, inplace_subset_query_vars=False, accelerator='auto', device='auto', unfrozen=False, freeze_dropout=False, freeze_expression=True, freeze_decoder_first_layer=True, freeze_batchnorm_encoder=True, freeze_batchnorm_decoder=False, freeze_classifier=True, transfer_batch=True, datamodule=None)[source]#
Online update of a reference model with scArches algorithm [Lotfollahi et al., 2021].
- Parameters:
- adata
AnnData|MuData(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
registry.- reference_model
str|BaseModelClass(default:None) Either an already instantiated model of the same class or a path to saved outputs for the reference model.
- inplace_subset_query_vars
bool(default:False) Whether to subset and rearrange query vars inplace based on vars used to train the reference 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 (
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.- unfrozen
bool(default:False) Override all other freeze options for a fully unfrozen model
- freeze_dropout
bool(default:False) Whether to freeze dropout during training
- freeze_expression
bool(default:True) Freeze neurons corresponding to expression in first layer
- freeze_decoder_first_layer
bool(default:True) Freeze neurons corresponding to first layer in decoder
- freeze_batchnorm_encoder
bool(default:True) Whether to freeze batchnorm weight and bias during training for encoder
- freeze_batchnorm_decoder
bool(default:False) Whether to freeze batchnorm weight and bias during training for decoder
- freeze_classifier
bool(default:True) Whether to freeze classifier completely. Only applies to
SCANVI.- transfer_batch
bool(default:True) Allow for surgery on the batch covariate. Only applies to
SYSVI.- datamodule
LightningDataModule|None(default:None) EXPERIMENTALALightningDataModuleinstance to use for training in place of the defaultDataSplitter. Can only be passed in if the model was not initialized withAnnData.
- adata
- static RESOLVI.load_registry(dir_path, prefix=None)[source]#
Return the full registry saved with the model.
- RESOLVI.predict(adata=None, indices=None, soft=False, batch_size=500, num_samples=30)[source]#
Return cell label predictions.
- Parameters:
- adata anndata.AnnData |
None(default:None) AnnData object that has been registered via
setup_anndata().- indices
Sequence[int] |None(default:None) Subsample AnnData to these indices.
- soft
bool(default:False) If True, returns per class probabilities
- batch_size
int|None(default:500) Minibatch size for data loading into the model. Defaults to
scvi.settings.batch_size.- num_samples
int|None(default:30) Samples to draw from the posterior for cell-type prediction.
- adata anndata.AnnData |
- Return type:
- static RESOLVI.prepare_query_anndata(adata, reference_model, return_reference_var_names=False, inplace=True)[source]#
Prepare data for query integration.
This function will return a new AnnData object with padded zeros for missing features, as well as correctly sorted features.
- 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
str|BaseModelClass Either an already instantiated model of the same class or a path to saved outputs for the reference model.
- return_reference_var_names
bool(default:False) Only load and return reference var names if True.
- inplace
bool(default:True) Whether to subset and rearrange query vars inplace or return new AnnData.
- adata
- Return type:
- Returns:
Query adata ready to use in
load_query_dataunlessreturn_reference_var_namesin which case a pd.Index of reference var names is returned.
- static RESOLVI.prepare_query_mudata(mdata, reference_model, return_reference_var_names=False, inplace=True)[source]#
Prepare multimodal dataset for query integration.
This function will return a new MuData object such that the AnnData objects for individual modalities are given padded zeros for missing features, as well as correctly sorted features.
- Parameters:
- mdata
MuData MuData organized in the same way as data used to train the model. It is not necessary to run setup_mudata, as MuData is validated against the
registry.- reference_model
str|BaseModelClass Either an already instantiated model of the same class or a path to saved outputs for the reference model.
- return_reference_var_names
bool(default:False) Only load and return reference var names if True.
- inplace
bool(default:True) Whether to subset and rearrange query vars inplace or return new MuData.
- mdata
- Return type:
- Returns:
Query mudata ready to use in
load_query_dataunlessreturn_reference_var_namesin which case a dictionary of pd.Index of reference var names is returned.
- classmethod RESOLVI.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.
- RESOLVI.sample_posterior(adata=None, input_dl=None, indices=None, num_samples=1000, return_sites=None, accelerator='auto', device='auto', batch_size=None, return_observed=False, return_samples=False, summary_frequency=None, summary_fun=None, **sample_kwargs)[source]#
Summarise posterior distribution.
Generate samples from posterior distribution for each parameter and compute mean, 5th/95th quantiles, standard deviation.
- Parameters:
- adata anndata.AnnData |
None(default:None) AnnData object to use for sampling. If
None, uses the registered AnnData object.- input_dl
AnnDataLoader|None(default:None) DataLoader object to use for sampling. If
None, creates one based onadata.- indices
ndarray|None(default:None) Indices of cells to use for sampling. If
None, uses all cells.- num_samples
int(default:1000) Number of posterior samples to generate.
- return_sites
list|None(default:None) List of variables for which to generate posterior samples, defaults to all variables.
- 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.- batch_size
int|None(default:None) Minibatch size for data loading into model. Defaults to
scvi.settings.batch_size.- return_observed
bool(default:False) Return observed sites/variables? Observed count matrix can be very large so not returned by default.
- return_samples
bool(default:False) Return all generated posterior samples in addition to sample mean, 5th/95th quantile and SD?
- summary_frequency
int|None(default:None) Compute summary_fn after summary_frequency batches. Reduces memory footprint.
- summary_fun
dict[str,Callable] |None(default:None) a dict in the form {“means”: np.mean, “std”: np.std} which specifies posterior distribution summaries to compute and which names to use. See below for default returns.
- sample_kwargs
Keyword arguments for
_get_posterior_samples.
- adata anndata.AnnData |
- Returns:
- post_sample_meansdict[str, numpy.ndarray]
Mean of the posterior distribution for each variable, a dictionary of numpy arrays for each variable;
- post_sample_q05dict[str, numpy.ndarray]
5th quantile of the posterior distribution for each variable;
- post_sample_q95dict[str, numpy.ndarray]
95th quantile of the posterior distribution for each variable;
- post_sample_stdsdict[str, numpy.ndarray]
Standard deviation of the posterior distribution for each variable;
- posterior_samplesdict[str, numpy.ndarray], optional
Posterior distribution samples for each variable as numpy arrays of shape
(n_samples, ...).
Notes
Note for developers: requires overwritten
list_obs_plate_varsproperty, which lists observation/minibatch plate name and variables. Seelist_obs_plate_varsfor details of the variables it should contain. This dictionary can be returned by model class propertyself.module.model.list_obs_plate_varsto keep all model-specific variables in one place.
- RESOLVI.save(dir_path, prefix=None, overwrite=False, save_anndata=False, save_kwargs=None, legacy_mudata_format=False, datamodule=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
Falseand directory already exists atdir_path, an 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().- legacy_mudata_format
bool(default:False) If
True, saves the modelvar_namesin the legacy format if the model was trained with aMuDataobject. The legacy format is a flat array with variable names across all modalities concatenated, while the new format is a dictionary with keys corresponding to the modality names and values corresponding to the variable names for each modality.- datamodule
LightningDataModule|None(default:None) EXPERIMENTALALightningDataModuleinstance to use for training in place of the defaultDataSplitter. Can only be passed in if the model was not initialized withAnnData.- anndata_write_kwargs
Kwargs for
write()
- dir_path
- classmethod RESOLVI.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 RESOLVI.setup_anndata(adata, layer=None, batch_key=None, labels_key=None, size_factor_key=None, categorical_covariate_keys=None, prepare_data=True, prepare_data_kwargs=None, 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. Rows represent cells, columns represent features.
- layer
str|None(default:None) if not
None, uses this as the key inadata.layersfor raw count data.- 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.- size_factor_key
str|None(default:None) Key in
adata.obscorresponding to pre-computed size factors. This is the physical size of a cell (e.g. cell volume) and will be used to replace the library size if size_scaling is True.- categorical_covariate_keys
list[str] |None(default:None) keys in
adata.obsthat 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.- prepare_data
bool|None(default:True) If True, prepares AnnData for training. Computes spatial neighbors and distances.
- prepare_data_kwargs
dict(default:None) Keyword args for
RESOLVI._prepare_data- unlabeled_category
str(default:'unknown') value in
adata.obs[labels_key]that indicates unlabeled observations.
- adata
- RESOLVI.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
- RESOLVI.train(max_epochs=50, lr=0.003, lr_extra=0.01, extra_lr_parameters=('per_neighbor_diffusion_map', 'u_prior_means'), batch_size=512, weight_decay=0.0, eps=0.0001, n_steps_kl_warmup=None, n_epochs_kl_warmup=20, plan_kwargs=None, expose_params=(), **kwargs)[source]#
Trains the model using amortized variational inference.
- Parameters:
- max_epochs
int(default:50) Number of passes through the dataset.
- lr
float(default:0.003) Learning rate for optimization.
- lr_extra
float(default:0.01) Learning rate for parameters (non-amortized and custom ones)
- extra_lr_parameters
tuple(default:('per_neighbor_diffusion_map', 'u_prior_means')) List of parameters to train with
lr_extralearning rate.- batch_size
int(default:512) Minibatch size to use during training.
- weight_decay
float(default:0.0) weight decay regularization term for optimization
- eps
float(default:0.0001) Optimizer eps
- 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_warmupis set to None. IfNone, defaults tofloor(0.75 * adata.n_obs).- n_epochs_kl_warmup
int|None(default:20) Number of epochs to scale weight on KL divergences from 0 to 1. Overrides
n_steps_kl_warmupwhen both are notNone.- plan_kwargs
dict|None(default:None) Keyword args for
PyroTrainingPlan. Keyword arguments passed totrain()will overwrite values present inplan_kwargs, when appropriate.- expose_params
list(default:()) List of parameters to train if running model in Arches mode.
- **kwargs
Other keyword args for
Trainer.
- max_epochs
Notes
RESOLVI trains with Pyro SVI and maintains per-cell global parameters, so it does not support a held-out validation set.
train_sizemust be1.0andearly_stoppingis not available.
- RESOLVI.transfer_fields(adata, **kwargs)[source]#
Transfer fields from a model to an AnnData object.
- Return type:
- RESOLVI.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
- RESOLVI.view_anndata_setup(adata=None, hide_state_registries=False)[source]#
Print summary of the setup for the initial AnnData or a given AnnData object.