Skip to main content
Scientific Reports logoLink to Scientific Reports
. 2026 Jun 19;16:28045. doi: 10.1038/s41598-026-55212-6

Seasonal water quality index prediction in Guilin karst water system: an explainable machine learning approach

Kun Dong 1,2,3, Yang Huang 1,2,3, Jiayu Yang 1,2,3, Haixiang Li 1,2,3, Sze-Mun Lam 1,2,3,4, Jin-Chung Sin 1,2,3,4, Dunqiu Wang 1,2,3,✉
PMCID: PMC13550486  PMID: 42321306

Abstract

Accurate prediction of the water quality index (WQI) in karst water systems remains challenging due to pronounced seasonal hydrological heterogeneity, dual-porosity flow regimes, and complex multi-factor pollution mechanisms. This study developed a season-stratified, explainable machine-learning framework for the Guilin karst water system (Guangxi, China), based on 208 samples from 104 stations covering the wet (June to August) and dry (December to February) seasons. A sample-adaptive feature engineering step, followed by a three-stage selection pipeline (Pearson correlation filtering, variance inflation factor (VIF) screening, and Random Forest importance ranking), reduced 16 candidate features to ten predictors per season. Ten base learners (Ridge, Lasso, ElasticNet, support vector regression (SVR), random forest (RF), gradient boosting (GBM), eXtreme gradient boosting (XGBoost), light gradient boosting machine (LightGBM), categorical boosting (CatBoost) and adaptive boosting (AdaBoost)) were trained separately for each season, and the top three per season were stacked through a regularised Ridge meta-learner. XGBoost performed best in the wet season (R2 = 0.9655, RMSE = 3.0938, MAE = 2.6754); the Stacking ensemble performed best in the dry season (R2 = 0.9785, RMSE = 2.9142, MAE = 2.4278), beating every individual learner. regression receiver operating characteristic (RROC) analysis confirmed these rankings via the Area Over the Curve (|AOC|) and exposed a cross-seasonal inversion: ensemble models improved from wet to dry season (|AOC| ratio 0.45–0.54), while linear baselines worsened by a factor of 4.1 to 4.3, supporting season-specific model selection. SHAP analysis showed a clear seasonal shift in the dominant drivers. NH3–N controlled wet-season WQI (53.47% importance); in the dry season, control was shared by NH3–N (26.00%), TN (25.09%), DO (21.29%) and the pollution-load index (20.19%), and total phosphorus dropped from 7.73 to 0.06%, reflecting carbonate-mediated sequestration specific to karst. The framework offers a transferable, interpretable template for season-aware WQI modelling in monsoonal subtropical karst settings and provides a practical basis for season-differentiated pollution control.

Supplementary Information

The online version contains supplementary material available at https://doi.org/10.1038/s41598-026-55212-6.

Keywords: Karst water systems, Water quality index, Explainable machine learning, SHapley additive exPlanations, Seasonal differentiation, Regression receiver operating characteristic

Subject terms: Climate sciences, Environmental sciences, Hydrology

Introduction

Karst water is an essential freshwater resource that supports human production and daily life. Karst regions cover approximately 15% of the world’s unfrozen land area1. Globally, about 678 million people rely on karst water for drinking and irrigation. In Southwest China, over 70% of towns and villages primarily depend on karst water as their main drinking water source2,3. Consequently, karst water serves as a vital water source in sustaining human survival, agricultural production, and ecological balance, particularly in arid and water-scarce regions4. However, anthropogenic pollutants have significantly degraded karst water quality worldwide, attracting increasing scientific and public attention5. Contaminated karst water bodies not only endanger human health but may also lead to agricultural losses, environmental degradation, and economic burdens. Therefore, continuous monitoring and precise assessment of karst water quality is essential for mitigating environmental risks and ensuring sustainable water resources management. Water quality assessment was initially developed to evaluate the suitability of water for human consumption, and typically involves various techniques to analyze data from different locations and samples. Surface water assessment typically entails indicators such as DO, pH, TN, TP, CODCr, and NH3-N, followed by processing these data to derive a Water Quality Index (WQI)6,7.

The WQI serves as a simplified tool that integrates multiple physical, chemical, and biological parameters into a single quantifiable index with assigned weights. This approach enables data visualization, interpretation, and comparative analysis of water quality across different spatiotemporal conditions8. Based on predefined thresholds, WQI values classify water bodies into different quality categories, enabling researchers and policymakers to identify pollution hotspots, optimize remediation priorities, and develop targeted management strategies9. Nevertheless, water quality is influenced by multiple factors including weather conditions, land use patterns, and seasonal variations, resulting in a complex formation mechanism that poses significant challenges for predicting the WQI10,11.

Although numerous indicators are used to characterize water quality, this study specifically focuses on predicting the WQI in karst water systems and their surrounding major rivers and lakes. Such water bodies typically receive direct urban domestic and industrial discharges, and are subject to intensive human disturbances. Consequently, their water quality status is closely linked to urban ecological security and public health. Traditionally, assessing these parameters in karst water systems requires measuring multiple physicochemical parameters through extensive field sampling and laboratory analysis, which is both time-consuming and resource-intensive. Meanwhile, traditional WQI calculations rely on direct physicochemical and microbiological measurements but lack predictive capabilities for unmonitored locations12.

In recent years, machine learning techniques have emerged as powerful tools for water quality prediction due to their strong ability to capture nonlinear relationships and complex interactions among environmental variables13. By analyzing historical monitoring data, machine learning models can automatically select relevant features, reduce data dimensionality, and uncover hidden relationships between water quality parameters and WQI14. Consequently, they enable precise WQI prediction based on existing information15,16. Over the past decades, extensive academic research has been conducted on water quality prediction and management for watershed systems to address their inherent complexity17,18. These studies consistently emphasize that developing precise assessment tools is crucial for supporting regional water resource management decisions and establishing effective early warning systems. Karst water systems are characterized by strong nonlinearity, non-stationarity, and high spatial heterogeneity. Water quality data in these environments are influenced by multiple factors simultaneously, including complex hydrogeological structures, variable flow conditions, and intense anthropogenic disturbances. These characteristics complicate data processing, model development, and interpretation.

Artificial intelligence models have demonstrated prominent theoretical and practical value in water quality simulation and modeling19–21. Numerous machine learning models have been employed for WQI prediction. Niazkar et al. found that Gaussian process regression (GPR) achieved optimal WQI prediction performance among 11 stacked methods22. Chen et al. compared 10 learning models using large-scale Chinese river and lake data, finding that Decision Tree (DT), RF, and Deep Cascade Forest (DCF) significantly improved prediction accuracy across six water quality grades23. Further studies confirm strong predictive performance: Support Vector Regression (SVM) achieved superior correlation and error metric for WQI prediction23, RF and SVM yielded correlation coefficients exceeding 0.97 across diverse environments24,25, and Artificial Neural Network (ANN) with RF demonstrated best performance among 14 ML methods26,27.

Building on this foundation, recent years have witnessed the rapid emergence of hybrid machine-learning architectures engineered for water-resource prediction. Weighted ensemble frameworks coupled with linear-programming-based weight optimization have been developed to enhance streamflow prediction28,Kalman-filter-driven hybrid models with feature analysis under uncertainty have been applied to the water-quality and ecosystem nexus29, stacked-hybridization strategies combining ANN with multi-stage preprocessing have been used for WQI prediction in riverine karsts30,and stacking ensemble regressors with SHAP-based explanation have been demonstrated on large-scale Indian river datasets31. Although mechanistic models such as SWAT and its enhanced variants are widely used to simulate hydrological processes and pollutant transport, their use in karst environments is often limited by parameter-calibration difficulties and high observational-data demand17,18.

Despite these advances, three interrelated gaps persist in the karst water quality prediction literature. First, ensemble methods particularly stacking, which integrates complementary base learners through a meta-learner remain underutilized relative to single-model approaches; no comprehensive study has yet evaluated stacking strategies tailored specifically to karst WQI estimation32–35, although stacking has demonstrated robust gains in variance reduction and predictive stability in adjacent fields22,36, Li, Ma et al. 2025 30. Second, although machine learning has been widely applied to non-karst water modeling and groundwater quality assessment14, its deployment in karst surface water environments characterized by dual-pore structures, pronounced seasonal hydrological variability, and rapid pollutant transport remains limited37. Existing karst-related studies have primarily focused on groundwater vulnerability or single-season snapshots, without addressing the seasonal regime shifts that govern surface water quality dynamics in karst systems. Third, where machine learning has been applied to karst or seasonally variable water quality, model interpretability has rarely been treated systematically,most studies report feature importance rankings without quantifying how driving mechanisms shift across hydrological seasons.

Guilin’s karst water system presents a compelling case study. Comprising four major rivers and associated wetlands arranged around the urban center, it serves critical water supply, ecological, and landscape functions. Accelerated urbanization has imposed mounting pressures: agricultural nonpoint nitrogen and phosphorus pollution in upper reaches, point source degradation in urban river sections, and severe nitrogen contamination in shallow groundwater during dry seasons. The system’s karst hydrology produces pronounced seasonal differentiation conduit flow can contribute up to 11.40% of total discharge during wet seasons, rapidly transporting over 90% of nitrate nitrogen load within the first two months, while dry seasons are characterized by flow attenuation and pollutant accumulation38,39. Yet no study has applied machine learning to evaluate WQI in karst systems using dry and wet seasons as temporal boundaries.

To address the knowledge gaps identified above, this study establishes a seasonally differentiated, interpretable machine-learning framework for WQI prediction in the Guilin karst water system. Within this overall objective, three research questions are posed and three corresponding hypotheses are tested. The three research questions are: Do machine-learning models with different structural assumptions exhibit season-dependent predictive performance under the pronounced hydrological heterogeneity of karst environments? Does the dominant driving mechanism of WQI variation undergo a systematic transition between wet and dry seasons? Can a Stacking ensemble effectively integrate the complementary strengths of heterogeneous base learners to enhance prediction stability under small-sample conditions? Three testable hypotheses are correspondingly formulated: the optimal algorithm differs between seasons because of distinct pollutant-input regimes and hydrodynamic characteristics; wet-season WQI is dominated by single-factor pulse inputs driven by rainfall-runoff, whereas dry-season WQI is governed by multi-factor synergistic constraints linked to flow attenuation; and a two-layer Stacking ensemble outperforms individual base learners through adaptive integration of complementary predictive advantages. To test these hypotheses, ten base algorithms are deliberately selected to span three methodological paradigms and to provide a fair comparative basis across model-complexity levels: regularized linear models (Ridge, Lasso, ElasticNet) for benchmarking linear assumptions, a kernel-based model (SVR) for capturing moderate non-linearity, and tree-based ensemble models (RF, GBM, AdaBoost, XGBoost, LightGBM, CatBoost) for modeling high-order interactions. For each season independently, the top three cross-validation performers are then integrated as Level-1 base learners into a two-layer Stacking meta-model with a strongly regularized Ridge regressor serving as the Level-2 meta-learner, so that the Stacking architecture exploits the complementary predictive strengths of season-specific base learners rather than enforcing a fixed combination across the annual cycle.

The novelty of this work is positioned on three interconnected but conceptually distinct levels. At the application level, every individual component used here, Ridge, Lasso, ElasticNet, SVR, RF, GBM, AdaBoost, XGBoost, LightGBM, CatBoost, two-layer Stacking, and SHAP, is an established technique; what is new is the specific integrated workflow that couples seasonal stratification, sample-adaptive feature engineering, a three-stage progressive feature-selection pipeline (Pearson correlation filtering, VIF multicollinearity diagnostics, Random Forest importance ranking), Stacking-ensemble construction with season-specific base-learner re-selection, and SHAP-based mechanistic decomposition, deployed for the first time on a karst surface-water WQI prediction task in the Guilin karst system. To our knowledge, this exact combination has not been reported in the karst water-quality literature, and it differs substantively from the single-temporal-block paradigm of prior data-driven WQI studies14, Najafzadeh et al. 2021) by re-identifying the optimal algorithm separately for wet and dry seasons rather than fixing it across the annual cycle. At the methodological level, this study introduces Regression Receiver Operating Characteristic (RROC) signal analysis into karst water-quality machine learning for the first time. RROC characterizes each model through the magnitude of the integrated Area Over the Curve (|AOC|) and resolves two diagnostic patterns that conventional scalar metrics obscure: a clear algorithmic regime boundary separating SVR from the linear baselines, and a cross-seasonal inversion in which ensemble methods improve from wet to dry season while linear baselines deteriorate by approximately a factor of four, thereby providing direct operational evidence for season-specific model selection. At the scientific-knowledge level, the SHAP-based decomposition yields new mechanistic evidence that the Guilin karst water system undergoes a hydrologically driven seasonal regime shift in pollution mechanisms, from single-factor NH3-N dominance under wet season pulse loading to multi-factor synergistic control by NH3-N, total nitrogen, dissolved oxygen, and the pollution-load index under dry-season baseflow conditions, accompanied by the near-complete disappearance of total-phosphorus influence in the dry season interpretable through karst-specific carbonate-mediated phosphorus sequestration. This regime-shift pattern is reproducible across multiple algorithms, consistent with independent biogeochemical evidence, and directly translatable into season-differentiated management interventions targeting agricultural non-point-source pulse loads in the wet season and point-source nitrogen baseflow accumulation in the dry season. The remainder of this paper is organized as follows: Section "Pearson correlation analysis" describes the study area, data acquisition, and the proposed modeling framework; Section "Multicollinearity detection using variance inflation factor (VIF)" presents the comparative performance evaluation, error diagnostics, and SHAP based driver identification across wet and dry seasons; Section "Random forest (RF) feature importance evaluation" discusses the findings in the context of recent literature and management implications; and Section "Final feature set and standardization" summarizes the conclusions, limitations, and future research directions.

Materials and methods

Research area

The study site is located within the urban water system of the central Lingui New District, Guilin City, Guangxi Zhuang Autonomous Region. Guilin situated in northeastern Guangxi at the southern end of the Xiang-Guang Corridor within the southwestern section of the Nanling Mountain Range. The region is characterized by a typical karst landscape dominated by peak forest plains. The geographical coordinates of the study area ranged from 109°57′46.90’' to 110°24′27.19’' east longitude, and 25°03′2.39’' N to 25°25′59.94’' N, covering a total area of approximately 1,786 km2. Administratively, it encompasses six urban districts of Guilin City (Lingui District, Xiufeng District, Xiangshan District, Diecai District, Qixing District, and Yanshan District) and two counties (Lingchuan County and Yongfu County) (see Fig. 1).

Fig. 1.

Fig. 1

Study area geographic map.

Observation data and preprocessing

The primary water bodies within the study area comprise four rivers, two streams, one ring, and one wetland, namely the Taohua River, Li River, Xiangsi River, Luoqing River, Liangfeng River, Taiping River, the urban water system surrounding the Lingui New District, and the Huixian karst wetland. These water bodies formed a north–south river network that surrounded the urban center (see Fig. 1). The spatial relationships among water bodies are as follows: the Taohua River flows eastward from the west and joins the middle reach of the Li River. The Li River flowed southward through the study area from the north, while the Liangfeng River flowed northeastward from the southwest and ultimately converged into the Li River. The Huixian Wetland study area exhibited distinct hydrological characteristics demarcated by the Fenshui Pond: water bodies in the west of the pond flowed toward the Xiangsi River, whereas water in east of the pond drained into the Liangfeng River. The Luoqing River flowed southward through the eastern part of the study area, with its tributary Xiangsi River joining the Luoqing River mainstem downstream.

The region’s complex river network and unique karst topography provided a representative study subject for this research. Considering the robustness of rivers under varying environmental conditions, this study aims to demonstrate their generalization capabilities across different hydrological and aquatic environments40. WQI includes pH (dimensionless), TN (mg/L), TP (mg/L), NH3-N (mg/L), DO (mg/L), and CODCr (mg/L). The average monthly rainfall in Lingui New District from June to August (wet season) was 244 mm, while the average monthly rainfall from December to February of the following year (dry season) was 72 mm.

Sampling station coordinates were determined by Google Earth Pro combined with GPS positioning, and the locations of all 104 stations are listed in Supplementary Table S1. Field sampling was carried out monthly from June to August 2025 and from December 2025 to February 2026. For each station, the three monthly measurements within a season were averaged to obtain one representative seasonal value per water quality parameter, giving 104 station-level records per season and 208 records in total. This aggregation was chosen to represent the integrated seasonal pollution state at each station and to reduce the influence of single-event outliers on spatial comparisons; the resulting dataset is therefore a seasonal cross-sectional snapshot rather than a time series. We acknowledge that monthly averaging inevitably attenuates within-season hydrological variability, including short term pulse events characteristic of karst conduit flow; this is noted as a limitation in Section "Final feature set and standardization".

Each seasonal dataset was processed in four steps before feature engineering (see Fig. 2). First, records with any missing value among the six core parameters (TN, TP, CODCr, NH3-N, DO, pH) or the WQI target were removed by listwise deletion; leaving 104 complete records per season. Second, within-season Z-score screening (|Z|> 3) was used to flag potential extreme values caused by instrumental error or transcription mistakes; since all samples were collected by trained personnel under standardised protocols, no record exceeded this threshold and none was excluded. Third, to ensure reliable model evaluation under the modest seasonal sample size (n = 104 per season), each wet- and dry-season dataset was independently partitioned via stratified random splitting (random state = 42) using an 80/20 train–test ratio (training set: n = 83; test set: n = 21). Feature engineering, the three-stage selection process, hyperparameter optimization, and final model training were conducted exclusively on the training portion through fivefold cross-validation. The held-out test set was reserved solely for unbiased final performance assessment, thereby preventing information leakage and providing a realistic gauge of model generalizability under distinct seasonal hydrochemical conditions. Fourth, Z-score standardisation was applied with StandardScaler fitted on the training partition only, and the same mean and standard deviation were then used to transform the test partition (Eq. 1).

graphic file with name d33e506.gif 1

where μ and σ represent the mean and standard deviation of each feature, respectively. This preprocessing step is essential for algorithms such as Support Vector Regression and regularized linear models, which are sensitive to feature scales (Najah Ahmed et al. 2025)91.

Fig. 2.

Fig. 2

Flowchart outlining the applied methodology.

