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 viasetup_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
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. |
|
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#
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. IfNone, defaults ton_genes // 50.- 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. IfFalseand 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().
- 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 with adata.If adata is None, deregisters all
AnnDataManagerinstances 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|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] |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 inpandas.DataFrame.query()If idx1 is not None, this option overrides group1 and group2.idx2 (
Sequence[int] |Sequence[bool] |None(default:None)) – Custom identifier for group2 that has the same properties as idx1. By default, includes all cells not specified in idx1.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_key registered insetup_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.weights (
Optional[Literal['uniform','importance']] (default:'uniform')) – Precomputed weight for importance sampling. If uniform no importance sampling is performed.filter_outlier_cells (
bool(default:False)) – Whether to filter outlier cells with :meth:`~scvi.model.base.DifferentialComputation.filter_outlier_cellsn_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 insetup_anndata()with size_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()
- Return type:
DataFrame- 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|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.neighbor_key (
str|None(default:None)) – Obsm key containing the spatial neighbors of each cell.idx1 (
Sequence[int] |Sequence[bool] |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 inpandas.DataFrame.query()If idx1 is not None, this option overrides group1 and group2.idx2 (
Sequence[int] |Sequence[bool] |None(default:None)) – Custom identifier for group2 that has the same properties as idx1. By default, includes all cells not specified in idx1.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 withfilter_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()
- Return type:
DataFrame- 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, ignores give_mean and mc_samples.
- 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 None performs no spatial weighting. Needs to be of shape n_cells by n_neighbors.return_mean (
bool(default:True)) – Whether to return the mean of the samples.return_numpy (
bool|None(default:None)) – Return andarrayinstead of aDataFrame. DataFrame includes gene names as columns. If either n_samples=1 or return_mean=True, defaults to False. Otherwise, it defaults to True.kwargs – Additional keyword arguments that have no effect and only serve for compatibility.
- Return type:
- Returns:
If n_samples is provided and return_mean is False, this method returns a 3d tensor of shape (n_samples, n_cells, n_celltypes). If n_samples is provided and return_mean is True, it returns a 2d tensor of shape (n_cells, n_celltypes). In this case, return type is
DataFrameunless return_numpy is True. Otherwise, the method expects n_samples_overall to 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 andarrayinstead of aDataFrame. DataFrame includes gene names as columns. If either n_samples=1 or return_mean=True, defaults to False. Otherwise, it defaults to True.%(de_silent)s
**kwargs – Additional keyword arguments passed
- Return type:
- Returns:
If n_samples is provided and return_mean is False, this method returns a 3d tensor of shape (n_samples, n_cells, n_genes). If n_samples is provided and return_mean is True, it returns a 2d tensor of shape (n_cells, n_genes). In this case, return type is
DataFrameunless return_numpy is True. Otherwise, the method expects n_samples_overall to 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 uniform no importance sampling is performed.return_mean (
bool(default:True)) – Whether to return the mean of the samples.return_numpy (
bool|None(default:None)) – Return andarrayinstead of aDataFrame. DataFrame includes gene names as columns. If either n_samples=1 or return_mean=True, defaults to False. Otherwise, it defaults to True.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().%(de_silent)s
- Return type:
- Returns:
If n_samples is provided and return_mean is False, this method returns a 3d tensor of shape (n_samples, n_cells, n_genes). If n_samples is provided and return_mean is True, it returns a 2d tensor of shape (n_cells, n_genes). In this case, return type is
DataFrameunless return_numpy is True. Otherwise, the method expects n_samples_overall to 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 scvi setup 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 (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.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)
- 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 theregistry.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 (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.unfrozen (
bool(default:False)) – Override all other freeze options for a fully unfrozen modelfreeze_dropout (
bool(default:False)) – Whether to freeze dropout during trainingfreeze_expression (
bool(default:True)) – Freeze neurons corresponding to expression in first layerfreeze_decoder_first_layer (
bool(default:True)) – Freeze neurons corresponding to first layer in decoderfreeze_batchnorm_encoder (
bool(default:True)) – Whether to freeze batchnorm weight and bias during training for encoderfreeze_batchnorm_decoder (
bool(default:False)) – Whether to freeze batchnorm weight and bias during training for decoderfreeze_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.
- 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|None(default:None)) – AnnData object that has been registered viasetup_anndata().indices (
Sequence[int] |None(default:None)) – Subsample AnnData to these indices.soft (
bool(default:False)) – If True, returns per class probabilitiesbatch_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.
- Return type:
ndarray|DataFrame
- 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 theregistry.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.
- Return type:
- Returns:
Query adata ready to use in load_query_data unless return_reference_var_names in 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 theregistry.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.
- Return type:
- Returns:
Query mudata ready to use in load_query_data unless return_reference_var_names in 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 | 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 on adata.indices (np.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 (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.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().
- Returns:
- post_sample_means: Dict[str,
np.ndarray] Mean of the posterior distribution for each variable, a dictionary of numpy arrays for each variable;
- post_sample_q05: Dict[str,
np.ndarray] 5th quantile of the posterior distribution for each variable;
- post_sample_q05: Dict[str,
np.ndarray] 95th quantile of the posterior distribution for each variable;
- post_sample_q05: Dict[str,
np.ndarray] Standard deviation of the posterior distribution for each variable;
- posterior_samples: Optional[Dict[str,
np.ndarray]] Posterior distribution samples for each variable as numpy arrays of shape (n_samples, …) (Optional).
- post_sample_means: Dict[str,
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 property self.module.model.list_obs_plate_vars to 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 False and directory already exists at dir_path, an error will be raised.save_anndata (
bool(default:False)) – If True, also saves the anndatasave_kwargs (
dict|None(default:None)) – Keyword arguments passed intosave().legacy_mudata_format (
bool(default:False)) – IfTrue, 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()
- 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 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 inadata.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.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.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 forscvi.external.RESOLVI._prepare_data()unlabeled_category (
str(default:'unknown')) – value in adata.obs[labels_key] that indicates unlabeled observations.
- RESOLVI.to_device(device)[source]#
Move the model to the device.
- Parameters:
device (
str|int|device) – Device to move model to. Options: ‘cpu’ for CPU, integer GPU index (e.g., 0), ‘cuda:X’ where X is the GPU index (e.g. ‘cuda:0’), or a torch.device object (including XLA devices for TPU). 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
- 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_extra learning rate.batch_size (
int(default:512)) – Minibatch size to use during training.weight_decay (
float(default:0.0)) – weight decay regularization term for optimizationeps (
float(default:0.0001)) – Optimizer epsn_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_warmup is set to None. If None, defaults to floor(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_warmup when both are not None.plan_kwargs (
dict|None(default:None)) – Keyword args forPyroTrainingPlan. Keyword arguments passed to train() will overwrite values present in plan_kwargs, when appropriate.expose_params (
list(default:())) – List of parameters to train if running model in Arches mode.**kwargs – Other keyword args for
Trainer.
- 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.
- 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.
- Parameters:
adata (
AnnData|MuData|None(default:None)) – AnnData object setup withsetup_anndataortransfer_fields().hide_state_registries (
bool(default:False)) – If True, prints a shortened summary without details of each state registry.
- Return type: