7  Machine learning

This chapter demonstrates two supervised ML algorithms, random forest and XGBoost, that can be applied to classification and regression tasks. For an introduction to ML and supervised learning, see Introduction to machine learning & AI.

7.1 Setup

Published fecal microbiome data (Qin et al. 2012; Pasolli et al. 2017) (see OMA: QinJ_2012 data set) will be used to illustrate how to deploy supervised machine learning algorithms to address classification and regression problems. For classification, two ML models will be used to classify subjects in two groups: Type II diabetes patients or Healthy individuals (encoded as T2D and healthy in the metadata). For regression, models will be use to predict the body mass index (BMI) of each subject. In both tasks the models will be trained with participants gut microbiome data.

Pasolli, Edoardo, Lucas Schiffer, Paolo Manghi, et al. 2017. “Accessible, Curated Metagenomic Data Through ExperimentHub.” Nature Methods 14 (11): 1023–24. https://doi.org/10.1038/nmeth.4468.
Ridaura, Vanessa K., Jeremiah J. Faith, Federico E. Rey, et al. 2013. “Gut Microbiota from Twins Discordant for Obesity Modulate Metabolism in Mice.” Science 341 (6150): 1241214. https://doi.org/10.1126/science.1241214.

Mounting evidence show associations between gut microbiome and the onset of type II diabetes. Thus, it has been suggested that microbiome data could be used to discriminate between patients and healthy individuals. Indeed, that hypothesis was explored in the research article where the dataset we will work with was released (Qin et al. 2012). On the other hand, experiments conducted with twins have shown that while the transplantation of gut microbiome from the obese twin induces obesity in mice, the gut microbiome of the lean twin doesn’t (Ridaura et al. 2013). Thus, predicting the health status of a person or their BMI from their gut microbiome seems a plausible task, and an interesting opportunity to learn about supervised ML algorithms using real-world data.

To do so, the R package mikropml (Topçuoğlu et al. 2020, 2021) will be used throughout this chapter. This package was developed to offer a user-friendly interface to supervised ML algorithms implemented in the caret package (Kuhn 2008). Here is a list of models supported by mikropml.

Topçuoğlu, Begüm D., Nicholas A. Lesniak, Mack T. Ruffin, Jenna Wiens, and Patrick D. Schloss. 2020. “A Framework for Effective Application of Machine Learning to Microbiome-Based Classification Problems.” mBio 11 (3): 10.1128/mbio.00434–20. https://doi.org/10.1128/mbio.00434-20.
Topçuoğlu, Begüm D., Zena Lapp, Kelly L. Sovacool, Evan Snitkin, Jenna Wiens, and Patrick D. Schloss. 2021. “mikropml: User-Friendly r Package for Supervised Machine Learning Pipelines.” Journal of Open Source Software 6 (61): 3073. https://doi.org/10.21105/joss.03073.
Kuhn, Max. 2008. “Building Predictive Models in R Using the caret Package.” Journal of Statistical Software 28 (5): 1–26. https://doi.org/10.18637/jss.v028.i05.

The code below will retrieve the data and show the number of participants on each category.

library(curatedMetagenomicData)
##  Loading required package: SummarizedExperiment
##  Loading required package: MatrixGenerics
##  Loading required package: matrixStats
##  
##  Attaching package: 'MatrixGenerics'
##  The following objects are masked from 'package:matrixStats':
##  
##      colAlls, colAnyNAs, colAnys, colAvgsPerRowSet, colCollapse,
##      colCounts, colCummaxs, colCummins, colCumprods, colCumsums,
##      colDiffs, colIQRDiffs, colIQRs, colLogSumExps, colMadDiffs,
##      colMads, colMaxs, colMeans2, colMedians, colMins, colOrderStats,
##      colProds, colQuantiles, colRanges, colRanks, colSdDiffs, colSds,
##      colSums2, colTabulates, colVarDiffs, colVars, colWeightedMads,
##      colWeightedMeans, colWeightedMedians, colWeightedSds,
##      colWeightedVars, rowAlls, rowAnyNAs, rowAnys, rowAvgsPerColSet,
##      rowCollapse, rowCounts, rowCummaxs, rowCummins, rowCumprods,
##      rowCumsums, rowDiffs, rowIQRDiffs, rowIQRs, rowLogSumExps,
##      rowMadDiffs, rowMads, rowMaxs, rowMeans2, rowMedians, rowMins,
##      rowOrderStats, rowProds, rowQuantiles, rowRanges, rowRanks,
##      rowSdDiffs, rowSds, rowSums2, rowTabulates, rowVarDiffs,
##      rowVars, rowWeightedMads, rowWeightedMeans, rowWeightedMedians,
##      rowWeightedSds, rowWeightedVars
##  Loading required package: GenomicRanges
##  Loading required package: stats4
##  Loading required package: BiocGenerics
##  Loading required package: generics
##  
##  Attaching package: 'generics'
##  The following objects are masked from 'package:base':
##  
##      as.difftime, as.factor, as.ordered, intersect, is.element,
##      setdiff, setequal, union
##  
##  Attaching package: 'BiocGenerics'
##  The following objects are masked from 'package:stats':
##  
##      IQR, mad, sd, var, xtabs
##  The following object is masked from 'package:utils':
##  
##      data
##  The following objects are masked from 'package:base':
##  
##      Filter, Find, Map, Position, Reduce, anyDuplicated, aperm,
##      append, as.data.frame, basename, cbind, colnames, dirname,
##      do.call, duplicated, eval, evalq, get, grep, grepl, is.unsorted,
##      lapply, mapply, match, mget, order, paste, pmax, pmax.int, pmin,
##      pmin.int, rank, rbind, rownames, sapply, saveRDS, scale,
##      sequence, table, tapply, transform, unique, unsplit, which.max,
##      which.min
##  Loading required package: S4Vectors
##  
##  Attaching package: 'S4Vectors'
##  The following object is masked from 'package:utils':
##  
##      findMatches
##  The following objects are masked from 'package:base':
##  
##      I, expand.grid, unname
##  Loading required package: IRanges
##  Loading required package: Seqinfo
##  Loading required package: Biobase
##  Welcome to Bioconductor
##  
##      Vignettes contain introductory material; view with
##      'browseVignettes()'. To cite Bioconductor, see
##      'citation("Biobase")', and for packages 'citation("pkgname")'.
##  
##  Attaching package: 'Biobase'
##  The following object is masked from 'package:MatrixGenerics':
##  
##      rowMedians
##  The following objects are masked from 'package:matrixStats':
##  
##      anyMissing, rowMedians
##  Loading required package: TreeSummarizedExperiment
##  Loading required package: SingleCellExperiment
##  Loading required package: Biostrings
##  Loading required package: XVector
##  
##  Attaching package: 'Biostrings'
##  The following object is masked from 'package:base':
##  
##      strsplit
##  OpenTelemetry error: there is no package called 'otelsdk'
##  Warning: replacing previous import 'BiocGenerics::version' by
##  'BiocManager::version' when loading 'AnnotationHub'
##  OpenTelemetry error: there is no package called 'otelsdk'