Estimation of WQI

WQI is a comprehensive evaluation tool that synthesizes multidimensional water quality parameters into a single numerical value, providing an intuitive reflection of the overall quality status of a water body41. Detailed monitoring parameters and detection methods are specified in Supplementary Table S2. The WQI was calculated using the weighted arithmetic aggregation method as expressed in Eq. (2):

graphic file with name d33e542.gif 2

where Pi is the weighting factor for the i-th water quality parameter, and Ci is the single-item pollution index or standardized index for that parameter. The weights (Pi) and normalized values (Ci) used in this study are listed in Supplementary Table S3.

Machine learning-based predictive modeling

The machine learning framework developed in this study consists of four core components: adaptive feature engineering, three-stage feature selection, multi-model construction, and stacking integration. The overall process structure is shown in Fig. 2.

Feature engineering and selection

Adaptive feature engineering strategy

Given the pronounced seasonal differentiation in hydrodynamic and material transport characteristics between wet and dry periods in typical karst water systems of Guilin, an adaptive feature engineering strategy was developed in this study. The core objective of this strategy is to address the balance between feature dimensionality and sample size under small-sample conditions. This balance is achieved by strictly following the well-established “10 samples per predictor” rule (p/n ≤ 0.1) of statistical learning, which has been validated both theoretically and empirically across linear, generalised linear, and modern machine-learning settings. Duke (2004)76 demonstrated in a widely cited tutorial that the variance inflation of regression coefficients grows rapidly when the sample-to-predictor ratio drops below 10. Jame (2015)99 extended this guidance to non-linear settings, recommending an events-per-variable ratio of 10–20 to keep the effective degrees of freedom within the regime of statistically stable estimation. van der Ploeg, Austin et al.42 further empirically validated the rule for support vector machines, random forests, and neural networks, showing that prediction-error variance and miscalibration increase sharply once p/n exceeds approximately 0.1 in cohorts of fewer than 200 samples. With a sample size of n = 104 per season in this study, unrestricted generation of derived features would substantially increase model variance and destabilize coefficient estimation. The adaptive feature engineering strategy developed herein therefore controls feature dimensionality while fully preserving the essential seasonal hydrodynamic and material transport information.

To mitigate this issue, a sample-size-dependent adaptive strategy was implemented: for n < 30, two core features are generated; for 30 ≤ n < 50, six to eight features are constructed; and for n ≥ 50, eight to twelve features are created. This hierarchical approach achieves an optimal trade-off between information gain and overfitting risk43 and enables dynamic adjustment of the feature space according to seasonal data characteristics, thereby preventing information loss while maintaining statistical robustness44. It is important to note that the engineered features, although constructed from the same raw parameters used in WQI calculation, do not constitute algebraic proxies for the target variable. The WQI formula involves piecewise linear normalization of raw concentrations against externally defined regulatory threshold values (see Supplementary Table S3 online), rendering WQI a non-linear, threshold-dependent composite that cannot be directly reconstructed from raw parameter values or their ratios. To verify the absence of information leakage, we conducted four empirical validation experiments (see Supplementary Tables S7-S10 online), these results collectively demonstrate that the derived features provide genuine, non-redundant predictive information that complements the original parameters without encoding WQI structure, and that the cross-validation procedure fully preserves the integrity of evaluation.

Based on the sample size of 104, ten candidate derived features were initially constructed in this study, encompassing nutrient limitation dynamics (N/P ratio, NH3-N/P ratio), nitrogen speciation transformation (TN/NH3-N ratio), pollution accumulation effects (pollution load index), and hydrodynamic responses(comprehensive nutrient index). These candidate features subsequently underwent a rigorous three-stage screening process (described below) to retain a final feature subset characterized by strong explanatory power for WQI and acceptable multicollinearity for modeling.

Pearson correlation analysis

The first stage of feature screening employed Pearson correlation coefficient analysis to quantify linear dependencies between each candidate feature and the target variable WQI. Pearson correlation coefficients (r) were calculated separately for wet and dry season datasets using the Eq. (3):

graphic file with name d33e604.gif 3

where Inline graphic represents individual feature values, Inline graphic represents WQI values, and Inline graphic,Inline graphic denote their respective means (Najah Ahmed et al. 2025)91.

Features exhibiting correlation coefficients with absolute values below the threshold (|r|< 0.03) were excluded from subsequent analysis, as they demonstrate negligible linear association with water quality variation. This correlation-based filtering serves as a preliminary noise reduction step, eliminating features that contribute minimal predictive information while potentially introducing computational overhead and model instability44.

Multicollinearity detection using variance inflation factor (VIF)

VIF quantifies the degree to which the variance of a regression coefficient is inflated due to linear dependencies with other predictors, calculated as Eq. (4):

graphic file with name d33e643.gif 4

where Inline graphic represents the coefficient of determination when regressing the i-th feature against all other features.

The VIF screening process was implemented iteratively. In each iteration, the feature with the maximum VIF value was removed, and VIF values were recalculated for the remaining feature set. This procedure continued until all retained features satisfied the VIF threshold criterion. A VIF value of 1 indicates complete independence among predictors. Although VIF > 10 is commonly cited as evidence of severe multicollinearity, this threshold is a practical convention rather than a formally derived criterion, and its appropriateness varies with sample size and modeling purpose (O'Brien. 2007;45). In environmental modeling contexts, relaxed thresholds up to 20 are frequently and justifiably adopted46. Because the present study is primarily predictive rather than inferential, moderate collinearity carries limited consequence for model accuracy47. Accordingly, the iterative removal procedure is bounded by a second stopping criterion: elimination terminates when the number of remaining variables reaches the target dimensionality prescribed by the Hawkins48 sample to feature rule (n/10), whichever occurs first. This safeguard prevents the feature pool from falling below the minimum needed for stable estimation under our modest sample size (n = 104 per season). The robustness of this strategy is confirmed by a sensitivity analysis across VIF thresholds of 5, 7, and 10, which produced identical retained feature sets, identical test-set performance, and perfectly stable SHAP importance rankings (Spearman ρ = 1.000) across all threshold settings.

Random forest (RF) feature importance evaluation

The third stage of feature selection employed Random Forest -based feature importance assessment to capture non-linear relationships and interaction effects that linear correlation analysis and VIF diagnostics cannot adequately characterize. Random Forest quantifies feature importance through mean decrease in node impurity (Gini importance) across all decision trees in the ensemble8, calculated as Eq. (5):

graphic file with name d33e681.gif 5

where T represents the total number of trees, Inline graphic denotes all nodes in tree t that split on feature j, and Inline graphic represents the decrease in Gini impurity at node i.

To prevent overfitting under limited sample conditions (n = 104), a regularized Random Forest configuration was implemented with conservative hyperparameters: 50 trees, a maximum depth of 3, a minimum samples per split of 10% of sample size, and a minimum samples per leaf of 5% of sample size. This conservative parameterization ensures stable importance rankings while reducing sensitivity to noise and outliers. Following importance evaluation, features were ranked in descending order of their importance scores, and the top 10 features were retained for final model training to maintain model parsimony and avoid overfitting in small-sample regression contexts44.

Final feature set and standardization

Through the three-stage selection process (Table 1), the candidate feature pool for both wet and dry seasons was reduced from 16 features (6 original water quality parameters and 10 derived features) to 10 features. All six original parameters (TN, TP, CODCr, NH3-N, DO, pH) were retained due to their direct environmental significance and established roles in water quality assessment frameworks. Among the 10 derived features, four-N/P ratio, NH3-N/P ratio, TN/NH3-N ratio, and pollution load index successfully passed all three screening stages, while the remaining six derived features were excluded due to either severe multicollinearity (VIF > 10) or weak correlation (|r|< 0.03).

Table 1.

Complementary logic of three-stage screening.

Stage Methods Solved problems Limitations
Stage one Pearson correlation Eliminate noise variables unrelated to WQI Cannot recognize collinearity between features
Stage two VIF collinearity removal Eliminating the Coefficient Instability Caused by Multicollinearity Nonlinear contributions cannot be evaluated
Stage three RF importance ranking capture nonlinear interaction effects highly sensitive to collinearity

The final 10-dimensional feature space achieves a balance between information completeness and model stability, maintaining a feature-to-sample ratio (p/n = 10/104 ≈ 0.0960) below the critical threshold of 0.1, thereby satisfying theoretical requirements for robust model estimation under small-sample conditions.

Machine learning algorithms

To comprehensively evaluate predictive performance across diverse model architectures, this study implemented ten base machine learning algorithms spanning linear, kernel-based, and tree-ensemble methodologies, complemented by a stacking meta-ensemble strategy. The algorithm portfolio was designed to capture a spectrum of model complexity, ranging from interpretable linear models to sophisticated non-linear ensembles, enabling systematic assessment of algorithm-specific advantages under seasonal hydrological regimes (Tiyasha et al. 2020).

Linear regression models

Three regularized linear regression algorithms were implemented to establish baseline performance benchmarks and evaluate the extent of linear relationships between water quality parameters and WQI.

Ridge Regression is particularly suitable when datasets contain both independent and correlated variables, as it overcomes the limitations of ordinary least squares by introducing an L2 penalty that minimizes the sum of squared errors while imposing regularization on model coefficients49. This approach effectively mitigates multicollinearity and prevents coefficient inflation in high-dimensional feature spaces. The objective function minimizes the regularized residual sum of squares as expressed in Eq. (6):

graphic file with name d33e783.gif 6

where Inline graphic is the least squares loss term, representing the squared differences between the predicted values Inline graphic and the true values Inline graphic, α is the regularization parameter, controlling the overall strength of regularization. Inline graphic represents the L2 norm (Euclidean norm) of the weight vector Inline graphic , which is the model coefficients.

Lasso, Least Absolute Shrinkage and Selection Operator regression50. Data values are compressed toward a central point, such as the mean. In shrinkage, an L1 penalty is added to the loss function. Lasso regression is a regularized regression algorithm. As a result, for high values of λ, many coefficients are exactly zeroed under LASSO. To run Lasso regression, you can use the glmnet function, with the alpha parameter set to 1. This addressed the issue of overfitting, which is associated with the linear regression problem. The Lasso selection property reduces the system measurement while impacting the estimating accuracy, which means lower computational complexity with higher efficiency21., both the Lasso output and the linear regression can be expressed using Eq. (7).

graphic file with name d33e822.gif 7

where β represent the regression coefficients, Inline graphic is the response variable, Inline graphic is the vector of predictors for observation i, λ Inline graphic 0 (Mosenah et al. 2026)101.

The Elastic Net regression model is a hybrid technique that combines the Ridge regression and Lasso methods. It minimizes a loss function that balances the strengths of L1 (Lasso) and L2 (Ridge) penalties, making it effective for feature selection and addressing multicollinearity in data sets. Elastic Net is particularly useful in large data sets, where the combined use of L1 and L2 penalties enhances predictive accuracy and model stability. The algorithm’s regularization parameters, ɑ (overall regularization strength), and ρ (mixing parameter balancing L1 and L2 regularization) are optimized through cross-validation (Mosaraf et al. 2025)102. The final model is trained on the input features to predict the WQI, leveraging these optimized parameters. Equation (8) represents the objective function of the Elastic Net:

graphic file with name d33e860.gif 8

where Inline graphic is the overall loss function, Inline graphic is the predicted values, and corresponding tactual values are represented by Inline graphic. Inline graphic is the regularization parameter which controls the strength of overall regularization, Inline graphic is the mixing parameter that determines the balance between L1 and L2 regularization, and Inline graphic represents the model coefficients.

Support vector regression

The Support Vector Machine (SVM) is one of the effective techniques considered to solve classification (Support Vector Classification-SVC) and regression (Support Vector Regression-SVR) issues. Its wide application is due to its efficient performance51,52. SVM consists of projecting inputs into a high-dimensional space based on a linear function and calibration using an ideal hyperplane to partition datasets by offset (Najafzadeh, M et al. 2024). The goal of SVR is to find a regression function f(x) that can adequately characterize the connection between the given input dataset x = {× 1, × 2, × 3,…,xn} and the target value y = {y1,y2,y3,…,yn} as follow53, Eq. (9):

f(x) = wϕ (x) + b 9

where w denotes the function weight vector, b the offset factor and ϕ is the nonlinear mapping.

SVR was implemented with three candidate kernels (RBF, linear, and polynomial), selected via cross-validation. The penalty coefficient C, governing the trade-off between margin width and training error, was searched over {0.01, 0.1, 0.5, 1, 2, 5, 10, 20, 50}; the ε-insensitive tube width over {0.001, 0.01, 0.05, 0.1, 0.2, 0.5}; and the kernel coefficient γ over {scale, auto, 0.001, 0.01, 0.1}. Input features were standardized (zero mean, unit variance) prior to training, as SVR is sensitive to feature scale.

Tree-based ensemble models

The RF model is an ensemble machine learning method used for classification and regression problems. It is based on a range of decision trees (CARTs) known as combined classifiers that randomly select predictors and calibration data for each independent tree and combine all the trees to provide more reliable predictions of the dependent variable . The number of trees (NTree) and the number of predictors chosen at each tree split (NPred) are the two most sensitive hyper-parameters of the RF algorithm (Huang et al. 2016). Since the RF algorithm does not overfit data, the number of trees does not have a significant impact on the model performance (Guan H et al. 2013)103 and a minimum of 500 trees is typically adequate (1300 trees were used in this study). But reducing the number of predictors at each split impacts the computation time, the correlations between trees and their predictive ability54,55. The number of trees (NTree) was searched over {20, 30, 50, 70, 100} and the number of candidate features at each split (NPred) over {sqrt, log2, 0.3, 0.5, 0.7} of total features. Maximum tree depth was restricted to {2, 3, 4, 5, 6}. Minimum samples required to split an internal node and to form a leaf node were set adaptively as {2, 5, 10, 0.1n, 0.2n} and {1, 2, 3, 0.05n, 0.1n} respectively, where n is the training set size, ensuring each leaf retained a statistically representative number of samples.

Gradient Boosting Machine (GBM) is an ensemble learning algorithm that constructs a strong learner by sequentially adding weak learners, each fitted to correct the residual errors made by its predecessors56. Given a training set Inline graphic, GBM aims to find an approximation F*(x) that minimizes the expected value of a loss function L(y,F(x)), Eq. (10):

graphic file with name d33e947.gif 10

For classification tasks, a logistic loss is adopted. The model is initialized with a constant learner Inline graphic and is then updated stage-wise. At the i-th boosting stage, the pseudo-residual (negative gradient of the loss) for each sample is computed as Eq. (11):

graphic file with name d33e960.gif 11

A base learner, typically a regression tree h(x;a) parameterized by α, is then fitted to the pseudo-residuals by solving as Eq. (12):

graphic file with name d33e973.gif 12

The optimal step size Inline graphic is subsequently determined via line search as Eq. (13):

graphic file with name d33e986.gif 13

and the model is updated as Eq. (14):

graphic file with name d33e994.gif 14

This procedure is repeated for i = 1,…,T, where T denotes the maximum number of boosting stages. Owing to the flexibility in selecting base learners and loss functions, GBM can be readily adapted to diverse classification problems.

Extreme gradient boosting or in short XGBoost, is an improved Gradient Boosting algorithm designed for high-performance regression and classification tasks. In addition to conventional Gradient Boosting, Extreme Gradient Boosting integrates advanced optimization techniques such as regularization (L1 and L2 penalties), tree pruning and parallel computation to improve the performance. XGBoost aims to solve the following optimization problem as Eq. (15):

graphic file with name d33e1005.gif 15

where Inline graphic is the loss function, Inline graphic are the decision trees used in boosting, Inline graphic is a regularization function that controls the complexity of individual trees, hence reducing the risk of overfitting. This function is defined as Eq. (16):

graphic file with name d33e1026.gif 16

where T is the number of leaves in the tree,Inline graphic are the leaf weights and λ and Inline graphic are regularization parameters57, Wang. Z et al. 2024).

The number of boosting trees T was searched over {30, 50, 100}, tree depth over {2, 3, 5}, and learning rate η over {0.01, 0.05, 0.1, 0.15}. L1 regularization α and L2 regularization λ were each searched over {1.0, 5.0, 10.0} to penalize model complexity. Row subsampling and column subsampling per tree (subsample, colsample_bytree) were both explored over {0.6, 0.8} to reduce variance.

Light gradient boosting machine also known as LightGBM is another gradient boosting algorithm which is used to improve the accuracy of the predictions. The key idea for developing LightGBM was to reduce memory usage and training time by keeping the model’s performance intact. It was able to achieve this by using histogram based learning, which involves binning data into histograms for faster computation. Also, instead of growing depth-wise, the leaves in this algorithm grows leaf-wise making it more efficient for large datasets58. LightGBM also optimizes the same objective function as XGBoost as Eq. (17):

graphic file with name d33e1054.gif 17

where Inline graphic is the loss function, Inline graphic are the decision trees used in boosting, Inline graphic is a regularization function that controls the complexity of individual trees, hence reducing the risk of overfitting. This function is defined as Eq. (18):

graphic file with name d33e1075.gif 18

where T is the number of leaves in the tree, Inline graphic are the leaf weights and λ and Inline graphic are regularization parameters.

LightGBM employs leaf-wise growth rather than depth-wise expansion, which reduces iterations for the same accuracy. The maximum number of leaves per tree was searched over {7, 15} to constrain complexity under small-sample conditions. Other hyperparameters followed the same grids as XGBoost.

The AdaBoost Regressor is a popular ensemble learning method that enhances robustness and accuracy by combining the predictions from multiple base estimators (Najafzadeh et al. 2026). This method assigns weights to each weak learner based on performance, prioritizing better-performing learners (Shanmugasundar et al. 2021; Najafzadeh, M, S et al. 2024). The objective function for this model is displayed in the following Eq. (19) :

graphic file with name d33e1096.gif 19

where Inline graphic represents the final prediction, Inline graphic denotes the weight assigned to the mth weak learner Inline graphic and M indicates the total number of weak learners. The weight adjustments ensure the focus shifts to correcting errors from previous iterations. The objective is to minimize the exponential loss function, as demonstrated in Eq. (20) , like XGBoost and light GBM Regressor:

graphic file with name d33e1119.gif 20

