Note
This page was generated from data_loading.ipynb. Interactive online version: .
Here we walk through the necessary steps to get your data into ready for scvi-tools.
[2]:
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]
[3]:
import scvi import scanpy as sc
scvi-tools supports the AnnData data format, which also underlies Scanpy. AnnData is quite similar to other popular single cell objects like that of Seurat and SingleCellExperiment. In particular, it allows cell-level and feature-level metadata to coexist in the same data structure as the molecular counts.
It’s also now possible to automatically convert these R-based objects to AnnData within a Jupyter notebook. See the following tutorial for more information.
scvi-tools has a number of convenience methods for loading data from .csv, .loom, and .h5ad formats. To load ouputs from Cell Ranger, please use Scanpy’s reading functionality.
.csv
.loom
.h5ad
Let us now download an AnnData object (.h5ad format) and load it using scvi-tools.
!wget 'http://falexwolf.de/data/pbmc3k_raw.h5ad'
--2021-02-23 18:30:03-- http://falexwolf.de/data/pbmc3k_raw.h5ad Resolving falexwolf.de (falexwolf.de)... 85.13.135.70 Connecting to falexwolf.de (falexwolf.de)|85.13.135.70|:80... connected. HTTP request sent, awaiting response... 200 OK Length: 5855727 (5.6M) Saving to: 'pbmc3k_raw.h5ad' pbmc3k_raw.h5ad 100%[===================>] 5.58M 2.85MB/s in 2.0s 2021-02-23 18:30:05 (2.85 MB/s) - 'pbmc3k_raw.h5ad' saved [5855727/5855727]
[4]:
pbmc3k = scvi.data.read_h5ad("pbmc3k_raw.h5ad")
[5]:
pbmc3k
AnnData object with n_obs × n_vars = 2700 × 32738 var: 'gene_ids'
This is a fairly simple object, it just contains the count data and the ENSEMBL ids for the genes.
[6]:
pbmc3k.var.head()
As another example, let’s download a dataset from 10x Genomics. This data was obtained from a CITE-seq experiment, so it also contains protein count data.
[7]:
!wget https://cf.10xgenomics.com/samples/cell-exp/3.0.2/5k_pbmc_protein_v3/5k_pbmc_protein_v3_filtered_feature_bc_matrix.h5
--2021-02-23 18:30:07-- https://cf.10xgenomics.com/samples/cell-exp/3.0.2/5k_pbmc_protein_v3/5k_pbmc_protein_v3_filtered_feature_bc_matrix.h5 Resolving cf.10xgenomics.com (cf.10xgenomics.com)... 104.18.0.173, 104.18.1.173, 2606:4700::6812:ad, ... Connecting to cf.10xgenomics.com (cf.10xgenomics.com)|104.18.0.173|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 17129253 (16M) [binary/octet-stream] Saving to: '5k_pbmc_protein_v3_filtered_feature_bc_matrix.h5' 5k_pbmc_protein_v3_ 100%[===================>] 16.33M 8.97MB/s in 1.8s 2021-02-23 18:30:09 (8.97 MB/s) - '5k_pbmc_protein_v3_filtered_feature_bc_matrix.h5' saved [17129253/17129253]
[8]:
pbmc5k = sc.read_10x_h5( "5k_pbmc_protein_v3_filtered_feature_bc_matrix.h5", gex_only=False )
Variable names are not unique. To make them unique, call `.var_names_make_unique`.
It’s often helpful to give the gene names unique names.
[9]:
pbmc5k.var_names_make_unique()
We can see that adata.X contains the concatenated gene and protein expression data.
adata.X
[10]:
pbmc5k.var.feature_types.astype("category").cat.categories
Index(['Antibody Capture', 'Gene Expression'], dtype='object')
We can use scvi-tools to organize this object, which places the protein expression in adata.obms["protein_expression].
adata.obms["protein_expression]
[11]:
scvi.data.organize_cite_seq_10x(pbmc5k)
[12]:
pbmc5k
AnnData object with n_obs × n_vars = 5247 × 33538 var: 'gene_ids', 'feature_types', 'genome' obsm: 'protein_expression'
[13]:
adata = pbmc5k.concatenate(pbmc3k)
Notice that the resulting AnnData has a batch key in .obs.
.obs
[14]:
adata.obs.head()
It is common to remove outliers, and even perform feature selection before model fitting. We prefer the Scanpy preprocessing module at this stage.
[15]:
sc.pp.filter_genes(adata, min_counts=3) sc.pp.filter_cells(adata, min_counts=3)
/home/galen/.pyenv/versions/3.8.3/envs/scvi-dev/lib/python3.8/site-packages/pandas/core/arrays/categorical.py:2487: FutureWarning: The `inplace` parameter in pandas.Categorical.remove_unused_categories is deprecated and will be removed in a future version. res = method(*args, **kwargs)
As it is popular to use normalize the data for many methods, we can use Scanpy for this; however, it’s important to keep the count information intact for scvi-tools models.
[16]:
adata.layers["counts"] = adata.X.copy()
Now we can proceed with common normalization methods.
[17]:
sc.pp.normalize_total(adata, target_sum=1e4) sc.pp.log1p(adata)
We can store the normalized values in .raw to keep them safe in the event the anndata gets subsetted feature-wise.
.raw
[18]:
adata.raw = adata
Now that we have an AnnData object, we need to alert scvi-tools of all the interesting data in our object. For example, now that we have batches in our AnnData, we can alert the models that we’d like to perform batch correction. Also, because we have the count data in a layer, we can use the layer argument.
layer
[19]:
scvi.data.setup_anndata(adata, layer="counts", batch_key="batch")
INFO Using batches from adata.obs["batch"] INFO No label_key inputted, assuming all cells have same label INFO Using data from adata.layers["counts"] INFO Computing library size prior per batch INFO Successfully registered anndata object containing 7947 cells, 14309 vars, 2 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.
/home/galen/.pyenv/versions/3.8.3/envs/scvi-dev/lib/python3.8/site-packages/pandas/core/arrays/categorical.py:2487: FutureWarning: The `inplace` parameter in pandas.Categorical.remove_unused_categories is deprecated and will be removed in a future version. res = method(*args, **kwargs) /home/galen/.pyenv/versions/3.8.3/envs/scvi-dev/lib/python3.8/site-packages/pandas/core/arrays/categorical.py:2487: FutureWarning: The `inplace` parameter in pandas.Categorical.remove_unused_categories is deprecated and will be removed in a future version. res = method(*args, **kwargs)
Notice the info messages notify us that batches were detected in the data. Just to demonstrate what happens if we don’t include this option:
[20]:
scvi.data.setup_anndata(adata, layer="counts")
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 Computing library size prior per batch INFO Successfully registered anndata object containing 7947 cells, 14309 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 integration-based tasks can no longer be performed in subsequent models because there is no knowledge of such information.
As PBMC5k is a CITE-seq dataset, we can use scvi-tools to register the protein expression. Note that totalVI is the only current model that uses the protein expression. The usage of registered items is model specific. As another example, registering the labels in the AnnData object will not affect totalVI or scVI, but is necessary to run scANVI.
We have not preprocessed the pbmc5k object, which we do recommend. We show how to run setup_anndata in this case for illustrative purposes.
setup_anndata
[21]:
scvi.data.setup_anndata(pbmc5k, protein_expression_obsm_key="protein_expression")
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 Computing library size prior per batch INFO Using protein expression from adata.obsm['protein_expression'] INFO Using protein names from columns of adata.obsm['protein_expression'] INFO Successfully registered anndata object containing 5247 cells, 33538 vars, 1 batches, 1 labels, and 32 proteins. Also registered 0 extra categorical covariates and 0 extra continuous covariates. INFO Please do not further modify adata until model is trained.
Warning
After setup_anndata has been run, the adata object should not be modified. In other words, the very next step in the workflow is to initialize and train the model of interest (e.g., scVI, totalVI). If you do modify the adata, it’s ok, just run setup_anndata again – and then reinitialize the model.
[22]:
scvi.data.view_anndata_setup(pbmc5k)
Anndata setup with scvi-tools version 0.0.0.
Data Summary ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┓ ┃ Data ┃ Count ┃ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━┩ │ Cells │ 5247 │ │ Vars │ 33538 │ │ Labels │ 1 │ │ Batches │ 1 │ │ Proteins │ 32 │ │ Extra Categorical Covariates │ 0 │ │ Extra Continuous Covariates │ 0 │ └──────────────────────────────┴───────┘
SCVI Data Registry ┏━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ Data ┃ scvi-tools Location ┃ ┡━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩ │ X │ adata.X │ │ batch_indices │ adata.obs['_scvi_batch'] │ │ local_l_mean │ adata.obs['_scvi_local_l_mean'] │ │ local_l_var │ adata.obs['_scvi_local_l_var'] │ │ labels │ adata.obs['_scvi_labels'] │ │ protein_expression │ adata.obsm['protein_expression'] │ └────────────────────┴──────────────────────────────────┘
Label Categories ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┓ ┃ Source Location ┃ Categories ┃ scvi-tools Encoding ┃ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━┩ │ adata.obs['_scvi_labels'] │ 0 │ 0 │ └───────────────────────────┴────────────┴─────────────────────┘
Batch Categories ┏━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┓ ┃ Source Location ┃ Categories ┃ scvi-tools Encoding ┃ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━┩ │ adata.obs['_scvi_batch'] │ 0 │ 0 │ └──────────────────────────┴────────────┴─────────────────────┘
In this section we will transfer the setup from one AnnData object to another AnnData object.
adata1 = scvi.data.synthetic_iid() print(adata1)
INFO Using batches from adata.obs["batch"] INFO Using labels from adata.obs["labels"] INFO Using data from adata.X INFO Computing library size prior per batch INFO Using protein expression from adata.obsm['protein_expression'] INFO Using protein names from adata.uns['protein_names'] INFO Successfully registered anndata object containing 400 cells, 100 vars, 2 batches, 3 labels, and 100 proteins. Also registered 0 extra categorical covariates and 0 extra continuous covariates. INFO Please do not further modify adata until model is trained. AnnData object with n_obs × n_vars = 400 × 100 obs: 'batch', 'labels', '_scvi_batch', '_scvi_labels', '_scvi_local_l_mean', '_scvi_local_l_var' uns: 'protein_names', '_scvi' obsm: 'protein_expression'
adata2 = scvi.data.synthetic_iid(run_setup_anndata=False) print(adata2)
AnnData object with n_obs × n_vars = 400 × 100 obs: 'batch', 'labels' uns: 'protein_names' obsm: 'protein_expression'
transfer_anndata_setup() will use the fields used to setup adata1 to register the data in adata2.
transfer_anndata_setup()
scvi.data.transfer_anndata_setup(adata1,adata2)
INFO Using data from adata.X INFO Computing library size prior per batch INFO Registered keys:['X', 'batch_indices', 'local_l_mean', 'local_l_var', 'labels', 'protein_expression'] INFO Successfully registered anndata object containing 400 cells, 100 vars, 2 batches, 3 labels, and 100 proteins. Also registered 0 extra categorical covariates and 0 extra continuous covariates.
[ ]: