Note

This page was generated from api_overview.ipynb. Interactive online version: Colab badge.

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.

[1]:
import sys

#if branch is stable, will install via pypi, else will install from source
branch = "stable"
IN_COLAB = "google.colab" in sys.modules

if IN_COLAB and branch == "stable":
    !pip install --quiet scvi-tools[tutorials]
elif IN_COLAB and branch != "stable":
    !pip install --quiet --upgrade jsonschema
    !pip install --quiet git+https://github.com/yoseflab/scvi-tools@$branch#egg=scvi-tools[tutorials]
[2]:
import scvi
import scanpy as sc

sc.set_figure_params(figsize=(4, 4))
Global seed set to 0

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.

Important

All scvi-tools models require AnnData objects as input.

[3]:
adata = scvi.data.heart_cell_atlas_subsampled()
INFO     Downloading file at data/hca_subsampled_20k.h5ad
Downloading...: 100%|███████████████████████████████████████████████████████████████████████████████████████████████| 65714/65714.0 [00:02<00:00, 31217.12it/s]
INFO     No batch_key inputted, assuming all cells are same batch
INFO     No label_key inputted, assuming all cells have same label
INFO     Using data from adata.X
INFO     Successfully registered anndata object containing 18641 cells, 26662 vars, 1
         batches, 1 labels, and 0 proteins. Also registered 0 extra categorical covariates
         and 0 extra continuous covariates.
INFO     Please do not further modify adata until model is trained.

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.

[4]:
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).

Important

Unless otherwise specific, scvi-tools models require the raw counts (not log library size normalized).

[5]:
adata.layers["counts"] = adata.X.copy() # preserve counts
sc.pp.normalize_total(adata, target_sum=1e4)
sc.pp.log1p(adata)
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.

[6]:
sc.pp.highly_variable_genes(
    adata,
    n_top_genes=1200,
    subset=True,
    layer="counts",
    flavor="seurat_v3",
    batch_key="cell_source"
)

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.

[8]:
scvi.model.SCVI.setup_anndata(
    adata,
    layer="counts",
    categorical_covariate_keys=["cell_source", "donor"],
    continuous_covariate_keys=["percent_mito", "percent_ribo"]
)
INFO     No batch_key inputted, assuming all cells are same batch
INFO     No label_key inputted, assuming all cells have same label
INFO     Using data from adata.layers["counts"]
INFO     Successfully registered anndata object containing 18641 cells, 1200 vars, 1 batches,
         1 labels, and 0 proteins. Also registered 2 extra categorical covariates and 2 extra
         continuous covariates.
INFO     Please do not further modify adata until model is trained.

Warning

If the adata is modified after running setup_anndata, please run setup_anndata again.

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.

[9]:
model = scvi.model.SCVI(adata)

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

[10]:
model
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

To print summary of associated AnnData, use: scvi.data.view_anndata_setup(model.adata)
[10]:

[11]:
model.train()
GPU available: True, used: True
TPU available: False, using: 0 TPU cores
LOCAL_RANK: 0 - CUDA_VISIBLE_DEVICES: [0,1,2]
Epoch 400/400: 100%|██████████████████████████████████████████████████████████████████████████████████████| 400/400 [09:24<00:00,  1.41s/it, loss=285, v_num=1]

Saving and loading

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

[15]:
# model.save("my_model/")
[16]:
# model = scvi.model.SCVI.load("my_model/", adata, use_gpu=True)

Obtaining model outputs

[17]:
latent = model.get_latent_representation()

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

[18]:
adata.obsm["X_scVI"] = latent

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.

[19]:
adata_subset = adata[adata.obs.cell_type == "Fibroblast"]
latent_subset = model.get_latent_representation(adata_subset)
INFO     Received view of anndata, making copy.
[20]:
denoised = model.get_normalized_expression(adata_subset, library_size=1e4)
denoised.iloc[:5, :5]
INFO     Received view of anndata, making copy.
[20]:
ISG15 TNFRSF18 VWA1 HES5 SPSB1
GTCAAGTCATGCCACG-1-HCAHeart7702879 0.391715 0.108618 1.482708 0.044681 4.104694
GAGTCATTCTCCGTGT-1-HCAHeart8287128 1.397898 0.196568 1.964663 0.019584 13.305335
CCTCTGATCGTGACAT-1-HCAHeart7702881 6.336600 0.497676 1.552831 0.097293 2.621925
CGCCATTCATCATCTT-1-H0035_apex 0.324017 0.045554 0.594264 0.083454 6.016561
TCGTAGAGTAGGACTG-1-H0015_septum 0.344446 0.028772 0.390438 0.795581 10.635545

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

[21]:
adata.layers["scvi_normalized"] = 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.

UMAP without batch correction

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.

[22]:
# run PCA then generate UMAP plots
sc.tl.pca(adata, svd_solver='arpack')
sc.pp.neighbors(adata, n_pcs=30, n_neighbors=20)
sc.tl.umap(adata, min_dist=0.3)
[23]:
sc.pl.umap(
    adata,
    color=["cell_type"],
    frameon=False,
)
sc.pl.umap(
    adata,
    color=["donor", "cell_source"],
    ncols=2,
    frameon=False,
)
../../_images/tutorials_notebooks_api_overview_38_0.png
../../_images/tutorials_notebooks_api_overview_38_1.png

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

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