This iterative process continues until a predefined accuracy level or maximum number of iterations is reached, making AdaBoost effective for handling complex regression tasks26,27.

The number of weak learners M was searched over {30, 50, 70, 100} and the learning rate over {0.01, 0.05, 0.1, 0.5, 1.0}. Three loss functions were evaluated including linear, square, and exponential, with the optimal combination determined by cross-validation. Decision tree regressors (max depth = 3) were used as base estimators.

CatBoost is another gradient boosting algorithm which is used specifically to deal with categorical data efficiently. This is because XGBoost and LightGBM require a lot of pre-processing such as one hot encoding, but CatBoost encodes categorical features without reducing the information. It uses symmetric trees where splits are made for all the nodes based on the same feature. CatBoost minimizes the loss function in Eq. (21):

graphic file with name d33e1139.gif 21

where Inline graphic is the final prediction as an ensemble of weak learners, Inline graphic is the error function and Inline graphic is the regularization term to prevent overfitting57.

CatBoost uses symmetric (oblivious) decision trees, in which all nodes at a given depth share the same split condition. The number of boosting iterations T was searched over {20, 30, 70}, tree depth over {2, 3, 5}, and learning rate η over {0.01, 0.03, 0.06}. The L2 leaf regularization parameter λ (l2 leaf reg) was searched over {5, 7}; bootstrap temperature and random split strength were fixed at 1.0 and 2.0 respectively to stabilize training on the limited wet-season and dry-season sample sizes.

Stacking ensemble strategy

A two-layer stacking architecture was implemented to synthesize complementary strengths of diverse base learners59. First, all base models were ranked based on their R2 scores obtained from fivefold cross-validation, and the top three models exhibiting optimal performance and positive R2 values were selected as Level-1 Learners. The cross-validation predictions of these base models on the training set were then used as meta-features to construct a new feature matrix for input into the Level-2 Meta-learner. The meta-learner employed strongly regularized Ridge regression (Inline graphic = 50 for small sample sizes < 30, Inline graphic = 10 for sufficient samples) to learn the optimal linear combination of base model predictions and generate the final output. The stacking strategy enables adaptive weight allocation by the meta-learner, effectively integrating locally optimal predictions from individual models while reducing the bias of single models and controlling the variance of ensemble predictions60.

Hyperparameter optimization

Exhaustive grid search combined with cross-validation was employed to identify the optimal hyperparameter configurations for each algorithm61,62. Moreover, hyperparameter ranges were dynamically adjusted based on sample size to ensure statistical robustness and the search space was systematically designed to balance model complexity and generalization capability under small-sample conditions (n = 104 per season).

All hyperparameter optimization employed k-fold cross-validation (k = 5 for n ≥ 50, k = 3 for n < 50) with R2 as the optimization objective. Grid search was parallelized across CPU cores to maintain computational efficiency. The complete hyperparameter search grids for all models are provided in Supplementary Table S4.

Model performance and interpretability analysis

The model performance evaluation phase employs three complementary metric: R-squared (R2), root mean squared error (RMSE), and mean absolute error (MAE) to comprehensively assess prediction accuracy from multiple perspectives. R2 measures the model’s explanatory power for total WQI variation, with values ranging from 0 to 1. A higher value indicates better model fit, as calculated in Eq. (22). RMSE quantifies the square root of the mean squared deviation between predicted and measured values, imposing heavier penalties on large errors. This metric is particularly sensitive to extreme prediction deviations during high-pollution periods, making it ideal for evaluating model performance under critical water quality deterioration scenarios, as shown in Eq. (23) . MAE calculates the arithmetic mean of absolute deviations between predicted and measured values, providing an intuitive measure of average prediction error, as detailed in Eq. (24) . The optimal algorithm models were selected by comparing their performance across these metric during wet and dry seasons.

To further evaluate model bias and dispersion characteristics, three supplementary metrics were calculated: mean bias error (MBE), discrepancy ratio (DR), and scatter index (SI). MBE quantifies systematic bias by measuring the average directional deviation between predictions and observations, with values closer to zero indicating minimal systematic over- or under-estimation, as expressed in Eq. (25). DR assesses the relative discrepancy normalized by the mean observed value, providing a dimensionless measure of prediction accuracy62, as shown in Eq. (26). SI characterizes the degree of scatter relative to the mean, with lower values indicating tighter clustering around observations63, as calculated in Eq. (27).

graphic file with name d33e1240.gif 22
graphic file with name d33e1244.gif 23
graphic file with name d33e1248.gif 24
graphic file with name d33e1252.gif 25
graphic file with name d33e1256.gif 26
graphic file with name d33e1260.gif 27

where Inline graphic denotes the measured WQI value of the i-th sample; Inline graphic represents the corresponding model-predicted value; Inline graphic is the arithmetic mean of all measured values; and n is the total number of samples.

To enhance the transparency and interpretability of machine learning models, this study employed the SHapley Additive Explanations (SHAP) method to conduct an in-depth analysis of the prediction mechanism of the optimal model. SHAP is based on the Shapley value theory from cooperative game theory, which decomposes the model’s predicted value into the sum of independent contributions from each input feature by calculating the marginal contribution of each feature across all possible feature combinations64. This approach enables both global and local explanations of the model’s output. The SHAP analysis method is particularly suitable for characterizing water quality response processes in karst water systems, which exhibit threshold effects, seasonal dependence, and nonlinear amplification characteristics. Because both the predictors and the target WQI are derived from the same physicochemical measurements, the absolute SHAP importance values reported below are partly conditioned by the WQI formula’s weighting structure and cannot be read as a fully independent feature ranking. To avoid circular interpretation, our mechanistic conclusions are anchored in the contrast of SHAP importance between wet and dry seasons rather than in absolute values within a single season. Since the formula weights Pi are season invariant by construction, any systematic shift in ranking across seasons must originate in the environmental data and cannot be recovered from the formula alone.

Regression receiver operating characteristic (RROC) signal analysis

While the scalar metrics R2, RMSE, and MAE summarise overall predictive accuracy, they cannot distinguish between models that achieve equivalent total error through symmetric versus asymmetric residual profiles. In environmental risk contexts, where under-prediction of WQI may delay pollution alerts while over prediction may trigger unnecessary remediation, thus explicit characterisation of the over- versus under-estimation balance is highly informative. To address this, we adopted the Regression Receiver Operating Characteristic (RROC) framework originally proposed by Hernández-Orallo65, which extends the classical ROC analysis from classification into regression by mapping a regression model into a two-dimensional space of total over-estimation against total under-estimation.

For each model and for each sample i ∈ {1, 2, …, n}, the residual was defined in strict accordance with Hernández-Orallo’s original convention, as expressed in Eq. 28:

graphic file with name d33e1305.gif 28

where Inline graphic is the predicted WQI and Inline graphic is the measured WQI. A positive Inline graphic indicates over-prediction of the i-th sample, and a negative Inline graphic indicates under-prediction. To trace the RROC curve, a shift parameter s ∈ ℝ (analogous to the decision threshold in classification ROC) was introduced, and at every shift the cumulative over-prediction and under-prediction quantities were computed as expressed in Eqs. (29) and (30):

graphic file with name d33e1337.gif 29
graphic file with name d33e1342.gif 30

Sweeping s from a lower bound to an upper bound traces a monotone curve in the (UNDER, OVER) plane that fully describes the model’s operating envelope. In our implementation, the shift range was set to [min(err) − 0.05·R, max(err) + 0.05·R], where R = max(err)Inline graphic min(err) is the residual span; the 5% padding on each end ensures the curve fully covers the residual distribution and that the natural operating point s = 0 always falls strictly inside the swept range. For a perfect model (Inline graphic≡0 for all i), the entire RROC curve collapses to the origin (0, 0); the closer a model’s curve lies to the origin, the more balanced and concentrated its residuals are.

The signed Area Over the RROC Curve (AOC) was computed by numerical integration of the parametric curve traced by (UNDER(s), OVER(s)) as s varies over the padded range. Because the RROC curve of an unbiased model is reflection-symmetric about the diagonal of the RROC space, the magnitude |AOC| rather than the signed AOC is used for cross-model ranking, as expressed in Eq. (31):

graphic file with name d33e1361.gif 31

RROC curves and |AOC| values were computed independently for the wet and dry seasons using the residuals obtained from the same training–testing protocol described in Section "Hyperparameter Optimization", ensuring full comparability between the conventional and RROC-based assessments. All eleven models including Ridge, Lasso, ElasticNet, SVR, RandomForest, GradientBoosting, XGBoost, LightGBM, AdaBoost, CatBoost, and the Stacking ensemble were evaluated under the same protocol.

Sensitivity analysis of derived features

To complement the three-stage feature-selection pipeline of Section "Feature engineering and selection" and to provide quantitative evidence of each derived feature’s marginal contribution to predictive performance, a systematic sensitivity analysis was implemented. The analysis tests the predictive performance of all eleven models (Ridge, Lasso, ElasticNet, SVR, RandomForest, GradientBoosting, AdaBoost, CatBoost, XGBoost, LightGBM, and the Stacking ensemble) under six feature-set configurations (the ten-feature baseline plus four single-variable removal variants and one full-derived-removal variant). The comparison metric is defined in Eq. 32:

graphic file with name d33e1380.gif 32

where v indexes the variant (one of remove Inline graphic, remove NH3-N/P, remove TN Inline graphic NH3-N, remove Pollution load, remove all derived). A positive Inline graphic indicates that retaining the corresponding feature(s) improves predictive performance. To stress-test indispensability under the most demanding comparison, the baseline used the GridSearchCV-optimised hyperparameters (best params) and the full Stacking configuration, while the variants used a unified set of deliberately weakened hyperparameters (Ridge α = 103, Lasso α = 5, ElasticNet α = 50, SVRC = 0.5 with ε = 0.1; tree-ensemble n-estimators = 15, max depth = 2–3, learning rate = 0.05 with subsample = colsample = 0.7; Stacking meta-learner Ridge α = 50 with uniform top-3 weights). All variants share the same weakened hyperparameter set, ensuring that the cross-variant ranking is invariant to this design choice and therefore provides an unbiased indicator of relative variable importance. The 80/20 train/test split (test size = 0.2, random state = 42) is identical to the main results to ensure direct comparability with Table 3.

Table 3.

Comparison of performance of water environment prediction models for the wet and dry seasons in Guilin karst water system.

Machine learning model Wet season Dry season
R2 RMSE MAE R2 RMSE MAE
XGBoost 0.9655 3.0938 2.6754 0.9682 3.5439 2.9534
Stacking 0.9499 3.7313 2.8381 0.9785 2.9142 2.4278
GradientBoosting 0.9289 4.4419 3.4278 0.9761 3.0699 2.3712
RandomForest 0.9250 4.5639 3.8581 0.9202 5.6127 4.4173
LightGBM 0.9003 5.2627 3.8674 0.9446 4.6763 3.6237
CatBoost 0.8991 5.2919 4.1670 0.9036 6.1698 4.2755
AdaBoost 0.8818 5.7282 4.3638 0.8848 6.7442 4.9474
SVR 0.8438 6.5852 4.8756 0.7886 9.1380 6.1680
Lasso 0.7764 7.8793 6.0121 0.5608 13.1701 10.8160
ElasticNet 0.7530 8.2817 6.3657 0.2786 16.8800 13.1458
Ridge 0.7379 8.5303 6.0827 0.2003 17.7723 13.3668

Spatial block cross validation

Conventional random k-fold cross validation assumes that samples are independent and identically distributed; however, water quality monitoring stations on the same river network often exhibit substantial spatial autocorrelation, with geographically adjacent stations sharing similar pollutant inputs and hydrodynamic conditions. Random k-fold CV applied to such spatially-clustered data can therefore overestimate predictive performance, because some training-set stations will be spatially adjacent to test set stations and the model effectively interpolates rather than extrapolates. To address this concern explicitly, a spatial block cross-validation protocol was implemented following the conceptual framework of David et al. (2017)75 and Jonne et al. (2017)104.

The 104 monitoring stations of each season were partitioned into five spatial blocks by K-means clustering on the (latitude, longitude) coordinates, with the number of blocks chosen to balance fold size (≥ 4 stations per block) and inter-block geographic separation. Leave-one-block-out cross-validation was then performed: in each of the five folds, one spatial block was held out as the test set while the remaining four blocks formed the training set. Each fold independently re-fitted the StandardScaler and re-trained the model with the same best_params and stacking_config as in the main results. The same five-fold split was used to run a standard random k-fold cross-validation as a paired comparison; the spatial-vs-random gap is summarised by the R2_drop metric expressed in Eq. 33:

graphic file with name d33e1447.gif 33

A small R2_drop (close to zero) indicates that the model is insensitive to spatial autocorrelation and therefore generalises robustly to new geographic locations; a large R2_drop indicates that the model’s high random-CV performance is partly attributable to spatial-adjacency leakage and that the true generalisation performance is materially lower. To quantify inter-block geographic separation, we additionally report for each block the minimum, mean, and maximum distance from each held-out test point to the nearest training point.

Results

This study systematically evaluated the performance of ten machine learning algorithms and their ensemble variants for predicting the WQI using 208 valid water samples collected from the urban water system of Guilin during wet and dry seasons. The dataset included six key water quality parameters: pH, DO, CODCr, TP, TN, and NH3-N. Model development incorporated comprehensive feature engineering and selection, rigorous fivefold cross-validation, and SHAP-based interpretability analysis to identify key drivers of WQI variation. The findings reveal pronounced seasonal differences in both model applicability and pollution driving mechanisms, providing robust scientific evidence for season-specific precision management of karst water systems.

Feature engineering and driver screening

To reduce redundancy and collinearity among raw water quality indicators, systematic feature screening was conducted prior to model construction. The screening workflow employed a three-stage progressive strategy, correlation analysis, multicollinearity test and random forest importance evaluation, aimed at retaining core features with significant contribution to WQI prediction while eliminating redundant variables and reducing model complexity66. Finally, the two seasons shared the following characteristics: TN, TP, CODCr, NH3-N, DO, pH, and four derived parameters (nitrogen-to-phosphorus ratio, ammonia–nitrogen-to-phosphorus ratio, TN-to-ammonia–nitrogen ratio, and pollution load index), as shown in Table 2.

Table 2.

Derived characteristics from the study and their construction basis.

Feature Formula Water environment science significance
Nitrogen-to-phosphorus ratio Inline graphic Determine the type of nutrient restriction: < 16 nitrogen restriction, > 16 phosphorus restriction
Ammonia nitrogen phosphorus ratio NH3–N/P Reflecting the relative pollution intensity of ammonia nitrogen and phosphorus, indicating point source pollution characteristics
TN/NH3-N ratio TN/NH3–N The distribution of nitrogen forms in the atmosphere indicated that the new pollution input was low
Pollution load CODCr + NH3–N × 2 + TP × 5 Comprehensive pollution pressure index, where the weights reflect the environmental hazard levels of each parameter

As shown in Fig. 3(a), Pearson correlation analysis revealed that pollution load index exhibited the highest correlation coefficient with WQI (0.6840), followed by NH3-N (0.6100) and TP (0.5710). Notably, although pollution load index is a composite indicator derived from CODCr , NH3-N, and TP, it demonstrated stronger correlation with WQI than any individual parameter, suggesting that integrated pollution pressure more effectively represents overall water quality deterioration during the wet season. VIF testing showed that except for NH3-N/P ratio (18.1000) and N/P ratio (18.1000), which slightly exceeded the empirical threshold (VIF = 10), all other features remained within acceptable ranges. Considering the potential nutrient limitation information embedded in ratio features and their VIF values not reaching the strict elimination criterion (VIF > 20), these features were retained for subsequent importance evaluation.

Fig. 3.

Fig. 3

Results of feature engineering and driving factor screening (a) Wet season (b) Dry season.

Random forest feature importance ranking further confirmed the dominant role of NH3-N's during the wet season, with an importance score of 0.5347, approximately 2.9 times that of pollution load index (0.1825). DO (0.1367) and TP (0.0773) ranked third and fourth, respectively. In contrast, the derived ratio features all exhibited importance below 0.02, indicating that wet season WQI variation is primarily driven by absolute pollutant concentrations, while nutrient structural proportions played a secondary role. All 10 features were ultimately retained for model training during the wet season.

As shown in Fig. 3(b), Pearson correlation analysis revealed a notable shift in correlation patterns. DO became the variable with strongest correlation (0.603), followed by pollution load index (0.579) and NH3–N (0.509). This reordering suggests that water quality during the dry season may be more constrained by redox conditions than by pollutant inputs. VIF testing showed that the N/P ratio (13.58) and NH3–N/P ratio (12.17) still presented collinearity risk, though slightly alleviated compared to the wet season.

Dry season feature importance distribution exhibited a distinctly different balanced pattern. Although NH3–N remained the most important feature (0.2600), its advantage narrowed substantially, with TN (0.2509) ranking second and differing by only 0.0091. DO (0.2129) and pollution load index (0.2019) followed closely, with the top four features showing importance differences compressed within 0.06. This flattened distribution indicates that dry season WQI variability is controlled synergistically by multiple water quality indicators rather than dominated by a single factor. Notably, the importance of TN increased dramatically (from 0.0234 to 0.2509), suggesting total nitrogen may exert stronger influence through internal release or accumulation effects during the dry season. Consistent with the wet season, 10 features were retained for model training.

Comparing screening results across seasons reveals a significant pattern: the wet season exhibited top-heavy importance distribution, the top three features (NH3–N, pollution load index, DO) accounted for cumulative importance of 0.8540, meaning that over 85% of model decisions were explained by these variables alone. NH3–N independently contributed 53.47%, indicating strong single-factor dominance. In contrast, the dry season showed multi-factor synergy, although the top four features reached cumulative importance of 0.9260, individual contributions of each feature were universally lower than the wet season’s dominant factor. This seasonal differentiation not only reflects hydrological controls on pollution driving mechanisms but also provides directional guidance for model selection: wet season conditions favor tree models with intrinsic feature selection capability (e.g., XGBoost), while dry season conditions require ensemble strategies capable of balancing multi-feature information.

Model performance evaluation

Comparative analysis of ML models and ensemble model