samples <- sampleMetadata[sampleMetadata[["study_name"]] == "QinJ_2012", ]

tse <- returnSamples(
    samples,
    dataType = "relative_abundance",
    counts = TRUE, # use counts instead of rel abundances
    rownames = "short"
)
##  
##  $`2021-10-14.QinJ_2012.relative_abundance`
##  dropping rows without rowTree matches:
##    k__Bacteria|p__Actinobacteria|c__Coriobacteriia|o__Coriobacteriales|f__Atopobiaceae|g__Olsenella|s__Olsenella_profusa
##    k__Bacteria|p__Actinobacteria|c__Coriobacteriia|o__Coriobacteriales|f__Coriobacteriaceae|g__Collinsella|s__Collinsella_stercoris
##    k__Bacteria|p__Firmicutes|c__Bacilli|o__Bacillales|f__Bacillales_unclassified|g__Gemella|s__Gemella_bergeri
##    k__Bacteria|p__Firmicutes|c__Bacilli|o__Lactobacillales|f__Carnobacteriaceae|g__Granulicatella|s__Granulicatella_elegans
##    k__Bacteria|p__Firmicutes|c__Clostridia|o__Clostridiales|f__Ruminococcaceae|g__Ruminococcus|s__Ruminococcus_champanellensis
##    k__Bacteria|p__Firmicutes|c__Erysipelotrichia|o__Erysipelotrichales|f__Erysipelotrichaceae|g__Bulleidia|s__Bulleidia_extructa
##    k__Bacteria|p__Proteobacteria|c__Betaproteobacteria|o__Burkholderiales|f__Sutterellaceae|g__Sutterella|s__Sutterella_parvirubra
##    k__Bacteria|p__Synergistetes|c__Synergistia|o__Synergistales|f__Synergistaceae|g__Cloacibacillus|s__Cloacibacillus_evryensis
##  Warning: dropping 5 taxa from `2021-10-14.QinJ_2012.relative_abundance` with no species-level name:
##    Collinsella_massiliensis
##    Streptococcus_anginosus_group
##    Enterobacter_cloacae_complex
##    Bacillus_cereus_group
##    Pseudomonas_aeruginosa_group
##  These are MetaPhlAn species groups and complexes that NCBI does not resolve to a species. Use rownames = "long" to keep every taxon.
##  Duplicated labels were made unique.

# Change assay's name to reflect its content
assayNames(tse) <- "counts"

table(tse[["disease"]]) |>
    t() |>
    knitr::kable()
T2D healthy
170 193

7.2 Data preprocessing

Before applying any ML algorithm, the data must be preprocessed. This speeds up the training of the models by reducing the amount of features analyzed, a desirable outcome when working with high-dimensional microbiome data. In addition to faster performance, common pre-processing steps have biological justifications. For instance:

  • Collapse highly correlated features: In a microbial community, it’s common for the abundance of two or more taxonomic features to be highly correlated due to ecological interactions. Thus, removing or collapsing correlated features allows the model to analyze them as one group.

  • Remove features with near-zero variance: Features that don’t vary enough across groups can hardly help in discerning between them, as they don’t hold any biologically relevant information. Additionally, under certain data splits, these variables can show zero variance.

  • Remove features with low prevalence: Microbiome data is sparse, and taxonomic features present in just a few samples of each group hardly provide useful biological information for their classification.

ImportantImportant: Data leakage is a common pitfall.

Data leakage occurs when information from the test set influences the model training process, leading to overly optimistic performance estimates. This can happen, for example, if preprocessing steps like scaling are applied to both the training and test data together, allowing the model to indirectly “see” the test data during training. Fortunately, there are questions we can ask ourselves to avoid data leakage (Bernett et al. 2024). The key rule is to split the data first and fit any data-dependent preprocessing on the training set only (Figure 7.1).

flowchart TB
    subgraph wrong["Leakage"]
        direction LR
        w1["All data"] --> w2["Preprocess"] --> w3["Split into<br/>train / test"] --> w4["Train &<br/>evaluate"]
    end
    subgraph right["No leakage"]
        direction LR
        r1["All data"] --> r2["Split into<br/>train / test"] --> r3["Fit preprocessing<br/>on train"] --> r4["Apply to test,<br/>train & evaluate"]
    end
    wrong ~~~ right
    classDef bad fill:#fbe9eb,stroke:#b2182b,color:#070707
    classDef good fill:#e6f3f7,stroke:#0087af,color:#070707
    class w1,w2,w3,w4 bad
    class r1,r2,r3,r4 good
Figure 7.1: Data-dependent preprocessing, such as scaling or filtering, causes leakage when it is fitted on all data before the split (top). Split first, fit the preprocessing on the training set, and apply the same fitted steps to the test set (bottom).

To avoid it here, we split the samples into a training set and a test set before preprocessing. Steps that learn from the data across samples, such as the prevalence filter, use only the training samples, and steps that use one sample at a time, such as relative abundances and alpha diversity, can be applied to all samples.

Bernett, Judith, David B. Blumenthal, Dominik G. Grimm, et al. 2024. “Guiding Questions to Avoid Data Leakage in Biological Machine Learning Applications.” Nature Methods 21 (8): 1444–53. https://doi.org/10.1038/s41592-024-02362-y.

First, we split the samples into a training set (80%) and a test set (20%). The split is stratified by disease status so that both sets have similar proportions of patients and healthy individuals.

library(mia)
##  Loading required package: MultiAssayExperiment
##  This is mia version 1.21.30
##  - Online documentation and vignettes: https://microbiome.github.io/mia/
##  - Online book 'Orchestrating Microbiome Analysis (OMA)': https://bioconductor.org/books/release/OMA/
library(mikropml)

set.seed(1)
train_idx <- caret::createDataPartition(
    tse[["disease"]],
    p = 0.8, list = FALSE
)[, 1]
train_samples <- colnames(tse)[train_idx]

Next, we keep the taxa that are present in more than 10% of the training samples, and calculate relative abundances and alpha diversity indices that provide ecosystem-level information. See OMA: Alpha diversity for a discussion on alpha diversity.

# Keep taxa present in more than 10% of the training samples
prevalence <- getPrevalence(tse[, train_samples], assay.type = "counts")
tse <- tse[prevalence > 0.1, ]

# Transform to relative abundances
tse <- transformAssay(
    x = tse,
    assay.type = "counts",
    method = "relabundance",
    MARGIN = "cols",
    pseudocount = TRUE
)
##  A pseudocount of 25 was applied.

# Alpha diversity indices to be calculated
alpha_divs <- c(
    "dbp_dominance",
    "faith_diversity",
    "observed_richness",
    "shannon_diversity"
)

# Add alpha diversity indices to the metadata for latter use in our ML tasks
tse <- addAlpha(
    tse,
    assay.type = "counts",
    index = alpha_divs
)

Finally, we join the outcome of interest (i.e., diagnosis status or BMI) of each participant with the microbiome abundances and alpha diversities using preprocess_data(). By default, this function also centers and scales the features, removes features with near-zero variance and can collapse correlated features. These steps learn from all samples, including the test set, so we turn them off. Random forests do not need centered or scaled features.

# Settings that keep preprocess_data() from learning from all samples
prep_args <- list(
    method = NULL, remove_var = NULL,
    collapse_corr_feats = FALSE, prefilter_threshold = -1
)

# Preprocess data for classification
tse <- do.call(preprocess_data, c(list(
    dataset = tse,
    outcome_colname = "disease",
    assay.type = "relabundance",
    name = "prep_classification",
    col.var = alpha_divs # add these to the predictors
), prep_args))
##  Using 'disease' as the outcome column.
##  Adding preprocessed data to altExp(dataset, 'prep_classification').

# Preprocess data for regression
tse <- do.call(preprocess_data, c(list(
    dataset = tse,
    outcome_colname = "BMI",
    assay.type = "relabundance",
    name = "prep_regression",
    col.var = alpha_divs
), prep_args))
##  Using 'BMI' as the outcome column.
##  Removed 19/363 (5.23%) of samples because of missing outcome value (NA).
##  Adding preprocessed data to altExp(dataset, 'prep_regression').

# Training samples among the remaining samples (samples without BMI are
# removed)
train_idx <- which(colnames(tse) %in% train_samples)

preprocess_data() stores the result in an altExp if the set of features changes, otherwise as an assay. Here the alpha diversity indices become features, so the results are in the altExps “prep_classification” and “prep_regression”, and col.var is not needed in run_ml(). Samples without BMI are removed, which is why the training samples are looked up again by name.

NoteNote: Preprocessing strategies impact the performance of ML models.

Although microbiome data is compositional, proportion-based transformations —such as relative abundance or Hellinger— or even simpler approaches often outperform compositional transformations like CLR when building supervised ML models (Yerke et al. 2024). The authors note that the impact of the chosen transformations decreases as the signal-to-noise ratio increases. In other words, the more distinct the conditions we aim to classify, the less influence preprocessing transformations will have on model performance.

The aforementioned paper described the effect in both regression and classification tasks. A similar observations have also been done in other papers where they extensively compared different transformations in microbiome classification data (Karwowska et al. 2025; Giliberti et al. 2022). These papers suggest presence/absence being the preferred approach in supervised ML applications. Even though the papers benchmarked transformations only in classification, their findings are likely applicable to regression as well.

These studies were conducted with stool samples which contain many sources of biases as they serve as proxy for our main interest: the gut microbiome. This can explain why the simpler approaches are more robust and reproducible. Moreover, in addition to improving model performance, proportion or presence/absence-based transformations are more intuitive and therefore easier to interpret.

Given this, it is worth exploring different preprocessing approaches. The preprocess_data function from the mikropml package supports a variety of strategies described here. For a discussion in transformations methods, see OMA: Transformation.

