Skip to Content
  • Article
  • Open Access

20 November 2026

27 Pages

LiteMicroFormer: A Lightweight Attention-Guided Transformer with Adaptive Cluster Under-Sampling for Metagenomic Disease Prediction

,
,
,
and
1
Department of Computer Science and Engineering, American International University-Bangladesh (AIUB), Dhaka 1229, Bangladesh
2
Department of Electrical Engineering and Computer Science, Texas A&M University-Kingsville, Kingsville, TX 78363, USA
3
Institute for Advanced Computing, Virginia Polytechnic Institute and State University (Virginia Tech), Blacksburg, VA 24061, USA
4
Department of Computer Science, College of Computer and Information Sciences, King Saud University, Riyadh 11543, Saudi Arabia
This article belongs to the Section Molecular Microbiology

Abstract

High-dimensional microbial abundance profiles, limited sample sizes, and severe class imbalance make accurate disease prediction from human gut metagenomics challenging. To address these limitations, we propose LiteMicroFormer, a lightweight attention-guided transformer framework for disease-specific binary classification using species-level microbiome profiles and metadata. LiteMicroFormer embeds species values, applies feature-gating attention, extracts microbial representations through a transformer, fuses metadata, and uses attention pooling to capture informative low-complexity patterns. To handle majority-class imbalance, the framework integrates AGACUS (Attention-Guided Adaptive Cluster Under-Sampling), which selectively downsamples majority instances using model uncertainty, attention relevance, and cluster diversity while preserving all minority disease samples. Evaluated using repeated subject-level partitions across four binary tasks (Healthy vs. Obesity, IBD, Cirrhosis, and CRC) over five random seeds, LiteMicroFormer achieved accuracies of 0.9321 , 0.9606 , 0.8553 , and 0.9417 , alongside ROC-AUC scores of 0.9743 , 0.9796 , 0.9205 , and 0.9719 , respectively. These results demonstrate strong internal predictive performance, while independent cross-cohort generalizability remains to be established. SHAP analysis was performed on learned latent representations to examine their contributions to model predictions, providing model-level explanations without claiming validated species-level biological interpretability.

1. Introduction

The human gut microbiome, containing trillions of microorganisms that reside inside the gastrointestinal tract, has emerged as a key factor in determining host health and disease [1,2]. The gut microbiota has demonstrated considerable potential to influence complex diseases, such as inflammatory bowel disease (IBD) and colorectal cancer (CRC), through large scale meta-analysis studies [3]. In particular, metabolome and microbiome analysis studies have shown that the disruption of the microbiome–metabolome interaction is a sign of the pathogenesis of CRC, and can be used as potential non-invasive markers for early detection [4]. Machine learning analysis of 870 human stool metagenomes from five countries has validated that the gut microbiome is a significant contributor to obesity, and found region-specific microbial markers for obesity [5]. Thus, there has been a growing interest in the use of computational methods to accurately predict disease from metagenomic data.
Although the clinical potential of gut microbiome data is of great promise, computational analysis is fraught with significant challenges. Microbiomic data are high-dimensional with more taxonomic features than samples, highly sparse with many data near zero, and compositional in that the abundance of one feature is directly correlated to the abundance of other features in the same sample [1,6]. These compositional effects result in artificial correlations, which leads to difficulties in statistical modelling and normalization [6]. Furthermore, the high dimensionality of metagenomic data and the complexity of computational analysis can make the extraction of meaningful biological insights challenging [1]. In real-world clinical cohorts, it is also typical to experience significant class imbalance between healthy controls and specific diseases, with the healthy individuals generally outnumbering the diseased. These natural challenges require strategic, computational approaches to overcome, and to gain clinically useful information from microbial sequencing data that extends beyond the capabilities of classic statistical solutions.

1.1. Motivation and Proposed Approach

In addressing these challenges, a number of machine learning and deep learning strategies have been suggested for metagenomic disease prediction. Moderate success has been yielded with traditional machine learning, for instance, Liu et al. [5] achieved an AUC of 0.85 for obesity, and Bakir-Gungor et al. [7] obtained an AUC of 0.98 with respect to IBD. Recent research has looked into deep learning architectures. Qureshi et al. [8] proposed an attention mechanism-based CNN architecture called MetaResNet. There are also transformer-based models that have been introduced, such as MSFT-Transformer by Wang et al. [9] with high IBD performance and poor obesity classification results, and MicroHDF by Shi et al. [10] that is a deep forest model with competitive IBD and cirrhosis performance but lower obesity classification performance. However, current methods have limitations: traditional ML methods may be limited in capturing complex nonlinear dependencies, graph-based approaches require suitable graph representations, CNN architectures may introduce substantial computational overhead, and transformer-based methods can exhibit inconsistent performance across disease-classification tasks. Moreover, none of them are able to effectively incorporate metadata and handle class imbalance by using model-based sampling.
To address the aforementioned limitations, this paper proposes the LiteMicroFormer framework with two key innovations. The first approach, Attention-Guided Adaptive Cluster Under-Sampling (AGACUS), aims to minimize class imbalance by selectively retaining informative Healthy samples based on uncertainty, attention relevance, and diversity scores obtained from a warm-up model, while removing less informative majority-class samples. Second, LiteMicroFormer is a lightweight transformer architecture, with 60,516 trainable parameters in the representative configuration, designed to compactly model inter-species relationships via a self-attention mechanism. The model features a noisy microbial signal suppression mechanism in the form of a feature attention gate and a sample-level information fusion mechanism in the form of a metadata encoder, which fuse sample-level information such as age, gender, country. This compact design preserves the benefits of transformer-based representation learning while maintaining a lightweight architecture for metagenomic disease prediction. The key contributions of this paper are twofold:
  • AGACUS: We propose an Attention-Guided Adaptive Cluster Under-Sampling (AGACUS) strategy that addresses class imbalance by selecting informative Healthy samples using model uncertainty, attention relevance, and cluster diversity. Unlike conventional model-independent sampling, AGACUS preserves all disease samples while adaptively retaining representative and decision-relevant majority samples.
  • LiteMicroFormer: We introduce LiteMicroFormer, a lightweight transformer with only 60,516 trainable parameters that jointly captures disease-relevant microbial features and inter-species relationships. It integrates species-aware representations, feature attention gating, attention-based encoding and pooling, and auxiliary metadata fusion within a compact architecture for metagenomic disease prediction.

1.2. Related Work

The human gut microbiome has become an important factor in host health, impacting physiological, immune and metabolic functions [11]. Metagenomic sequencing enables high-resolution taxonomic abundance profile, thereby providing a non-invasive approach to biomarker development for disease [12]. But analyzing metagenomic data still has a number of pitfalls. Researchers face the challenge of high-dimensional feature spaces where the number of microbial taxa is far more than the number of samples, extreme data sparsity and reference database biases [13]. The complex nature of sequencing data, due to the sequential abundance of each of the taxa, leads to spurious correlations that makes statistical modeling difficult [11]. Moreover, in a real-world cohort, the disease cases and healthy controls have often significant class imbalance, as in the present study [14]. These inherent complexities require the development of advanced computational approaches that can go beyond conventional statistical analyses to uncover clinically relevant knowledge and insights from microbial sequencing data [12].
The initial approaches to metagenomic disease prediction were predominantly based on classic machine learning and search-based methods. A search-based approach for health status detection based on species-level profiles was proposed by Chen and Su [15], and reported moderate performance with an AUC of 0.65 for inflammatory bowel disease (IBD) and 0.79 for colorectal cancer (CRC) which is significantly lower than the more recent deep learning methods. To overcome the limitations of shallow models, ensemble and graph-based deep learning architectures were introduced. Recently, Shen et al. [16] proposed an ensemble deep learning model called EnsDeepDP, which fused several neural networks to overcome the overfitting problem in high-dimensional microbiome data; they achieved an AUC score of 0.723 for obesity and an AUC score of 0.858 for IBD. The ensemble architecture, however, required a huge computational cost and there was still potential to improve on more complex disease tasks. Liao et al. [17] introduced a graph convolutional network (GCN) using a deep adaptation network to classify the host disease status, with high AUC on cirrhosis (0.968) and IBD (0.936). However, graph-based methods might not be efficient in the large dimensions of the species features, and the obesity (0.741) and CRC (0.923) solutions from GDmicro indicate that the results may vary across different disease contexts. In the case of CRC, Bakir-Gungor et al. [18] used random forest at the species, enzyme and pathway levels with an AUC of 0.83, which shows usefulness of traditional ML methods, but still not as good as more advanced architectures. As discussed by Roy et al. [11], the interpretability and generalization of deep learning techniques across various cohorts to achieve clinical utility continue to be unaddressed challenges in the field of metagenomic analysis, despite their progress in solving sparsity and compositionality issues.
Recently, transformer architectures have been popular in the field of metagenomic disease prediction because of their ability to model inter-species dependencies via self-attention. Using strong IBD performance (AUC 0.974) and weak obesity classification (AUC 0.677), Wang et al. [9] proposed MSFT-Transformer that has poor task generalization. Alternatively, Shi et al. [10] developed a deep forest framework called MicroHDF, with competitive AUCs of 0.9182 for IBD, 0.9469 for cirrhosis, but a lower AUC of 0.7664 for CRC, which suggests that deep forest approaches might not be well-suited for some disease signatures. Roy et al. [19] demonstrated the use of MetagenBERT, a method that uses genomic large language models (DNABERT-2 and DNABERT-MS) to generate embeddings for each read without relying on prior annotations, leading to competitive AUC across various disease tasks. However, raw sequencing reads require significant amounts of computational effort for processing, and clustering may result in loss of species-level resolution. Likewise, Generanno is a large 500-million-parameter transformer for metagenomic annotation (Li et al. [20]), which is restricted to gene annotation and has a large parameter size, making it unsuitable for clinical applications. The application field of pathogen identification is different from host phenotype classification, with Peng et al. [21] proposing TCINet to enhance pathogen identification. Although these contributions are all advances, none of them have tackled adaptive metadata integration, adaptive model-guided class imbalance correction, and a lightweight parameter based model at the same time.
A remaining challenge in metagenomic disease prediction is the class imbalance between disease cases and healthy controls. Moon et al. [22] extended the idea of propensity score matching to the borderline-SMOTE for classification of CRC and obesity, but synthetic oversampling can produce microbial profiles that are not real community structures. Traditional ML methods without attention mechanisms were used in a study on prediction of IBD (91% F1-score with explicit handling of imbalance) [23]. Zhou et al. [24] showed that the classification accuracy is boosted by 15–30% for CRC, IBD and obesity tasks when using doppelgänger bias, but reported their findings from an observational study without recommending mitigation. An alternative to SMOTE is KDE-based sampling [25], which has not been validated on the gut metagenomic data. Although those developments have been achieved, the reviewed approaches provide limited consideration of model-guided uncertainty for selecting informative Healthy samples. This motivates further investigation of uncertainty-aware majority-class selection in metagenomic disease prediction.
Existing metagenomic methods exhibit three major limitations: traditional ML approaches are less effective for high-dimensional and sparse data [15]; transformer-based methods are often computationally demanding or provide limited model guidance and metadata integration [9,10]; and existing class-imbalance strategies are largely model-independent, limiting their ability to preserve samples that are informative for disease prediction [22,24]. These limitations reveal key research gaps in model-guided imbalance handling, efficient representation of complex microbial relationships, and effective integration of microbiome features with auxiliary metadata. To address these gaps, this paper introduces an integrated framework combining AGACUS and LiteMicroFormer. AGACUS selectively retains informative healthy samples based on uncertainty, attention relevance, and diversity scores obtained from a warm-up model. LiteMicroFormer employs a lightweight transformer to capture inter-species relationships, suppress less informative signals through feature attention gating, and integrate microbiome representations with metadata. Together, these components provide an efficient framework for disease prediction across Obesity, IBD, Cirrhosis, and CRC-related classification tasks.
The remainder of this paper is organized as follows. Section 2 presents experimental results, comparisons, ablation studies, and SHAP analysis. Section 3 discusses the principal findings, methodological implications, interpretability, and limitations of the study. Section 4 describes the materials and methods, including AGACUS and LiteMicroFormer. Section 5 concludes the paper.

2. Results