To systematically assess algorithm performance in water quality prediction, ten base models including Ridge, Lasso, ElasticNet, SVR, Random Forest, Gradient Boosting, XGBoost, AdaBoost, CatBoost and LightGBM, along with the Stacking ensemble model were constructed and optimized via fivefold cross-validation. Model performance was evaluated using R2, RMSE, and MAE as comprehensive metric. Tables 3 and 4 and Fig. 4 present model performance across wet and dry seasons.

Table 4.

Comparison of driving factors importance in the wet season and the dry season.

Ranking Characteristics of the wet season Importance Characteristics of the dry season Importance
1 NH3-N 0.5347 NH3-N 0.2600
2 Pollution load 0.1825 TN 0.2509
3 DO 0.1367 DO 0.2129
4 TP 0.0773 Pollution load 0.2019
5 CODCr 0.0239 CODCr 0.0362
6 TN 0.0234 pH 0.0172
7 NH3-N/P 0.0158 TN/NH3-N 0.0092
8 pH 0.0027 NH3-N/P 0.0065
9 TN/NH3-N 0.0024 N/P 0.0047
10 N/P 0.0005 TP 0.0006
Fig. 4.

Fig. 4

Performance comparison of karst water systems prediction models during wet season and dry season. (a) Performance comparison of the wet season model (b) Performance comparison of the dry season model (c) Performance radar of the wet season model (d) Performance radar of the dry season model.

Figure 4 compares the performance of the ten base learners and the Stacking ensemble across the wet and dry seasons. Panels (a) and (b) show R2, RMSE and MAE as bar charts, with models ranked by descending R2, together with the corresponding cross-validation distributions as boxplots below. Panels (c) and (d) summarise overall performance on radar charts whose three axes are R2, inverse RMSE and inverse MAE; a larger area indicates better balanced performance.

In the wet season, XGBoost covers the largest radar area, followed closely by Stacking and Gradient Boosting. The three form near-equilateral triangles, meaning their accuracy is balanced across the three metrics rather than driven by one. The cross-validation boxplots support this: XGBoost and Stacking have the tightest R2 distributions and the smallest RMSE/MAE spreads, indicating both high accuracy and high stability. The linear models (Ridge, Lasso, ElasticNet) trace the smallest and most distorted shapes, with the deficit concentrated on the R2 axis.

In the dry season, Stacking moves to the largest radar area, with Gradient Boosting and XGBoost essentially overlapping it. Their cross-validation distributions are also tight and almost indistinguishable, confirming the seasonal switch in the best-performing model. The linear models again sit at the inner edge of the chart and show clearly inflated RMSE and MAE spreads in cross-validation, with Ridge and ElasticNet dropping below R2 = 0.30. Together, the four panels show that ensemble methods dominate in both seasons but the identity of the single best model is season-dependent, supporting the season-stratified modelling strategy adopted in this study.

Specifically, the model performance evaluation results demonstrate significant differences in the performance of various machine learning algorithms between the wet and dry seasons. During the wet season, XGBoost achieved optimal prediction performance with R2 = 0.9655, RMSE = 3.0938, MAE = 2.6754, outperforming all other models. The Stacking ensemble and Gradient Boosting ranked second and third with R2 values of 0.9499 and 0.9289, respectively. CatBoost and AdaBoost occupied fifth and sixth positions (R2 = 0.8991 and 0.8818, respectively). In contrast, linear regression models exhibited substantially weaker prediction: Lasso, ElasticNet, and Ridge achieved R2 values of merely 0.7764, 0.7530, and 0.7379, respectively, with correspondingly higher RMSE and MAE values. These results indicate significant nonlinear characteristics in wet season water quality processes, with tree-based models demonstrating superior fitting capability compared to linear approaches.

The evaluation results for the dry season present different characteristics. The Stacking ensemble achieved the highest prediction accuracy with R2 = 0.9785, RMSE = 2.9142, and MAE = 2.4278. Notably, Gradient Boosting and XGBoost performed comparably, achieving R2 values of 0.9761 and 0.9682, respectively. Although Stacking’s R2 exceeded that of Gradient Boosting by only 0.2 percentage points, it demonstrated clear advantages in error reduction based on RMSE and MAE metric12. Cross-seasonal comparison reveals smaller inter-model performance gaps during the dry season, with universally lower RMSE and MAE values, suggesting stronger regularity and predictability in dry season water quality dynamics. CatBoost and AdaBoost ranked sixth and seventh in the dry season (R2 = 0.9036 and 0.8848), exhibiting a moderate performance gap relative to LightGBM (R2 = 0.9446). Notably, CatBoost’s dry-season R2 exceeded its wet-season value by 0.0045, suggesting marginally improved stability under the simpler multi-factor synergy regime, whereas AdaBoost showed a similar cross-seasonal improvement of 0.003. Linear models showed further degraded performance during the dry season. Ridge, ElasticNet, and Lasso achieved R2 values of 0.2003, 0.2786, and 0.5608, respectively, with error metric substantially exceeding those of tree-based and ensemble models, reaffirming the necessity of nonlinear modeling approaches.

Error analysis

Comprehensive residual analysis is visualized via heatmaps in Fig. 5. As shown in Fig. 5(b), linear models including Ridge, Lasso, and ElasticNet displayed obvious systematic bias across the entire sample sequence in the dry season, with residuals often reaching extreme values between ± 10 and ± 15 mg/L. Red (positive residual) and blue (negative residual) alternated without a clear pattern, indicating strong systematic bias and randomness. SVR showed a scattered residual distribution with positive and negative residuals alternating, although the extreme values narrowed to within ± 10 mg/L. Tree-based models (Random Forest, Gradient Boosting, CatBoost, AdaBoost) and advanced ensembles (XGBoost, LightGBM) showed markedly improved residual distributions, predominantly displaying light blue and light red, indicating residuals concentrated within ± 5 mg/L. The Stacking model displayed the most uniform residual distribution, with an overall light color palette and few deep red or blue extreme residuals, indicating optimal prediction stability.

Fig. 5.

Fig. 5

Comprehensive residual analysis of the predictive model visualized by heat map (a) Wet season (b) Dry season.

Residual statistics quantitatively validated the heatmap observations. Linear models showed high standard deviations (Ridge: 13.05, ElasticNet: 10.72, Lasso: 13.03), indicating large residual dispersion, and the Q25-Q75 quartiles revealed wide distribution ranges (Ridge: − 10.46 to 13.49; ElasticNet: − 13.06 to 15.35). By contrast, the Stacking model showed a standard deviation of only 2.91 and a mean of -0.08 (near-zero bias), with Q25 = − 2.23 and Q75 = 1.90, indicating a highly concentrated residual distribution. A median of − 0.68 further confirmed its high precision and low bias.

During the wet season (Fig. 5(a)), residual distributions improved across the board compared with the dry season. Linear models still exhibited substantial fluctuation, although extreme value frequency and magnitude decreased. Tree-based and ensemble models showed further improvement, with XGBoost and LightGBM residuals confined predominantly within ± 5 mg/L. The Stacking model achieved the best residual distribution in the wet season, with nearly all sample residuals concentrated within ± 5 mg/L.

Statistical summaries also showed universally reduced residual dispersion during the wet season. Linear models improved (Ridge std: 6.29, Lasso: 6.53, ElasticNet: 5.39), although Q25–Q75 ranges remained relatively wide. The Stacking model exhibited exceptional statistics, with std = 3.72, mean = − 0.27 (near-zero), and median = − 0.44, as well as Q25 = − 2.69 and Q75 = 1.79, indicating a compact and symmetric residual distribution.

Violin plots in Fig. 6 further validated the conclusions drawn from Fig. 5 across three dimensions: residual distribution, absolute error, and relative error. For the dry season (see Fig. 6(b) online), linear models exhibited wide violin plots (approximately ± 40 mg/L) with multimodal or asymmetric characteristics. The SVR showed notable bulging in the middle of the distribution. Tree-based and ensemble models narrowed their residual ranges to within ± 20 mg/L, CatBoost and AdaBoost produced violin bodies of intermediate width, consistent with their mid-tier R2 rankings, while Stacking residuals appeared as spindle-shaped and highly concentrated near zero, with an absolute error median below 5 mg/L and relative errors mostly within ± 25%. During the wet season (see Fig. 6(a) online), error distributions across all models contracted toward zero overall, with Stacking performing the best. Its absolute error median fell below 3 mg/L and relative errors concentrated within ± 20%, which is consistent with the residual statistics in Fig. 5, where Stacking model achieved standard deviations of 2.91 (dry season) and 3.72 (wet season) with near-zero means. From dry to wet season, linear models narrowed their residual width by approximately 25–30%, although they retain notable irregularity. Tree-based models transition from multimodal to unimodal distributions, while the Stacking model consistently maintained the narrowest and most symmetric error distributions across both periods, demonstrating robust cross-seasonal predictive capability.

Fig. 6.

Fig. 6

Error distribution analysis of machine learning model using residual, absolute error and relative error index in (a) Wet season and (b) Dry season.

Predicted vs. measured consistency analysis

To intuitively assess prediction accuracy under different hydrological conditions, Fig. 7 presents scatter plots comparing predicted versus measured values for eleven models across the dry and wet seasons. This visualization reveals systematic bias, outlier prediction capability, and performance differences across concentration ranges, providing intuitive evidence for model selection. Black dashed lines represent ideal 1:1 reference lines, red solid lines represent actual fitted lines, and the deviation of scatter point from the reference line reflects magnitude and direction of prediction errors.

Fig. 7.

Fig. 7

Comparison of predicted and measured WQI values of karst water system (a) Wet season (b) Dry season.

The predictive performance of each model under dry season conditions is demonstrated in Fig. 7(a). Linear models (Ridge, Lasso, ElasticNet) exhibited significant scatter dispersion, with numerous sample points deviating from the 1:1 reference line. Particularly in the high concentration range (WQI > 60), pronounced systematic underestimation was evident, with scatter points predominantly located below the reference line. Ridge achieved a RMSE of 17.5400, and the scatter exhibited an obvious horizontal banding distribution, indicating an inability to effectively capture WQI variation patterns. Although Lasso and ElasticNet showed slight improvement, scatter dispersion remained substantial, with partial overestimation in the low concentration range (WQI < 40) and noticeable deviation of fitted line from the reference line.

SVR showed improved scatter convergence compared to linear models, with higher R2 and reduced RMSE. However, considerable scatter points still deviated from the reference line in the moderate-to-high concentration range (WQI 50–70). The fitted lines exhibited slight nonlinear curvature, indicating limitations in handling extreme values.

Tree-based and ensemble models demonstrated significant advantages. Random Forest scatter points tightly clustered along the 1:1 reference line, exhibiting a narrow linear banding distribution with only minor deviations in several individual high-concentration samples. The fitted lines nearly coincided with the reference lines. Gradient Boosting showed similar performance, with small vertical scatter dispersion and stable prediction accuracy across the full concentration range. XGBoost and LightGBM showed further improvement, displaying more compact scatter distribution. Even in high-pollution sample ranges (WQI > 70), scatter points remained close to the reference line without obvious systematic overestimation or underestimation, and residual magnitudes were substantially smaller than those of linear models and SVR. CatBoost and AdaBoost showed scatter distributions intermediate between SVR and RandomForest, with moderate clustering around the 1:1 reference line but noticeable scatter in the moderate-to-high WQI range (50–70 mg/L).

The Stacking model achieved optimal performance during the dry season, with scatter plots exhibiting extremely high linear consistency. Nearly all sample points were distributed tightly within an extremely narrow band along the 1:1 reference line, and the fitted and reference lines perfectly coincide (p < 0.1 indicating high statistical significance).

The predictive performance of each model under wet season conditions is illustrated in Fig. 7(b). Overall prediction accuracy improved across all models, although inter-model performance differences remained significant. Scatter dispersion for linear model decreased, yet Ridge, Lasso, and ElasticNet still exhibited relatively wide dispersion patterns. Unlike in the dry season, wet season linear models showed reduced prediction bias in the low concentration range (WQI < 35). Nevertheless, obvious underestimation tendencies persisted in the moderate-to-high concentration range (WQI 45–65), with fitted line slopes less than 1, indicating persistent systematic bias.

SVR showed markedly improved performance during the wet season, with scatter points converging toward the reference line, a reduced number of outliers, and a smaller angle between the fitted line with the reference line. However, sporadic large deviations remained observable at high-concentration extreme samples (WQI > 65), indicating room for improvement in predicting extreme pollution events.

Tree-based and ensemble models maintained excellent performance during the wet season. Random Forest and Gradient Boosting scatter distributions were extremely compact, with fitted lines highly coincident with the reference lines and no obvious prediction blind spots across the full concentration range. XGBoost achieved optimal wet season performance, with scatter plots displaying a near-perfect linear arrangement. Even for samples with drastic pollution level changes, prediction-measurement deviations remained extremely limited, with residual magnitudes controlled within ± 3 mg/L. LightGBM performed comparably, with minimal vertical scatter dispersion, demonstrating a strong capability for capturing nonlinear relationships and feature interactions. CatBoost and AdaBoost scatter plots contracted toward the reference line relative to SVR, with reduced outlier frequency, though fitted line slopes remained slightly below 1, indicating residual systematic underestimation at high WQI concentrations.

The Stacking model also performed excellently during the wet season. Although R2 was slightly lower than in the dry season, the scatter distribution remained highly concentrated near the reference line, maintaining extremely high overall fitting quality. Comprehensive scatter plots showed that XGBoost and Stacking distributions nearly overlap during the wet season, while the scatter of linear models still exhibited obvious vertical dispersion, further validating the superiority of ensemble learning models.

From dry to wet season, all models showed varying degrees of R2 improvement and RMSE reduction, indicating that wet season water quality variation patterns are relatively easier to capture. Linear models showed average R2 improvements of approximately 0.2–0.3, yet even during the wet season, their maximum R2 remained far below the minimum values achieved by tree-based models, indicating fundamental limitations of linear assumptions in water quality prediction. Conversely, tree-based and ensemble models demonstrated consistently strong and stable predictive capabilities across both seasons. XGBoost performed optimally during the wet season, which is highly correlated with wet season characteristics such as diverse pollution sources, drastic indicator fluctuations, and complex feature interactions. Through the gradient boosting mechanisms, XGBoost effectively captures complex feature interaction patterns under conditions of large sample sizes and strong nonlinear relationships. Its scatter plots exhibited virtually no systematic bias or obvious outliers, validating its powerful fitting capability for multi-factor coupled water quality prediction tasks.

In contrast, the Stacking model achieved more stable predictive capability during the dry season, significantly outperforming its wet season performance. This difference was associated with the fact that dry season water quality changes controlled by a few dominant factors. By integrating the prediction advantages of diverse structural models (Gradient Boosting, XGBoost, LightGBM), the Stacking model achieves more precise ensemble effects when data structure is relatively simple and dominant factors are clear. Its dry season scatter plots exhibited near-perfect linear consistency, with deviations between the fitted and reference line being almost negligible.

RROC signal analysis

To further validate the seasonal model rankings, an RROC signal analysis was conducted for all eleven models in both seasons. The magnitude of the Area Over the Curve (|AOC|), accompanied by R2 and RMSE from the same training–testing run, is summarised in Table 5; the corresponding RROC curves are displayed in Figs. 8, 9 and 10.

Table 5.

RROC signal analysis of the eleven models in the wet and dry seasons.

Machine learning model Wet season Dry season
Inline graphic R2 RMSE Rank Inline graphic R2 RMSE Rank
Stacking 3434.4 0.9499 3.7313 2 1543.0 0.9785 2.9142 1
GradientBoosting 4345.2 0.9289 4.4419 3 1723.1 0.9761 3.0699 2
XGBoost 3215.5 0.9655 3.0938 1 1961.4 0.9682 3.5439 3
LightGBM 5806.0 0.9003 5.2627 5 4818.7 0.9446 4.6763 4
RandomForest 4492.0 0.9250 4.5939 4 6797.1 0.9202 5.6127 5
CatBoost 6130.3 0.8991 5.2919 6 8390.4 0.9036 6.1698 6
AdaBoost 7131.2 0.8818 5.7282 7 9923.0 0.8848 6.7442 7
SVR 9263.9 0.8438 6.5852 8 17,879.3 0.7886 9.1380 8
Lasso 13,669.1 0.7764 7.8793 9 38,209.6 0.5608 13.1701 9
ElasticNet 15,124.3 0.7530 8.2817 10 62,551.7 0.2786 16.8800 10
Ridge 16,027.8 0.7379 8.5303 11 69,037.4 0.2003 17.7723 11

Note: |AOC|= magnitude of the Area Over the RROC Curve, computed by numerical integration of the parametric (UNDER(s), OVER(s)) curve over a 5% padded shift range, following Hernández-Orallo65. Models are listed by their dry season |AOC| ranking. Lower |AOC| is better. R2 values reported here are from the same training testing run used for the RROC computation and are fully consistent with Table 3.

Fig. 8.

Fig. 8

Comparison of the importance ranking of SHAP features of various algorithms in the dry season and the wet season.

Fig. 9.

Fig. 9

Scatter distribution characteristics of SHAP values of various algorithms in high and low water periods.

Fig. 10.

Fig. 10

RROC curves of the eleven models in the (a) wet season and (b) dry season.

The RROC curves of the eleven models are shown as Fig. 10 for (a) the wet season and (b) the dry season. The horizontal axis represents cumulative under-prediction Inline graphic and the vertical axis represents cumulative over-prediction Inline graphic; both are obtained by sweeping the shift parameter s across a 5% padded residual range. The origin (0,0) marked by a star, denotes the position of a hypothetical perfect model whose residuals are all zero. Curves that lie closer to the origin therefore correspond to better-balanced and more concentrated predictions. The Stacking ensemble (dry season; |AOC|= 1543.0) and XGBoost (wet season; |AOC|= 3215.5) lie closest to the origin in their respective seasons, while the linear baselines Ridge, Lasso, and ElasticNet trace curves that extend far into the high error region of the RROC space, visually confirming the |AOC| rankings reported in Table 5. The RROC space additionally reveals a clear regime boundary between SVR (rank 8 in both seasons) and the linear baselines (ranks 9–11), separating models that can resolve the dry season multi-factor synergy from those constrained to linear additivity.

