Note

This page was generated from linear_decoder.ipynb. Interactive online version: Colab badge. Some tutorial content may look better in light mode.

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 model 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 version 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.

[ ]:
!pip install --quiet scvi-colab
from scvi_colab import install
install()
[2]:
import scanpy as sc
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

import scvi

sc.set_figure_params(figsize=(4, 4), frameon=False)

%config InlineBackend.print_figure_kwargs={'facecolor' : "w"}
%config InlineBackend.figure_format='retina'
Global seed set to 0
/usr/local/lib/python3.7/dist-packages/numba/np/ufunc/parallel.py:363: NumbaWarning: The TBB threading layer requires TBB version 2019.5 or later i.e., TBB_INTERFACE_VERSION >= 11005. Found TBB_INTERFACE_VERSION = 9107. The TBB threading layer is disabled.
  warnings.warn(problem)

Initialization#

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

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

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)

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.model.LinearSCVI.setup_anndata(adata, layer="counts")
[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: False, using: 0 TPU cores
IPU available: False, using: 0 IPUs
LOCAL_RANK: 0 - CUDA_VISIBLE_DEVICES: [0]
Epoch 250/250: 100%|██████████| 250/250 [03:45<00:00,  1.11it/s, loss=381, 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]:
<matplotlib.axes._subplots.AxesSubplot at 0x7fca504859d0>
../../_images/tutorials_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/tutorials_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.519028 0.115697 0.204663 -0.139746 0.351287 -0.691419 -0.076580 -0.602822 0.216240 -0.051359
HES4 0.406792 -0.108052 0.540742 -0.659631 0.347530 -0.434338 0.161793 -0.263663 0.222727 -0.088947
ISG15 0.548010 0.323460 0.257682 -0.335991 -0.134195 -0.154423 0.146381 -0.134070 -0.024315 0.423179
TNFRSF18 0.332918 0.282825 1.185913 0.118478 -0.564653 -0.013676 0.432177 -0.502266 0.359847 1.863203
TNFRSF4 0.653144 0.716128 1.060974 -0.063657 -0.623073 -0.290106 0.525347 -0.279947 0.130863 1.474835

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.98     PTGS2, -0.92    CD1E, -0.91     IL1B, -0.84     SLC4A10, -0.8
        ...
        CDKN3, 1.4      RRM2, 1.4       AC007240.1, 1.5 MYLK3, 1.5      FOXP3, 1.7
---------------------------------------------------------------------------------------

Z_1:    HLA-DQA1, -1.1  C1QA, -1.1      HLA-DQA2, -1.0  HLA-DRB5, -0.86 HLA-DRB1, -0.84
        ...
        LRRN3, 1.7      NELL2, 1.8      IL7R, 1.9       CD8A, 2.0       CD8B, 2.3
---------------------------------------------------------------------------------------

Z_2:    CD8A, -1.0      LINC02446, -1.0 CD8B, -0.91     IGLV1-51, -0.89 MIR4432HG, -0.88
        ...
        C1QC, 1.4       C1QA, 1.4       RTKN2, 1.4      LMNA, 1.4       IFI27, 1.7
---------------------------------------------------------------------------------------

Z_3:    S100B, -1.8     C1QB, -1.6      TRDC, -1.5      C1QA, -1.5      KLRC2, -1.4
        ...
        LINC01781, 0.68 TNFRSF13B, 0.81 SSPN, 0.81      COCH, 0.81      OSTN-AS1, 0.82
---------------------------------------------------------------------------------------

Z_4:    ZNF683, -1.3    LMNA, -1.3      MRC1, -1.3      TMEM136, -1.1   EMP1, -0.96
        ...
        PTPRG, 0.64     TIMD4, 0.74     LPL, 0.84       LYPD2, 0.84     MEG3, 1.1
---------------------------------------------------------------------------------------

Z_5:    EGR3, -1.3      CERS3, -1.1     CXCL8, -0.98    CD40LG, -0.9    TSHZ2, -0.83
        ...
        CD8B, 1.3       XCL2, 1.3       KLRC1, 1.5      ZNF683, 1.7     KLRC2, 2.0
---------------------------------------------------------------------------------------

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

Z_7:    CXCL10, -1.7    FCRL5, -1.1     TTC36, -1.1     GP9, -1.0       C19ORF71, -0.89
        ...
        BIRC5, 0.99     CCNB2, 1.0      CAVIN3, 1.1     ENHO, 1.2       FCER1A, 1.3
---------------------------------------------------------------------------------------

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

Z_9:    NRG1, -2.0      ALDH1A1, -1.9   S100A8, -1.9    S100A12, -1.8   S100A9, -1.8
        ...
        KLRB1, 2.2      XCL2, 2.2       TRGC1, 2.4      GZMK, 2.4       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.

[14]:
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)
[15]:
sc.pl.umap(adata, color=["leiden_scVI"])
../../_images/tutorials_notebooks_linear_decoder_22_0.png
[16]:
zs = [f'Z_{i}' for i in range(model.n_latent)]
sc.pl.umap(adata, color=zs, ncols=3)
../../_images/tutorials_notebooks_linear_decoder_23_0.png