Giliberti, Renato, Sara Cavaliere, Italia Elisa Mauriello, Danilo Ercolini, and Edoardo Pasolli. 2022. “Host Phenotype Classification from Human Microbiome Data Is Mainly Driven by the Presence of Microbial Taxa.” PLOS Computational Biology 18 (4): 1–22. https://doi.org/10.1371/journal.pcbi.1010066.
Karwowska, Zuzanna, Oliver Aasmets, Mait Metspalu, et al. 2025. “Effects of Data Transformation and Model Selection on Feature Importance in Microbiome Classification Data.” Microbiome 13 (1). https://doi.org/10.1186/s40168-024-01996-6.
Yerke, Aaron, Daisy Fry Brumit, and Anthony A. Fodor. 2024. “Proportion-Based Normalizations Outperform Compositional Data Transformations in Machine Learning Applications.” Microbiome 12 (1): 45. https://doi.org/10.1186/s40168-023-01747-z.

7.3 Model training

Now we can deploy supervised ML models on the preprocessed data. In this section, two algorithms will be covered:

  • Random Forest, for classification and regression
  • XGBoost, compared with random forest at the end of the chapter

These are within the most used supervised ML methods in the microbiome field. Possible reasons are that they can be used for classification and regression tasks, and that they show a good balance between performance and interpretability. Since the focus of this book is the implementation and interpretation of these models, other resources are suggested for an introduction to the mathematical underpinnings of these —and other— models (Gareth James 2013).

Gareth James, Robert Tibshirani, Trevor Hastie. 2013. An Introduction to Statistical Learning: With Applications in R. New York : Springer, [2013] ©2013. https://search.library.wisc.edu/catalog/9910207152902121.

To evaluate how well a model generalizes to new data, the data is split into a training set and a test set, commonly in an 80/20 ratio, as we did above. Other proportions can be used depending on the size of the dataset and the application.

Training is usually combined with cross-validation (Stone 1974) to make the model more robust. In K-fold cross-validation, the data is divided into K folds (subsets) of similar size. The model is trained on K-1 folds and validated on the remaining fold. This is repeated K times so that each fold serves as the validation set once (Figure 7.2).

Stone, M. 1974. “Cross-Validatory Choice and Assessment of Statistical Predictions.” Journal of the Royal Statistical Society: Series B (Methodological) 36 (2): 111–33. https://doi.org/10.1111/j.2517-6161.1974.tb00994.x.
Grid of tiles with five rows, one per iteration, and five fold columns plus a separate test-set column. In each row one fold, moving along the diagonal, is coloured as validation and the other four as training, while the test-set tile is coloured as test in every row.
Figure 7.2: 5-fold cross-validation. The data is first split into a training set (80%) and a test set (20%). The training set is divided into five folds. In each iteration, the model is trained on four folds and validated on the remaining fold. The test set is used only for the final evaluation.

When the dataset is small, splitting it into training and test sets might not be feasible. In such cases, cross-validation alone can provide a rough estimate of the model’s performance. While this approach is not as reliable as having a separate test set, it still indicates how well the model might perform on new data.

Random Forests (RF) (Breiman 2001) is an ensemble algorithm. That means that RF deploys and combines the outputs of multiple decision trees through majority voting or averaging the predicted numerical outcome. Since each tree is trained on a random subset of the data and features, RF reduces overfitting and enhance generalization to new data.

Breiman, Leo. 2001. “Random Forests.” Machine Learning 45 (1): 5–32. https://doi.org/10.1023/A:1010933404324.

We give run_ml() the training samples with training_frac, so that the model is trained on the same samples that were used in preprocessing. The remaining samples form the test set. See the documentation of mikropml for repeating the analysis with multiple splits.

7.4 Classification with random forest

When applied to classification problems, each tree predicts the class of an observation (e.g., healthy or T2D) based on the values of the features (e.g., taxonomic). Each tree finds the best split of the data by reducing how mixed the classes are, often using metrics like entropy or Gini impurity.

7.4.1 Training

Below, the RF algorithm is used for a classification task:

# Train random forest for classification
rf_classification <- run_ml(
    dataset = tse,
    method = "rf",
    outcome_colname = "disease",
    altexp = "prep_classification",
    assay.type = "prep_classification",
    seed = 1,
    kfold = 2,
    cv_times = 2,
    training_frac = train_idx,
    find_feature_importance = FALSE
)
##  Using 'disease' as the outcome column.
##  Using the custom training set indices provided by `training_frac`.
##        The fraction of data in the training set will be 0.79
##  Training the model...
##  Loading required package: lattice
##  
##  Attaching package: 'caret'
##  The following object is masked from 'package:future':
##  
##      cluster
##  The following object is masked from 'package:mikropml':
##  
##      compare_models
##  The following object is masked from 'package:mia':
##  
##      cluster
##  The following object is masked from 'package:generics':
##  
##      train
##  Training complete.

7.4.2 Performance

After the model is trained (i.e., learns patterns) on the training samples, the test samples, which the model has not seen, are used to assess how well the model generalizes the patterns it learned to new data.

# RF performance in classification tasks
rf_classification[["performance"]] |> knitr::kable()
cv_metric_AUC logLoss AUC prAUC Accuracy Kappa F1 Sensitivity Specificity Pos_Pred_Value Neg_Pred_Value Precision Recall Detection_Rate Balanced_Accuracy method seed
0.7435415 0.6367394 0.6784579 0.6742414 0.6338028 0.2627796 0.6666667 0.7027027 0.5588235 0.6341463 0.6333333 0.6341463 0.7027027 0.3661972 0.6307631 rf 1

