Introduction to scvi-tools#

In this introductory tutorial, we go through the different steps of an scvi-tools workflow.

While we focus on scVI in this tutorial, the API is consistent across all models.

Uncomment the following lines in Google Colab in order to install scvi-tools:

# !pip install --quiet scvi-colab
# from scvi_colab import install

# install()
import os
import tempfile

import scanpy as sc
import scvi
import torch
scvi.settings.seed = 0
print("Last run with scvi-tools version:", scvi.__version__)
Last run with scvi-tools version: 1.0.3

You can modify save_dir below to change where the data files for this tutorial are saved.

sc.set_figure_params(figsize=(4, 4))
save_dir = tempfile.TemporaryDirectory()

# for white background of figures (only for docs rendering)
%config InlineBackend.print_figure_kwargs={'facecolor' : "w"}
%config InlineBackend.figure_format='retina'

Loading and preparing data#

Let us first load a subsampled version of the heart cell atlas dataset described in Litviňuková et al. (2020). scvi-tools has many “built-in” datasets as well as support for loading arbitrary .csv, .loom, and .h5ad (AnnData) files. Please see our tutorial on data loading for more examples.

  • Litviňuková, M., Talavera-López, C., Maatz, H., Reichart, D., Worth, C. L., Lindberg, E. L., … & Teichmann, S. A. (2020). Cells of the adult human heart. Nature, 588(7838), 466-472.


All scvi-tools models require AnnData objects as input.

adata =
INFO     Downloading file at /tmp/tmpeeo44pku/hca_subsampled_20k.h5ad                                              
Downloading...: 100%|██████████| 65714/65714.0 [00:00<00:00, 101337.79it/s]
AnnData object with n_obs × n_vars = 18641 × 26662
    obs: 'NRP', 'age_group', 'cell_source', 'cell_type', 'donor', 'gender', 'n_counts', 'n_genes', 'percent_mito', 'percent_ribo', 'region', 'sample', 'scrublet_score', 'source', 'type', 'version', 'cell_states', 'Used'
    var: 'gene_ids-Harvard-Nuclei', 'feature_types-Harvard-Nuclei', 'gene_ids-Sanger-Nuclei', 'feature_types-Sanger-Nuclei', 'gene_ids-Sanger-Cells', 'feature_types-Sanger-Cells', 'gene_ids-Sanger-CD45', 'feature_types-Sanger-CD45', 'n_counts'
    uns: 'cell_type_colors'

Now we preprocess the data to remove, for example, genes that are very lowly expressed and other outliers. For these tasks we prefer the Scanpy preprocessing module.

sc.pp.filter_genes(adata, min_counts=3)

In scRNA-seq analysis, it’s popular to normalize the data. These values are not used by scvi-tools, but given their popularity in other tasks as well as for visualization, we store them in the anndata object separately (via the .raw attribute).


Unless otherwise specified, scvi-tools models require the raw counts (not log library size normalized). scvi-tools models will run for non-negative real-valued data, but we strongly suggest checking that these possibly non-count values are intended to represent pseudocounts (e.g. SoupX-corrected counts), and not some other normalized data, in which the variance/covariance structure of the data has changed dramatically.

adata.layers["counts"] = adata.X.copy()  # preserve counts
sc.pp.normalize_total(adata, target_sum=1e4)
adata.raw = adata  # freeze the state in `.raw`

Finally, we perform feature selection, to reduce the number of features (genes in this case) used as input to the scvi-tools model. For best practices of how/when to perform feature selection, please refer to the model-specific tutorial. For scVI, we recommend anywhere from 1,000 to 10,000 HVGs, but it will be context-dependent.


Now it’s time to run setup_anndata(), which alerts scvi-tools to the locations of various matrices inside the anndata. It’s important to run this function with the correct arguments so scvi-tools is notified that your dataset has batches, annotations, etc. For example, if batches are registered with scvi-tools, the subsequent model will correct for batch effects. See the full documentation for details.

In this dataset, there is a “cell_source” categorical covariate, and within each “cell_source”, multiple “donors”, “gender” and “age_group”. There are also two continuous covariates we’d like to correct for: “percent_mito” and “percent_ribo”. These covariates can be registered using the categorical_covariate_keys argument. If you only have one categorical covariate, you can also use the batch_key argument instead.

    categorical_covariate_keys=["cell_source", "donor"],
    continuous_covariate_keys=["percent_mito", "percent_ribo"],


If the adata is modified after running setup_anndata, please run setup_anndata again, before creating an instance of a model.

Creating and training a model#

While we highlight the scVI model here, the API is consistent across all scvi-tools models and is inspired by that of scikit-learn. For a full list of options, see the scvi documentation.

model = scvi.model.SCVI(adata)

We can see an overview of the model by printing it.

SCVI Model with the following params: 
n_hidden: 128, n_latent: 10, n_layers: 1, dropout_rate: 0.1, dispersion: gene, gene_likelihood: zinb, 
latent_distribution: normal
Training status: Not Trained
Model's adata is minified?: False


All scvi-tools models run faster when using a GPU. By default, scvi-tools will use a GPU if one is found to be available. Please see the installation page for more information about installing scvi-tools when a GPU is available.

Epoch 400/400: 100%|██████████| 400/400 [04:29<00:00,  1.48it/s, v_num=1, train_loss_step=314, train_loss_epoch=284]Epoch 400/400: 100%|██████████| 400/400 [04:29<00:00,  1.49it/s, v_num=1, train_loss_step=314, train_loss_epoch=284]

Saving and loading#

Saving consists of saving the model neural network weights, as well as parameters used to initialize the model.

model_dir = os.path.join(, "scvi_model"), overwrite=True)
model = scvi.model.SCVI.load(model_dir, adata=adata)
INFO     File /tmp/tmpeeo44pku/scvi_model/ already downloaded                                              

Obtaining model outputs#

It’s often useful to store the outputs of scvi-tools back into the original anndata, as it permits interoperability with Scanpy.


latent = model.get_latent_representation()
adata.obsm[SCVI_LATENT_KEY] = latent
(18641, 10)

The model.get...() functions default to using the AnnData that was used to initialize the model. It’s possible to also query a subset of the anndata, or even use a completely independent anndata object as long as the anndata is organized in an equivalent fashion.

adata_subset = adata[adata.obs.cell_type == "Fibroblast"]
latent_subset = model.get_latent_representation(adata_subset)
INFO     Received view of anndata, making copy.                                                                    
INFO     Input AnnData not setup with scvi-tools. attempting to transfer AnnData setup                             
(18641, 10)
denoised = model.get_normalized_expression(adata_subset, library_size=1e4)
denoised.iloc[:5, :5]
GTCAAGTCATGCCACG-1-HCAHeart7702879 1.641572 0.145801 1.785529 0.044370 6.079365
GAGTCATTCTCCGTGT-1-HCAHeart8287128 2.046075 0.062743 6.147265 0.007941 24.129694
CCTCTGATCGTGACAT-1-HCAHeart7702881 1.392460 0.600145 3.574077 0.040121 6.708357
CGCCATTCATCATCTT-1-H0035_apex 0.162660 0.174260 0.504738 0.018581 13.968432
TCGTAGAGTAGGACTG-1-H0015_septum 0.833162 0.224296 0.311983 0.051068 9.441295

Let’s store the normalized values back in the anndata.

SCVI_NORMALIZED_KEY = "scvi_normalized"

adata.layers[SCVI_NORMALIZED_KEY] = model.get_normalized_expression(library_size=10e4)

Interoperability with Scanpy#

Scanpy is a powerful python library for visualization and downstream analysis of scRNA-seq data. We show here how to feed the objects produced by scvi-tools into a scanpy workflow.

Visualization without batch correction#


We use UMAP to qualitatively assess our low-dimension embeddings of cells. We do not advise using UMAP or any similar approach quantitatively. We do recommend using the embeddings produced by scVI as a plug-in replacement of what you would get from PCA, as we show below.