Under dry season conditions, the Stacking ensemble achieved the smallest |AOC| (1543.0), followed by GradientBoosting (1723.1) and XGBoost (1961.4). Stacking outperformed the second-best model, Gradient Boosting, by 10.4% in |AOC| terms. Notably, this margin is far larger than the corresponding R2 difference (0.9785 vs. 0.9761, a gap of just 0.24 percentage points), demonstrating that RROC effectively amplifies model selection signals that are obscured in the saturated upper range of R2. Tree-ensemble base learners occupied ranks 4–7 with intermediate |AOC| values (LightGBM:4818.7; RandomForest:6797.1; CatBoost:8390.4; AdaBoost:9922.97). Among linear baseline models, |AOC| values increased markedly across algorithms: SVR at 17,879.3, Lasso at 38,209.6, ElasticNet at 62,551.7, and Ridge at 69,037.4. The poorest-performing Ridge model yielded an |AOC| value 44.7 times greater than the optimal result for the dry season. This disparity offers a far more intuitive reflection of the performance gap between linear and ensemble models than the R2 ratio of 0.2003 versus 0.9814 alone. Furthermore, the sharp rise in |AOC| from 17,879 for SVR (rank 8) to 38,210 for Lasso (rank 9) delineates a clear threshold. This boundary separates models capable of capturing multi factor synergies of dry season water quality parameters including NH3–N, TN, DO and pollution load from those limited to simple linear additivity.

Under wet season conditions, XGBoost attained the smallest |AOC| (3215.5), followed closely by Stacking (3434.4) and GradientBoosting (4345.2). The XGBoost advantage over Stacking was only 6.4% in |AOC| terms, mirroring their near identical R2 values (0.9655 vs. 0.9499) and confirming that during the wet season single-factor NH3–N regime, the marginal benefit of the Stacking meta-learner over its strongest base learner is small. RandomForest (|AOC|= 4492.0) ranked fourth, with LightGBM (5806.0), CatBoost (6130.3) and AdaBoost (7131.2) trailing among the tree ensembles. The linear baselines again ranked last (Lasso: 13,669.1; ElasticNet:15,124.3; Ridge:16,027.8), with the worst-performing Ridge accumulating an |AOC| 5.0 times higher than the wet season optimum. Although the performance gap between linear and ensemble models is smaller in the wet season than in the dry season, linear models still show an excessively large absolute |AOC| penalty. For Ridge, this cumulative integrated residual area exceeds 12,000 units, which is not acceptable in practical application. This is especially true because the high NH3-N period in the wet season exactly overlaps with pollution events, when accurate WQI prediction is most urgently needed.

Two further cross seasonal patterns merit emphasis. First, the dry to wet |AOC| ratio reveals fundamentally different algorithmic suitabilities across the two hydrological regimes. For the top three ensemble methods, this ratio falls within the narrow band of 0.45 to 0.54 (Stacking: 1543.0/3434.4 = 0.45; GradientBoosting: 1961.4/4345.2 = 0.45; XGBoost: 1723.1/3215.5 = 0.54), confirming that ensemble approaches benefit from the structurally simpler dry season target. In striking contrast, for the linear baselines the ratio inverts: Ridge accumulates 4.3 times more |AOC| in the dry season than in the wet season (69,037/1602 = 4.31), and ElasticNet 4.1 times more (62,552/15,124 = 4.14). This inversion provides a powerful, quantitative refutation of the temptation to extrapolate a single fixed season model across the annual cycle. Second, the dry-season Stacking |AOC| (1543.0) is 52.0% lower than the wet season XGBoost |AOC| (3215.5), demonstrating that when an algorithm is well matched to the hydrological regime, the residual envelope in the dry season can be reduced to a far smaller magnitude than that in the wet season. This asymmetric outcome reflects the underlying hydrology: dry season WQI variation is controlled by stable multi-factor synergy that ensemble methods can synthesise tightly, whereas wet season WQI is driven by stochastic ammonia pulses that fundamentally bound the achievable predictive precision.

Sensitivity analysis of derived features

The sensitivity analysis tested the marginal contribution of each derived feature to predictive performance. The complete Inline graphic matrix for both seasons is reported in Figs. 11 and 12 and Table 6.

Fig. 11.

Fig. 11

Spatial distribution of basic water quality indexes in Guilin ring water system (a) in wet seasons (b) in dry seasons.

Fig. 12.

Fig. 12

ΔR2 grouped bar chart from the sensitivity analysis.

Table 6.

Wet and dry season Inline graphic.

Model removal variant Wet season Dry season
TN/TP NH3-N/P TN/NH3-N Pollution load All derived TN/TP NH3-N/P TN/NH3-N Pollution load All derived
Ridge 0.426 0.426 0.461 0.481 0.518 0.086 0.079 0.114 0.144 0.087
Lasso 0.213 0.213 0.213 0.287 0.287 0.153 0.153 0.153 0.195 0.195
ElasticNet 0.757 0.757 0.757 0.757 0.757 0.288 0.288 0.288 0.288 0.288
SVR 0.641 0.641 0.579 0.645 0.587 0.627 0.626 0.625 0.649 0.598
Random Forest 0.061 0.059 0.061 0.130 0.104 0.054 0.048 0.044 0.054 0.054
Gradient Boosting 0.347 0.339 0.347 0.364 0.364 0.407 0.403 0.403 0.404 0.403
AdaBoost 0.154 0.154 0.154 0.146 0.183 0.057 0.057 0.057 0.083 0.083
CatBoost 0.373 0.375 0.379 0.441 0.467 0.387 0.391 0.399 0.407 0.403
XGBoost 0.438 0.442 0.442 0.434 0.455 0.419 0.419 0.422 0.432 0.428
LightGBM 0.370 0.370 0.370 0.417 0.387 0.425 0.426 0.425 0.424 0.414
Stacking 0.107 0.102 0.108 0.124 0.128 0.059 0.056 0.056 0.068 0.069

Note: (all values > 0; bold marks the largest single-variable; Inline graphic per row).

Across the 11 models × 5 variants × 2 seasons matrix, all 110 Inline graphic values were strictly positive, providing universal empirical evidence that each derived feature contributes positively to predictive performance under the most demanding stress-test conditions. In the wet season, Inline graphic magnitudes ranged from 0.059 (RandomForest, remove NH3-N/P) to 0.757 (ElasticNet, all single-variable removals collapse to the same value because the L1 + L2 penalty under the weakened Inline graphic = 50 setting drives the variant model to an essentially null prediction). In the dry season, Inline graphic magnitudes ranged from 0.044 (RandomForest, remove TN/NH3-N) to 0.649 (SVR, remove Pollution load). The narrower dry season range reflects the fact that linear-model baselines achieve lower test-set R2 in the dry season and therefore have less performance to lose.

The most informative single derived feature was Pollution load: it produced the largest single-variable Inline graphic in 7 of 11 wet season models and 7 of 11 dry season models , which is the most consistent ranking among the four derived features. This is biogeochemically intuitive because Pollution load aggregates CODCr, NH3-N, and TP with environmental hazard weighted coefficients and therefore consolidates multiple non-linear pollution signals into a single high information feature. The next most informative was NH3-N/P (largest single-variable Inline graphic in 1 of 22 model-season cells), followed by TN/TP (4 cells); TN/NH3-N did not produce the largest single-variable ΔR2 in any model-season cell, consistent with its low Pearson |r|.

Comparing single-variable to all derived removal, the cumulative information contributed by the four derived features collectively exceeds the sum of their individual contributions only for a subset of models. For Stacking, the all-derived Inline graphic (0.128 wet, 0.069 dry) is comparable to the largest single-variable Inline graphic (0.124 wet for Pollution load, 0.068 dry for Pollution load), indicating that the derived features carry largely overlapping information that any one of them can substantially substitute for. For CatBoost and Ridge in the wet season, however, the all derived Inline graphic (0.467 and 0.518 respectively) substantially exceeds the largest single-variable Inline graphic (0.441 and 0.481), indicating that for these less redundant models the derived features carry partially non-overlapping information whose joint removal compounds the performance loss.

Spatial block cross validation

The five-block K-means partition produced spatial blocks of sizes 25, 35, 10, 4, and 30 monitoring stations in each season. The minimum distance from each test point to the nearest training point ranged from 0.008°(about 0.9 km, the closest case in blocks 0 and 4) to 0.071°(about 7.9 km, in block 3); the mean distance ranged from 0.148°(about 16.4 km) to 0.228°(about 25.3 km). These distance statistics confirm that the spatial blocks are meaningfully separated and that no test-set station lies immediately adjacent to a training-set station, which is a necessary precondition for the spatial CV protocol to provide an unbiased generalisation estimate.

Table 7 and Fig. 13 summarises the spatial CV performance of all eleven models in both seasons, alongside the paired random CV result and the R2_drop diagnostic. The Stacking ensemble achieves the best spatial CV performance in both seasons (R2_mean = 0.923 in dry, 0.855 in wet) and simultaneously achieves the smallest R2_std (0.043 in dry, 0.091 in wet), demonstrating that its predictive accuracy is both the highest and the most stable across spatial blocks. The GradientBoosting and XGBoost models follow closely (dry-season R2_mean of 0.916 and 0.912, respectively); their slightly larger R2_std values (0.054 and 0.050 in dry, 0.164 and 0.219 in wet) reflect modestly higher sensitivity to which spatial block is held out, consistent with their reliance on single-model variance versus the Stacking ensemble’s multi-model averaging.

Table 7.

Spatial block cross validation results of 11 models in both seasons (5-block K-means, leave one block out CV).

Model Wet season Dry season
R2_mean R2_std R2_drop R2_mean R2_std R2_drop
Stacking 0.855 0.091 0.098 0.923 0.043 0.032
GradientBoosting 0.793 0.164 0.165 0.916 0.054 0.031
XGBoost 0.757 0.219 0.172 0.912 0.050 0.041
RandomForest 0.645 0.205 0.211 0.847 0.084 0.049
LightGBM 0.640 0.316 0.248 0.861 0.074 0.069
AdaBoost 0.547 0.329 0.298 0.816 0.113 0.055
CatBoost 0.538 0.320 0.329 0.852 0.070 0.034
SVR 0.239 0.578 0.555 0.519 0.310 0.247
Ridge -0.241 0.848 diverges 0.484 0.228 -0.312
Lasso -0.301 0.873 diverges 0.256 0.604 -0.982
ElasticNet -0.415 1.266 diverges 0.503 0.218 -0.270

Note: R2 _mean and R2 _std (standard deviation of R2) are calculated based on the five spatial folds. R2_drop is defined as the difference between R2_random (R2 from random cross-validation) and R2_spatial (R2 from spatial cross-validation); a smaller R2_drop value is better, and values close to zero mean the model has strong robustness against spatial autocorrelation. The term “diverges” indicates that the R2 values of some random cross-validation folds are abnormally negative, which distorts the average R2. All models are listed in descending order of their R2_mean values from spatial cross-validation in the dry season.

Fig. 13.

Fig. 13

Spatial block visualisation with (a) monitoring stations by K-means block index (b) Spatial CV R2 of models and (c) the Spatial vs. random CV R2.

The R2_drop diagnostic (R2_random − R2_spatial) reveals a clear three-tier structure. Tier 1, the R2_drop of Stacking, GradientBoosting, and XGBoost are 0.031–0.041 (dry) and 0.098–0.172 (wet), confirming that their strong random-CV performance is only marginally inflated by spatial leakage. Tier 2, the R2_drop of LightGBM, CatBoost, RandomForest, and AdaBoost are 0.034–0.069 (dry) and 0.211–0.329 (wet), reflecting moderate but acceptable spatial robustness. Tier 3, the R2_drop of SVR and the three linear baselines ≥ 0.247 (dry) and pathologically extreme values (wet), indicating unreliable random-CV estimates under the small-sample condition.

Two caveats apply to the linear baselines. In the wet season, first, the wet-season random CV for Ridge, Lasso, and ElasticNet diverged into negative-R2 states in individual folds, these arose because the small per-fold sample size (approximately 21 points) combined with the unregularised default penalty produced numerically unstable predictions that, when averaged across folds, dominate the mean. In the dry season, negative R2_drop values (Ridge: -0.312; ElasticNet: -0.270; Lasso: -0.982), they reflect random-CV instability severe enough that individual folds underperform spatial CV. Both artefacts confirm that linear specifications are unsuitable for WQI prediction at this sample size.

SHAP-based key driver identification and optimal model mechanism interpretation

Table 4 quantitatively measures the contribution of each driving factor to WQI prediction during the wet and dry seasons. The SHAP importance value is defined as the mean absolute value of SHAP values for each feature across all samples (mean|SHAPvalue|), reflecting the overall impact strength of features on model outputs64,67.

A comprehensive comparison of SHAP feature importance across the ten main models for both seasons is presented in Fig. 8. In the wet season, the feature importance distribution exhibited obvious algorithm dependency. In gradient boosting algorithms (Gradient Boosting, XGBoost, Random Forest), NH3–N importance values ranked the highest, which is consistent with these algorithms’ proficiency in capturing nonlinear relationships and feature interaction effects. Conversely, linear models (Ridge, Lasso, ElasticNet, CatBoost and AdaBoost) showed significant changes in feature importance rankings. Pollution load inedx and DO rose to the first positions, while NH3–N retreated to third or fourth position. This difference reflected the tendency of linear models to directly associate with baseline indicators that carry larger weights in WQI calculation formulas. Derived ratio features (N/P ratio, TN/NH3–N ratio, NH3–N/P ratio) ranked last across all algorithms with importance values below 0.05, indicating that wet season water quality fluctuations were primarily driven by absolute pollutant concentrations, while nutrient structural proportions played limited roles.

In the dry season, feature importance distribution exhibited more complex multi-factor competitive patterns. The importance of DO increased significantly across most algorithms, ranking first in Ridge and XGBoost, second in Gradient Boosting and LightGBM, with importance values generally exceeding 0.20. This change suggested that dry season water body redox conditions exerted enhanced constraining effects on water quality status. The importance of TN showed a dramatic increase during the dry season, jumping to first position in Random Forest algorithms and maintaining top-three positions in Gradient Boosting, LightGBM, and XGBoost, corroborating the increase reported in Table 4 from 0.0234 to 0.2509. Although NH3–N maintained first position in Gradient Boosting , its importance declined notably in linear models, ranking only third in Lasso and Random Forest, and seventh in ElasticNet. The importance of pollution load index exhibited algorithm differentiation during the dry season, ranking second in Lasso but declining in gradient boosting algorithms. The importance of pH increased during the dry season, with importance values rising to the 0.0150–0.0250 range across most algorithms, possibly related to decreased buffering capacity of water body. The ranking of TP remained low, further confirming that phosphorus was not a limiting nutrient element during the dry season.

The sample-level distribution patterns of SHAP values are further illustrated in Fig. 9. In the wet season, NH3-N SHAP value scatter in gradient boosting algorithms showed an obvious positive aggregation patterns, where high concentrations corresponded to high SHAP values. However, in linear models, NH3–N SHAP value scatter exhibited greater vertical span, with enhanced variability at identical concentration levels, reflecting the difficulty of linear models in accurately characterizing NH3–N interactions with other factors. The pollution load index showed stronger concentration in linear models, with SHAP value distributions displaying narrow positive banding, while gradient boosting algorithms exhibited richer color gradients. DO SHAP value distributions appeared relatively regular across all algorithms, however, LightGBM scatter color gradients were most pronounced, validating its high sensitivity to DO. The TP and TN indicator SHAP value scatter plots were highly dispersed with alternating positive and negative values, indicating that their WQI impacts are modulated by other factors. Ratio feature SHAP value scatter densely distributed near zero and predominantly displayed in light blue colors, validating their marginal roles during the wet season.

Dry season SHAP value distributions exhibited distinctly different characteristics from the wet season. TN SHAP value scatter in ElasticNet and Random Forest showed significant bidirectional distribution, where high-concentration samples could generate both strong positive contributions and negative impacts. This complex non-monotonic relationship reflected TN’s potential influence on water quality through multiple pathways during the dry season (e.g., nitrification–denitrification balance, algal growth limitation transitions). The DO SHAP value scatter exhibited wider numerical spans and richer color gradients during the dry season, particularly in Ridge and XGBoost, indicating enhanced DO impact intensity on WQI with nonlinear characteristics. Although NH3-N SHAP values remained predominantly positive, the vertical dispersion of scatter points increased across most algorithms, suggesting enhanced synergistic constraints from other factors on WQI impacts. The pollution load index SHAP value distributions in Lasso showed obvious positive aggregation, yet displayed stronger dispersion in gradient boosting algorithms. It should be acknowledged that the absolute SHAP magnitudes reportedare not fully independent of the WQI calculation, because predictors and target share their measurement basis. The interpretation in this section therefore rests on the seasonal contrast in importance rather than on the within-season ordering. Pi does not vary with season, so the shifts most notably TN’s 10.7-fold increase, TP’s near disappearance, and DO’s elevation from 13.67 to 21.29% cannot be derived from the formula and must reflect seasonal changes in the field distributions of these parameters. This contrast is the basis on which we read SHAP as informative about pollution driving mechanisms rather than as a reflection of formula structure.

Analysis of spatial and temporal distribution of water quality factors and water environment

The study systematically analyzed the concentration ranges, mean values, and coefficient of variation of key water quality parameters (DO, pH, TN, NH3–N, CODCr, and TP) during both wet and dry seasons across monitoring areas. This comprehensive analysis provides critical insights into the pollution characteristics and spatial distribution patterns of Guilin’s urban water systems, establishing a robust data foundation for developing water quality assessment models and identifying key influencing factors. The karst water monitoring results are shown in Supplementary Table S5.

The spatial distribution during the wet season, as shown in Fig. 11(a), reveals that the highest CODCr concentrations are concentrated in the central and northwestern river sections, with a peak value of 54.26 mg/L, while the eastern section shows a significantly lower concentration of 0.26 mg/L, resulting in a concentration range of 54.00 mg/L, which demonstrates a pronounced spatial gradient. DO exhibits a distribution pattern of higher levels in the east and lower levels in the west, ranging from 0.09 to 12.99 mg/L (12.90 mg/L). The pH values range from 7.32 to 8.69, showing minimal spatial variation. TN concentrations range from 0.00 to 53.77 mg/L, with high values concentrated in the southwest region but dispersed. TP reached a peak at 1.65 mg/L, occurring in localized sections of the northwestern and central river segments. The NH3-N concentrations ranged from 0.00 to 10.67 mg/L, with the highest values located in the central river section.