This section details the experimental assessment of the proposed LiteMicroFormer framework on four metagenomic classification tasks specific to disease. The results are evaluated with respect to their predictive performance, their stability of training, their class-discriminative capability and their robustness with respect to multiple random seeds. Moreover, the behaviour of the proposed model is also studied using visual analyses based on loss curve, confusion matrix and ROC-AUC characteristics.
The performance of LiteMicroFormer for the classification tasks of Healthy vs. Obesity, Healthy vs. IBD, Healthy vs. Cirrhosis and Healthy vs. CRC-related is shown in Table 1 for five independent random seeds. Among the four tasks, Healthy vs. IBD achieved the strongest overall performance, obtaining an accuracy of ( 0.9606 ± 0.0138 ) , recall of ( 0.9598 ± 0.0722 ) , macro-F1 of ( 0.9291 ± 0.0272 ) , and ROC-AUC of ( 0.9796 ± 0.0116 ) . These results indicate that LiteMicroFormer achieved strong discriminative performance for the IBD classification task under the repeated subject-level evaluation protocol.
Table 1. Performance of the proposed LiteMicroFormer model across four disease-specific tasks.
Similarly, LiteMicroFormer achieved high discriminative performance for Healthy vs. Obesity and Healthy vs. CRC-related classification, yielding ROC-AUC scores of ( 0.9743 ± 0.0040 ) and ( 0.9719 ± 0.0080 ) , respectively. In contrast, the Healthy vs. Cirrhosis task produced comparatively lower performance, with an accuracy of ( 0.8553 ± 0.0580 ) , macro-F1 of ( 0.7421 ± 0.0680 ) , and ROC-AUC of ( 0.9205 ± 0.0341 ) . However, LiteMicroFormer achieved a disease recall of ( 0.8000 ± 0.0497 ) for the Cirrhosis classification task. Overall, the results show variation in classification performance across the evaluated disease tasks, with Cirrhosis exhibiting comparatively lower performance.
The accuracy distributions over 5 random seeds are shown in Figure 1. The distributions of obesity, IBD-related tasks and CRC-related tasks are relatively compact, suggesting good consistency and repeatability. The Cirrhosis task has a broader range of scores, reflecting its higher standard deviation and poorer overall classification scores. The results further corroborate the idea of Cirrhosis being the most difficult of the disease settings to classify.
Figure 1. Accuracy distribution of LiteMicroFormer across five random seeds for four disease-specific classification tasks. Colors distinguish the tasks; solid lines indicate medians, dashed orange lines indicate means, boxes represent interquartile ranges, whiskers show the non-outlier spread, and blue points represent individual seed accuracies.
Figure 2 presents the mean confusion matrices across five random seeds, with each entry reporting the mean and standard deviation of predictions per test run rather than pooled subject counts. LiteMicroFormer correctly classified most Healthy and disease samples across all four tasks, with particularly few disease-class misclassifications for IBD and CRC-related classification. Cirrhosis exhibited more false-positive predictions (19.2 ± 9.7 per run) and lower disease sensitivity, contributing to its comparatively weaker classification performance. Overall, the results indicate effective disease discrimination across repeated internal evaluations, although performance varied across tasks and random seeds.
Figure 2. Mean confusion matrices across five random seeds for four disease classification tasks. Values represent mean ± SD per test run, rather than pooled counts of unique subjects.
The curves of training and validation loss over the various tasks evaluated are shown in Figure 3. In all scenarios, both losses converge and decrease gradually during training, indicating progressive optimization of the model parameters. The training loss generally declines as the number of epochs increases, while the validation loss follows a comparable downward trajectory, reflecting improvements in model fitting across the two data partitions. Although the loss values and convergence patterns vary among the four disease classification tasks, the curves generally exhibit a reduction in loss during the initial training stages, followed by smaller changes as training progresses. The relatively small differences between training and validation losses indicate comparable optimization behavior across the two partitions, without pronounced divergence during training. These observations suggest that the optimization process reaches relatively stable loss values across the evaluated tasks.
Figure 3. Training and validation loss curves of the proposed LiteMicroFormer framework across four disease-specific classification tasks. Solid lines represent mean losses across five random seeds, while shaded regions indicate variability of ± 1 standard deviation.
Figure 4 illustrates the mean ROC curves across five random seeds, highlighting the discriminative performance of LiteMicroFormer across four disease classification tasks. The mean ROC-AUC values were 0.9743 ± 0.0040 , 0.9796 ± 0.0116 , 0.9205 ± 0.0341 , and 0.9719 ± 0.0080 for Obesity, IBD, Cirrhosis, and CRC-related classification, respectively. The results indicate strong discrimination between Healthy and disease samples, with comparatively greater variability observed for Cirrhosis. Overall, these findings demonstrate consistent predictive performance across repeated internal evaluations.
Figure 4. Mean ROC curves across five random seeds for four disease classification tasks. Solid lines represent mean ROC curves, shaded regions indicate ± 1 SD, and faint lines show individual seed curves. ROC-AUC is reported as mean ± SD.
The comparison of sampling strategies is provided in Table 2 with the fixed LiteMicroFormer architecture. The proposed AGACUS consistently outperformed the other sampling strategies across all four disease-classification tasks, achieving ROC-AUC values of 0.9743, 0.9796, 0.9205, and 0.9719 for Obesity, IBD, Cirrhosis, and CRC-related classification, respectively. The four tasks showed improvements in ROC-AUC of 0.1623, 0.1346, 0.1855 and 0.1469 with AGACUS compared to no sampling. AGACUS also performed better than Random Under-Sampling and SMOTE, with higher ROC-AUC values across all four tasks. Among the evaluated methods, AGACUS achieved the highest ROC-AUC for each disease- classification task under the same model architecture.
Table 2. Comparison of sampling strategies using LiteMicroFormer as the classifier (ROC-AUC).
Table 3 presents the sensitivity of AGACUS to different scoring weights and majority-to-minority retention ratios. The original configuration achieved ROC-AUC values of 0.9743, 0.9796, 0.9205, and 0.9719 for Obesity, IBD, Cirrhosis, and CRC-related classification, respectively. Alternative configurations generally maintained competitive performance, with equal weighting yielding the highest IBD ROC-AUC (0.9828), attention-dominant weighting for CRC-related classification (0.9721), and higher retention ratios for Cirrhosis (0.9352). However, lower retention reduced Obesity performance to 0.9517, indicating some sensitivity to class balance. Overall, the results demonstrate relatively stable predictive performance across the examined settings, although parameter sensitivity remains evident for certain disease tasks.
Table 3. Sensitivity analysis of AGACUS scoring weights and majority-to-minority retention ratios across four disease classification tasks (ROC-AUC, mean ± SD). The weighting coefficients ( α , β , γ ) represent uncertainty, attention relevance, and cluster diversity, respectively. The ratio bounds ( r min , r max ) specify the minimum and maximum majority-to-minority retention settings, subject to cluster-allocation constraints.
Table 4 shows the result of the incremental ablation experiment on LiteMicroFormer with ROC-AUC as the evaluation metric. The contribution of individual architectural components was isolated by training all variants on the same preprocessed training data provided by AGACUS. The base model performed worst on all tasks, with ROC-AUC values of 0.7199, 0.7369, 0.7084, and 0.7957 for Obesity, IBD, Cirrhosis, and CRC-related classification, respectively. Using metadata led to substantial improvements in ROC-AUC: from 0.7199 to 0.9070 for Obesity, 0.7369 to 0.8968 for IBD, 0.7084 to 0.8402 for Cirrhosis, and 0.7957 to 0.9100 for CRC-related classification. The new feature attention gate further boosted the performance on all tasks, followed by additional improvements after incorporating the transformer encoder. In the four tasks, the complete LiteMicroFormer achieved the highest ROC-AUC scores: 0.9743 for Obesity, 0.9796 for IBD, 0.9205 for Cirrhosis and 0.9719 for CRC-related classification. Overall, the ablation results show progressive improvements in ROC-AUC across the evaluated architectural configurations.
Table 4. Ablation study of LiteMicroFormer on AGACUS-preprocessed data using ROC-AUC.
Table 5 presents the metadata ablation analysis of LiteMicroFormer across the four disease classification tasks, evaluating the contribution of microbial features and demographic information to predictive performance. The microbiome-only configuration achieved ROC-AUC values of 0.9337, 0.9295, 0.8951, and 0.9210 for Obesity, IBD, Cirrhosis, and CRC-related classification, respectively, demonstrating strong discrimination without explicit metadata inputs. Incorporating age and gender further improved performance to 0.9491, 0.9467, 0.9063, and 0.9372, while the complete model, additionally incorporating country, achieved the highest ROC-AUC values of 0.9743, 0.9796, 0.9205, and 0.9719 across the respective tasks. In contrast, the metadata-only configuration produced substantially lower ROC-AUC values of 0.7825, 0.8147, 0.7633, and 0.8019, indicating that metadata alone provided less discriminative information than microbial features under the evaluated protocol.
Table 5. Metadata ablation analysis of LiteMicroFormer across four disease classification tasks (ROC-AUC, Mean ± SD).
Table 6 presents a comparison of LiteMicroFormer with six baseline classifiers evaluated using their default hyperparameter settings under the same data preparation, sampling, and evaluation protocol. The results of LiteMicroFormer across all four tasks showed higher recall, F1-score, and ROC-AUC values than the evaluated baselines. The strongest result was obtained for Healthy vs. IBD, where the proposed model reached 0.9606 ± 0.0138 accuracy, 0.9598 ± 0.0722 recall, 0.9291 ± 0.0272 F1-score, and 0.9796 ± 0.0116 ROC-AUC. For Obesity and CRC-related classification, LiteMicroFormer also achieved higher performance across the reported evaluation metrics compared with the baseline classifiers. Although Cirrhosis remained the most challenging classification task, LiteMicroFormer achieved the highest recall, F1-score, and ROC-AUC among the evaluated models for this task.
Table 6. Baseline comparison across four disease-specific classification tasks.
Table 7 provides a contextual comparison of LiteMicroFormer with recent metagenomic disease prediction studies based on their reported ROC-AUC values. LiteMicroFormer achieved ROC-AUC scores of 0.9743 ± 0.0040 , 0.9796 ± 0.0116 , 0.9205 ± 0.0341 , and 0.9719 ± 0.0080 for Obesity, IBD, Cirrhosis, and CRC-related classification, respectively. The reported ROC-AUC values for LiteMicroFormer were higher than those of the listed studies for Obesity, IBD, and CRC-related classification, whereas several previous studies reported higher ROC-AUC values for Cirrhosis.
Table 7. Contextual comparison of reported ROC-AUC values from recent metagenomic disease prediction studies. Results originate from the respective publications and may differ in datasets, preprocessing procedures, and evaluation protocols.
To examine the interpretability of LiteMicroFormer, SHAP analysis was performed on the learned fused representations across four disease-specific classification tasks, as illustrated in Figure 5. The fused representation consists of 64 microbiome-derived dimensions and 32 metadata-derived dimensions, corresponding to indices 0–63 and 64–95, respectively. Therefore, the analyzed embedding features represent learned latent information from the microbiome and metadata branches rather than individual microbial species. For each task, the SHAP beeswarm plot illustrates the direction and magnitude of feature contributions, while the corresponding bar plot ranks the latent dimensions according to their mean absolute SHAP values. Positive SHAP values indicate contributions toward the Disease class, whereas negative values indicate contributions toward the Healthy class. The results demonstrate task-specific variations in the importance of learned representations, with contributions from both microbiome-derived and metadata-derived features.
Figure 5. SHAP-based interpretation of LiteMicroFormer’s fused latent representations across four disease-specificclassification tasks: (a) Healthy vs. Obesity; (b) Healthy vs. IBD; (c) Healthy vs. Cirrhosis; and (d) Healthy vs. CRC-related. Each subplot presents SHAP beeswarm and feature importance plots for microbiome-derived and metadata-derived dimensions, providing model-level explanations rather than species-level biological interpretations.

