Annotation with CellAssign#
Assigning single-cell RNA-seq data to known cell types#
CellAssign is a probabilistic model that uses prior knowledge of cell-type marker genes to annotate scRNA data into predefined cell types. Unlike other methods for assigning cell types, CellAssign does not require labeled single cell data and only needs to know whether or not each given gene is a marker of each cell type. The original paper and R code are linked below.
Code: https://github.com/Irrationone/cellassign
This notebook will demonstrate how to use CellAssign on follicular lymphoma and HGSC scRNA data.
!pip install --quiet scvi-colab
from scvi_colab import install
install()
import gdown
import matplotlib.pyplot as plt
import pandas as pd
import scanpy as sc
import scvi
import seaborn as sns
from scvi.external import CellAssign
To demonstrate CellAssign, we use the data from the original publication, which we converted into h5ad format. The data are originally available from here:
https://zenodo.org/record/3372746
url = "https://drive.google.com/uc?id=10l6m2KKKioCZnQlRHomheappHh-jTFmx"
output = "sce_follicular_annotated_final.h5ad"
gdown.download(url, output, quiet=False)
url = "https://drive.google.com/uc?id=1Pae7VEcoZbKRvtllGAEWG4SOLWSjjtCO"
output = "sce_hgsc_annotated_final.h5ad"
gdown.download(url, output, quiet=False)
url = "https://drive.google.com/uc?id=1Mk5uPdnPC4IMRnuG5N4uFvypT8hPdJ74"
output = "HGSC_celltype.csv"
gdown.download(url, output, quiet=False)
url = "https://drive.google.com/uc?id=1tJSOI9ve0i78WmszMLx2ul8F8tGycBTd"
output = "FL_celltype.csv"
gdown.download(url, output, quiet=False)
'FL_celltype.csv'
sc.set_figure_params(figsize=(4, 4))
%config InlineBackend.print_figure_kwargs={'facecolor' : "w"}
%config InlineBackend.figure_format='retina'
Follicular Lymphoma Data#
Load follicular lymphoma data and marker gene matrix (see Supplementary Table 2 from the original paper).
adata = sc.read("sce_follicular_annotated_final.h5ad")
adata.var_names_make_unique()
adata.obs_names_make_unique()
marker_gene_mat = pd.read_csv("FL_celltype.csv", index_col=0)
Create and fit CellAssign model#
The anndata object and cell type marker matrix should contain the same genes, so we index into adata
to include only the genes from marker_gene_mat
.
bdata = adata[:, marker_gene_mat.index].copy()
Then we setup anndata and initialize a CellAssign
model. Here we set the size_factor_key
to “size_factor”, which is a column in bdata.obs
.
Note
A size factor may be defined manually as scaled library size (total UMI count) and should not be placed on the log scale, as the model will do this manually. The library size should be computed before any gene subsetting (in this case, technically, a few notebook cells up).
This can be acheived as follows:
lib_size = adata.X.sum(1)
adata.obs["size_factor"] = lib_size / np.mean(lib_size)
scvi.external.CellAssign.setup_anndata(bdata, size_factor_key="size_factor")
model = CellAssign(bdata, marker_gene_mat)
model.train()
Epoch 400/400: 100%|██████████| 400/400 [00:22<00:00, 17.59it/s, loss=19.9, v_num=1]
Inspecting the convergence:
model.history["elbo_validation"].plot()
<AxesSubplot:xlabel='epoch'>
Predict and plot assigned cell types#
Predict the soft cell type assignment probability for each cell.
predictions = model.predict()
predictions.head()
B cells | Cytotoxic T cells | CD4 T cells | Tfh | other | |
---|---|---|---|---|---|
0 | 1.000000e+00 | 1.739431e-19 | 7.751762e-16 | 1.869599e-17 | 4.378877e-15 |
1 | 1.000000e+00 | 2.178871e-21 | 9.382402e-18 | 1.186499e-19 | 7.339101e-17 |
2 | 1.000000e+00 | 1.889330e-26 | 1.200271e-22 | 1.176634e-24 | 1.285317e-21 |
3 | 1.000000e+00 | 3.226794e-44 | 1.242664e-37 | 2.663802e-40 | 3.492028e-34 |
4 | 3.411843e-17 | 7.348493e-13 | 9.995215e-01 | 4.784879e-04 | 2.219958e-18 |
We can visualize the probabilities of assignment with a heatmap that returns the probability matrix for each cell and cell type.
sns.clustermap(predictions, cmap="viridis")
<seaborn.matrix.ClusterGrid at 0x7fbb9c6fd250>
We then create a UMAP plot labeled by maximum probability assignments from the CellAssign model. The left plot contains the true cell types and the right plot contains our model’s predictions.
bdata.obs["scvi-tools predictions"] = predictions.idxmax(axis=1).values
# celltype is the original CellAssign prediction
sc.pl.umap(bdata, color=["celltype", "scvi-tools predictions"], frameon=False, ncols=1)
Model reproducibility#
We see that the scvi-tools implementation highly reproduces the original implementation’s predictions.
df = bdata.obs
confusion_matrix = pd.crosstab(
df["scvi-tools predictions"],
df["celltype"],
rownames=["scvi-tools predictions"],
colnames=["Original predictions"],
)
confusion_matrix /= confusion_matrix.sum(1).ravel().reshape(-1, 1)
fig, ax = plt.subplots(figsize=(5, 4))
sns.heatmap(
confusion_matrix,
cmap=sns.diverging_palette(245, 320, s=60, as_cmap=True),
ax=ax,
square=True,
cbar_kws=dict(shrink=0.4, aspect=12),
)
<AxesSubplot:xlabel='Original predictions', ylabel='scvi-tools predictions'>
HGSC Data#
We can repeat the same process for HGSC data.
hgsc_adata = scvi.data.read_h5ad("sce_hgsc_annotated_final.h5ad")
hgsc_adata.var_names_make_unique()
hgsc_adata.obs_names_make_unique()
marker_gene_mat_hgsc = pd.read_csv("HGSC_celltype.csv", index_col=0)
Create and fit CellAssign model#
hgsc_bdata = hgsc_adata[:, marker_gene_mat_hgsc.index].copy()
scvi.external.CellAssign.setup_anndata(hgsc_bdata, "size_factor")
model_hgsc = CellAssign(hgsc_bdata, marker_gene_mat_hgsc)
model_hgsc.train()
Epoch 400/400: 100%|██████████| 400/400 [00:16<00:00, 23.85it/s, loss=41.5, v_num=1]
model_hgsc.history["elbo_validation"].plot()
<AxesSubplot:xlabel='epoch'>
Predict and plot assigned cell types#
predictions_hgsc = model_hgsc.predict()
sns.clustermap(predictions_hgsc, cmap="viridis")
<seaborn.matrix.ClusterGrid at 0x7fbb8690a3d0>
hgsc_bdata.obs["scvi-tools predictions"] = predictions_hgsc.idxmax(axis=1).values
sc.pl.umap(
hgsc_bdata,
color=["celltype", "scvi-tools predictions"],
ncols=1,
frameon=False,
)
Model reproducibility#
df = hgsc_bdata.obs
confusion_matrix = pd.crosstab(
df["scvi-tools predictions"],
df["celltype"],
rownames=["scvi-tools predictions"],
colnames=["Original predictions"],
)
confusion_matrix /= confusion_matrix.sum(1).ravel().reshape(-1, 1)
fig, ax = plt.subplots(figsize=(5, 4))
sns.heatmap(
confusion_matrix,
cmap=sns.diverging_palette(245, 320, s=60, as_cmap=True),
ax=ax,
square=True,
cbar_kws=dict(shrink=0.4, aspect=12),
)
<AxesSubplot:xlabel='Original predictions', ylabel='scvi-tools predictions'>