First, we demonstrate the presence of nuisance variation with respect to nuclei/whole cell, age group, and donor by plotting the UMAP results of the top 30 PCA components for the raw count data.

# run PCA then generate UMAP plots
sc.pp.neighbors(adata, n_pcs=30, n_neighbors=20), min_dist=0.3)
    color=["donor", "cell_source"],
../../../_images/6a2c4ffa6bbcae31e0c88e447cf6bf217b77931ae1b32d8b672e4dee9ad8d59a.png ../../../_images/9d8f13eef2bfb85255e110d88fc4cae0a1fbe441afb61679e4571d8dd9fb6fd9.png

We see that while the cell types are generally well separated, nuisance variation plays a large part in the variation of the data.

Visualization with batch correction (scVI)#

Now, let us try using the scVI latent space to generate the same UMAP plots to see if scVI successfully accounts for batch effects in the data.

# use scVI latent space for UMAP generation
sc.pp.neighbors(adata, use_rep=SCVI_LATENT_KEY), min_dist=0.3)
    color=["donor", "cell_source"],
../../../_images/b3f2b57529e4548b2184f2d683f6366b702adbe7dfd898f039d7bdebb50f8f31.png ../../../_images/ff755e22ed09ae27cb7d659b277fa34165a4d7100ea44217c52b01f756eda57e.png

We can see that scVI was able to correct for nuisance variation due to nuclei/whole cell, age group, and donor, while maintaining separation of cell types.

Clustering on the scVI latent space#

The user will note that we imported curated labels from the original publication. Our interface with scanpy makes it easy to cluster the data with scanpy from scVI’s latent space and then reinject them into scVI (e.g., for differential expression).

# neighbors were already computed using scVI
SCVI_CLUSTERS_KEY = "leiden_scVI", key_added=SCVI_CLUSTERS_KEY, resolution=0.5)

Differential expression#

We can also use many scvi-tools models for differential expression. For further details on the methods underlying these functions as well as additional options, please see the API docs.

AACTCCCCACGAGAGT-1-HCAHeart7844001                      Myeloid
ATAACGCAGAGCTGGT-1-HCAHeart7829979    Ventricular_Cardiomyocyte
GTCAAGTCATGCCACG-1-HCAHeart7702879                   Fibroblast
GGTGATTCAAATGAGT-1-HCAHeart8102858                  Endothelial
AGAGAATTCTTAGCAG-1-HCAHeart8102863                  Endothelial
Name: cell_type, dtype: category
Categories (11, object): ['Adipocytes', 'Atrial_Cardiomyocyte', 'Endothelial', 'Fibroblast', ..., 'Neuronal', 'Pericytes', 'Smooth_muscle_cells', 'Ventricular_Cardiomyocyte']

For example, a 1-vs-1 DE test is as simple as:

de_df = model.differential_expression(
    groupby="cell_type", group1="Endothelial", group2="Fibroblast"
DE...: 100%|██████████| 1/1 [00:00<00:00,  3.39it/s]
proba_de proba_not_de bayes_factor scale1 scale2 pseudocounts delta lfc_mean lfc_median lfc_std ... raw_mean1 raw_mean2 non_zeros_proportion1 non_zeros_proportion2 raw_normalized_mean1 raw_normalized_mean2 is_de_fdr_0.05 comparison group1 group2
EGFL7 0.9994 0.0006 7.417964 0.007995 0.000380 0.0 0.25 4.723679 4.743503 1.524890 ... 2.376779 0.036795 0.741543 0.025756 89.507553 1.169474 True Endothelial vs Fibroblast Endothelial Fibroblast
ABCA10 0.9986 0.0014 6.569875 0.000082 0.006681 0.0 0.25 -7.768283 -8.068472 2.589131 ... 0.014359 1.282508 0.007788 0.499591 0.501825 69.613876 True Endothelial vs Fibroblast Endothelial Fibroblast
SLC9A3R2 0.9986 0.0014 6.569875 0.011579 0.000194 0.0 0.25 6.021041 6.096311 1.783054 ... 4.451492 0.045380 0.712339 0.034342 111.582703 1.657324 True Endothelial vs Fibroblast Endothelial Fibroblast
COL6A3 0.9984 0.0016 6.436144 0.000190 0.004790 0.0 0.25 -5.150349 -5.200835 1.633370 ... 0.026284 1.228131 0.021903 0.498365 1.195808 54.193195 True Endothelial vs Fibroblast Endothelial Fibroblast
ABCA9-AS1 0.9982 0.0018 6.318161 0.000083 0.005979 0.0 0.25 -12.389173 -14.428207 6.051195 ... 0.009735 1.192971 0.005111 0.405151 0.376233 54.827084 True Endothelial vs Fibroblast Endothelial Fibroblast

5 rows × 22 columns

We can also do a 1-vs-all DE test, which compares each cell type with the rest of the dataset:

de_df = model.differential_expression(
DE...: 100%|██████████| 11/11 [00:05<00:00,  2.08it/s]
proba_de proba_not_de bayes_factor scale1 scale2 pseudocounts delta lfc_mean lfc_median lfc_std ... raw_mean1 raw_mean2 non_zeros_proportion1 non_zeros_proportion2 raw_normalized_mean1 raw_normalized_mean2 is_de_fdr_0.05 comparison group1 group2
GPAM 0.9990 0.0010 6.906745 0.024736 0.000200 0.0 0.25 7.417807 7.414870 2.504309 ... 17.372416 0.035791 0.896552 0.031520 280.340485 1.565905 True Adipocytes vs Rest Adipocytes Rest
PNPLA3 0.9988 0.0012 6.724225 0.002720 0.000030 0.0 0.25 7.679917 7.476880 3.092558 ... 2.020689 0.002811 0.537931 0.002757 28.458160 0.127947 True Adipocytes vs Rest Adipocytes Rest
FASN 0.9988 0.0012 6.724225 0.011835 0.000140 0.0 0.25 6.669803 6.777160 2.120691 ... 7.062068 0.025086 0.841379 0.022167 129.074371 1.084626 True Adipocytes vs Rest Adipocytes Rest
DGAT2 0.9986 0.0014 6.569875 0.004218 0.000038 0.0 0.25 7.355606 7.403279 2.460390 ... 2.682757 0.005028 0.593103 0.004866 43.613537 0.194096 True Adipocytes vs Rest Adipocytes Rest
PLIN1 0.9986 0.0014 6.569875 0.004477 0.000042 0.0 0.25 8.163296 7.893727 3.277964 ... 2.799999 0.004379 0.806897 0.004325 52.921761 0.196486 True Adipocytes vs Rest Adipocytes Rest

5 rows × 22 columns

We now extract top markers for each cluster using the DE results.

markers = {}
cats =
for i, c in enumerate(cats):
    cid = f"{c} vs Rest"
    cell_type_df = de_df.loc[de_df.comparison == cid]

    cell_type_df = cell_type_df[cell_type_df.lfc_mean > 0]

    cell_type_df = cell_type_df[cell_type_df["bayes_factor"] > 3]
    cell_type_df = cell_type_df[cell_type_df["non_zeros_proportion1"] > 0.1]

    markers[c] = cell_type_df.index.tolist()[:3], groupby="cell_type", use_rep="X_scVI")

We can also visualize the scVI normalized gene expression values with the layer option.
    figsize=(8, 12),

Logging information#

Verbosity varies in the following way:

  • logger.setLevel(logging.WARNING) will show a progress bar.

  • logger.setLevel(logging.INFO) will show global logs including the number of jobs done.

  • logger.setLevel(logging.DEBUG) will show detailed logs for each training (e.g the parameters tested).

This function’s behaviour can be customized, please refer to its documentation for information about the different parameters available.

In general, you can use scvi.settings.verbosity to set the verbosity of the scvi package. Note that verbosity corresponds to the logging levels of the standard python logging module. By default, that verbosity level is set to INFO (=20). As a reminder the logging levels are:


Numeric value













Clean up#

Uncomment the following line to remove all data files created in this tutorial:

# save_dir.cleanup()