--- title: Flexible clustering for Bioconductor author: - name: Aaron Lun email: infinite.monkeys.with.keyboards@gmail.com output: BiocStyle::html_document package: bluster vignette: > %\VignetteIndexEntry{1. Clustering algorithms} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, echo=FALSE} knitr::opts_chunk$set(error=FALSE, message=FALSE, warnings=FALSE) library(BiocStyle) ``` # Introduction The `r Biocpkg("bluster")` package provides a flexible and extensible framework for clustering in Bioconductor packages/workflows. At its core is the `clusterRows()` generic that controls dispatch to different clustering algorithms. We will demonstrate on some single-cell RNA sequencing data from the `r Biocpkg("scRNAseq")` package; our aim is to cluster cells into cell populations based on their PC coordinates. ```{r} library(scRNAseq) sce <- ZeiselBrainData() # Trusting the authors' quality control, and going straight to normalization. library(scuttle) sce <- logNormCounts(sce) # Feature selection based on highly variable genes. library(scran) dec <- modelGeneVar(sce) hvgs <- getTopHVGs(dec, n=1000) # Dimensionality reduction for work (PCA) and pleasure (t-SNE). set.seed(1000) library(scater) sce <- runPCA(sce, ncomponents=20, subset_row=hvgs) sce <- runUMAP(sce, dimred="PCA") mat <- reducedDim(sce, "PCA") dim(mat) ``` # Based on distance matrices ## Hierarchical clustering Our first algorithm is good old hierarchical clustering, as implemented using `hclust()` from the _stats_ package. This automatically sets the cut height to half the dendrogram height. ```{r} library(bluster) hclust.out <- clusterRows(mat, HclustParam()) plotUMAP(sce, colour_by=I(hclust.out)) ``` Advanced users can achieve greater control of the procedure by passing more parameters to the `HclustParam()` constructor. Here, we use Ward's criterion for the agglomeration with a dynamic tree cut from the `r CRANpkg("dynamicTreeCut")` package. ```{r} hp2 <- HclustParam(method="ward.D2", cut.dynamic=TRUE) hp2 hclust.out <- clusterRows(mat, hp2) plotUMAP(sce, colour_by=I(hclust.out)) ``` ## Affinity propagation Another option is to use affinity propagation, as implemented using the `r CRANpkg("apcluster")` package. Here, messages are passed between observations to decide on a set of exemplars, each of which form the center of a cluster. This is not particularly fast as it involves the calculation of a square similarity matrix between all pairs of observations. So, we'll speed it up by taking analyzing a subset of the data: ```{r} set.seed(1000) sub <- sce[,sample(ncol(sce), 200)] ap.out <- clusterRows(reducedDim(sub), AffinityParam()) plotUMAP(sub, colour_by=I(ap.out)) ``` The `q` parameter is probably the most important and determines the resolution of the clustering. This can be set to any value below 1, with smaller (possibly negative) values corresponding to coarser clusters. ```{r} set.seed(1000) ap.out <- clusterRows(reducedDim(sub), AffinityParam(q=-2)) plotUMAP(sub, colour_by=I(ap.out)) ``` # With a fixed number of clusters ## $k$-means clustering A classic algorithm is $k$-means clustering, as implemented using the `kmeans()` function. This requires us to pass in the number of clusters, either as a number: ```{r} set.seed(100) kmeans.out <- clusterRows(mat, KmeansParam(10)) plotUMAP(sce, colour_by=I(kmeans.out)) ``` Or as a function of the number of observations, which is useful for vector quantization purposes: ```{r} kp <- KmeansParam(sqrt) kp set.seed(100) kmeans.out <- clusterRows(mat, kp) plotUMAP(sce, colour_by=I(kmeans.out)) ``` A variant of this approach is mini-batch $k$-means, as implemented in the `r Biocpkg("mbkmeans")` package. This uses mini-batching to approximate the full $k$-means algorithm for greater speed. ```{r} set.seed(100) mbkmeans.out <- clusterRows(mat, MbkmeansParam(20)) plotUMAP(sce, colour_by=I(mbkmeans.out)) ``` ## Self-organizing maps We can also use self-organizing maps (SOMs) from the `r CRANpkg("kohonen")` package. This allocates observations to nodes of a simple neural network; each node is then treated as a cluster. ```{r} set.seed(1000) som.out <- clusterRows(mat, SomParam(20)) plotUMAP(sce, colour_by=I(som.out)) ``` The key feature of SOMs is that they apply additional topological constraints on the relative positions of the nodes. This allows us to naturally determine the relationships between clusters based on the proximity of the nodes. ```{r, fig.wide=TRUE} set.seed(1000) som.out <- clusterRows(mat, SomParam(100), full=TRUE) par(mfrow=c(1,2)) plot(som.out$objects$som, "counts") grid <- som.out$objects$som$grid$pts text(grid[,1], grid[,2], seq_len(nrow(grid))) ``` # Graph-based clustering We can build shared or direct nearest neighbor graphs and perform community detection with `r CRANpkg("igraph")`. Here, the number of neighbors `k` controls the resolution of the clusters. ```{r} set.seed(101) # just in case there are ties. graph.out <- clusterRows(mat, NNGraphParam(k=10)) plotUMAP(sce, colour_by=I(graph.out)) ``` It is again straightforward to tune the procedure by passing more arguments such as the community detection algorithm to use. ```{r} set.seed(101) # just in case there are ties. np <- NNGraphParam(k=20, cluster.fun="louvain") np graph.out <- clusterRows(mat, np) plotUMAP(sce, colour_by=I(graph.out)) ``` # Density-based clustering We also implement a version of the DBSCAN algorithm for density-based clustering. This focuses on identifying masses of continuous density. ```{r} dbscan.out <- clusterRows(mat, DbscanParam()) plotUMAP(sce, colour_by=I(dbscan.out)) ``` Unlike the other methods, it will consider certain points to be noise and discard them from the output. ```{r} summary(is.na(dbscan.out)) ``` The resolution of the clustering can be modified by tinkering with the `core.prop`. Smaller values will generally result in smaller clusters as well as more noise points. ```{r} dbscan.out <- clusterRows(mat, DbscanParam(core.prop=0.1)) summary(is.na(dbscan.out)) ``` # Two-phase clustering We also provide a wrapper for a hybrid "two-step" approach for handling larger datasets. Here, a fast agglomeration is performed with $k$-means to compact the data, followed by a slower graph-based clustering step to obtain interpretable meta-clusters. (This dataset is not, by and large, big enough for this approach to work particularly well.) ```{r} set.seed(100) # for the k-means two.out <- clusterRows(mat, TwoStepParam()) plotUMAP(sce, colour_by=I(two.out)) ``` Each step is itself parametrized by `BlusterParam` objects, so it is possible to tune them individually: ```{r} twop <- TwoStepParam(second=NNGraphParam(k=5)) twop set.seed(100) # for the k-means two.out <- clusterRows(mat, TwoStepParam()) plotUMAP(sce, colour_by=I(two.out)) ``` # Obtaining full clustering statistics Sometimes the vector of cluster assignments is not enough. We can obtain more information about the clustering procedure by setting `full=TRUE` in `clusterRows()`. For example, we could obtain the actual graph generated by `NNGraphParam()`: ```{r} nn.out <- clusterRows(mat, NNGraphParam(), full=TRUE) nn.out$objects$graph ``` The assignment vector is still reported in the `clusters` entry: ```{r} table(nn.out$clusters) ``` # Further comments `clusterRows()` enables users or developers to easily switch between clustering algorithms by changing a single argument. Indeed, by passing the `BlusterParam` object across functions, we can ensure that the same algorithm is used through a workflow. It is also helpful for package functions as it provides diverse functionality without compromising a clean function signature. However, the true power of this framework lies in its extensibility. Anyone can write a `clusterRows()` method for a new clustering algorithm with an associated `BlusterParam` subclass, and that procedure is immediately compatible with any workflow or function that was already using `clusterRows()`. # Session information {-} ```{r} sessionInfo() ```