A common metric to quickly assess model performance in binary classification tasks is the area under the receiver operator characteristic curve ‘AUC’. Notice that the result tables include two types of AUC metrics: cv_metric_AUC, which is the cross-validated AUC within the 80% of data used in training (each fold is predicted by a model that did not see it during fitting), and AUC, which is the AUC for the 20% used in testing. Both estimate performance on unseen data, so they should be similar. A cross-validation AUC that clearly exceeds the test AUC may indicate that the model selection overfitted the training set or that the test set differs from the training set. Small differences in either direction are expected by chance and thus shouldn’t be a concern.

Now let’s take a look at the results. The AUC values (cross-validation AUC = 0.744 and test AUC = 0.678) suggest a relatively good performance considering that predicting outcomes based on complex microbiome data is typically a challenging task. With a single, fairly small test set, the test AUC can differ from the cross-validation AUC by chance, in either direction.

Now let’s interpret our results at the light of previous research. In the largest multi-cohort analysis of gut microbiome associations with T2D published to date (Mei et al. 2024), authors trained RF models to discriminate healthy participants and T2D patients using microbiome and anthropometric variables like age, sex and BMI. Interestingly, they included the study we are working with in their analysis. Their reported AUC of 0.74 can be compared with ours. Comparable values would support the potential of the gut microbiome to discriminate between healthy individuals and T2D patients.

Although the tasks we addressed required binomial classification (i.e., classify sampples either as patients or controls), some research questions will require the classification of observations in more than just two groups, a task known as multiclass classification. For instance, we may have been interested in classifying patients as (1) healthy individuals, (2) T2D patients with obesity, and (3) T2D patients without obesity by integrating BMI information. In such cases, metrics like AUC (developed for binary classification) can be generalized. This metric is known as multiclass AUC, or One-vs-Rest AUC. This approach evaluates how well each class is distinguished from the others, enabling the assessment of model performance in multiclass problems. Multiclass classification can be implemented with run_ml too, as described here.

TipTip: Always use multiple performance metrics

Regardless of the type of classification task performed, it is often desirable to look at different metrics to accurately assess the model’s performance. This is particularly relevant in cases where classes are imbalanced. Suppose a dataset consists of 95% healthy individuals, and only 5% T2D patients. In such a case, a model can easily achieve 95% accuracy by just predicting (labelling) all samples as healthy, despite being useless for the classification of T2D patients.

This is an extreme case and hopefully we won’t encounter such situations. However, it highlights that class imbalance can lead to misleading interpretations of performance metrics like accuracy and AUC. Thus, when dealing with imbalanced classes, other metrics like F1-score and the area under the precision recall curve (prAUC), might be more appropriate.

In addition to relying in other performance metrics, different strategies for handling class imbalance datasets have been discussed (Papoutsoglou et al. 2023) and applied (Diez Lopez et al. 2022) in microbiome data analysis before.

Diez Lopez, Celia, Diego Montiel Gonzalez, Athina Vidaki, and Manfred Kayser. 2022. “Prediction of Smoking Habits from Class-Imbalanced Saliva Microbiome Data Using Data Augmentation and Machine Learning.” Frontiers in Microbiology 13. https://doi.org/10.3389/fmicb.2022.886201.
Papoutsoglou, Georgios, Sonia Tarazona, Marta B. Lopes, et al. 2023. “Machine Learning Approaches in Microbiome Research: Challenges and Best Practices.” Frontiers in Microbiology 14. https://doi.org/10.3389/fmicb.2023.1261889.

7.4.3 Visualization

The area under the receiver-operator characteristic (ROC) curve, also called ‘AUC’ was introduced before as common metric to assess model’s performance in binary classification tasks. As it name suggests, AUC is just the area under a curve. Since different ROC curves can have similar AUC, visualizing the curve can give complementary information.

Complementary to ROC curves, the precision-recall curves (PRC) are preferred in datasets with class imbalance, where AUC can be misleading, as discussed above.

The code below is used to calculate the metrics required to generate both curves:

# calc_model_sensspec() treats the first class level of the model as the
# positive class. The levels are in alphabetical order (healthy, T2D), so we
# reorder them to make T2D the positive class.
pos_class <- "T2D"
model_t2d <- rf_classification[["trained_model"]]
model_t2d[["levels"]] <- c(pos_class, setdiff(model_t2d[["levels"]], pos_class))

# Calculate RF model metrics required for plotting
senspec <- calc_model_sensspec(model_t2d, rf_classification[["test_data"]])
##  Using 'disease' as the outcome column.
# Add model label to data
senspec$model <- "rf"

# Inspect part of the output
senspec |>
    head() |>
    knitr::kable()
T2D healthy actual tp fp sensitivity fpr specificity precision model
T2D-050 0.798 0.202 T2D 1 0 0.0294118 0 1 1 rf
T2D-083 0.758 0.242 T2D 2 0 0.0588235 0 1 1 rf
T2D-026 0.710 0.290 T2D 3 0 0.0882353 0 1 1 rf
T2D-092 0.688 0.312 T2D 4 0 0.1176471 0 1 1 rf
T2D-089 0.680 0.320 T2D 5 0 0.1470588 0 1 1 rf
T2D-017 0.674 0.326 T2D 6 0 0.1764706 0 1 1 rf

The metrics ‘Sensitivity’ and ‘Specificity’ are used in ROC curves, and ‘Sensitivity’ and ‘Precision’ are used in PRC curves. Note that ‘Sensitivity’ and ‘Recall’ are the same metric. While the term ‘Sensitivity’ is preferred in the biomedical literature, ‘Recall’ is more prevalent in other fields. ‘Precision’, also called positive predictive value, is the proportion of samples predicted as positive that are truly positive.

The code below generates the ROC and PRC curves and shows them side by side (Figure 7.3):

Show the plotting code
library(patchwork)