Figure 11(b) illustrates the spatial distribution during the dry season, with CODCr peaking at 81.73 mg/L. The high-value zone expanded toward the northwest and southward, while the eastern region dropped to 0.00 mg/L. The DO range narrowed to 3.22–8.99 mg/L (range: 5.77 mg/L), with the high-value zone concentrated in the central area. pH ranged from 6.85 to 9.53 showed no significant changes in their spatial distribution. TN peaked at 66.68 mg/L, forming a large high-value zone in the southern region. TP reached 2.65 mg/L, with the southern high-value zone expanding significantly. NH3-N peaked at 16.04 mg/L, exhibiting new clusters in the northwest and south, thereby demonstrating a multi-center distribution pattern.

From a modeling perspective, the broad concentration ranges of various indicators require accurate prediction of WQI across different concentration intervals. Linear models use uniform regression coefficients, which struggle to adapt to the varying concentration-WQI response relationships across river sections. In contrast, XGBoost’s tree splitting mechanism enables the construction of differentiated rules for different concentration intervals, while the Stacking integration model combines the predictive strengths of multiple algorithms. This explains the superior performance of both approaches compared with linear models in spatially heterogeneous water systems.

Discussion

This study conducted comprehensive monitoring of water-quality parameters in the karst water system of Guilin across the wet and dry seasons. Karst aquifers are characterized by high heterogeneity and complex subsurface hydrological systems, making water-quality monitoring and management particularly challenging (Goldscheider et al. 2005)5. Six core physico-chemical parameters including pH, DO, CODCr, TN, TP, and NH3–N, were measured at 104 stations, and ten machine-learning algorithms (Ridge, Lasso, ElasticNet, SVR, Random Forest, Gradient Boosting, AdaBoost, XGBoost, LightGBM, CatBoost) were independently trained and evaluated for the wet and dry seasons. The three best cross-validation performers in each season were then integrated as base learners into a two-layer Stacking meta-model. Conventional scalar metrics (R2, RMSE, MAE) were complemented by RROC signal analysis to resolve the over versus under-prediction balance, and SHAP attribution was applied across all models to identify the seasonally dominant pollution drivers. This integrated workflow is intended to address the structural challenges of karst water-quality modelling: small sample sizes, dual-porosity hydrogeological heterogeneity, and pronounced seasonal non-stationarity.

The methodological contribution lies not in the invention of a new algorithm, but in the theoretically principled integration of existing tools: seasonal stratification, adaptive feature engineering, progressive selection, and stacking ensemble into a coherent framework specifically designed for the structural challenges of karst water quality modeling: small samples, dual-porosity heterogeneity, and pronounced seasonal nonstationarity. This framework addresses what Goldscheider1 identified as a critical barrier to karst water resource management: the absence of predictive tools capable of capturing the system’s inherent temporal complexity. The scientific contribution lies in the SHAP-quantified evidence that karst water systems exhibit a hydrologically driven seasonal regime shift in pollution mechanisms, a pattern that is robust across multiple algorithms and consistent with independent biogeochemical evidence59,68, and that carries direct implications for the design of precision management strategies.

Evaluation via R2, RMSE, and MAE revealed marked distinctions in predictive capability under different hydrological conditions. During the wet season, XGBoost performed optimally (R2 = 0.9655, RMSE = 3.0938, MAE = 2.6754), effectively capturing complex relationships between pollutant inputs from rainfall-runoff and dilution from increased water volume. During the dry season, the Stacking ensemble model demonstrated the highest stability (R2 = 0.9785, RMSE = 2.9142, MAE = 2.4278) by integrating multi-model advantages to more accurately characterize pollutant distribution. These results indicate that model selection should be determined by seasonal water-quality process characteristics, providing a reference for practitioners selecting appropriate machine-learning methods for karst-water-quality prediction.

These findings are broadly consistent with, yet extend, recent comparative literature on machine-learning-based WQI prediction. Choudhary et al.31 developed a stacked regression ensemble using XGBoost, CatBoost, Random Forest, Gradient Boosting, Extra Trees, and AdaBoost as base learners with linear regression as meta-learner, achieving R2 = 0.9952 on 1,987 river samples in India, slightly higher than the present dry season Stacking performance (R2 = 0.9785). This disparity likely reflects the substantially larger training set used by Choudhary et al. (nearly tenfold the 208 valid samples available here), which affords the meta-learner greater capacity to integrate base-learner outputs. Critically, that study applied a single static dataset, whereas the present study implements season-differentiated modelling to reveal temporal shifts in pollution-driving mechanisms with stronger implications for precision seasonal management. At the individual-model level, Hridoy et al.8 demonstrated that XGBoost achieved the highest WQI regression accuracy (R2 = 0.9685) among the evaluated algorithms, consistent with the XGBoost superiority observed here in the wet season. Zhang et al.33,34 further reported that CatBoost and XGBoost both achieved R2 = 0.994 with high inter-model consistency in karst-influenced coastal rivers in South China, corroborating the robustness of tree-based ensembles in spatially heterogeneous aquatic systems. Alshehri and Rahman69 proposed a CNN-Stacking ensemble for groundwater WQI prediction and showed that the Stacking framework (R2 = 0.99) substantially outperformed the standalone CNN (R2 = 0.90); this finding parallels the dry season pattern in the present study, where Stacking consistently surpassed individual base learners, affirming that integrating complementary model strengths is a robust strategy for stable prediction under low-flow, low-variance hydrological conditions. Mo et al.70 examined seasonal WQI prediction in a coastal city and identified NH3-N and TP as pivotal drivers, reporting that prediction accuracy for the “good” grade declined to approximately 70% in summer and autumn, which is consistent with the wet season prediction challenges observed here, further justifying season-differentiated modelling. Taken together, the present work advances the understanding of ML-based WQI prediction in karst water systems by integrating three components that have rarely been combined in prior classical-ML studies: (i) a seasonally stratified modelling strategy, (ii) an adaptive feature-engineering pipeline constrained by statistical-learning-theory bounds, and (iii) SHAP-based decomposition of prediction mechanisms. While previous studies have generally focused on single temporal snapshots or aggregated annual datasets22,31, the present framework explicitly treats wet and dry seasons as hydrologically distinct regimes requiring separate model selection and interpretation.

Recent years have witnessed rapid development of hybrid architectures that couple machine learning with deep sequential models (Transformers, LSTM), state-space data-assimilation techniques (Kalman filters), weighted ensemble schemes, and meta-heuristic optimization algorithms. Because these architectures attack water-quality prediction with fundamentally different inductive biases, a critical comparison with the present season-stratified Stacking-with-SHAP framework helps to clarify where our contribution sits within the broader landscape and which application contexts each family is best suited to.

First, Transformer-based architectures have recently been deployed to capture the long-range temporal dependencies of water-quality time series. Orozco-López et al. (2024) 27 developed an interpretable Transformer Neural Network for one to fourteen-day-ahead forecasting of streamflow, stage, water temperature, and salinity across the Peace River watershed (Florida) and the northern Gulf of Mexico, combining historical observations with spatially distributed weather forecasts. Chen et al.71 proposed a coupled Transformer-based model to address non-stationarity and data limitations in river-water-quality prediction over coastal Chinese basins. These deep sequential models excel when high-frequency, long-record monitoring data are available and when the forecasting horizon is sub-daily to multi-day. The present study, by contrast, focuses on a seasonally aggregated cross-sectional dataset (one observation per station per season; 208 stations × seasons in total) for which the temporal axis is collapsed by design; the predictive question we address is therefore the spatial diagnosis of seasonal WQI states rather than the temporal forecasting of future values. The Stacking ensemble we adopt is well matched to this small-sample, cross-sectional, structurally heterogeneous setting, where a Transformer would be over-parameterized and under-trained, but Transformer-based models remain the appropriate choice for future sub-monthly or event-based extensions of the present framework.

Second, Gao et al.72 developed an ML-Kalman filter data-assimilation framework integrating Kalman filtering with LSTM, RF, XGBoost, and SVR for the Dahei River Basin, reporting accuracy gains of 4.3–17.6% for TN, TP, and CODMn, with the largest improvement for TP. Poursaeid29 introduced a Kalman-filter-driven hybrid model with feature analysis under uncertainty for the water-quality–ecosystem nexus. These approaches are powerful for operational forecasting under continuous-sensor deployment because they explicitly propagate observation and process noise. The present framework operates upstream of this regime: it characterizes the seasonal driving structure from historical field samples and, in doing so, identifies which parameters (NH3-N in the wet season; the NH3-N, TN, DO, pollution-load synergy in the dry season) should be prioritized for high-frequency assimilation in future Kalman-filter-coupled deployments. The two approaches are therefore complementary.

Third, weighted ensemble learning has emerged as an effective strategy for combining multiple ML models when no single algorithm consistently dominates across operating conditions. Poursaeid28 developed a linear-programming-optimized weighted ensemble for streamflow prediction in the Kashkan River Basin, demonstrating that mathematically optimized weights outperform equal-weight averaging. Our two-layer Stacking framework occupies a related but distinct position: rather than externally optimizing fixed scalar weights, the Level-2 Ridge meta-learner adaptively combines Level-1 base-learner predictions through regularized regression on the cross-validated out-of-fold predictions, which can be viewed as a learned, data-driven weighting that is automatically re-fitted for each season. Applying linear or nonlinear programming optimization to the meta-learner weights of our season-specific Stacking ensembles is a natural extension we identify for future work.

Fourth, optimization-ML hybrids couple meta-heuristic algorithms (e.g., particle swarm, genetic algorithms, simulated annealing) with single ML learners to navigate the hyperparameter space more efficiently than grid or random search. Poursaeid73 integrated single-layer feedforward networks with particle swarm optimization (PSO-SLFN) and genetic algorithms (GA-SLFN) for dissolved oxygen and electrical conductivity prediction in the Colorado River, with PSO-SLFN attaining R2 = 0.865 for EC. In the present study, hyperparameters of all ten base learners are tuned via fivefold grid-search cross-validation; while this approach is computationally tractable for the present sample size, meta-heuristic optimization would offer a clear advantage in scaled-up cross-karst deployments with substantially larger search spaces, and represents another natural extension of the framework.

Finally, mechanistic-data hybrid models such as SWAT and its variants have been used to simulate hydrological processes and pollutant transport17,18, but their use in karst environments is typically limited by parameter-calibration difficulties and high observational-data demand. Our purely data-driven framework circumvents these calibration challenges, at the cost of not explicitly representing conduit-flow physics; a hybrid mechanistic-ML formulation, in which a calibrated SWAT-karst variant supplies process-based features to a SHAP-interpretable ensemble, is a promising direction for future work.

Taken together, these four comparisons clarify the scope of the present contribution: the season-stratified, SHAP-interpretable Stacking framework is designed for the data regime that characterizes most karst surface-water monitoring programmes in subtropical China, namely modest cross-sectional sample sizes, season-differentiated pollution inputs, and the need for a defensible mechanistic interpretation that can inform season-specific management. It is not a substitute for Transformer-based long-horizon forecasting, Kalman-filter-driven assimilation, or weighted-ensemble optimization where those approaches are warranted by the available data, but it is complementary to all of them and provides the diagnostic foundation on which any of them could be subsequently layered.

The study further revealed seasonal transition patterns in the pollution-driving mechanisms of the Guilin karst water system based on SHAP interpretability analysis. During the wet season (June to August), NH3–N exhibited absolute dominance, accounting for 53.47% of feature importance and reflecting agricultural non-point-source pollution input during rainfall events. This single-factor dominance pattern aligns with hydrological processes in which ammonium nitrogen accumulated in soil rapidly enters water bodies via surface runoff during heavy rainfall, causing sharp increases in NH3–N concentrations within short timeframes. The pollution load index (18.25%) and dissolved oxygen (13.67%) served as secondary drivers, reflecting overall pollution pressure and re-aeration capacity of the water body, respectively. In contrast, during the dry season (December to the following February), the driving pattern transitioned toward multi-factor synergistic control. Although NH3–N remained the primary factor (26.00%), the importance of TN (25.09%) increased substantially, indicating enhanced nitrogen accumulation in water bodies following flow reduction. Dissolved oxygen elevated to 21.29%, reflecting reduced flow velocity and decreased re-aeration capacity, while the pollution load index maintained relatively high contribution (20.19%), embodying the increased relative influence of point-source discharges under baseflow conditions. Notably, the contribution of TP declined from 7.73% in the wet season to only 0.06% in the dry season, possibly related to enhanced phosphorus adsorption and fixation in sediments during the dry season.

A caveat applies when SHAP is used on a composite index built from the same predictor variables: the absolute importance values partly reflect the index’s own weighting scheme and cannot be cleanly separated from it. Our seasonal design helps absorb this. If only the fixed weights were driving SHAP, the rankings should stay the same across seasons. Under identical Pi, TN rises from 2.34% to 25.09% and TP falls from 7.73% to 0.06% in this study. This instability shows the model is reading environmental signal beyond the formula.

The seasonal pattern we identify is consistent with other karst and riverine studies and extends them. In the Wujiang karst watershed of Southwest China, Xu et al.59 used XGBoost-SHAP and found CODMn, TN and TP to be the main drivers of impairment, attributing rapid pollutant transport to the high permeability of carbonate rocks. The same mechanism underlies the wet-season NH3–N dominance we observe. The strong wet-season role of NH₃–N (53.47%) is also consistent with Fang et al.68, who reported that NH4+–N in the Yanshan River karst near Guilin was positively correlated with agricultural and built-up land cover, with a stronger coupling in the wet season. Our SHAP analysis reproduces this pattern at the model-feature level. Taken together, the shift from single-factor NH3–N dominance in wet seasons to four-factor synergistic control in dry seasons appears to be a real feature of subtropical karst water systems rather than an artifact of our modelling choices.Several findings warrant explicit discussion as unexpected. First, the near-complete disappearance of TP as a driver during the dry season, declining from 7.73% SHAP importance in the wet season to only 0.06%, is more pronounced than typically reported in non-karst water systems. In conventional riverine systems, TP typically remains a meaningful water-quality driver throughout the year due to continuous point-source discharge from wastewater treatment plants. The extreme attenuation of TP influence in the dry season can be explained by enhanced sediment phosphorus sequestration under low-flow, aerobic, and high-pH conditions characteristic of karst aquifer baseflow. Carbonate-rich sediments have a much higher phosphorus adsorption capacity than silicate-dominated systems, and the alkaline pH measured in the dry season (up to 9.53) favours calcite co-precipitation of phosphate. This geochemical pathway is largely absent in non-karst waters.

Based on these findings, differentiated control measures should be implemented for wet and dry seasons. During the wet season, agricultural NH3-N interception should be strengthened by constructing ecological ditches and vegetative buffer zones in agricultural concentration areas to intercept ammonium nitrogen in surface runoff. Additionally, improving early-stage rainwater storage facilities can reduce pollutant pulse loads during storm periods. During the dry season, stricter control of point-source total nitrogen discharge should be implemented by adopting more stringent nitrogen reduction standards for urban sewage treatment plants. Increasing ecological water supplementation projects can also improve river hydrodynamic conditions, enhancing self-purification and re-aeration efficiency of the water body.

Conclusions, limitations, and future research

The current study provides baseline insights into the complexity and variability of the urban water system around Guilin karst region and its surrounding major rivers and lakes. Based on systematic monitoring data from 208 valid water samples, a three-stage feature selection framework was applied, including correlation filtering-VIF collinearity elimination random forest importance ranking. Ten advanced machine learning models (Ridge, Lasso, ElasticNet, SVR, Random Forest, Gradient Boosting, XGBoost, LightGBM, AdaBoost and CatBoost) were subsequently evaluated. Furthermore, a Stacking ensemble was developed in which the top three cross-validation performers were re-selected as base learners independently for each season, with adaptive weight allocation supplied by a regularized Ridge meta-learner. This framework enabled high-precision prediction of WQI and facilitated analysis of key driving mechanisms of water quality during both wet and dry seasons in the Guilin karst region. The study systematically evaluated machine learning model robustness and determined that XGBoost performed optimally during the wet season (R2 = 0.9655, RMSE = 3.0938, MAE = 2.6754), effectively capturing complex relationships between pollutant inputs from rainfall runoff and water volume dilution. During the dry season, the Stacking ensemble model demonstrated highest stability by integrating multi-model advantages to more accurately identify pollutant distribution characteristics (R2 = 0.9785, RMSE = 2.9142, MAE = 2.4278). Complementary RROC signal analysis confirmed these conventional rankings with greater operational resolution: the Stacking ensemble achieved the smallest dry season |AOC| (1543.0), XGBoost achieved the smallest wet season |AOC| (3215.5), and the cross seasonal |AOC| ratios revealed a fundamental algorithmic inversion in which ensemble methods improve from wet to dry season (|AOC| ratio 0.45–0.54) while linear baselines deteriorate by a factor of 4.13–4.31, providing direct quantitative evidence that operational deployment in karst water systems requires season-specific model selection rather than a single fixed-season model. Additionally, the study revealed significant spatiotemporal variability among various water quality parameters in the dynamic and complex karst water systems. Feature importance analysis indicated that NH3–N dominated during the wet season, accounting for 53.47% of the total importance. During the dry season, water quality was controlled by a multi-factor synergistic mechanism, including NH3-N (26.00%), TN (25.09%), DO (21.29%), and pollution load index (20.19%). These findings suggest that the combined effects of urbanization processes and seasonal hydrological variations significantly impacted karst water system quality, posing potential threats to karst water systems. This study shows that combining machine learning with SHAP interpretation provides an effective route for uncovering the driving mechanisms of complex aquatic systems and supports water-quality evaluation and precision management in similar karsts. We draw a clear distinction between the karst-specific findings and the methodological contribution. The numerical SHAP importance values reported here are tied to Guilin’s karst hydrogeology, monsoonal rainfall regime and land-use composition, and should not be extrapolated as such to other regions.The analytical framework itself, however, is designed to be portable, and we justify its external validity on four grounds. First, it relies only on routinely monitored parameters (TN, TP, CODCr, NH3–N, DO, pH) that are available in standard water-quality programmes worldwide, so no Guilin-specific input is required at deployment. Second, the three-stage adaptive feature-selection module is fully data-driven; it re-identifies the dominant predictors from each new dataset rather than inheriting them from Guilin, which avoids any hard-coded local prior. Third, the seasonally stratified Stacking design targets the wet–dry contrast that characterises most monsoonal subtropical karst, and the same stratification logic remains valid wherever a comparable hydrological seasonality exists. Fourth, SHAP is a model-agnostic explanation method, so its diagnostic capability is preserved on any retrained model regardless of region.External validity is therefore strongest for other subtropical karst with carbonate-dominated hydrogeochemistry and pronounced wet/dry seasonality, provided that feature-selection thresholds and learner hyperparameters are recalibrated to local conditions. Transfer to non-karst lowland rivers, alpine systems or arid catchments would require further validation; we acknowledge this as a limitation of the present single-karst study and a priority for future cross-karst work. We therefore offer this study as both a karst-scale diagnosis of Guilin’s seasonal water-quality drivers and a transferable analytical template for interpretable, seasonally aware water-quality modelling in karst environments. Figure 14 provides a graphical summary of the proposed seasonal WQI prediction framework.