3. Discussion

The experimental findings demonstrate the potential of LiteMicroFormer for disease-specific classification using gut metagenomic profiles under repeated subject-level internal evaluation. The comparatively strong performance observed for Obesity, IBD, and CRC-related classification suggests that the proposed framework can learn discriminative representations from high-dimensional microbial abundance data. However, the lower performance and greater variability observed for Cirrhosis indicate that classification difficulty differs across disease conditions. Such variation may be associated with differences in biological heterogeneity, disease progression, medication exposure, or patient-specific microbial characteristics, although these factors were not directly investigated. Furthermore, the relatively small number of disease-positive samples in individual test partitions increases uncertainty in recall and macro-F1 estimates. Although training and validation loss trajectories generally showed stable convergence, these observations alone cannot establish the absence of overfitting. Consequently, the reported performance should be interpreted within the scope of the repeated internal evaluation rather than as evidence of reliable prediction across independent clinical populations.
An important contribution of the proposed framework is AGACUS, which addresses class imbalance through selective retention of informative Healthy samples while preserving all disease-positive training instances. The improvements observed over no sampling, random under-sampling, and SMOTE suggest that incorporating model uncertainty, attention relevance, and cluster diversity into majority-class selection can provide a useful alternative to conventional sampling strategies. Rather than treating all Healthy samples as equally informative, AGACUS prioritizes instances that may contribute to decision-boundary learning while maintaining diversity within the retained majority class. The sensitivity analysis further indicates that predictive performance remains generally competitive across alternative scoring weights and retention-ratio configurations, although certain disease tasks exhibit greater sensitivity to parameter changes. Importantly, the original weighting coefficients and retention-ratio bounds were selected heuristically according to the proposed sampling design rather than optimized using test-set performance. Nevertheless, the observed advantages are limited to the evaluated experimental settings, and additional investigation is required to determine whether similar improvements persist across independent cohorts and different imbalance distributions.
The architectural ablation experiments provide further evidence that the integration of metadata, feature attention gating, transformer-based representation learning, and attention pooling is associated with improved predictive performance. The progressive gains across the evaluated configurations are consistent with the intended functions of these components, particularly the representation of microbial relationships and the integration of auxiliary sample information. However, cumulative ablation experiments do not independently establish the biological mechanisms underlying these improvements. The metadata ablation analysis offers an additional perspective by demonstrating that microbiome-only models retain substantial predictive capability, while the inclusion of age, gender, and country produces further improvements. Notably, the additional gain obtained after incorporating country raises concerns that part of the predictive information may originate from geographical or cohort-specific characteristics rather than disease-associated microbial patterns alone. Therefore, although the findings support the predictive contribution of microbial representations, they do not eliminate the possibility of population-related confounding.
The comparison with conventional machine learning classifiers further illustrates the predictive potential of LiteMicroFormer under the investigated protocol. The proposed framework achieved higher evaluation scores than Logistic Regression, SVM, Random Forest, XGBoost, LightGBM, and MLP across the four disease-classification tasks. The use of consistent subject-level partitions, preprocessing procedures, feature selection, metadata inputs, and AGACUS-resampled training subsets supports methodological consistency across these experiments. Nevertheless, the baseline models were evaluated using default hyperparameter configurations without additional optimization. Consequently, these findings establish the relative performance of the evaluated configurations but do not demonstrate superiority over individually tuned alternatives. A more comprehensive comparison involving systematic hyperparameter optimization and additional architectural baselines would strengthen conclusions regarding the comparative advantages of LiteMicroFormer.
When considered alongside previously published metagenomic disease prediction methods, LiteMicroFormer reports competitive ROC-AUC values while maintaining a compact architecture containing 60,516 trainable parameters. This relatively small parameter count represents a potentially useful characteristic for computationally efficient metagenomic analysis. However, parameter efficiency should not be interpreted as demonstrated clinical readiness or superiority in computational cost without standardized runtime, memory, and deployment evaluations. Similarly, the reported performance differences between LiteMicroFormer and previous studies cannot be treated as direct comparative evidence because the underlying datasets, cohort compositions, preprocessing strategies, and evaluation protocols differ. The comparatively lower Cirrhosis performance relative to several published approaches also illustrates the importance of considering disease-specific differences rather than assuming consistent superiority across tasks. Standardized benchmarking using common datasets and matched experimental conditions is therefore necessary to establish the broader comparative effectiveness of the proposed framework.
The SHAP analysis provides a model-level perspective on the contribution of learned microbiome-derived and metadata-derived representations to the final predictions. The observed task-specific attribution patterns indicate that the model relies on different combinations of latent features across the four disease-classification problems. Nevertheless, these explanations operate on the fused embedding dimensions rather than directly on individual microbial species. As a result, high SHAP importance for a microbiome-derived dimension cannot be interpreted as evidence that a particular taxon represents a clinically meaningful biomarker. Although the feature attention mechanism produces species-associated gating information, its biological validity and correspondence with species-level feature importance were not established in the current experiments. Future interpretability investigations should therefore combine direct input-level attribution, species-level validation, and relevant biological evidence before drawing conclusions regarding microbial biomarkers or disease-associated mechanisms.
Despite these encouraging internal results, independent generalizability remains a central limitation of the present study. The source dataset combines metagenomic profiles from multiple published studies, but incomplete cohort identifiers and potential subject overlap across publications complicate reliable study-disjoint evaluation. Furthermore, disease-positive samples for IBD, Cirrhosis, and CRC-related classification were geographically concentrated within individual countries, introducing potential associations between disease labels and population or study characteristics. Although subject-level splitting prevented records belonging to the same identified individual from appearing in different partitions within a single experimental run, it did not ensure separation of the underlying studies or geographical populations. The five-seed protocol therefore quantifies variability under repeated internal partitions but cannot independently establish robustness to cohort shifts, batch effects, or geographical differences. The metadata ablation analysis provides useful evidence regarding the contribution of country information, but it cannot resolve these confounding factors. Future work should prioritize independently verified study-level partitions, external cohort evaluation, stronger control of technical and geographical batch effects, and more comprehensive biological interpretation. Until such evidence is available, LiteMicroFormer should be regarded as a promising lightweight framework for internal metagenomic disease classification rather than a clinically validated or cross-cohort generalizable diagnostic system.

4. Materials and Methods

The proposed LiteMicroFormer framework is a sequential framework for metagenomic disease prediction as shown in Figure 6. The process starts with the collection of data from the human gut metagenomic abundance data, followed by data preprocessing, disease-label organization and feature preparation. To alleviate the dominance of the healthy class, while keeping the majority samples informative, Attention-Guided Adaptive Cluster Under-Sampling (AGACUS) is applied. The data is then resampled to train and build the LiteMicroFormer model, and its performance is assessed using test data that were not used to train the model. Lastly, XAI is performed to understand the model behaviours and to examine the contributions of learned microbiome-derived and metadata-derived latent representations to model predictions.
Figure 6. Overall workflow of the methodology for metagenomic disease prediction.

4.1. Dataset Preparation and Binary Task Formation