# 1. Plot the ROC curve
roc_p <- ggplot(data = senspec) +
    geom_path(aes(x = fpr, y = sensitivity, color = model))
# 1.1 Add line representing 'random guess' performance
roc_p <- roc_p +
    geom_abline(color = "grey30", linetype = "dashed")
# 1.2 Add axis titles and custom theme
roc_p <- roc_p +
    labs(x = "FPR or (1 - Specificity)", y = "Sensitivity", title = "ROC") +
    theme_bw()


# 2. Plot the PRC curve
prc_p <- ggplot(data = senspec) +
    geom_path(aes(x = sensitivity, y = precision, color = model))
# 2.1 Add line representing 'random guess' performance, which is the
# proportion of the positive class in the test data
baseline <- mean(rf_classification[["test_data"]][["disease"]] == pos_class)
prc_p <- prc_p +
    geom_hline(color = "grey30", linetype = "dashed", yintercept = baseline)
# 2.2 Add axis titles and custom theme
prc_p <- prc_p +
    labs(x = "Recall or Sensitivity", y = "Precision", title = "PRC") +
    theme_bw()


# 3. Plot ROC and PRC side by side
roc_p + prc_p + plot_layout(guides = "collect")
Two side-by-side line plots. The left ROC panel plots sensitivity against false positive rate with a dashed diagonal line, and the right precision-recall panel plots precision against recall with a dashed horizontal line at the proportion of T2D patients in the test set.
Figure 7.3: ROC curve (left) and precision-recall curve (right) of the random forest model classifying T2D patients and healthy individuals in the QinJ_2012 test data. Dashed grey lines show the expected performance of random guessing.

Before describing the plots and their meaning, it is worth noting that the ROC curve resembles the curve presented in the article where this dataset was first analyzed (Qin et al. 2012) (see Figure 4B). Interestingly, authors used other supervised ML algorithm, and it was trained in a set of 50 microbiome genes (instead of taxonomic features and alpha diversity metrics, as we did). However, it is interesting that concordant AUCs and ROC curves shapes were obtained using different microbiome-derived information.

Regarding our figures, note the dashed gray lines in both plots representing the expected performance of a model that is classifying samples randomly. In the PRC plot, this is the proportion of the positive class (T2D) in the test data, here 0.48. Therefore, the greater the distance between that reference and the line representing our model’s performance, the better. Thus, perfect performance will be achieve when the line is the farthest from that reference.

In our example, a model with perfect performance is such that, by learning patterns from the microbiome data, it can correctly identify T2D patients with perfect sensitivity (i.e., all T2D patients are classified as such) while maintaining a false positive rate (FPR) of 0 (i.e., no healthy individual is misclassified as T2D). In the ROC plot, this means the model consistently achieves a Sensitivity of 1 and a FPR of 0, pushing the curve towards the top left corner.

In terms of the PRC plot, the perfect model would consistently achieve a Recall and Precision of 1, pushing the curve towards the top right corner. That, in turn, would mean that the model has perfect Sensitivity (i.e., all T2D patients are classified as such), while maintaining a perfect Precision (i.e., every individual classified as T2D is actually a T2D patient).

NoteNote: Visualization of multiclass ROC curves

It was discussed above that ROC curves (and AUCs) can be extended to multiclass classification tasks. One example of such approach is this article (Su et al. 2022) where authors used gut microbiome data to train different classification supervised ML algorithms to discriminate between patients of 9 different diseases. Notice that the visualization of multiclass ROC curves can be achieved in a similar way to what was described in this chapter. In addition, the R package pROC (Robin et al. 2011) provides handy functions to build multiclass visualizations.

Robin, Xavier, Natacha Turck, Alexandre Hainard, et al. 2011. “pROC: An Open-Source Package for R and S+ to Analyze and Compare ROC Curves.” BMC Bioinformatics 12: 77. https://doi.org/10.1186/1471-2105-12-77.
Su, Qi, Qin Liu, Raphaela Iris Lau, et al. 2022. “Faecal Microbiome-Based Machine Learning for Multi-Class Disease Diagnosis.” Nature Communications 13 (1). https://doi.org/10.1038/s41467-022-34405-3.

7.4.4 Model interpretation

Besides the performance of the model, researchers are often interested in understanding what are the features that are affecting the model’s performance, a property of ML models called interpretability.

ML models have different degrees of interpretability. One way to understand how different features (e.g., taxonomic identity) affect model’s performance is by randomly permuting the values of that feature across samples and then evaluating the amount of change in a performance metric.

The code below shows how to determine feature importance for the RF model trained for classification. Minimal changes are required to determine feature importance for the other models in this chapter, like the RF model used in regression. The ten most important features are shown in Figure 7.4.

# estimate features importance
feat_imp <- get_feature_importance(
    trained_model = rf_classification[["trained_model"]],
    test_data = rf_classification[["test_data"]],
    outcome_colname = "disease",
    perf_metric_function = multiClassSummary,
    perf_metric_name = "AUC",
    class_probs = TRUE,
    method = "rf",
    seed = 1,
    nperms = 5 # 1/20 of default to speed calculations up
)

# Identify the 10 most important features
ordered_features <- order(feat_imp$perf_metric_diff, decreasing = TRUE)
ordered_features <- ordered_features[1:10]

# Retain only those features
feat_imp <- feat_imp[ordered_features, ]

# Conver column 'feat' into a factor to fix its order in the plot
feat_imp$feat <- factor(feat_imp$feat, levels = rev(feat_imp$feat))

# Plot mean feature importance
ggplot(feat_imp) +
    geom_col(aes(x = perf_metric_diff, y = feat)) +
    labs(x = "Decrease in performance", y = "Feature") +
    theme_classic()