Fig. 14.

Fig. 14

Graphical summary of the seasonal WQI prediction framework.

Despite employing systematic modeling approaches and achieving high prediction accuracy, this study has several limitations requiring full consideration in result interpretation and application extension. Accurately identifying these limitations is crucial for rationally assessing research conclusion applicability boundaries and guiding future research directions. First, sample size imposes certain constraints on machine learning model performance. Although this study employed 208 valid samples for modeling and effectively controlled overfitting risks through strong regularization strategies, adaptive cross-validation, and conservative feature selection, limited sample size still constrains application of high-parameter-complexity models. Particularly, insufficient coverage of extreme pollution events may affect model prediction reliability in tail distribution intervals. Recommendations include increasing long-term continuous monitoring, especially strengthening high-frequency sampling during extreme hydrological events to enhance model generalization capability for non-routine pollution scenarios. Second, monitoring points in the study area were deployed along river corridors, with hydraulic connectivity existing among adjacent stations. Global Moran’s I tests confirmed statistically significant positive spatial autocorrelation in WQI (dry season: I = 0.1724, p < 0.001; wet season: I = 0.1816, p < 0.001) and in several driving parameters (see Supplementary Fig. S1 and Table S6 online), indicating that the independence assumption underlying random k-fold cross validation is partially violated. Although the independent 20% hold out test set was reserved prior to all model fitting to provide an unbiased external evaluation, residual spatial dependence between training and test samples may still generate slightly optimistic generalization estimates. Future work should therefore adopt explicitly spatial cross validation schemes (e.g., spatial block, buffered leave one out, or hydrologically connected fold partitioning) and consider models that explicitly encode spatial topology, such as Graph Neural Networks (GNNs) using the karst river network as the adjacency structure, to formally accommodate hydraulic connectivity. Third, current models employ separate static dataset modeling for wet and dry seasons without explicitly characterizing temporal evolution patterns of water quality indicators. Karst water system water quality processes are regulated by factors like rainfall, yet static models struggle to capture these dynamic mechanisms. The three monthly measurements per station were averaged into a single seasonal value; while this approach stabilises spatial comparisons across 104 stations, it inevitably attenuates within-season hydrological pulses particularly conduit-driven storm events that are ecologically significant in karst environments. Future studies should incorporate event-based or sub-monthly sampling to resolve these short-term dynamics. Integrating Long Short-Term (LSTM) Memory networks or Temporal Convolutional Networks with existing machine learning models to construct dynamic prediction frameworks with spatiotemporal collaborative modeling capabilities could potentially enhance model responsiveness to dynamic scenarios like storm events and seasonal transitions (Ouyang,36).

Despite the above limitations, this study’s model prediction results and SHAP driving factor analysis still provide practical guidance for precision management of karst water systems. First, season-differentiated pollution control strategies should be established. Wet season requires strengthened agricultural non-point source NH3-N interception by constructing ecological ditches and vegetative buffer zones in agricultural concentration areas to intercept ammonium nitrogen in surface runoff, while improving early-stage rainwater storage facilities to reduce pollutant pulse loads during storm periods. Dry season should strictly control point source TN discharge by implementing more stringent nitrogen reduction standards for urban sewage treatment plants and increasing ecological water supplement projects to improve river hydrodynamic conditions and enhance water body self-purification and re-aeration efficiency. Second, water quality monitoring network layouts should be optimized. Automatic monitoring stations should be added at key nodes where nutrient concentration seasonal differences are significant, achieving high-frequency online monitoring of key indicators like NH3–N, TN, and DO to provide real-time data support for early warning models. Additionally, the machine learning prediction framework constructed in this research can be integrated with existing water quality monitoring systems to achieve dynamic WQI prediction and advance pollution risk warning, providing scientific basis for management department emergency decision-making. Finally, the carbonate buffering effect characteristic of karst regions maintains relatively stable pH conditions in karst water systems, yet also means water bodies have limited buffering capacity for acidic pollutants. Therefore, special attention should be paid to potential impacts of industrial wastewater discharge on the acid–base balance of karst water systems. Future water quality protection standards should be formulated with explicit consideration of karst hydrogeological characteristics to ensure sustainable management of these vulnerable aquatic environments.

Supplementary Information

Acknowledgements

The authors gratefully acknowledge the financial support of this work by the Guangxi Key Research and Development Program (Grant number GuikeAB24010118), the Guangxi Natural Science Foundation (Grant Numbers 2025GXNSFDA069043 and 2025GXNSFBA069116), the Natural Science Foundation of China (Grant Number 52260023) and the Research funds of The Guangxi Key Laboratory of Theory and Technology for Environmental Pollution Control (Grant Number 2301Z003). We would like to thank Editage (www.editage.cn) for English language editing.

Author contributions

Kun Dong: Conceptualization, Writingoriginal draft, Writing–review & editing. Yang Huang: Writing–original draft, Visualization, Validation. Jiayu Yang: Investigation. Haixiang Li: Validation. Sze-Mun Lam: Supervision. Jin-Chung Sin: Methodology, Resources. Dunqiu Wang: Project administration, Funding acquisition, Conceptualization, Methodology, Visualization.

Data availability

All data supporting the findings of this study are available within the paper and its Supplementary Information.

Declarations

Competing interests

The authors declare no competing interests.

Ethical Approval

Water sample collection for the project "Water Sample Collection and Water Quality Environmental Testing and Research in Lingui New District, Guilin City" was approved by Guilin University of Technology. Regulatory approval was also obtained from the Lingui New District Branch of the Guilin Municipal Ecology and Environment Bureau, the Guilin Municipal Water Resources Bureau, and relevant urban and county-level environmental protection authorities. Sampling was conducted between June and August 2025, and December 2025 to February of the following year. All sampling sites were located in public waters across six urban districts and two counties in Guilin City. The sampling explicitly did not involve special protected areas such as the Li River Scenic Area or drinking water source protection zones. This study strictly complies with the Environmental Protection Law and the Water Pollution Prevention and Control Law of the People’s Republic of China. Furthermore, standardized sampling methods were employed by professionally trained personnel to ensure no environmental pollution or interference with local activities occurred during the process.

Footnotes

Publisher’s note

Springer Nature remains neutral with regard to jurisdictional claims in published maps and institutional affiliations.