The abundance data from the Public Human gut metagenomic was used for this study which is provided as an abundance.txt file [26]. The dataset consists of data and metadata from over 3000 public metagenomic datasets, microbial taxonomic abundance profiles derived from metagenomic sequence data and metadata at the sample level. The raw file consists of a set of columns (samples) and a set of rows (metadata and features of the microbial abundance). Thus, the matrix was transposed to create a standard learning table with each row representing a sample and each column representing a metadata variable or a microbial feature. In the present dataset, samples of various body sites and disease conditions were collected but only stool samples were retained as this research aims to predict disease based on the gut microbiome.
Once the data is loaded the ND, NA, blank strings, and non-informative values were cleaned. Standardization of the disease labels to clinically meaningful categories was then performed, such as Healthy, Obesity, inflammatory bowel disease (IBD), liver cirrhosis and colorectal cancer-related conditions. For each binary classification task, only samples with clearly defined Healthy or target-disease labels were retained, while samples belonging to other disease categories or without a definitive disease annotation were excluded. To ensure a consistent species-level representation, the species level features were extracted by filtering taxonomic columns (only those with species annotations) and removing strain level features. Body mass index was excluded because of high missingness and other metadata variables (age, gender, country) were kept as auxiliary inputs.
The classification tasks were binary classification problems for each disease, which were created as follows: Healthy vs. Obesity, Healthy vs. IBD, Healthy vs. Cirrhosis, and Healthy vs. CRC-related samples. Healthy samples were used as the control class for each task while the samples from the target disease group were used as the positive group. To minimize subject-level data leakage, splitting was performed based on subjectID, ensuring that all records associated with the same individual were assigned to a single partition within each experimental run. The training, validation, and test sets for each task were defined using a 70:15:15 splitting ratio. This partitioning procedure was repeated using five different random seeds, with each seed generating a new subject-level split rather than only changing model initialization. Consequently, test-set membership varied across runs, although individual subjects could appear in the test partitions of multiple runs. These evaluations therefore represent repeated internal validation rather than independent external cohort assessments. The training set was employed for feature selection, metadata preprocessing, AGACUS sampling and optimization of the model while the validation set was employed for early stopping and the values of the threshold; the test set was reserved for final evaluation. The detailed dataset distribution prior to the splitting, after subject-level partitioning and after preprocessing in the training set using AGACUS is detailed in Table 8.
Table 8. Dataset-specific sample distributions before and after AGACUS preprocessing for random seed 2024. H and D denote Healthy and disease-positive samples, respectively.
Table 8 presents the sample distribution for random seed 2024 as a representative example. Since each random seed generates a separate subject-level partition, the corresponding sample counts may vary between runs. The reported classification performance is summarized across five independent random seeds rather than being calculated solely from the representative partition.
The dataset integrates metagenomic profiles originating from multiple published studies. An examination of the available metadata indicated that conventional cohort and project identifiers were not populated for the selected samples, although source-publication information was available through PubMed identifiers. However, some records associated with different publications shared subject identifiers, indicating potential overlap among the contributing biological cohorts and preventing publication identifiers alone from guaranteeing study-level independence. Furthermore, disease-positive samples were geographically concentrated, with all IBD, Cirrhosis, and CRC-related cases originating from Spain, China, and France, respectively. These characteristics constrain geographically independent validation and complicate the reconstruction of reliable study-disjoint partitions. Therefore, repeated subject-level partitioning was adopted for internal evaluation, while acknowledging that this strategy does not eliminate potential study-specific or geographical confounding.

4.2. Feature Selection and AGACUS Sampling

