Skip to content

Dimensionality Reduction

PCA compresses the 2,000 selected genes into 50 components, and the neighbor graph and the two-dimensional embeddings are built on those components. This page runs all three steps on PBMC 3k.

The setup repeats the steps of Quality Control, Normalization and Feature Selection, and keeps the 2,000 highly variable genes.

Setup code and its output

The MAD helper below adapts cells 18, 20 and 22 of the archived quality-control notebook. This version computes MAD with pandas and changes the filter combination. The source is copyright 2021 Theislab under Apache 2.0.

The source matrix is 10x Genomics’ PBMC 3k dataset, processed with Cell Ranger 1.1.0 and published in 2016. The provider licenses it under CC BY 4.0. This lesson converts the matrix to AnnData and derives the displayed summaries and analysis results.

import numpy as np
import scanpy as sc
import matplotlib.pyplot as plt
sc.settings.verbosity = 3
np.random.seed(42)
adata = sc.read_10x_mtx("/opt/data/pbmc3k", var_names="gene_symbols",
make_unique=True)
adata.layers["counts"] = adata.X.copy()
adata.var["mt"] = adata.var_names.str.startswith("MT-")
sc.pp.calculate_qc_metrics(adata, qc_vars=["mt"], percent_top=None,
log1p=False, inplace=True)
def is_outlier(adata, metric, nmads):
"""Flag cells whose metric sits more than nmads MADs from the median.
Args:
adata: AnnData object holding the metric in .obs.
metric: Column of adata.obs to test.
nmads: Number of median absolute deviations for the cutoff.
Returns:
Boolean Series, True where the cell is an outlier.
"""
values = adata.obs[metric]
median = values.median()
mad = (values - median).abs().median()
return (values < median - nmads * mad) | (values > median + nmads * mad)
adata.obs["log1p_total_counts"] = np.log1p(adata.obs["total_counts"])
adata.obs["log1p_n_genes_by_counts"] = np.log1p(
adata.obs["n_genes_by_counts"]
)
adata.obs["outlier"] = (
is_outlier(adata, "log1p_total_counts", 5)
| is_outlier(adata, "log1p_n_genes_by_counts", 5)
| is_outlier(adata, "pct_counts_mt", 3)
)
adata = adata[~adata.obs["outlier"]].copy()
sc.pp.filter_genes(adata, min_cells=3)
sc.pp.normalize_total(adata, target_sum=1e4)
sc.pp.log1p(adata)
sc.pp.highly_variable_genes(adata, layer="counts", n_top_genes=2000,
flavor="seurat_v3")
adata.raw = adata
adata = adata[:, adata.var["highly_variable"]]
print(adata.shape)
(2428, 2000)
sc.pp.scale(adata, max_value=10)
# Run PCA.
sc.tl.pca(adata, n_comps=50, random_state=42)
ratio = adata.uns["pca"]["variance_ratio"]
print("first five variance ratios:", np.round(ratio[:5], 4))
cumulative = np.cumsum(ratio)
print("cumulative at 10, 20, 30 components:",
np.round(cumulative[[9, 19, 29]], 4))
first five variance ratios: [0.0305 0.0117 0.0081 0.0054 0.004 ]
cumulative at 10, 20, 30 components: [0.0718 0.09 0.1072]

PC1 explains 3.05 percent of the variance of the 2,000 scaled genes, and PC2 1.17 percent. The first 10 components explain 7.18 percent together and the first 30 explain 10.72 percent. Ratios this small are normal for single-cell data, where every gene carries a large share of sampling noise.

# The elbow plot, to choose the number of components to carry forward.
# Fifty component labels need a wide figure to stay readable.
sc.pl.pca_variance_ratio(adata, n_pcs=50, show=False)
plt.gcf().set_size_inches(12, 4)
plt.savefig("outputs/dimensionality-reduction_elbow.png", dpi=150,
bbox_inches="tight")
plt.close()

Variance ratio per principal component. PC1 explains about 3 percent of the variance and PC2 about 1.2 percent, and the curve is almost flat from about PC7 onward. The section still carries 30 components into the neighbor graph.

The curve drops through the first six or seven components and is almost flat after them. The section still carries 30 components into the neighbor graph. An extra component past the elbow costs little, while a component cut too early can lose a small population.

sc.pl.pca(adata, color="total_counts", show=False)
plt.savefig("outputs/dimensionality-reduction_pca.png", dpi=150,
bbox_inches="tight")
plt.close()

The first two principal components colored by total counts. PC1 separates two groups of cells. The group on the right has more counts per cell, and inside that group the counts rise along PC1.

PC1 separates two groups of cells, and the group on the right has more counts per cell. When two cell types differ in RNA content, depth and identity line up on the same axis, so a depth gradient along a component is not proof of a technical artifact.

# Build the neighbor graph on 30 components, then embed it with UMAP.
sc.pp.neighbors(adata, n_neighbors=15, n_pcs=30, random_state=42)
sc.tl.umap(adata, random_state=42)
print(adata.obsm["X_umap"].shape)
(2428, 2)
sc.pl.umap(adata, color="total_counts", show=False)
plt.savefig("outputs/dimensionality-reduction_umap.png", dpi=150,
bbox_inches="tight")
plt.close()

UMAP embedding colored by total counts. The cells form three separate groups with wide gaps between them, a large group at the upper left with visible substructure, a group at the right and a small group at the bottom. Depth varies inside every group.

UMAP lays the neighbor graph out in two dimensions. It shows three separate groups, and the largest has visible substructure. Total counts vary inside each group, so depth does not split the embedding.

# t-SNE preserves local neighborhoods more strongly than UMAP and
# distorts global distances more, so it suits looking for tight
# subpopulations rather than overall layout.
sc.tl.tsne(adata, n_pcs=30, random_state=42)
print(adata.obsm["X_tsne"].shape)
(2428, 2)
sc.pl.tsne(adata, color="total_counts", show=False)
plt.savefig("outputs/dimensionality-reduction_tsne.png", dpi=150,
bbox_inches="tight")
plt.close()

t-SNE embedding colored by total counts. The same three groups appear, but they spread over more of the frame and the gaps between them are narrower than in the UMAP. The group with the highest counts, at the lower left, splits into two clumps.

t-SNE finds the same three groups, spreads each one over more of the plot with narrower gaps between them, and splits the group with the highest counts into two clumps. In both plots the distance between two groups carries little meaning, so the next page clusters on the neighbor graph, not on these coordinates.

Wolf, Angerer, and Theis, 2018 describe Scanpy, the Python toolkit for large-scale single-cell expression analysis.

The Single-cell best practices dimensionality-reduction chapter explains PCA, neighbor graphs, and nonlinear embeddings. It also describes why distances in UMAP or t-SNE need careful interpretation.

The AnnData introduction explains observation-aligned matrices such as PCA and UMAP coordinates. It shows how embeddings relate to the original cells.