[24]:
# use scVI latent space for UMAP generation
sc.pp.neighbors(adata, use_rep="X_scVI")
sc.tl.umap(adata, min_dist=0.3)
[25]:
sc.pl.umap(
    adata,
    color=["cell_type"],
    frameon=False,
)
sc.pl.umap(
    adata,
    color=["donor", "cell_source"],
    ncols=2,
    frameon=False,
)
../../_images/tutorials_notebooks_api_overview_43_0.png
../../_images/tutorials_notebooks_api_overview_43_1.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).

[26]:
# neighbors were already computed using scVI
sc.tl.leiden(adata, key_added="leiden_scVI", resolution=0.5)
[27]:
sc.pl.umap(
    adata,
    color=["leiden_scVI"],
    frameon=False,
)
../../_images/tutorials_notebooks_api_overview_48_0.png

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.

[28]:
adata.obs.cell_type.head()
[28]:
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:

[29]:
de_df = model.differential_expression(
    groupby="cell_type",
    group1="Endothelial",
    group2="Fibroblast"
)
de_df.head()
DE...: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:02<00:00,  2.73s/it]
[29]:
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.9992 0.0008 7.130086 0.008717 0.000372 0.0 0.25 4.893379 4.850852 1.549909 ... 2.376779 0.036795 0.741543 0.025756 89.507553 1.169474 True Endothelial vs Fibroblast Endothelial Fibroblast
SOX17 0.9990 0.0010 6.906745 0.001581 0.000031 0.0 0.25 6.293764 6.294940 2.144020 ... 0.784371 0.006541 0.307617 0.004497 17.128170 0.185868 True Endothelial vs Fibroblast Endothelial Fibroblast
SLC9A3R2 0.9988 0.0012 6.724225 0.010693 0.000173 0.0 0.25 5.962310 6.061585 1.685714 ... 4.451492 0.045380 0.712339 0.034342 111.582703 1.657324 True Endothelial vs Fibroblast Endothelial Fibroblast
ABCA10 0.9980 0.0020 6.212601 0.000085 0.006314 0.0 0.25 -7.989011 -8.471928 2.809034 ... 0.014359 1.282508 0.007788 0.499591 0.501825 69.613876 True Endothelial vs Fibroblast Endothelial Fibroblast
STC1 0.9978 0.0022 6.117091 0.001757 0.000037 0.0 0.25 5.997184 6.017246 2.182741 ... 0.785346 0.004088 0.198832 0.003271 17.157606 0.194772 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:

[30]:
de_df = model.differential_expression(
    groupby="cell_type",
)
de_df.head()
DE...: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 11/11 [00:30<00:00,  2.73s/it]
[30]:
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
CIDEC 0.9984 0.0016 6.436144 0.002358 0.000030 0.0 0.25 7.176971 7.151240 2.708683 ... 1.137931 0.001406 0.510345 0.001406 21.809771 0.057564 True Adipocytes vs Rest Adipocytes Rest
PLIN1 0.9980 0.0020 6.212601 0.004842 0.000049 0.0 0.25 7.895473 7.601839 2.946511 ... 2.799999 0.004379 0.806897 0.004325 52.921761 0.196486 True Adipocytes vs Rest Adipocytes Rest
PNPLA3 0.9976 0.0024 6.029880 0.003653 0.000035 0.0 0.25 7.668899 7.620012 3.098989 ... 2.020689 0.002811 0.537931 0.002757 28.458160 0.127947 True Adipocytes vs Rest Adipocytes Rest
LBP 0.9976 0.0024 6.029880 0.001643 0.000021 0.0 0.25 7.902142 7.526886 3.887111 ... 0.620690 0.003406 0.110345 0.002271 8.261559 0.083845 True Adipocytes vs Rest Adipocytes Rest
GPAM 0.9976 0.0024 6.029880 0.023799 0.000205 0.0 0.25 7.370276 7.378508 2.523409 ... 17.372416 0.035791 0.896552 0.031520 280.340485 1.565905 True Adipocytes vs Rest Adipocytes Rest

5 rows × 22 columns

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

[31]:
markers = {}
cats = adata.obs.cell_type.cat.categories
for i, c in enumerate(cats):
    cid = "{} vs Rest".format(c)
    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]
[32]:
sc.tl.dendrogram(adata, groupby="cell_type", use_rep="X_scVI")
[33]:
sc.pl.dotplot(
    adata,
    markers,
    groupby='cell_type',
    dendrogram=True,
    color_map="Blues",
    swap_axes=True,
    use_raw=True,
    standard_scale="var",
)
../../_images/tutorials_notebooks_api_overview_58_0.png

We can also visualize the scVI normalized gene expression values with the layer option.

[34]:
sc.pl.heatmap(
    adata,
    markers,
    groupby='cell_type',
    layer="scvi_normalized",
    standard_scale="var",
    dendrogram=True,
    figsize=(8, 12)
)
../../_images/tutorials_notebooks_api_overview_60_0.png

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:

Level

Numeric value

CRITICAL

50

ERROR

40

WARNING

30

INFO

20

DEBUG

10

NOTSET

0