Once the dataset is constructed as per the task, feature preparation is done on the training partition data only to avoid information leakage. The abundance features at the species level were initially filtered by prevalence, removing rarely observed microbial taxa. The prevalence of a species feature x j was defined as the proportion of training samples in which the feature was non-zero, as expressed in Equation (1):
P j = 1 N train ∑ i = 1 N train I ( x i j > 0 ) ,
where N train denotes the number of training samples and I ( · ) is the indicator function. Species features with P j < 0.05 , corresponding to a presence in fewer than 5% of the training samples, were removed. These abundance values were then transformed with the function log ( 1 + x ) to minimize skewness due to large variability in and low abundance of microbes. Lastly, the remaining species features were ranked by their variance in the training partition, and up to F max = 300 species features were retained. The actual number of selected species features, denoted by F, depends on the features remaining after prevalence filtering. This same species list was then used on the validation and test partitions.
Microbial features were not processed with metadata variables. The training-set median was used as an imputation for age and the training-set statistics were used to standardize age. Categorical metadata, such as gender and country, were filled in using the training-set mode and were encoded via one-hot representation. BMI was not included because it had a high proportion of missing values. The result was two matrices: a species abundance matrix X micro and a metadata matrix X meta for each task.
In this study, to address the dominance of the Healthy class, AGACUS is introduced, as shown in Figure 7. This attention-guided adaptive cluster under-sampling strategy selectively removes less informative majority-class Healthy samples while retaining informative representatives based on model uncertainty, attention-based relevance, and cluster-level diversity. All minority-class disease samples are preserved during the under-sampling procedure. The training set is split into the majority set of healthy samples H and the minority set of disease samples D with the healthy majority | H | > | D | . All samples in D are stored without change, and AGACUS only works on H . Table 8 shows the training distribution of data before and after AGACUS preprocessing, by training task.
Figure 7. Mechanism of the proposed AGACUS module. Healthy majority samples are analyzed using warm-up LiteMicroFormer outputs and K-means clustering, while all disease samples are retained. AGACUS computes uncertainty, attention, and diversity scores, applies adaptive target sizing and cluster-wise quota assignment, and forms a resampled training set for final LiteMicroFormer training.
In the first stage, a warm-up LiteMicroFormer model is trained on the original imbalanced training partition. For each Healthy training sample, the warm-up model generates a disease probability p i , token-level attention weights, and feature-gating scores. Healthy samples are subsequently clustered using their concatenated preprocessed species abundance features and metadata representations. The disease probability is used to indicate how close a Healthy sample is to the decision boundary. The uncertainty score for sample i is defined in Equation (2):
U i = 1 − 2 | p i − 0.5 | ,
where p i denotes the disease probability predicted by the warm-up model. The uncertainty score reaches its maximum when p i is close to 0.5, indicating greater model uncertainty for that sample. So samples classified as “healthy” in the vicinity of the decision boundary have higher uncertainty scores and are used as more informative for disease discrimination.
Attention relevance measures the contribution of each Healthy sample based on the feature-gating scores and token-level attention weights produced by the warm-up LiteMicroFormer. Specifically, the attention weights α i j are extracted from the attention-pooling layer following transformer encoding, where softmax normalization is applied across the selected species tokens. The feature-gating values g i j are obtained from the sigmoid-based feature attention gate. The sample-level attention relevance score is computed as the attention-weighted aggregation of the gating values, as defined in Equation (3):
A i = ∑ j = 1 F α i j g i j
where F denotes the number of selected species features, α i j represents the attention-pooling weight assigned to species token j of sample i, and g i j denotes its corresponding feature-gating value. The attention weights satisfy ∑ j = 1 F α i j = 1 .
To preserve diversity among Healthy samples, AGACUS applies K-means clustering to the concatenated preprocessed species abundance and metadata feature vectors. The number of clusters is set to C = min ( 10 , N H ) for N H > 1 , with n_init = 10 and the corresponding experimental seed as the random state. For each Healthy sample i, let x i denote its concatenated feature vector, and let μ c denote the centroid of its assigned cluster c, computed as the mean of the cluster members.
The diversity score is calculated using Bray–Curtis dissimilarity between the sample vector and its corresponding cluster centroid, as defined in Equation (4). The dissimilarity is evaluated on the concatenated preprocessed feature vectors following Euclidean K-means clustering. Because standardized metadata can contain negative values, the resulting dissimilarity may exceed one.
D i = ∑ j = 1 P x i j − μ c j ∑ j = 1 P x i j + μ c j
where P denotes the total dimensionality of the concatenated preprocessed feature vector. For clusters containing a single sample, the diversity score is set to zero. Non-finite distance values are also replaced with zero before score normalization.
Before aggregation, the uncertainty, attention relevance, and diversity scores are independently normalized using min-max normalization across the Healthy training samples. For each component V i ∈ { U i , A i , D i } , the normalized score is calculated as defined in Equation (5):
V ˜ i = V i − V min V max − V min + ε
where V min and V max denote the minimum and maximum values of the corresponding components among Healthy training samples, and ε = 10 − 12 ensures numerical stability. When the score range is smaller than 10 − 12 , the normalized component is set to zero.
The preliminary informativeness score for each Healthy sample combines uncertainty, attention-guided relevance, and diversity, as defined in Equation (6):
S i raw = α U ˜ i + β A ˜ i + γ D ˜ i
where α = 0.50 , β = 0.20 , and γ = 0.30 , with α + β + γ = 1 . These coefficients were heuristically fixed as normalized design weights to reflect the intended relative importance of the three selection criteria rather than being obtained through hyperparameter optimization. Uncertainty was assigned the largest weight (0.50) because AGACUS primarily aims to retain difficult Healthy samples near the model’s decision boundary, which can provide useful information for distinguishing disease samples from controls. Diversity was assigned a moderate weight (0.30) to preserve heterogeneous Healthy profiles and prevent the selected subset from being dominated by similar samples. Attention relevance was assigned a weight of 0.20 as a complementary model-guided criterion for retaining Healthy samples whose microbial features receive greater emphasis from the warm-up model. Thus, the normalized weighting prioritizes decision-boundary uncertainty while maintaining contributions from sample diversity and model-derived relevance.
The preliminary informativeness scores are subsequently normalized using Equation (5) to obtain the final scores S i , which are used for cluster-wise quota allocation and ranking of Healthy samples.
Rather than enforcing strict 1 : 1 class balancing, AGACUS determines an adaptive majority-class retention target. The intended retention interval is defined by the number of disease-positive training samples and the predefined majority-to-minority ratio bounds, as expressed in Equation (7):
r min | D | ≤ N keep ≤ r max | D | ,
where r min = 1.5 and r max = 3.0 specify the lower and upper majority-to-minority retention ratios, respectively. The exact retention target is determined using the available Healthy samples and a cluster-based target-sizing parameter. Let N H = | H | and N D = | D | denote the numbers of Healthy and disease-positive training samples, respectively; C the number of nonempty Healthy clusters; and m the cluster-based target-sizing parameter. The corresponding lower and upper target limits are defined in Equation (8):
L = max r min N D , m C , U = min r max N D , N H
For N H > N D , the retained majority-class sample size is calculated using Equation (9):
N keep = min max ( L , N D ) , U .
When N H ≤ N D , under-sampling is not performed. The upper limit takes precedence when the cluster-based target exceeds the permitted retention budget. When the available Healthy samples are insufficient to satisfy the lower retention bound, the retained sample count is limited by the available Healthy population, and the intended lower ratio cannot be guaranteed.
Once the target size is determined, AGACUS distributes the sampling budget among the Healthy clusters based on their membership and informativeness. For each cluster c, let n c denote the number of Healthy samples and S ¯ c their mean normalized informativeness score. The cluster weight and preliminary sampling quota are calculated using Equations (10) and (11), respectively:
w c = n c ( 1 + S ¯ c ) ,
q c ∗ = N keep w c ∑ j = 1 C w j
where w c represents the allocation weight of cluster c. If the total cluster weight is nonpositive, allocation is performed proportionally to cluster membership. The preliminary quota is rounded to the nearest integer using ties-to-even rounding and constrained by the available cluster membership, as defined in Equation (12):
q c = min n c , max 1 , round ( q c ∗ ) ,
where q c denotes the initial integer allocation for cluster c. Each nonempty cluster initially receives at least one sample, and its allocation cannot exceed the available membership. If the total allocation differs from N keep , quotas are adjusted iteratively by removing allocations from eligible clusters with the lowest mean informativeness or assigning additional allocations to eligible clusters with the highest mean informativeness, subject to the allocation bounds. After cluster-wise sample selection, if the total number of selected Healthy samples exceeds N keep , the excess samples are randomly removed without replacement. If the selected subset contains fewer than N keep samples, additional Healthy samples are randomly selected without replacement from the remaining unselected majority-class samples, subject to availability. The correction uses the corresponding experimental random seed.
Within each cluster, Healthy samples are ranked according to their informativeness scores S i , and the top q c samples are retained, as defined in Equation (13):
H sel = ⋃ c = 1 C Top q c { h i ∈ H c ∣ S i }
The final resampled training set is constructed by combining the selected Healthy samples with all disease samples, as defined in Equation (14):
T AGACUS = H sel ∪ D ,
where H sel denotes the set of Healthy samples selected by AGACUS, D represents the complete set of disease samples, and T AGACUS denotes the final resampled training set.
This mechanism reduces class imbalance while retaining informative Healthy samples, model-relevant microbial profiles, and cluster-level diversity. The final LiteMicroFormer training is done using the training set re-sampled by AGACUS. Only training partition is resampled with AGACUS, validation and test partitions remain unchanged for an unbiased evaluation setting.
The AGACUS scoring weights for uncertainty, attention relevance, and cluster diversity were set to ( 0.50 , 0.20 , 0.30 ) , respectively. The majority-to-minority retention-ratio bounds were set to r min = 1.5 and r max = 3.0 , with C = 10 Healthy clusters and a cluster-based target-sizing parameter of m = 12 . The parameter m contributes to the global retention target rather than imposing a fixed minimum allocation on individual clusters. Cluster-wise quotas are instead constrained by the available membership, with an initial minimum allocation of one sample per nonempty cluster. To assess parameter sensitivity, alternative weighting schemes, including equal ( 0.33 , 0.33 , 0.34 ) , attention-dominant ( 0.20 , 0.50 , 0.30 ) , and diversity-dominant ( 0.20 , 0.30 , 0.50 ) configurations, were evaluated alongside lower (1.0–2.0) and higher (2.0–3.0) retention-ratio bounds. Each configuration was evaluated across four disease classification tasks using five random seeds, with the original parameter settings serving as the reference for assessing sensitivity to alternative configurations under an otherwise unchanged experimental protocol. The original AGACUS parameters were heuristically specified based on the proposed uncertainty-guided sampling design and the need to balance informative majority-class retention with class imbalance reduction, rather than through test-set-driven hyperparameter optimization.

4.3. Proposed LiteMicroFormer Architecture

