Clustering
Leiden clustering partitions the neighbor graph into communities of cells. This page clusters PBMC 3k at resolution 0.5 and then tests how much the partition depends on that choice.
Load, filter, embed
Section titled “Load, filter, embed”The setup repeats the steps of the earlier pages, from Quality Control to the neighbor graph and the UMAP of Dimensionality Reduction.
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 npimport scanpy as scimport matplotlib.pyplot as plt
sc.settings.verbosity = 3np.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 = adataadata = adata[:, adata.var["highly_variable"]]sc.pp.scale(adata, max_value=10)sc.tl.pca(adata, n_comps=50, random_state=42)sc.pp.neighbors(adata, n_neighbors=15, n_pcs=30, random_state=42)sc.tl.umap(adata, random_state=42)print(adata.shape)(2428, 2000)Leiden clustering
Section titled “Leiden clustering”# Leiden community detection on the KNN graph, the clustering# sc-best-practices recommends. The igraph flavour is the current# default backend.sc.tl.leiden(adata, resolution=0.5, key_added="leiden", random_state=42, flavor="igraph", n_iterations=2, directed=False)
print(adata.obs["leiden"].value_counts().sort_index())leiden0 10991 4562 4123 3154 146Name: count, dtype: int64Leiden at resolution 0.5 finds five clusters. Cluster 0 holds 1,099 of the 2,428 cells, 45 percent, and cluster 4 holds 146.
sc.pl.umap(adata, color="leiden", show=False)plt.savefig("outputs/clustering_leiden.png", dpi=150, bbox_inches="tight")plt.close()
The clusters follow the groups of the embedding. The large group on the left holds clusters 0 and 2, the bottom group is cluster 3, and clusters 1 and 4 split the group on the right.
Testing resolutions
Section titled “Testing resolutions”# Try multiple resolutions. Higher resolution splits more populations# apart; sc-best-practices uses these sweeps to focus on# substructures.for resolution in (0.2, 0.4, 0.6, 0.8, 1.0): sc.tl.leiden(adata, resolution=resolution, key_added=f"leiden_{resolution}", random_state=42, flavor="igraph", n_iterations=2, directed=False) n_clusters = adata.obs[f"leiden_{resolution}"].nunique() print(f"resolution {resolution}: {n_clusters} clusters")resolution 0.2: 4 clustersresolution 0.4: 5 clustersresolution 0.6: 6 clustersresolution 0.8: 8 clustersresolution 1.0: 8 clustersThe cluster count rises from 4 at resolution 0.2 to 8 at 0.8, then stays at 8 at 1.0. Resolution 0.4 also gives five clusters.
Comparing the partitions
Section titled “Comparing the partitions”from sklearn.metrics import adjusted_rand_score
# The adjusted Rand index measures agreement between two partitions,# corrected for chance. Agreement above 0.9 means the resolutions# describe almost the same structure.for resolution in (0.2, 0.4, 0.6, 0.8, 1.0): ari = adjusted_rand_score(adata.obs["leiden"], adata.obs[f"leiden_{resolution}"]) print(f"ARI of {resolution} against 0.5: {ari:.3f}")ARI of 0.2 against 0.5: 0.889ARI of 0.4 against 0.5: 0.990ARI of 0.6 against 0.5: 0.987ARI of 0.8 against 0.5: 0.656ARI of 1.0 against 0.5: 0.653Resolutions 0.4 and 0.6 agree with 0.5 at an ARI of 0.990 and 0.987, so the partition holds across that range. At 0.8 the ARI falls to 0.656, the point where the large groups start to split. A partition that holds across a range of resolutions is a safer basis for annotation than one that changes at every step.
sc.pl.umap(adata, color=["leiden_0.2", "leiden_0.4", "leiden_0.8"], show=False)plt.savefig("outputs/clustering_resolutions.png", dpi=150, bbox_inches="tight")plt.close()
At 0.2 the two clusters of the right group merge into one. At 0.8 the large group on the left splits into four clusters and the right group into three, while the bottom group stays whole.
Scientific references
Section titled “Scientific references”Wolf, Angerer, and Theis, 2018 describe Scanpy, the Python toolkit for large-scale single-cell expression analysis.
Further reading
Section titled “Further reading”The Scanpy Leiden reference defines resolution, random state, and partition implementation. Those settings matter when comparing the cluster assignments shown here.
The Scanpy PBMC 3k workflow connects preprocessing, the neighbor graph, and clustering on the same source dataset. Its legacy settings provide a comparison rather than a required parameter choice.