Note

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

Linearly decoded VAE

This notebook shows how to use the ‘linearly decoded VAE’ model which explicitly links latent variables of cells to genes.

The scVI package learns low-dimensional latent representations of cells which get mapped to parameters of probability distributions which can generate counts consistent to what is observed from data. In the standard VAE model of scVI these parameters for each gene and cell arise from applying neural networks to the latent variables. Neural networks are flexible and can represent non-linearities in the data. This comes at a price, there is no direct link between a latent variable dimension and any potential set of genes which would covary across it.

The LDVAE model replaces the neural networks with linear functions. Now a higher value along a latent dimension will directly correspond to higher expression of the genes with high weights assigned to that dimension.

This leads to a generative model comparable to probabilistic PCA or factor analysis, but generates counts rather than real numbers. Using the framework of scVI also allows variational inference which scales to very large datasets and can make use of GPUs for additional speed.

This notebook demonstrates how to fit an LDVAE model to scRNA-seq data, plot the latent variables, and interpret which genes are linked to latent variables.

As an example, we use the PBMC 10K from 10x Genomics.

[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 scanpy as sc
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

import scvi

%matplotlib inline

Initialization

Load data and select the top 1000 variable genes with seurat_v3 method

[3]:
save_path = 'data'
adata = sc.read(os.path.join(save_path, "pbmc_10k_protein_v3.h5ad"), backup_url="https://github.com/YosefLab/scVI-data/raw/master/pbmc_10k_protein_v3.h5ad?raw=true")

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

sc.pp.highly_variable_genes(adata, flavor='seurat_v3', layer='counts', n_top_genes=1000, subset=True)
/home/adam/.pyenv/versions/scvi-tools-dev/lib/python3.8/site-packages/scanpy/preprocessing/_highly_variable_genes.py:144: FutureWarning: Slicing a positional slice with .loc is not supported, and will raise TypeError in a future version.  Use .loc with labels or .iloc with positions instead.
  df.loc[: int(n_top_genes), 'highly_variable'] = True

Create and fit LDVAE model

First subsample 1,000 genes from the original data.

Then we initialize an LinearSCVI model. Here we set the latent space to have 10 dimensions.

[4]:
# setup the anndata for scvi-tools
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 6855 cells, 1000 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.
[5]:
# initialize LinearSCVI model
model = scvi.model.LinearSCVI(adata, n_latent=10)
[6]:
# train for 250 epochs, compute metrics every 10 epochs
model.train(max_epochs=250, plan_kwargs={'lr':5e-3}, check_val_every_n_epoch=10)
GPU available: True, used: True
TPU available: None, using: 0 TPU cores
Epoch 250/250: 100%|██████████| 250/250 [01:37<00:00,  2.55it/s, loss=373, v_num=1]

Inspecting the convergence

[7]:
train_elbo = model.history['elbo_train'][1:]
test_elbo = model.history['elbo_validation']
[8]:
ax = train_elbo.plot()
test_elbo.plot(ax = ax)
[8]:
<AxesSubplot:xlabel='epoch'>
../../_images/user_guide_notebooks_linear_decoder_11_1.png

Extract and plot latent dimensions for cells

From the fitted model we extract the (mean) values for the latent dimensions. We store the values in the AnnData object for convenience.

[9]:
Z_hat = model.get_latent_representation()
for i, z in enumerate(Z_hat.T):
    adata.obs[f'Z_{i}'] = z

Now we can plot the latent dimension coordinates for each cell. A quick (albeit not complete) way to view these is to make a series of 2D scatter plots that cover all the dimensions. Since we are representing the cells by 10 dimensions, this leads to 5 scatter plots.

[10]:
fig = plt.figure(figsize=(12, 8))

for f in range(0, 9, 2):
    plt.subplot(2, 3, int(f / 2) + 1)

    plt.scatter(adata.obs[f'Z_{f}'], adata.obs[f'Z_{f + 1}'], marker='.', s=4, label='Cells')

    plt.xlabel(f'Z_{f}')
    plt.ylabel(f'Z_{f + 1}')

plt.subplot(2, 3, 6)
plt.scatter(adata.obs[f'Z_{f}'], adata.obs[f'Z_{f + 1}'], marker='.', label='Cells', s=4)
plt.scatter(adata.obs[f'Z_{f}'], adata.obs[f'Z_{f + 1}'], c='w', label=None)
plt.gca().set_frame_on(False)
plt.gca().axis('off')

lgd = plt.legend(scatterpoints=3, loc='upper left')
for handle in lgd.legendHandles:
    handle.set_sizes([200])


plt.tight_layout()
../../_images/user_guide_notebooks_linear_decoder_15_0.png

The question now is how does the latent dimensions link to genes?

For a given cell x, the expression of the gene g is proportional to x_g = w_(1, g) * z_1 + … + w_(10, g) * z_10. Moving from low values to high values in z_1 will mostly affect expression of genes with large w_(1, :) weights. We can extract these weights from the LDVAE model, and identify which genes have high weights for each latent dimension.

[11]:
loadings = model.get_loadings()
loadings.head()
[11]:
Z_0 Z_1 Z_2 Z_3 Z_4 Z_5 Z_6 Z_7 Z_8 Z_9
index
AL645608.8 0.486227 0.117515 0.246465 -0.126585 0.444820 -0.718101 -0.113966 -0.495691 0.315081 -0.046976
HES4 0.327915 -0.055428 0.578027 -0.641510 0.459892 -0.398796 0.128159 -0.182453 0.290446 -0.088780
ISG15 0.569520 0.307747 0.209110 -0.343599 -0.071104 -0.252339 0.125312 -0.143066 -0.028154 0.444637
TNFRSF18 0.375155 0.337450 1.087759 0.031596 -0.659312 0.006224 0.424024 -0.563259 0.250876 1.804788
TNFRSF4 0.711863 0.781351 0.980736 -0.165529 -0.722523 -0.259003 0.530245 -0.365604 0.014596 1.363712

For every latent variable Z, we extract the genes with largest magnitude, and separate genes with large negative values from genes with large positive values. We print out the top 5 genes in each direction for each latent variable.

[12]:
print('Top loadings by magnitude\n---------------------------------------------------------------------------------------')
for clmn_ in loadings:
    loading_ = loadings[clmn_].sort_values()
    fstr = clmn_ + ':\t'
    fstr += '\t'.join([f'{i}, {loading_[i]:.2}' for i in loading_.head(5).index])
    fstr += '\n\t...\n\t'
    fstr += '\t'.join([f'{i}, {loading_[i]:.2}' for i in loading_.tail(5).index])
    print(fstr + '\n---------------------------------------------------------------------------------------\n')
Top loadings by magnitude
---------------------------------------------------------------------------------------
Z_0:    GZMK, -0.94     PTGS2, -0.91    CD1E, -0.85     EGR3, -0.83     IL1B, -0.82
        ...
        MYLK3, 1.5      AC007240.1, 1.5 RRM2, 1.5       SELP, 1.5       FOXP3, 1.8
---------------------------------------------------------------------------------------

Z_1:    HLA-DQA1, -1.1  HLA-DQA2, -1.0  C1QA, -0.91     HLA-DRB5, -0.88 HLA-DRB1, -0.84
        ...
        TRAV4, 1.7      NELL2, 1.8      CD8A, 1.8       IL7R, 2.0       CD8B, 2.1
---------------------------------------------------------------------------------------

Z_2:    LINC02446, -1.2 CD8A, -1.1      CD8B, -1.0      MIR4432HG, -0.93        IGLV1-51, -0.91
        ...
        C1QB, 1.2       LMNA, 1.3       C1QC, 1.3       C1QA, 1.4       IFI27, 1.7
---------------------------------------------------------------------------------------

Z_3:    S100B, -1.6     TRDC, -1.6      C1QA, -1.6      C1QB, -1.5      FPR3, -1.5
        ...
        IGHG1, 0.69     OSTN-AS1, 0.79  SSPN, 0.83      COCH, 0.83      TNFRSF13B, 0.84
---------------------------------------------------------------------------------------

Z_4:    LMNA, -1.4      ZNF683, -1.3    MRC1, -1.2      FCER1A, -1.1    EMP1, -1.1
        ...
        CXCL3, 0.73     LYPD2, 0.78     LPL, 0.88       TIMD4, 0.95     MEG3, 1.2
---------------------------------------------------------------------------------------

Z_5:    EGR3, -1.3      CERS3, -1.1     CXCL8, -1.0     CD40LG, -0.95   LINC02195, -0.86
        ...
        TUBB1, 1.3      ITGA2B, 1.3     KLRC1, 1.4      ZNF683, 1.7     KLRC2, 1.9
---------------------------------------------------------------------------------------

Z_6:    CES1, -1.6      TYROBP, -1.1    GNLY, -0.99     CCL3, -0.99     S1PR5, -0.97
        ...
        FCRL1, 2.0      IGHD, 2.1       FAM30A, 2.2     VPREB3, 2.2     CD24, 2.3
---------------------------------------------------------------------------------------

Z_7:    CXCL10, -1.7    FCRL5, -1.0     GP9, -1.0       TTC36, -1.0     C19ORF71, -0.97
        ...
        BIRC5, 1.1      CD8B, 1.1       CCNB2, 1.1      ENHO, 1.1       FCER1A, 1.2
---------------------------------------------------------------------------------------

Z_8:    ARG1, -1.4      FOXP3, -1.3     PMCH, -1.2      SHISA8, -1.2    SDR16C5, -1.1
        ...
        IL3RA, 0.93     KCNK17, 1.0     PTCRA, 1.0      S100B, 1.0      BAALC, 1.1
---------------------------------------------------------------------------------------

Z_9:    NRG1, -2.0      S100A8, -1.8    S100A12, -1.8   ALDH1A1, -1.8   S100A9, -1.8
        ...
        TRGC2, 2.3      XCL2, 2.4       TRGC1, 2.4      GZMK, 2.5       TRDC, 2.7
---------------------------------------------------------------------------------------

It is important to keep in mind that unlike traditional PCA, these latent variables are not ordered. Z_0 does not necessarily explain more variance than Z_1.

These top genes can be interpreted as following most of the structural variation in the data.

The LinearSCVI model further supports the same scVI functionality as the SCVI model, so all posterior methods work the same. Here we show how to use scanpy to visualize the latent space.

[13]:
adata.obsm["X_scVI"] = Z_hat
sc.pp.neighbors(adata, use_rep="X_scVI", n_neighbors=20)
sc.tl.umap(adata, min_dist=0.3)
sc.tl.leiden(adata, key_added="leiden_scVI", resolution=0.8)
[14]:
sc.pl.umap(adata, color=["leiden_scVI"])
../../_images/user_guide_notebooks_linear_decoder_22_0.png
[15]:
zs = [f'Z_{i}' for i in range(model.n_latent)]
sc.pl.umap(adata, color=zs, ncols=3)
../../_images/user_guide_notebooks_linear_decoder_23_0.png