The proposed LiteMicroFormer is a low-parameter attention-based transformer model for binary disease prediction based on species-level microbiome profile of the gut microbiome. The architecture has two complementary branches, a microbiome encoder, which learns disease-relevant representations from selected species abundance features, and a metadata encoder, which processes available sample-level information (See Figure 8). Both representations are combined prior to the final classifier to give predictions of Healthy/Disease.
Figure 8. The proposed LiteMicroFormer model’s layer-wise architecture is shown. Species-level abundance values are embedded as values and species identity is embedded as a vector of species. The tokens are feature-sensitively gated and then fed into a lightweight transformer encoder and then pooled by attention pooling. This creates a microbiome representation, which is then combined with metadata features and transferred to a classifier head for a Healthy/Disease prediction.
Let X micro ∈ R B × F be the input microbiome abundance matrix, where B denotes the batch size and F denotes the actual number of selected species features after prevalence filtering, with F ≤ F max = 300 . First, every species abundance is a scalar, so LiteMicroFormer maps each abundance value into a dense token representation using a value embedding layer, as defined in Equation (15):
E i j v = W v x i j + b v
where E i j v ∈ R d , and d = 64 is the token embedding dimension. In order to preserve the species identity, a learnable species embedding E j s ∈ R d is added to the value embedding. The final token representation for species j in sample i is obtained by combining the value embedding with the corresponding species identity embedding, as defined in Equation (16):
T i j = E i j v + E j s
This generates a token sequence of F species tokens, T ∈ R B × F × d , where each sample is coded as a sequence of microbiome tokens identifying species. The token distribution is then stabilized by performing layer normalization before attention-based learning.
A feature attention gate is placed before the transformer encoder to minimize the impact of the weak or noisy microbial features. A lightweight nonlinear projection is applied to compute the feature gate, as defined in Equation (17):
g i j = σ W 2 GELU ( W 1 T i j + b 1 ) + b 2
The learned gate score for species token j is g i j ∈ [ 0 , 1 ] . The resulting gate score is then used to modulate the normalized token representation, as defined in Equation (18):
T ˜ i j = g i j T i j
This operation enables the model to focus on the relevant species tokens, while attenuating the redundant abundance signals. Although the gate scores operate on species-token representations, their suitability for direct species-level biological interpretation was not established in the present study.
The gated token sequence T ˜ is fed to a lightweight transformer encoder comprised of one encoder layer and four heads of self-attention. The transformer encoder learns inter-species dependencies by enabling each species token to look at other species tokens in the same sample. It has a hidden dimension of 128 and GELU activation and dropout in its feed-forward block. Furthermore, to minimize computation complexity and the risk of overfitting, a shallow encoder was chosen for this work, where the sample sizes were relatively low and the number of features high in the metagenomic tasks.
The model then performs attention pooling over the encoded sequence of tokens to produce a fixed-length microbiome representation after the transformer encoding. An attention logit is computed for each encoded token Z i j , as defined in Equation (19):
e i j = W p tanh ( W a Z i j + b a ) + b p
The softmax function is applied to normalize the attention logits and obtain the attention weight of each species token, as defined in Equation (20):
α i j = exp ( e i j ) ∑ m = 1 F exp ( e i m )
The final microbiome representation is then obtained as the attention-weighted sum of the encoded species tokens, as defined in Equation (21):
z i micro = ∑ j = 1 F α i j Z i j
where z i micro ∈ R 64 . This attention pooling layer allows the model to pay more attention to the species tokens that can make stronger predictions rather than even paying attention to all species. The microbiome representation goes through a final layer normalization.
While the metadata branch handles the auxiliary metadata vector X meta ∈ R B × M (where M is the imputed, standardized, and one-hot encoded metadata dimension), the original vector is passed on to the auxiliary branch, which is evaluated in parallel with the metadata branch. The metadata encoder is implemented as a compact multilayer perceptron, as defined in Equation (22):
z i meta = Dropout GELU LayerNorm ( W m x i meta + b m )
which generates a metadata representation z i meta ∈ R 32 . The context information (e.g., age, gender, country) is captured in this branch and does not get mixed with the species tokens.
The microbiome and metadata representations are concatenated to obtain the final fused representation, as defined in Equation (23):
z i fusion = z i micro ; z i meta
where z i fusion ∈ R 96 . The fused vector is fed into a classifier head that consists of a fully connected layer, GELU activation, dropout, and a fused representation is passed through the classification head followed by a linear output layer, as defined in Equation (24):
y ^ i = W o Dropout GELU W c z i fusion + b c + b o
The output, y ^ i ∈ R 2 , is the logits corresponding to the two classes, Healthy and Disease. Then, the softmax function is applied to the output logits to obtain the class probabilities, as defined in Equation (25):
P ( y i = c ∣ x i ) = exp ( y ^ i c ) ∑ r = 0 1 exp ( y ^ i r ) , c ∈ { 0 , 1 }
The final prediction is assigned using a disease-class probability threshold selected on the validation set to maximize macro-F1, as defined in Equation (26):
c ^ i = 1 , P ( y i = 1 ∣ x i ) ≥ τ ∗ , 0 , P ( y i = 1 ∣ x i ) < τ ∗
where τ ∗ denotes the decision threshold selected using the validation-set macro-F1. The selected threshold is subsequently applied to the corresponding test partition without further adjustment.
Therefore, the LiteMicroFormer framework is designed to fuse the species-aware token embedding and feature attention gating with lightweight transformer encoding, attention pooling, metadata fusion and binary classification in a compact architecture well suited to metagenomic disease prediction.
Table 9 shows the distribution of model parameters across the different layers of a representative LiteMicroFormer configuration with 243 selected species features and 14 encoded metadata inputs. This configuration contains 60,516 trainable parameters, while the exact parameter count may vary across disease-specific tasks according to their selected species and encoded metadata dimensions. The transformer encoder and the species identity embedding contribute the majority of parameters, whereas the attention gate, attention pooling, metadata encoder, value embedding, and normalization layers contribute only a few.
Table 9. Layer-wise parameter distribution of a representative LiteMicroFormer configuration.
Overall, this parameter distribution demonstrates the lightweight design of LiteMicroFormer. The model retains the advantages of transformer-based representation learning with low computation complexity for metagenomic disease prediction.

4.4. Experimental Setup

All experiments were carried out on a Kaggle notebook environment with an NVIDIA Tesla T4 GPU and all the experiments were coded in Python (version 3.13.15) with PyTorch. The preprocessing, feature selection, clustering, and evaluation were carried out using NumPy, pandas, and scikit-learn library. All binary disease tasks were trained separately and following the same experimental protocol.
The most important hyperparameter values are summarized in Table 10. LiteMicroFormer is trained using AdamW with a batch size of 32, learning rate of 1 × 10 − 3 , weight decay of 1 × 10 − 4 and dropout of 0.30. We used a 10-epoch warm-up model to create uncertainty, attention and diversity-based sampling signals in AGACUS. The threshold for making decisions was determined on the validation set, based on macro-F1, and all experiments were performed with five different random seeds: 42, 7, 21, 100, and 2024. For each seed, LiteMicroFormer was trained and evaluated separately using the corresponding subject-level data partitions. The performance metrics were subsequently reported as the mean and standard deviation across the five runs, reflecting variability under repeated internal validation.
Table 10. Key hyperparameter settings used in the experiments.
For baseline comparison, six conventional machine learning models, including Logistic Regression (LR), Support Vector Machine (SVM), Random Forest (RF), XGBoost, LightGBM, and Multilayer Perceptron (MLP), were implemented using their respective default hyperparameter configurations. All baseline models were evaluated using the same disease-specific datasets, subject-level training, validation, and test partitions, microbial feature selection, metadata inputs, and preprocessing procedures as LiteMicroFormer. The same AGACUS-resampled training subsets were used for all models, while validation and test partitions remained unchanged. Performance was evaluated across five random seeds using the same evaluation metrics. No additional hyperparameter optimization was performed for the baseline models.

5. Conclusions

The findings of this study demonstrate that LiteMicroFormer provides effective metagenomic disease classification under repeated subject-level internal validation, while addressing substantial class imbalance through a lightweight learning framework. Across the four evaluated tasks, the proposed approach showed consistently strong discrimination, particularly for Obesity, IBD, and CRC-related prediction, while Cirrhosis remained comparatively more challenging. The sampling comparison confirmed the advantage of informed majority-class selection over conventional sampling strategies, while the ablation results demonstrated that metadata integration, feature gating, and attention-based representation learning each contributed to the final performance. These results suggest that preserving informative majority samples and focusing the model on disease-relevant representations can improve minority-disease recognition without relying on a large computational architecture. The study is nevertheless limited by embedding-level interpretability, restricted metadata availability, and cohort heterogeneity. In particular, the concentration of disease-positive samples within limited geographical populations and the potential overlap of subjects across source publications complicate the construction of reliably independent study-level partitions. Consequently, the reported results reflect subject-level internal validation, and potential study-specific, geographical, and batch-related confounding cannot be excluded. Future work will therefore focus on external cohort validation, stronger batch-effect control, integration of richer clinical and multi-omics information, and direct species-level biomarker interpretation.

Author Contributions

Conceptualization, M.T.H.S.; methodology, M.T.H.S., S.A.H. and M.S.; validation, T.M., M.S. and D.C.; formal analysis, S.A.H. and M.T.H.S.; investigation, M.T.H.S. and D.C.; resources, T.M. and M.S.; data curation, M.T.H.S. and S.A.H.; writing—original draft preparation, M.T.H.S., S.A.H. and M.S.; writing—review and editing, S.A.H., T.M. and D.C.; visualization, S.A.H. and T.M.; supervision, M.S.; funding acquisition, M.S. All authors have read and agreed to the published version of the manuscript.

Funding

This research is funded by the Ongoing Research Funding Program (ORF-2026-1027), King Saud University, Riyadh, Saudi Arabia.

Institutional Review Board Statement

Not applicable.

Data Availability Statement

The dataset used in this study is the publicly available in [26], here is the link for direct access. https://doi.org/10.1371/journal.pcbi.1004977.

Acknowledgments

The authors extend their appreciation to King Saud University for funding this research through Ongoing Research Funding Program (ORF-2026-1027), King Saud University, Riyadh, Saudi Arabia.

Conflicts of Interest

