# Load dependencies
library(bluster)14 Community typing
Community typing in microbial ecology involves identifying distinct microbial communities by recognizing patterns in the data. The community types are described based on taxonomic feature characteristics, representing each community. The samples are described by community type assignments, which are defined by the ecosystem features in the sample. Community typing techniques can typically be divided into unsupervised clustering and dimensionality reduction techniques, where clustering is more commonly used.
In this chapter, we first walk you through some common clustering schemes in use for microbial community ecology, then focus on more detailed community typing techniques based on data dimensionality reduction.
14.1 Clustering methods
Clustering techniques aim to find groups, called clusters, that share a pattern in the data. In the microbiome context, clustering techniques are included in microbiome community typing methods. For example, clustering allows samples to be distinguished from each other based on their microbiome community composition. A clustering scheme consists of two steps: the first is to compute the sample dissimilarities with a given distance metric, and the second is to form the clusters based on the dissimilarity matrix. The data can be clustered either based on features or on samples. The examples below are focused on sample clustering.
There are multiple clustering algorithms available. bluster is a Bioconductor package providing tools for clustering data in the SummarizedExperiment container. It offers multiple algorithms such as hierarchical clustering, DBSCAN, and K-means.
In the examples of this chapter we use the peerj13075 data (Potbhare et al. 2022) (Section D.3) for microbiota community typing. This chapter illustrates how different results can be obtained depending on the choice of the algorithm. To reduce calculation time we decided to agglomerate taxonomic features onto ‘Class’ level and filter out the least prevalent taxonomic features as well as less commonly detected within a sample resulting in 26 features in the data (25 classes and an “Other” group that combines the remaining features).
library(mia)
data("peerj13075", package = "mia")
tse <- peerj13075
# Filter out most taxa to ease the calculation
tse_prev <- agglomerateByRank(tse, rank = "class")
tse_prev <- addPrevalence(tse_prev, detection = 0.01)
altExp(tse, "prevalent") <- subsetBy(
tse_prev,
rows = prevalence > 0.2, collapse = TRUE
)14.1.1 Hierarchical clustering
Hierarchical clustering aims to find hierarchy between samples or features. There are two approaches: agglomerative (“bottom-up”) and divisive (“top-down”). In the agglomerative approach, each observation is first in a unique cluster, after which the algorithm continues to agglomerate similar data points into clusters. The divisive approach, instead, starts with one cluster that contains all observations. Clusters are split recursively into clusters that differ the most. The clustering can be continued until each cluster contains only one observation.
In this example we use the addCluster() function from mia to cluster the data. The addCluster() function allows you to choose a clustering algorithm and offers multiple parameters to shape the result. The HclustParam() parameter is used for hierarchical clustering, and it accepts several sub-parameters, as further detailed in the HclustParam documentation of bluster (see ?bluster::HclustParam). Notably, the by argument specifies whether clustering is performed based on features or samples. Here, we cluster counts data, for which we compute the dissimilarities with the Bray-Curtis distance (Bray and Curtis 1957) using the ward.D2 method (Ward 1963; Murtagh and Legendre 2014). Statistical information can be optionally returned with the full parameter. Finally, the clust.col parameter allows us to choose the name of the column in the colData (default name is cluster).
library(vegan)
# Set seed for reproducibility
set.seed(174923)
# Add cluster
altExp(tse, "prevalent") <- addCluster(
altExp(tse, "prevalent"),
assay.type = "counts",
by = "cols",
HclustParam(method = "ward.D2", dist.fun = getDissimilarity, metric = "bray"),
full = TRUE,
clust.col = "hclust"
)
# Print the result table
table(altExp(tse, "prevalent")$hclust)
##
## 1 2 3 4 5 6
## 13 5 8 16 11 5From the table we can see that the hierarchical clustering suggests six clusters to describe the data. Unless the number of clusters (k) or the cutting height (h) is given in the cut.params argument of HclustParam(), the tree is cut at half of its total height; the number of branches crossing this height determines the number of clusters.
Now, we visualize the hierarchical structure of the clusters with a dendrogram tree using dendextend (Galili 2015). In each splitting point, the tree is divided into two clusters leading to the hierarchy. In this example, each sample is labeled by its dominant taxon to visualize ecological differences between the clusters (Figure 14.1).
library(dendextend)
# Get hclust data from metadata
hclust_data <- metadata(altExp(tse, "prevalent"))$clustering$hclust
# Get the dendrogram object
dendro <- as.dendrogram(hclust_data)
k <- length(unique(altExp(tse, "prevalent")$hclust))
# Color the branches by clusters, with the same Okabe-Ito colors as in the
# miaViz plots (black, the first color, is skipped)
cols <- palette.colors(k + 1, "Okabe-Ito")[-1]
# Order the colors to be equivalent to the factor levels; color_branches()
# colors the clusters from left to right in the order of the leaves
leaf_order <- order.dendrogram(dendro)
leaf_clusters <- altExp(tse, "prevalent")$hclust[leaf_order]
cols <- cols[unique(as.integer(leaf_clusters))]
dend <- color_branches(dendro, k = k, col = unlist(cols))
# Label the samples by their dominant taxon, in the order of the leaves
altExp(tse, "prevalent") <- addDominant(altExp(tse, "prevalent"))
labels(dend) <- altExp(tse, "prevalent")$dominant_taxa[leaf_order]
dend <- color_labels(dend, k = k, col = unlist(cols))
# Adjust frame for the figure
par(mar = c(9, 3, 0.5, 0.5))
# Plot dendrogram
dend |>
set("labels_cex", 0.8) |>
plot()
We can also visualize the clusters by projecting the data onto a two-dimensional surface that captures the most variability in the data. In this example, we use multidimensional scaling (MDS) (see Section 13.4). The resulting ordination is shown in Figure 14.2.
plotOrdination(
altExp(tse, "prevalent"), "MDS",
colour.by = "hclust", add.expl.var = TRUE
) +
labs(colour = "Cluster")
14.1.2 Agglomerate by cluster
Another way to agglomerate the data is to perform it based on clusters of the taxonomic features. To do so, we usually start by doing a compositionality-aware transformation such as CLR (Fernandes et al. 2014), followed by the application of a standard clustering method.
Below is an example of a CLR transformation followed by the hierarchical clustering algorithm. We will use the Kendall dissimilarity, that is, one minus Kendall’s rank correlation (Kendall 1938).
# The result of the CLR transform is stored in the assay clr
tse <- transformAssay(tse, method = "clr", pseudocount = 1)
tse <- transformAssay(
tse,
assay.type = "clr", method = "standardize", MARGIN = "rows"
)
# Declare the Kendall dissimilarity computation function
kendall_dissimilarity <- function(x) {
as.dist(1 - cor(t(x), method = "kendall"))
}
# Cluster (with Kendall dissimilarity) on the features of the `standardize` assay
tse <- addCluster(
tse,
assay.type = "standardize",
clust.col = "hclustKendall",
by = "rows",
HclustParam(dist.fun = kendall_dissimilarity, method = "ward.D2")
)The results are stored in the rowData column specified with the clust.col parameter. To better visualize the results and the distribution of the clusters, we can plot the number of features in each cluster (Figure 14.3).
library(miaViz)
plotBarplot(tse, row.var = "hclustKendall") +
labs(x = "Feature cluster", y = "Number of features")
Then we can merge data to clusters.
# Aggregate clusters as a sum of each cluster values
tse_merged <- agglomerateByVariable(tse, by = "rows", group = "hclustKendall")
tse_merged
## class: TreeSummarizedExperiment
## dim: 4 58
## metadata(0):
## assays(3): counts clr standardize
## rownames(4): 1 2 3 4
## rowData names(7): kingdom phylum ... genus hclustKendall
## colnames(58): ID1 ID2 ... ID57 ID58
## colData names(5): Sample Geographical_location Gender Age Diet
## reducedDimNames(0):
## mainExpName: NULL
## altExpNames(1): prevalent
## rowLinks: NULL
## rowTree: NULL
## colLinks: NULL
## colTree: NULLThis confirms that the operation succeeded, as the number of rows now matches the number of clusters. You can find more information on agglomeration from Chapter 9.
14.1.3 DMM
This section focuses on Dirichlet Multinomial Mixture Model (DMM) analysis (Holmes et al. 2012). It is a Bayesian clustering technique that allows searching for sample patterns that reflect sample similarity in the data using both prior information and the data.
In this example, we cluster the data with DMM clustering. In the example below, we calculate model fit using Laplace approximation to reduce the calculation time. The cluster information is added to the metadata with an optional name. In this example, we use a prior assumption that the optimal number of clusters to describe the data would be in the range from 1 to 6.
# Runs the model and calculates the most likely number of clusters from 1 to 6
set.seed(1495723)
altExp(tse, "prevalent") <- addCluster(
altExp(tse, "prevalent"),
assay.type = "counts",
name = "DMM",
DmmParam(k = 1:6, type = "laplace"),
by = "cols",
full = TRUE,
clust.col = "dmmclust"
)Figure 14.4 represents the Laplace approximation to the model evidence for each of the six models. We can see that the best number of clusters is two, as the minimum value of Laplace approximation determines the optimal k.
library(miaViz)
plotDMNFit(altExp(tse, "prevalent"), type = "laplace", name = "DMM") +
scale_x_continuous(breaks = 1:6)
Two clusters describe the data best. Now we can plot which taxonomic features define the key cluster features (Figure 14.5).
library(DirichletMultinomial)
# Get the estimates of how much each class contributes to each cluster
models <- metadata(altExp(tse, "prevalent"))$DMM
n_clusters <- models[["best"]]
best_model <- models[["dmm"]][[n_clusters]]
drivers <- fitted(best_model, scale = TRUE)
# Plot by utilizing miaViz's function plotLoadings
plotLoadings(drivers, ncomponents = n_clusters)
As well as in hierarchical clustering, we can also visualize the clusters by projecting the data onto a two-dimensional surface calculated using MDS (Figure 14.6). The plot rather clearly demonstrates the cluster division.
# DMM clusters
plotOrdination(
altExp(tse, "prevalent"), "MDS",
colour.by = "dmmclust", add.expl.var = TRUE
) +
labs(colour = "DMM cluster")
14.2 Dimensionality reduction
Dimensionality reduction can be considered a part of community typing, where the aim is to find underlying structure in the data. Dimensionality reduction relies on the idea that the data can be described as a lower rank representation, where latent features with different loads of the observed ones describe the sample set. This representation stores the information about sample dissimilarity with significantly reduced amount of data dimensions. Unlike clustering, where each sample is assigned into one cluster, dimensionality reduction allows continuous memberships of all samples across all community types. Dimensionality reduction techniques are explained in more detail in Chapter 13.
14.2.1 NMF
In this section, we will particularly focus on Non-negative Matrix Factorization (NMF) (Lee and Seung 1999). NMF decomposes the original data X into two lower rank matrices: H representing key taxonomic feature characteristics of each community type and W representing continuous sample memberships across all community types. The NMF algorithm calculates the minimum distance between the original data and its approximation using Kullback-Leibler divergence.
Here, we use the mia wrapper getNMF for the NMF package (Gaujoux and Seoighe 2010). To reduce calculation time, we set the number of components k to four instead of optimizing the number of components that describe the original data the best. The matrix returned by getNMF contains the sample scores, while the NMF output and NMF feature loadings are stored in the attributes NMF_output and loadings, respectively.
library(NMF)
# Calculate NMF
set.seed(3221)
res <- getNMF(altExp(tse, "prevalent"), k = 4)
# Obtain the relative membership of each component in each sample
wrel <- t(apply(res, 1, function(x) {
x / sum(x)
}))
# Define the community type of a sample with the highest relative abundance
altExp(tse, "prevalent")$NMFcomponent <- as.factor(apply(wrel, 1, which.max))
table(altExp(tse, "prevalent")$NMFcomponent)
##
## 1 2 3 4
## 11 14 28 5Now, we can plot the NMF community types calculated based on maximum membership for each sample onto a two-dimensional surface (Figure 14.7).
# NMF community types
plotOrdination(
altExp(tse, "prevalent"), "MDS",
colour.by = "NMFcomponent", add.expl.var = TRUE
) +
labs(colour = "NMF component")
Latent Dirichlet Allocation (LDA) (Blei et al. 2003) is an alternative to NMF. It is a probabilistic topic model for count data: each sample is a mixture of “topics”, i.e., community types, and each topic is a distribution over the features. In mia, LDA is calculated with addLDA() (or getLDA()), and its results are used in the same way as those of NMF.
14.3 Heatmaps with clusters
In Section 11.2, we visualized community composition with heatmaps. We can visualize the data similarly but add additional information on clusters.
# Keep only counts; transformed assays cannot be meaningfully agglomerated
assays(tse) <- assays(tse)["counts"]
# Agglomerate to Genus level
tse <- agglomerateByRank(tse, rank = "genus")
tse <- addPrevalence(tse)
tse <- subsetBy(tse, rows = prevalence > 0.5, collapse = TRUE)
# Apply clr and scale data
tse <- transformAssay(tse, method = "clr", pseudocount = 0.5)
tse <- transformAssay(
tse,
assay.type = "clr", method = "standardize", MARGIN = "rows"
)Now we can cluster rows. The resulting tree of taxa, plotted with ggtree (Yu et al. 2017), is shown in Figure 14.8.
library(ape)
library(ggtree)
# Hierarchical clustering
tse <- addCluster(
tse,
assay.type = "standardize", HclustParam(method = "complete"),
full = TRUE
)
taxa_hclust <- metadata(tse)[["clustering"]][["hclust"]]
# Creates a tree
taxa_tree <- as.phylo(taxa_hclust)
ggtree(taxa_tree) + geom_tiplab(size = 3) + hexpand(0.3)
Based on the phylo tree, we decide to create eight clusters.
# Hierarchical clustering with k = 8
tse <- addCluster(
tse,
assay.type = "standardize",
HclustParam(method = "complete", cut.params = list(k = 8)),
clust.col = "taxa_cluster"
)For the columns, we can utilize k-means clustering (Hartigan and Wong 1979). First we have to specify the number of clusters. Figure 14.9 shows the elbow and silhouette (Rousseeuw 1987) methods for this purpose.
library(factoextra)
library(patchwork)
# Samples must be in rows, so we transpose the assay
mat <- t(assay(tse, "standardize"))
# Elbow method
p1 <- fviz_nbclust(mat, kmeans, method = "wss") +
labs(y = "Total within-cluster sum of squares")
# Silhouette method
p2 <- fviz_nbclust(mat, kmeans, method = "silhouette")
p1 + p2 & labs(title = NULL)
The decrease in the within-cluster sum of squares levels off after about three clusters, and the average silhouette width is highest for two clusters and second highest for three. Based on the results, we split the columns into three clusters.
# K-means clustering with 3 clusters
tse <- addCluster(
tse,
assay.type = "standardize", by = "cols",
KmeansParam(centers = 3),
clust.col = "sample_cluster"
)
# Number of samples in each cluster
table(colData(tse)[["sample_cluster"]])
##
## 1 2 3
## 15 13 30Now we can create a heatmap where the taxa are grouped by their clusters, and the samples by their clusters and gender (Figure 14.10).
plotHeatmap(
tse,
assay.type = "standardize",
row.var = "taxa_cluster",
col.var = c("sample_cluster", "Gender")
)
For more community typing techniques applied to the SprockettTHData dataset, see the attached .Rmd file.
14.4 Exercises
We use the GlobalPatterns dataset.
Solve the exercises in order, as each exercise continues from the previous one. Try to solve each exercise yourself before opening the solution.