Horizontal bar chart of ten taxonomic features (y-axis) ordered by their decrease in model performance (x-axis), with the most important feature at the top.
Figure 7.4: The ten most important features of the random forest model classifying T2D patients and healthy individuals in the QinJ_2012 data, measured as the decrease in test AUC when the values of each feature are permuted.

This plot shows the features with the highest effect on model’s performance. In other words, which features have most of the information required to differentiate between healthy participant and T2D patients. However, note that the differences in model performance are very close to zero, which indicates a small contribution of each taxonomic feature in allowing the model to distinguish between groups.

Interestingly, our results are coherent with what authors of the original analysis reported (Qin et al. 2012). They report several Clostridium representatives enriched in the T2D patients (see Figure 2A), and the two most important features of our model, [Clostridium] innocuum and Erysipelatoclostridium ramosum (formerly Clostridium ramosum), belong to this group. Clostridium was also reported as having the largest differences in the mean abundances between groups (Mei et al. 2024) (see Figures 2A and 2B). Note that the ranking of features can change with the data split and the random seed.

Qin, Junjie, Yingrui Li, Zhiming Cai, et al. 2012. “A Metagenome-Wide Association Study of Gut Microbiota in Type 2 Diabetes.” Nature 490: 55–60. https://doi.org/10.1038/nature11450.
Mei, Zhendong, Fenglei Wang, Amrisha Bhosle, et al. 2024. “Strain-Specific Gut Microbial Signatures in Type 2 Diabetes Identified in a Cross-Cohort Analysis of 8,117 Metagenomes.” Nature Medicine 30 (8): 2265–76. https://doi.org/10.1038/s41591-024-03067-7.
ImportantImportant: A call to avoid oversimplifications

Feature importance plots are often interpreted in the literature with a reductionist mindset. Thus, researchers often conclude that a single feature is responsible of a complex clinical output of interest. However, more often than not, microbes interact with one another, and thus the effect of a single taxonomic feature doesn’t always inform about ecosystem-level properties of the microbiome. It is important to bear that in mind when interpreting the results of our models.

7.5 Regression with random forest

For regression tasks, each tree predicts a numerical outcome (e.g., BMI) based on the values of the features (e.g., taxonomic). Each tree split the data to minimize the difference between predicted and real (observed) values, often using metrics like mean squared error (MSE). One strength of RF is that it can learn non-linear patterns in the data that simpler regression algorithms might not capture.

7.5.1 Training

Regarding its implementation, note that just by changing the outcome from a categorical to a continuous variable, RF models can now be used in regression tasks:

# Train random forest for regression
rf_regression <- run_ml(
    dataset = tse,
    method = "rf",
    outcome_colname = "BMI",
    altexp = "prep_regression",
    assay.type = "prep_regression",
    seed = 1,
    kfold = 2,
    cv_times = 2,
    training_frac = train_idx,
    find_feature_importance = FALSE
)
##  Using 'BMI' as the outcome column.
##  Using the custom training set indices provided by `training_frac`.
##        The fraction of data in the training set will be 0.79
##  Training the model...
##  Training complete.

7.5.2 Performance

When RF are used in regression tasks, the performance metrics are different to what was discussed for classifications.

# RF performance in regression tasks
rf_regression[["performance"]] |> knitr::kable()
cv_metric_RMSE RMSE Rsquared MAE method seed
3.488552 3.432807 0.1269172 2.673672 rf 1

A commonly used metric to quickly assess model performance in regression tasks is the root mean square error (RMSE). As its name suggests, this metric is just the root of the mean squared difference between the observed and predicted values of the outcome variable (patient’s BMI in this example).

Similarly to AUC in classification, the results table include two types of RMSE metrics: cv_metric_RMSE, which is the cross-validated RMSE within the training data, and RMSE, which is the metric for the test data. The cross-validation (3.489) and test (3.433) RMSE are similar. As discussed in the classification results, a clearly worse test performance would suggest overfitting, which doesn’t seem to be the case here. However, this does not tell whether the predictions are useful. For that, we compare the model with a null model that predicts the mean BMI of the training samples for every test sample.

# BMI of the training and test samples
train_bmi <- colData(tse)[train_idx, "BMI"]
test_bmi <- rf_regression[["test_data"]][["BMI"]]

# RMSE of the null model in the test data
null_rmse <- sqrt(mean((test_bmi - mean(train_bmi))^2))
null_rmse
##  [1] 3.598795

7.5.3 Visualization

In this chapter RF was used to learn patterns in the gut microbiome to predict the BMI of the participants. The most used diagnostic visualization of model’s performance is to compare observed against predicted BMI values.

The code below is used to generate that plot using the observations in the test data (Figure 7.5).

# Get the test set: data not used in training the model
test_data <- rf_regression[["test_data"]]

# Get the trained model
model <- rf_regression[["trained_model"]][["finalModel"]]

# Use the model to predict BMI values in the test set
pred <- predict(model, test_data)

# Add predicted BMI values to the test dataset
test_data$pred <- pred
# Add diagnosis status to test data.
# This variable was created when preprocessing for classification
ids <- rownames(test_data)
test_data$disease <- colData(tse)[ids, "disease"]

table(test_data$disease)
##  
##      T2D healthy 
##       34      37

# Plot actual (y-axis) vs predicted (x-axis) BMI values
obs_vs_pred <- ggplot(data = test_data) +
    geom_point(aes(x = pred, y = BMI, color = disease), size = 2)