References

  • 1.Goldscheider, N. et al. Global distribution of carbonate rocks and karst water resources. Hydrogeol J28(5), 1661–1677. 10.1007/s10040-020-02139-5 (2020). [DOI] [Google Scholar]
  • 2.Hawkins, D. M. The problem of overfitting. J. Chem. Inf. Comput. Sci.44(1), 1–12. 10.1021/ci0342472 (2004). [DOI] [PubMed] [Google Scholar]
  • 3.Poursaeid, M. Unraveling the water quality-ecosystem nexus using Kalman filter-driven models and feature analysis under uncertainty. J. Hydrol.657, 133092. 10.1016/j.jhydrol.2025.133092 (2025). [DOI] [Google Scholar]
  • 4.Subudhi, S., Pati, A. K. & Bose, S. Prediction of groundwater quality assessment by integrating boosted learning with DE optimizer.. Sci. Rep.16, 618. 10.1038/s41598-025-30122-1 (2026). [DOI] [PMC free article] [PubMed] [Google Scholar]
  • 5.Awaleh, M. O. et al. Groundwater vulnerability assessment of the Djibouti aquifer system (East Africa Rift System): A comparative study of DRASTIC, Hybrid-DRASTICs, and DRASTIC-based multi-objective evolutionary algorithm. J. Groundwater Sci. Eng. 10.1016/j.jgsd.2025.101564 (2025). [DOI] [Google Scholar]
  • 6.Najafzadeh, M., Basirian, S. & Li, Z. Vulnerability of the rip current phenomenon in marine environments using machine learning models. Results Eng.21, 101704. 10.1016/j.rineng.2023.101704 (2024). [DOI] [Google Scholar]
  • 7.Ultrasonic flowmeter fault early warning method based on Bayesian optimization XGBoost
  • 8.Helmreich, J. E. Regression modeling strategies with applications to linear models, logistic and ordinal regression and survival analysis (2nd edition). J. Stat. Softw.70(1), 1–3. 10.18637/jss.v070.b02 (2016). [DOI] [Google Scholar]
  • 9.Sheykhmousa, M. et al. Support vector machine versus random forest for remote sensing image classification: A meta-analysis and systematic review.. IEEE J Sel Top Appl Earth Observ Remote Sens13, 6308–6325. 10.1109/JSTARS.2020.3026724 (2020). [DOI] [Google Scholar]
  • 10.Ehteram, M., Ahmed, A. N., Sherif, M. & El-Shafie, A. An advanced deep learning model for predicting water quality index. Ecol. Indic.160, 111806. 10.1016/j.ecolind.2024.111806 (2024). [DOI] [Google Scholar]
  • 11.Shams, M. Y. et al. Water quality prediction using machine learning models based on grid search method. Multimed. Tools Appl.83(12), 35307–35334. 10.1007/s11042-023-16737-4 (2024). [DOI] [Google Scholar]
  • 12.Singha, C. et al. Prediction of urban surface water quality scenarios using hybrid stacking ensembles machine learning model in Howrah Municipal Corporation, West Bengal.. J. Environ. Manage.370, 122721. 10.1016/j.jenvman.2024.122721 (2024). [DOI] [PubMed] [Google Scholar]
  • 13.Abba, S. I. et al. Implementation of data intelligence models coupled with ensemble machine learning for prediction of water quality index. Environ. Sci. Pollut. Res.27(33), 41524–41539. 10.1007/s11356-020-09689-x (2020). [DOI] [PubMed] [Google Scholar]
  • 14.Bakhtiarizadeh, A., Najafzadeh, M. & Mohamadi, S. Enhancement of groundwater resources quality prediction by machine learning models on the basis of an improved DRASTIC method. Sci. Rep.14, 29933. 10.1038/s41598-024-80876-8 (2024). [DOI] [PMC free article] [PubMed] [Google Scholar]
  • 15.McGovern, A. et al. Making the black box more transparent: Understanding the physical implications of machine learning. Bull. Am. Meteorol. Soc.100(11), 2175–2199. 10.1175/bams-d-18-0195.1 (2019). [DOI] [Google Scholar]
  • 16.Stevanović, Z. Karst waters in potable water supply: A global scale overview. Environ. Earth Sci.78(23), 662. 10.1007/s12665-019-8670-9 (2019). [DOI] [Google Scholar]
  • 17.Wang, W. et al. A novel method for hydrology and water quality simulation in karst regions using machine learning model. Ecol. Indic.178, 113862. 10.1016/j.ecolind.2025.113862 (2025). [DOI] [Google Scholar]
  • 18.Wang, Z. J. et al. The effect of heavy rainfall events on nitrogen patterns in agricultural surface and underground streams and the implications for karst water quality protection. Agric. Water Manag.266, 107600. 10.1016/j.agwat.2022.107600 (2022). [DOI] [Google Scholar]
  • 19.Aguilera, H. et al. Building inexpensive topsoil saturated hydraulic conductivity maps for land planning based on machine learning and geostatistics. CATENA208, 105788. 10.1016/j.catena.2021.105788 (2022). [DOI] [Google Scholar]
  • 20.Liu, D. et al. Rainfall estimation using measurement report data from time-division Long Term Evolution networks. J. Hydrol.600, 126530. 10.1016/j.jhydrol.2021.126530 (2021). [DOI] [Google Scholar]
  • 21.Lundberg, S. M. et al. From local explanations to global understanding with explainable AI for trees. Nat. Mach. Intell.2(1), 56–67. 10.1038/s42256-019-0138-9 (2020). [DOI] [PMC free article] [PubMed] [Google Scholar]
  • 22.O’Brien, R. M. A caution regarding rules of thumb for variance inflation factors. Qual. Quant.41(3), 673–690. 10.1007/s11135-006-9018-6 (2007). [DOI] [Google Scholar]
  • 23.Chen, K. et al. Comparative analysis of surface water quality prediction performance and identification of key water parameters using different machine learning models based on big data. Water Res.171, 115454. 10.1016/j.watres.2019.115454 (2020). [DOI] [PubMed] [Google Scholar]
  • 24.Asadollah, S. B. H. S., Sharafati, A., Motta, D. & Yaseen, Z. M. River water quality index prediction and uncertainty analysis: A comparative study of machine learning models. J. Environ. Chem. Eng.9(1), 104599. 10.1016/j.jece.2020.104599 (2021). [DOI] [Google Scholar]
  • 25.Shanmugasundar, G. et al. A comparative study of linear, random forest and adaboost regressions for modeling non-traditional machining. Processes9(11), 2015. 10.3390/pr9112015 (2021). [DOI] [Google Scholar]
  • 26.Bility, M. T., Vora, T., Lakhani, P. N., Bhogayata, A. C. & Bhagat, S. K. Assessment of Lasso and Ridge models for soil swelling potential prediction. Sci. Rep.16(1), 11922–11922. 10.1038/S41598-026-39917-2 (2026). [DOI] [PMC free article] [PubMed] [Google Scholar]
  • 27.Orozco López, E., Kaplan, D. & Linhoss, A. Interpretable transformer neural network prediction of diverse environmental time series using weather forecasts. Water Resour. Res.60(11), e2023WR036337. 10.1029/2023WR036337 (2024). [DOI] [Google Scholar]
  • 28.Poursaeid, M. A new framework for water quality instabilities simulation by artificial intelligence approaches and optimization algorithms under uncertainty. Environ. Dev. Sustain. 10.1007/s10668-025-06356-4 (2025). [DOI] [Google Scholar]
  • 29.Rezaie-Balf, M. et al. Physicochemical parameters data assimilation for efficient improvement of water quality index prediction: Comparative assessment of a noise suppression hybridization approach. J. Clean. Prod.271, 122576. 10.1016/j.jclepro.2020.122576 (2020). [DOI] [Google Scholar]
  • 30.Li, H, J. Ma, Y. Wang, C. Zhang, S. Wu, H. Su (2025) A combinatorial machine learning models -based method for predicting the viscosity-temperature relationship of crude oil. 2025 In IEEE 7th International Conference on Communications, Information System and Computer Engineering (CISCE). https://ieeexplore.ieee.org/iel8/11064916/11064920/11065411
  • 31.Choudhary, R. et al. Predicting water quality index using stacked ensemble regression and SHAP based explainable artificial intelligence. Sci. Rep.15(1), 31139. 10.1038/s41598-025-09463-4 (2025). [DOI] [PMC free article] [PubMed] [Google Scholar]
  • 32.Xu, G. Y. et al. Decoding river pollution trends and their landscape determinants in an ecologically fragile karst karst using a machine learning model. Environ. Res.214(4), 113843. 10.1016/J.ENVRES.2022.113843 (2022). [DOI] [PubMed] [Google Scholar]
  • 33.Zhi, W. et al. From hydrometeorology to river water quality: Can a deep learning model predict dissolved oxygen at the continental scale?. Environ. Sci. Technol.55(4), 2357–2368. 10.1021/acs.est.0c06783 (2021). [DOI] [PubMed] [Google Scholar]
  • 34.Zhao, Y., Wang, Y., Liu, X., Shi, Y. & Yang, J. A machine learning-based study on ecological sensitivity and its driving factors in the karst landforms of Yangshuo County, Guilin. Front. Environ. Sci.13, 1742310–1742310. 10.3389/FENVS.2025.1742310 (2026). [DOI] [Google Scholar]
  • 35.Zhu, Q. et al. Benchmarking machine learning and deep learning models for groundwater level prediction in karst aquifers: The dominant role of hydrogeological complexity. Water18(8), 939–939. 10.3390/W18080939 (2026). [DOI] [Google Scholar]
  • 36.Zhang, J. Y. et al. Machine learning-based correlation analysis of conventional water quality parameters and composite pollution index in the Luoqing river of the South China Sea Coastal Zone. Front Mar Sci13, 1782614. 10.3389/fmars.2026.1782614 (2026). [DOI] [Google Scholar]
  • 37.Lixun, C. et al. Data-driven reliability assessment method of integrated energy systems based on probabilistic deep learning and Gaussian mixture model-hidden Markov model. Renew. Energy174, 952–970. 10.1016/J.RENENE.2021.04.102 (2021). [DOI] [Google Scholar]
  • 38.Wang, Z, N. Wei, Z. Zhai, H. Su (2024) Ultrasonic flowmeter fault early warning method based on Bayesian optimization XGBoost. 2024 4th International Symposium on Artificial Intelligence and Intelligent Manufacturing (AIIM). https://ieeexplore.ieee.org/iel8/10934113/10934151/10934315
  • 39.Wu, Z. et al. Water quality assessment based on the water quality index method in Lake Poyang: The largest freshwater lake in China. Sci. Rep.7(1), 17999. 10.1038/s41598-017-18285-y (2017). [DOI] [PMC free article] [PubMed] [Google Scholar]
  • 40.Chen, X. et al. Water quality parameters-based prediction of dissolved oxygen in estuaries using advanced explainable ensemble machine learning. J. Environ. Manage.380, 125146. 10.1016/j.jenvman.2025.125146 (2025). [DOI] [PubMed] [Google Scholar]
  • 41.Zhang, H. et al. Comprehensive assessment of the water environment carrying capacity based on machine learning. J. Clean. Prod.472, 143465. 10.1016/j.jclepro.2024.143465 (2024). [DOI] [Google Scholar]
  • 42.Wang, F., Chen, H., Lian, J., Fu, Z. & Nie, Y. Hydrological response of karst stream to precipitation variation recognized through the quantitative separation of runoff components. Sci. Total Environ.748, 142483. 10.1016/j.scitotenv.2020.142483 (2020). [DOI] [PubMed] [Google Scholar]
  • 43.Hair, J. F., Black, W. C., Babin, B. J. & Anderson, R. E. Multivariate Data Analysis 7th ed. (Pearson, 2010). [Google Scholar]
  • 44.Van der Ploeg, T., Austin, P. C. & Steyerberg, E. W. Modern modelling techniques are data hungry: A simulation study for predicting dichotomous endpoints. BMC Med. Res. Methodol.14(1), 137. 10.1186/1471-2288-14-137 (2014). [DOI] [PMC free article] [PubMed] [Google Scholar]
  • 45.Hajihosseinlou, M., Maghsoudi, A. & Ghezelbash, R. A novel scheme for mapping of MVT-type Pb–Zn prospectivity: LightGBM, a highly efficient gradient boosting decision tree machine learning algorithm. Nat. Resour. Res.32(6), 2417–2438. 10.1007/S11053-023-10249-6 (2023). [DOI] [Google Scholar]
  • 46.Wang, D. et al. Interpretable combinatorial machine learning-based shale fracability evaluation methods. Energies18(1), 186–186. 10.3390/EN18010186 (2025). [DOI] [Google Scholar]
  • 47.Dormann, C. F. et al. Collinearity: A review of methods to deal with it and a simulation study evaluating their performance. Ecography36, 27–46. 10.1111/j.1600-0587.2012.07348.x (2013). [DOI] [Google Scholar]
  • 48.Hernández-Orallo, J. ROC curves for regression. Pattern Recogn.46(12), 3395–3411. 10.1016/j.patcog.2013.06.014 (2013). [DOI] [Google Scholar]
  • 49.Huang, B. F. F. & Boutros, P. C. The parameter sensitivity of random forests. BMC Bioinformatics17(1), 1–13. 10.1186/s12859-016-1228-x (2016). [DOI] [PMC free article] [PubMed] [Google Scholar]
  • 50.Tyralis, H., Papacharalampous, G. & Langousis, A. A brief review of random forests for water scientists and practitioners and their recent history in water resources. Water11(5), 910. 10.3390/w11050910 (2019). [DOI] [Google Scholar]
  • 51.Ghorbanpour, A. K., Hessels, T., Moghim, S. & Afshar, A. Comparison and assessment of spatial downscaling methods for enhancing the accuracy of satellite-based precipitation over Lake Urmia Basin. J. Hydrol.596, 126055. 10.1016/j.jhydrol.2021.126055 (2021). [DOI] [Google Scholar]
  • 52.Liu, X., Lu, D., Zhang, A., Liu, Q. & Jiang, G. Data-driven machine learning in environmental pollution: Gains and problems. Environ. Sci. Technol.56(4), 2124–2133. 10.1021/acs.est.1c06157 (2022). [DOI] [PubMed] [Google Scholar]
  • 53.Bargam, B., Boudhar, A. & Kinnard, C. Evaluation of the support vector regression (SVR) and the random forest (RF) models accuracy for streamflow prediction under a data-scarce basin in Morocco. Discov. Appl. Sci.6, 306. 10.1007/s42452-024-05994-z (2024). [DOI] [Google Scholar]
  • 54.Basirian, S., Najafzadeh, M. & Demir, I. Water quality monitoring for coastal hypoxia: Integration of satellite imagery and machine learning models. Mar. Pollut. Bull.222(2), 118735 (2025). [DOI] [PubMed] [Google Scholar]
  • 55.Singh, B., Sihag, P., Singh, V. P., Sepahvand, A. & Singh, K. Soft computing technique-based prediction of water quality index. Water Supply21(8), 4015–4029. 10.2166/ws.2021.157 (2021). [DOI] [Google Scholar]
  • 56.AlShourbaji, I. et al. An efficient churn prediction model using gradient boosting machine and metaheuristic optimization. Sci. Rep.13(1), 14441–14441. 10.1038/S41598-023-41093-6 (2023). [DOI] [PMC free article] [PubMed] [Google Scholar]
  • 57.Tiyasha, Tung TM, Yaseen ZM (2020) A survey on river water quality modelling using artificial intelligence models: 2000–2020. J Hydrol 585:124670. 10.1016/j.jhydrol.2020.124670 [DOI]
  • 58.Han, X. & Zhou, E. Bacterial diversity, co-occurrence networks, and assembly processes differed between sediment and water in alpine karst springs of the Baiyi karst, Southwest China. Total Environ. Microbiol.2(1), 100062. 10.1016/j.temicr.2026.100062 (2026). [DOI] [Google Scholar]
  • 59.Zhang, J. et al. Machine learning-based correlation analysis of conventional water quality parameters and composite pollution index in the Luoqing river of the South China Sea Coastal Zone. Front. Mar. Sci.13, 1782614–1782614. 10.3389/FMARS.2026.1782614 (2026). [DOI] [Google Scholar]
  • 60.Zhou, R. & Zhang, Y. Predicting and explaining karst spring dissolved oxygen using interpretable deep learning approach. Hydrol. Process.37(8), e14948. 10.1002/hyp.14948 (2023). [DOI] [Google Scholar]
  • 61.Breiman, L. Random forests. Mach. Learn.45(1), 5–32. 10.1023/a:1010933404324 (2001). [DOI] [Google Scholar]
  • 62.Wenlan, Y. et al. Monitoring multi-water quality of internationally important karst wetland through deep learning, multi-sensor and multi-platform remote sensing images: A case study of Guilin, China. Ecol. Indic. 10.1016/J.ECOLIND.2023.110755 (2023). [DOI] [Google Scholar]
  • 63.Pohjankukka, J., Pahikkala, T., Nevalainen, P. & Heikkonen, J. Estimating the prediction performance of spatial models via spatial k-fold cross validation. Int. J. Geogr. Inf. Sci.31(10), 2001–2019. 10.1080/13658816.2017.1346255 (2017). [DOI] [Google Scholar]
  • 64.Niazkar, M. et al. Applications of XGBoost in water resources engineering: A systematic literature review. Environ. Model. Softw.174, 105971. 10.1016/J.ENVSOFT.2024.105971 (2024). [DOI] [Google Scholar]
  • 65.Hossain, M., Ehteram, M. & Elshafie, A. Machine learning methods for better water quality prediction. J. Hydrol.578, 124084. 10.1016/j.jhydrol.2019.124084 (2019). [DOI] [Google Scholar]
  • 66.Vatcheva, K. P., Lee, M., McCormick, J. B. & Rahbar, M. H. Multicollinearity in regression analyses conducted in epidemiologic studies. Epidemiology (Sunnyvale)6(2), 227–247. 10.4172/2161-1165.1000227 (2016). [DOI] [PMC free article] [PubMed] [Google Scholar]
  • 67.Mo, Y. M., Xu, J., Liu, C. J., Wu, J. R. & Chen, D. Assessment and prediction of water quality index (WQI) by seasonal key water parameters in a coastal city: Application of machine learning models. Environ. Monit. Assess.196(11), 1008. 10.1007/s10661-024-13209-6 (2024). [DOI] [PubMed] [Google Scholar]
  • 68.Fang, Z. et al. Scale effects of landscape patterns on nitrogen and phosphorus pollution in Yanshan River karst, Guilin, China. Water16(17), 2472. 10.3390/w16172472 (2024). [DOI] [Google Scholar]
  • 69.Alshehri, F. & Rahman, A. Coupling machine and deep learning with explainable artificial intelligence for improving prediction of groundwater quality and decision-making in arid region, Saudi Arabia. Water15(12), 2298. 10.3390/w15122298 (2023). [DOI] [Google Scholar]
  • 70.Nishat, M. H. et al. Comparative analysis of machine learning models for predicting water quality index in Dhaka’s rivers of Bangladesh. Environ. Sci. Eur.37(1), 31–31. 10.1186/S12302-025-01078-W (2025). [DOI] [Google Scholar]
  • 71.Chen, S., Huang, J., Wang, P., Tang, X. & Zhang, Z. A coupled model to improve river water quality prediction towards addressing non-stationarity and data limitation. Water Res.248, 120895. 10.1016/j.watres.2023.120895 (2024). [DOI] [PubMed] [Google Scholar]
  • 72.Guan, H. et al. Integration of orthoimagery and lidar data for object-based urban thematic mapping using random forests. Int. J. Remote Sens.34, 5166–5186. 10.1080/01431161.2013.788261 (2013). [DOI] [Google Scholar]
  • 73.Saberi-Movahed, F., Najafzadeh, M. & Mehrpooya, A. Receiving more accurate predictions for longitudinal dispersion coefficients in water pipelines: Training Group Method of Data Handling using Extreme Learning Machine Conceptions. Water Resour. Manag.34(2), 529–561. 10.1007/s11269-019-02463-w (2020). [DOI] [Google Scholar]
  • 74.Chen T, Guestrin C (2016) XGBoost: a scalable tree boosting system, in Proceedings of the 22nd ACM SIGKDD international conference on knowledge discovery and data mining, pp 785–794. 10.1145/2939672.2939785 [DOI]
  • 75.Roberts, D. R. et al. Cross‐validation strategies for data with temporal, spatial, hierarchical, or phylogenetic structure. Ecography40(8), 913–929. 10.1111/ecog.02881 (2017). [DOI] [Google Scholar]
  • 76.Duke University Medical Center, Durham, NC 27710, USA. michael.babyak@duke.edu (2004) What you see may not be what you get: a brief, nontechnical introduction to overfitting in regression-type models. Psychosomatic medicine, 66(3), 411–21. [DOI] [PubMed]
  • 77.Friedman, J. H. Greedy function approximation: A gradient boosting machine. Ann. Stat.29(5), 1189–1232. 10.1214/aos/1013203451 (2001). [DOI] [Google Scholar]
  • 78.Goldscheider, N. Karst groundwater vulnerability mapping: Application of a new method in the Swabian Alb, Germany. Hydrogeol. J.13(4), 555–564. 10.1007/s10040-003-0291-3 (2005). [DOI] [Google Scholar]
  • 79.Granata, F., Papirio, S., Esposito, G., Gargano, R. & De Marinis, G. Machine learning algorithms for the forecasting of wastewater quality indicators. Water9(2), 105. 10.3390/w9020105 (2017). [DOI] [Google Scholar]
  • 80.Gao, Z. et al. Kalman filtering assimilated machine learning methods significantly improve the prediction performance of water quality parameters. Ecol. Inform.90, 103337. 10.1016/j.ecoinf.2025.103337 (2025). [DOI] [Google Scholar]
  • 81.Hoerl, A. E. & Kennard, R. W. Ridge regression: Biased estimation for nonorthogonal problems. Technometrics42(1), 80–86. 10.1080/00401706.2000.10485983 (2000). [DOI] [Google Scholar]
  • 82.Hridoy, M. A. A. M. et al. Advanced machine learning models for accurate water quality classification and WQI prediction: Implications for aquatic disease risk management. Sci. Total Environ.1008, 180965. 10.1016/j.scitotenv.2025.180965 (2025). [DOI] [PubMed] [Google Scholar]
  • 83.Jingjing, H., Zhaoming, Y. & Huai, S. Dynamic prediction of natural gas calorific value based on deep learning. Energies16(2), 799–799. 10.3390/EN16020799 (2023). [DOI] [Google Scholar]
  • 84.Kushwaha, N. L. et al. Stacked hybridization to enhance the performance of artificial neural networks (ANN) for prediction of water quality index in the Bagh river karst, India. Heliyon10(11), e31085. 10.1016/j.heliyon.2024.e31085 (2024). [DOI] [PMC free article] [PubMed] [Google Scholar]
  • 85.Lin, F. et al. A deep reinforcement learning-based method for predictive management of demand response in natural gas pipeline networks. J. Clean. Prod. 10.1016/J.JCLEPRO.2021.130274 (2022).36246409 [DOI] [Google Scholar]
  • 86.Li, S., Zhou, Y., Cheng, J. & Yao, H. Delay-aware karst spring discharge prediction. J. Hydrol.626, 130250. 10.1016/j.jhydrol.2023.130250 (2023). [DOI] [Google Scholar]
  • 87.Masood, A., Niazkar, M., Zakwan, M. & Piraei, R. A machine learning-based framework for water quality index estimation in the Southern Bug River. Water15(20), 3543. 10.3390/w15203543 (2023). [DOI] [Google Scholar]
  • 88.Najafzadeh, M., Ahmadi-Rad, E. S. & Gebler, D. Ecological states of watercourses regarding water quality parameters and hydromorphological parameters: Deriving empirical equations by machine learning models. Stoch. Environ. Res. Risk Assess.38, 665–688. 10.1007/s00477-023-02593-z (2024). [DOI] [Google Scholar]
  • 89.Najafzadeh, M., Homaei, F. & Mohamadi, S. Reliability evaluation of groundwater quality index using data-driven models. Environ. Sci. Pollut. Res.29, 8174–8190. 10.1007/s11356-021-16158-6 (2022). [DOI] [PubMed] [Google Scholar]
  • 90.Najafzadeh, M. & Shahsavari, M. Assessment of flood susceptibility in Minab County, Iran, through the integration of topographic, climatic, and land-surface indices using ensemble machine learning models. J. Hydrol. Reg. Stud.65, 103327. 10.1016/j.ejrh.2026.103327 (2026). [DOI] [Google Scholar]
  • 91.Najah Ahmed, A. et al. Enhancing estimation of water quality index using stacking machine learning techniques: the case of Southern Bug River. Sci Total Environ1003, 180744. 10.1016/j.scitotenv.2025.180744 (2025). [DOI] [PubMed] [Google Scholar]
  • 92.Nishat, M. H. et al. Comparative analysis of machine learning models for predicting water quality index in Dhaka’s rivers of Bangladesh. Environ. Sci. Eur.37(1), 31. 10.1186/s12302-025-01078-w (2025). [DOI] [Google Scholar]
  • 93.Ouyang, B., Zhang, G., Liu, W., Qiu, S., Ding, W., Zhang, Z., Su, H. (2024) A method for predicting the gel point of mixed crude oil based on deep learning. In 2024 International Conference on Image Processing, Computer Vision and Machine Learning (ICICML). https://ieeexplore.ieee.org/document/10957978
  • 94.Peng, G. et al. Karst water quality, source of pollution, and health risk assessment in China. Sci. Total Environ.973, 179120. 10.1016/j.scitotenv.2025.179120 (2025). [DOI] [PubMed] [Google Scholar]
  • 95.Poursaeid, M. A novel approach for water resources management to accurate river flow prediction: Utilization of linear programming and weighted ensemble learning. Water Resour. Manag.39(11), 5827–5843. 10.1007/s11269-025-04230-6 (2025). [DOI] [Google Scholar]
  • 96.Shukla, B. K. et al. Integrative assessment of surface water contamination using GIS, WQI, and machine learning in urban–industrial confluence zones surrounding the National Capital Territory of the Republic of India.. Water17(7), 1076. 10.3390/w17071076 (2025). [DOI] [Google Scholar]
  • 97.Tibshirani, R. Regression shrinkage and selection via the Lasso.. J. Roy. Stat. Soc.: Ser. B (Methodol.)58(1), 267–288. 10.1111/j.2517-6161.1996.tb02080.x (2018). [DOI] [Google Scholar]
  • 98.Uddin, M. G., Nash, S., Rahman, A. & Olbert, A. I. A comprehensive method for improvement of water quality index (WQI) models for coastal water quality assessment. Water Res.219, 118532. 10.1016/j.watres.2022.118532 (2022). [DOI] [PubMed] [Google Scholar]
  • 99.James E. Helmreich (2015) Regression Modeling Strategies with Applications to Linear Models, Logistic and Ordinal Regression and Survival Analysis (2nd Edition). Journal of Statistical Software, 70(1), 1-3. https://doi.org/10.18637/jss.v070.b02
  • 101.Mosenah Turkle Bility, Tarak Vora, Parth Navneetbhai Lakhani, Ankur C Bhogayata, Suraj Kumar Bhagat (2026) Assessment of Lasso and Ridge models for soil swelling potential prediction. Scientific reports, 16(1), 11922-11922. https://doi.org/10.1038/S41598-026-39917-2 [DOI] [PMC free article] [PubMed]
  • 102.Mosaraf Hosan Nishat, Md. Habibur Rahman Bejoy Khan, Tahmeed Ahmed, Syed Nahin Hossain, Amimul Ahsan, M. M. El Sergany, Mohammad T. Alresheedi (2025) Comparative analysis of machine learning models for predicting water quality index in Dhaka’s rivers of Bangladesh. Environmental Sciences Europe, 37(1), 31-31. https://doi.org/10.1186/S12302-025-01078-W
  • 103.Guan H, Li J, Chapman M, Deng F, Ji Z, Yang X (2013) Integration of orthoimagery and lidar data for object-based urban thematic mapping using random forests. Int J Remote Sens. 34:5166–86. https://doi.org/10.1080/01431161.2013.788261
  • 104.Jonne Pohjankukka, Tapio Pahikkala, Paavo Nevalainen, Jukka Heikkonen (2017) Estimating the prediction performance of spatial models via spatial k-fold cross validation.International Journal of Geographical Information Science, 31(10), 2001-2019. https://doi.org/10.1080/13658816.2017.1346255
  • 105.Goldscheider N (2005) Karst groundwater vulnerability mapping: application of a new method in the Swabian Alb, Germany. Hydrogeol J 13(4):555-564. https://doi.org/10.1007/s10040-003-0291-3 Orozco-López et al. 2024

Associated Data

This section collects any data citations, data availability statements, or supplementary materials included in this article.

Supplementary Materials

Data Availability Statement

All data supporting the findings of this study are available within the paper and its Supplementary Information.


Articles from Scientific Reports are provided here courtesy of Nature Publishing Group

RESOURCES