The authors declare no conflicts of interest. The funder had no role in the design of the study; in the collection, analyses, or interpretation of data; in the writing of the manuscript; or in the decision to publish the results.

References

  1. Liu, Y.X.; Qin, Y.; Chen, T.; Lu, M.; Qian, X.; Guo, X.; Bai, Y. A practical guide to amplicon and metagenomic analysis of microbiome data. Protein Cell 2021, 12, 315–330. [Google Scholar] [CrossRef] [Scilit]
  2. Asnicar, F.; Manghi, P.; Fackelmann, G.; Baldanzi, G.; Bakker, E.; Ricci, L.; Piccinno, G.; Piperni, E.; Mladenovic, K.; Amati, F.; et al. Gut micro-organisms associated with health, nutrition and dietary interventions. Nature 2026, 650, 450–458. [Google Scholar] [CrossRef] [Scilit]
  3. Jin, D.M.; Morton, J.T.; Bonneau, R. Meta-analysis of the human gut microbiome uncovers shared and distinct microbial signatures between diseases. mSystems 2024, 9, e00295-24. [Google Scholar] [CrossRef] [Scilit]
  4. Kong, C.; Liang, L.; Liu, G.; Du, L.; Yang, Y.; Liu, J.; Shi, D.; Li, X.; Ma, Y. Integrated metagenomic and metabolomic analysis reveals distinct gut-microbiome-derived phenotypes in early-onset colorectal cancer. Gut 2023, 72, 1129–1142. [Google Scholar] [CrossRef] [Scilit]
  5. Liu, Y.; Zhu, J.; Wang, H.; Lu, W.; Lee, Y.K.; Zhao, J.; Zhang, H. Machine learning framework for gut microbiome biomarkers discovery and modulation analysis in large-scale obese population. BMC Genom. 2022, 23, 850. [Google Scholar] [CrossRef] [Scilit]
  6. Xia, Y. Statistical normalization methods in microbiome data with application to microbiome cancer research. Gut Microbes 2023, 15, 2244139. [Google Scholar] [CrossRef] [Scilit]
  7. Bakir-Gungor, B.; Temiz, M.; Jabeer, A.; Wu, D.; Yousef, M. microBiomeGSM: The identification of taxonomic biomarkers from metagenomic data using grouping, scoring and modeling (G-S-M) approach. Front. Microbiol. 2023, 14, 1264941. [Google Scholar] [CrossRef] [Scilit]
  8. Qureshi, A.; Wahid, A.; Qazi, S.; Khattak, H.A.; Hussain, S.F. MetaResNet: Enhancing Microbiome-Based Disease Classification through Colormap Optimization and Imbalance Handling. bioRxiv 2026. [Google Scholar] [CrossRef] [Scilit]
  9. Wang, N.; Wu, M.; Gu, W.; Dai, C.; Shao, Z.; Subbalakshmi, K.P. MSFT-transformer: A multistage fusion tabular transformer for disease prediction using metagenomic data. Brief. Bioinform. 2025, 26, bbaf217. [Google Scholar] [CrossRef] [Scilit]
  10. Shi, K.; Liu, Q.; Ji, Q.; He, Q.; Zhao, X.M. MicroHDF: Predicting host phenotypes with metagenomic data using a deep forest-based framework. Brief. Bioinform. 2024, 25, bbae530. [Google Scholar] [CrossRef] [Scilit]
  11. Roy, G.; Prifti, E.; Belda, E.; Zucker, J.D. Deep learning methods in metagenomics: A review. Microb. Genom. 2024, 10, 001231. [Google Scholar] [CrossRef] [Scilit]
  12. Kumar, A.; Xu, C.; Dakal, T.C. Microbiome based precision medicine through integrated multiomics and machine learning. Microbiol. Res. 2026, 303, 128384. [Google Scholar] [CrossRef] [Scilit]
  13. Pita-Galeana, M.A.; Ruhle, M.; López-Vázquez, L.; De Anda-Jáuregui, G.; Hernández-Lemus, E. Computational Metagenomics: State of the Art. Int. J. Mol. Sci. 2025, 26, 9206. [Google Scholar] [CrossRef] [Scilit]
  14. Curry, K.D.; Nute, M.G.; Treangen, T.J. It takes guts to learn: Machine learning techniques for disease detection from the gut microbiome. Emerg. Top. Life Sci. 2021, 5, 815–827. [Google Scholar] [CrossRef] [Scilit]
  15. Chen, Y.; Su, X. Search-based health status detection and disease classification using species-level profiles of metagenomes. Med. Microecol. 2022, 11, 100048. [Google Scholar] [CrossRef] [Scilit]
  16. Shen, Y.; Zhu, J.; Deng, Z.; Lu, W.; Wang, H. EnsDeepDP: An Ensemble Deep Learning Approach for Disease Prediction Through Metagenomics. IEEE/ACM Trans. Comput. Biol. Bioinform. 2023, 20, 986–998. [Google Scholar] [CrossRef] [Scilit]
  17. Liao, H.; Shang, J.; Sun, Y. GDmicro: Classifying host disease status with GCN and deep adaptation network based on the human gut microbiome data. Bioinformatics 2023, 39, btad747. [Google Scholar] [CrossRef] [Scilit]
  18. Bakir-Gungor, B.; Temiz, M.; Inal, Y.; Cicekyurt, E.; Yousef, M. CCPred: Global and population-specific colorectal cancer prediction and metagenomic biomarker identification at different molecular levels using machine learning techniques. Comput. Biol. Med. 2024, 182, 109098. [Google Scholar] [CrossRef] [Scilit]
  19. Roy, G.; Belda, E.; Hennecart, B.; Chevaleyre, Y.; Prifti, E.; Zucker, J.D. MetagenBERT: A Transformer-based Architecture using Foundational genomic Large Language Models for novel Metagenome Representation. arXiv 2026. [Google Scholar] [CrossRef] [Scilit]
  20. Li, Q.; Wu, W.; Zhu, Y.; Feng, F.; Ye, J.; Wang, Z. Generanno: A Genomic Foundation Model for Metagenomic Annotation. arXiv 2025. [Google Scholar] [CrossRef] [Scilit]
  21. Peng, X.; Wei, Y.; Zhou, X. Enhancing pathogen identification through AI-assisted metagenomic sequencing. Front. Microbiol. 2025, 16, 1634194. [Google Scholar] [CrossRef] [Scilit]
  22. Moon, J.; Liu, Z.; Park, T. PSM-SMOTE: Propensity score matching and synthetic minority oversampling for handling unbalanced microbiome data. Genes Genom. 2025, 47, 1175–1185. [Google Scholar] [CrossRef] [Scilit]
  23. Mihajlović, A.; Mladenović, K.; Lončar-Turukalo, T.; Brdar, S. Machine Learning Based Metagenomic Prediction of Inflammatory Bowel Disease. In Studies in Health Technology and Informatics; Blobel, B., Giacomini, M., Eds.; IOS Press: Amesterdam, The Netherlands, 2021. [Google Scholar] [CrossRef] [Scilit]
  24. Zhou, R.; Ng, S.K.; Sung, J.J.Y.; Wong, S.H.; Goh, W.W.B. Detecting and mitigating doppelgänger bias in microbiome data: Impacts on machine learning and disease classification. Gut Microbes 2025, 17, 2554196. [Google Scholar] [CrossRef] [Scilit]
  25. Taccaliti, E.; Aguilar–Ruiz, J.S. Improving classification on imbalanced genomic data via KDE–based synthetic sampling. Biodata Min. 2025, 18, 60. [Google Scholar] [CrossRef] [Scilit]
  26. Pasolli, E.; Truong, D.T.; Malik, F.; Waldron, L.; Segata, N. Machine Learning Meta-analysis of Large Metagenomic Datasets: Tools and Biological Insights. PLoS Comput. Biol. 2016, 12, e1004977. [Google Scholar] [CrossRef] [Scilit]
Disclaimer/Publisher’s Note: The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content.

Article Metrics

Citations

Article Access Statistics

Multiple requests from the same IP address are counted as one view.