# Add line showing perfect prediction
obs_vs_pred <- obs_vs_pred + geom_abline(color = "grey30", linetype = "dashed")
# Make axes of same scale, covering all observed and predicted values
lims <- range(c(test_data$pred, test_data$BMI))
obs_vs_pred <- obs_vs_pred + coord_equal(xlim = lims, ylim = lims)
# Custom axes titles
obs_vs_pred <- obs_vs_pred + labs(x = "Predicted BMI", y = "Observed BMI")
# Add custom theme and visualize the plot
obs_vs_pred + theme_bw()
Scatter plot of predicted BMI (x-axis) against observed BMI (y-axis) on equal scales covering all observed and predicted values, with points coloured by disease status and a dashed diagonal line marking perfect prediction.
Figure 7.5: Observed versus random forest-predicted BMI in the QinJ_2012 test data, coloured by disease status. The dashed grey line shows perfect prediction.

The dashed gray line in the plot above represents a perfect correlation between the observed and the model-predicted BMI values of each participant. Thus, the line indicates perfect performance of the model. We can see that while the predictions are around the mean BMI (close to 23), the observed values range approximately between 17 and 38, showing poor correlation between observed and predicted BMI values. Note that both groups show a similar spread in BMI.

This plot clearly indicates a poor performance of our model. This usually means that either the gut microbiome is not related to BMI, making it impossible for the model to use microbiome patterns to predict it, or that our model is overfitted. The similar cross-validation and test RMSE suggest that the model is not overfitted. Moreover, the test RMSE of the model (3.433) is not much better than that of the null model (3.599). Thus, in this dataset the gut microbiome composition, as used here, seems to carry little information about BMI.

This illustrate another important aspect of supervised ML. Regardless of the complexity of the models deployed, their predictive performance depends in their ability to learn meaningful patterns from the data. If such patterns don’t exist it would be impossible for the model to make accurate predictions. This is most likely what happened in this regression task. Notice that this can certainly happen in classification tasks too.

7.6 Random forest vs XGBoost

Extreme Gradient Boosting (XGBoost) (Chen and Guestrin 2016) is another ensemble algorithm where decision trees are sequentially built. In this strategy, each new tree improves the performance of the previous.

Chen, Tianqi, and Carlos Guestrin. 2016. “XGBoost: A Scalable Tree Boosting System.” Proceedings of the 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining, KDD ’16, 785–94. https://doi.org/10.1145/2939672.2939785.

When applied to classification, each tree predicts the class of an observation (e.g., healthy or T2D) based on feature values (e.g., taxonomic). However, instead of ‘voting’ like in Random Forest, XGBoost adds the predictions of the trees. Each new tree is fitted to the gradient of the loss function (for squared error loss, the residuals) of the current ensemble, so that it corrects the errors of the previous trees.

It must be noted that XGBoost is a more complex model usually described as one of the best performing models for tabular data (Shwartz-Ziv and Armon 2022), such as the count tables used in microbiome data analysis.

Shwartz-Ziv, Ravid, and Amitai Armon. 2022. “Tabular Data: Deep Learning Is Not All You Need.” Information Fusion 81: 84–90. https://doi.org/https://doi.org/10.1016/j.inffus.2021.11.011.
NoteNote: XGBoost is currently not run

The code in this section is not run, because the current versions of xgboost (3.x) and caret, which mikropml uses, are not compatible. It works with xgboost 1.7.

The XGBoost model is trained in the same way as the random forest, only the method changes:

# Train XGBoost for classification
xgb <- run_ml(
    dataset = tse,
    method = "xgbTree",
    outcome_colname = "disease",
    altexp = "prep_classification",
    assay.type = "prep_classification",
    seed = 1,
    kfold = 2,
    cv_times = 2,
    training_frac = train_idx,
    find_feature_importance = FALSE
)

# Compare the performance of the two models
rbind(
    RF = rf_classification[["performance"]],
    XGBoost = xgb[["performance"]]
) |>
    knitr::kable()

# Compare ROC curves: combine the metrics of both models and plot them
# with the code used for the random forest above
xgb_model <- xgb[["trained_model"]]
xgb_model[["levels"]] <- model_t2d[["levels"]] # T2D as the positive class
xgb_senspec <- calc_model_sensspec(xgb_model, xgb[["test_data"]])
xgb_senspec$model <- "XGBoost"
senspec <- rbind(senspec, xgb_senspec)

Comparing the AUC values and the ROC curves of the two models shows whether the more complex XGBoost model performs better than RF on this task. Often their performance is similar. This illustrates an important point in ML: sometimes simpler models can perform as good as more complex ones. Thus, it is often a good idea to deploy different models and compare their performance on the same task.

Although not demonstrated in this chapter, XGBoost can be used in regressions tasks using similar code to the one shown above. The only difference will be the outcome variable selected. See the RF example as a reference.

TipExercises

Goal: After completing these exercises, you should be able to fit supervised machine learning model to microbiome data.

Exercise 1: Supervised ML

  1. Load any of the example datasets mentioned in OMA: Open data resources.

  2. Observe colData and check that the metadata includes outcome variables that you want to model.

  3. Visualize the selected outcome variable with a histogram if it is continuous, or a bar plot if it is categorical. What is the distribution? If the distribution is biased, how can this affect the training of the model?

  4. Apply a transformation, such as relative abundance or presence/absence (see the note on preprocessing strategies above).

  5. Split the samples into training and test sets. Filter the features using only the training samples, and preprocess the data without steps that learn from all samples.

  6. Fit a random forest model with find_feature_importance = TRUE.

  7. Visualize results. Do the model perform well by predicting the outcome with a high accuracy?

  8. What features are the most important for predicting the outcome?

Useful functions:

utils::data(), SummarizedExperiment::colData(), miaViz::plotHistogram(), miaViz::plotBarplot(), mia::getPrevalence(), mia::transformAssay(), mikropml::preprocess_data(), mikropml::run_ml(), mikropml::plot_model_performance()

Back to top