Method Article

Water Quality Anomaly Detection Method Based on Attention-Gated Liquid Neural Network

DOI:

10.3791/69492

February 6th, 2026

* These authors contributed equally

In This Article

Summary

Loading...
$$\rightleftharpoonup{xx}$$ $$\longleftharp{xx}$$, $$\longrightharp{xx}$$,

This study proposes an Attention-Gated Liquid Neural Network for water quality anomaly detection that achieves superior accuracy and interpretability through continuous-time modeling and attention-based gating, thereby enhancing the reliability of environmental monitoring and supporting sustainable water management.

Abstract

Loading...
$$\rightleftharpoonup{xx}$$ $$\longleftharp{xx}$$, $$\longrightharp{xx}$$,

With the rapid expansion of water monitoring networks, time-series anomaly detection has become increasingly crucial for safeguarding aquatic environments and ensuring their sustainable management. However, conventional models often struggle with irregular sampling intervals, multivariate correlations, and interpretability in practical applications. To address these challenges, this study proposes an Attention Gated-Liquid Neural Network (AG-LNN) that integrates the dynamic modeling capability of the Liquid Neural Network (LNN) with attention-based gating mechanisms. The model introduces an input-attention gate to emphasize anomaly-relevant variables such as Dissolved Oxygen (DO) and the Permanganate Index (CODMn), and a time-constant gate that adaptively adjusts the model's temporal memory. Using data from the China National Environmental Monitoring Center (CNEMC) collected between 2019 and 2024 across 13 provinces, AG-LNN demonstrated superior performance over baseline models, including Long Short-Term Memory (LSTM), Temporal Convolutional Network (TCN), Transformer, and Graph Neural Network (GNN) architectures. It achieves a Precision-Recall Area Under Curve (PR-AUC) of 0.95 and an F1-score of 0.90, while maintaining stability under cross-region and temporal evaluations. A compact version, AG-LNN-light, reduces parameters by 62% with minimal accuracy loss, enabling efficient edge deployment. The results confirmed that attention-gated continuous-time modeling provides a robust and interpretable approach for large-scale water quality anomaly detection.

Introduction

Loading...
$$\rightleftharpoonup{xx}$$ $$\longleftharp{xx}$$, $$\longrightharp{xx}$$,

Water quality monitoring is essential for protecting public health, sustaining aquatic ecosystems, and ensuring compliance with environmental regulations. Traditional water quality models, such as the Soil and Water Assessment Tool (SWAT), the mechanistic QUAL model, and statistical forecasting approaches, often struggle to capture the highly nonlinear, multivariate, and temporally irregular nature of water systems influenced simultaneously by chemical, biological, hydrological, and meteorological factors1,2,3,4,5,6. Therefore, improving anomaly detection in water-quality data remains a pressing challenge.

In practical terms, the proposed framework is designed for multi-parameter water quality sensing networks that measure variables such as potential of hydrogen (pH), dissolved oxygen (DO), total nitrogen (TN), total phosphorus (TP), and permanganate index (CODMn), turbidity, and conductivity, with typical sampling intervals ranging from 15 to 60 min. This model tolerates irregular sampling and missing observations, making it suitable for real-world deployment in surface water and reservoir monitoring systems.

Application of machine learning in water quality anomaly detection

In recent years, machine learning (ML) and deep learning (DL) methods have gained traction for water quality applications. For example, Wang et al.7 introduced a Long Short-Term Memory Autoencoder with Attention (LSTMA-AE) combined with mechanistic constraints to improve accuracy and reduce false alarms in anomaly detection of water injection pump operations, achieving significantly better performance than the interpolation, random forest, or LSTM-AE methods.

Similarly, Zhao et al.8 proposed a Gated Recurrent Unit with Physics-Informed Neural Network (GRU-PINN) model that incorporates physical constraints into the loss function, significantly boosting interpretability and the F1-score in water quality anomaly detection tasks. ElShafeiy et al.9 developed a Multivariate Convolutional Network-LSTM (MCN-LSTM) architecture, combining Multivariate Convolutional Networks with LSTM for real-time anomaly detection in water quality sensor data, demonstrating enhanced detection capabilities in field environments. Another advancement is the Gated-Liquid Neural Network (Gated-LNN) model10, which fuses gating mechanisms into Liquid Neural Networks to accurately predict the Water Quality Index (WQI) and classify water quality, achieving R2 ≈ 0.9995 and classification accuracy of 99.74% on Indian datasets.

Time series anomaly detection

Beyond DL-specific applications, time-series anomaly detection has seen rapid development across various domains. Time-series anomaly detection has become a key technique for improving water quality monitoring and early warning. Traditional statistical methods often fail to capture the nonlinear and dynamic characteristics of water quality data, thereby prompting the application of deep learning models. For instance, Zhang et al.11 combined Empirical Mode Decomposition (EMD) with LSTM to better handle non-stationary signals, significantly improving prediction accuracy of Chemical Oxygen Demand (COD), Biochemical Oxygen Demand (BOD₅), Total Phosphorus (TP), Total Nitrogen (TN), and Ammonia Nitrogen (NH₃-N). Building on this, Wang et al.12 proposed an LSTM-based fluctuation analysis method using Approximate Entropy, which enhances real-time anomaly detection performance.

Recent advances have emphasized attention mechanisms and hybrid frameworks. Arepalli et al.13 introduced a lightweight spatially shared attention LSTM for hypoxia detection in aquaculture, achieving 99.8% accuracy, while Zhang et al.14 showed that spatial and temporal attention significantly improved CNN-LSTM prediction of Dissolved Oxygen (DO) and NH₃-N. Similarly, Long et al.15 integrated Complete Ensemble Empirical Mode Decomposition with Adaptive Noise-Variational Mode Decomposition (CEEMDAN-VMD) with attention-enhanced LSTM, achieving Nash-Sutcliffe Efficiency (NSE) values up to 0.99 across multiple indicators. At the application level, Xie et al.16 demonstrated a mobile LSTM-sequence-to-sequence (Seq2Seq) system for operational, real-time water quality prediction across river basins.

Overall, these studies highlight a clear trend in LSTM-based baselines, attention-augmented hybrid models, and system-level applications. Although accuracy has improved substantially, challenges remain in interpretability, robustness under noisy conditions, and generalization across diverse monitoring networks.

Application of graph neural networks and spatiotemporal models in environmental monitoring

Graph neural networks (GNNs) and spatiotemporal deep learning models have recently demonstrated significant potential in environmental monitoring by capturing both spatial correlations among monitoring sites and temporal dependencies in water quality dynamics. For example, Wu et al.17 proposed a pre-training enhanced Spatio-Temporal Graph Neural Network (PT-STGNN) for wastewater treatment plants, integrating transformer-based pre-training and graph structure learning to improve long-term prediction of COD, NH₃-N, TP, TN, pH, and flow rate. Similarly, Wan et al.18 developed a Spatio-Temporal Feature GNN (STF-GNN) that combined graph convolution, GRU, and attention mechanisms, significantly improving Dissolved Oxygen (DO) and TN predictions while demonstrating robust cross-basin generalization.

Hybrid frameworks have emerged beyond purely data-driven designs to enhance generalization. Mu et al.19 introduced the spatiotemporal graph physics-informed neural network (ST-GPINN), which embeds hydraulic principles into Graph Neural Network (GNN)-based models for water distribution systems. By coupling graph representations with physics-informed constraints, ST-GPINN achieves state-of-the-art accuracy while scaling effectively from small to large networks. Together, these studies highlight the growing role of spatio-temporal GNNs in environmental monitoring, advancing predictive accuracy, interpretability, and robustness, and laying the foundation for next-generation intelligent water management systems.

Advantages and potential of liquid neural networks

Liquid Neural Networks (LNNs), also known as Liquid Time-Constant networks, uniquely model continuous-time dynamics using input-dependent, learnable time constants. Hasani et al.20 introduced LNNs and demonstrated their expressive power, stability, and efficiency in time-series tasks. Their brain-inspired adaptability makes them promising candidates for modeling dynamic environmental phenomena such as water quality, yet their integration with attention mechanisms remains underexplored.

Attention mechanisms, especially attention gates, are powerful tools for focusing on relevant features and enabling interpretability. Although widely used in medical imaging, Attention U-Net sets a foundation for selective feature refinement via learnable attention gates. Attention has also been applied in sensor-based anomaly detection frameworks, such as LSTMA-AE7 and GRU-PINN8, enhancing sensitivity to critical patterns and improving model transparency.

Taken together, these observations indicate the need for a hybrid architecture that synergizes continuous-time adaptability with interpretable attention mechanisms. Hence, we propose an Attention-Gated Liquid Neural Network (AG-LNN) that integrates the dynamic modeling capabilities of Liquid Neural Networks (LNNs) with attention gates that focus on salient inputs or temporal segments. This architecture aims to enhance robustness to sensor noise and irregular sampling, improve sensitivity to short-duration anomalies, and offer interpretability through attention heatmaps and adaptive time-constant trajectories. The AG-LNN was evaluated on real-world multivariate water quality datasets and benchmarked against LSTM, Transformer, pure LNN, and traditional ML baselines. Both quantitative (Precision, Recall, F1, AUC) and qualitative (attention visualizations, time-constant dynamics) analyses demonstrated the effectiveness and transparency of the proposed model.

Access restricted. Please log in or start a trial to view this content.

Protocol

Loading...
$$\rightleftharpoonup{xx}$$ $$\longleftharp{xx}$$, $$\longrightharp{xx}$$,

NOTE: The overall workflow of this study is shown in Figure 1.

1. Data acquisition

  1. Data source identification
    1. Obtain water quality time-series data from the China National Environmental Monitoring Center (CNEMC) public database (https://www.cnemc.cn/sssj/). Retrieve continuous national-level monitoring records covering major lakes and reservoirs in China. Key physicochemical indicators included pH, dissolved oxygen (DO), total phosphorus (TP), total nitrogen (TN), permanganate index (CODMn), turbidity (NTU), and electrical conductivity (EC). 
    2. Ensure that the corresponding metadata, such as monitoring time, station operational status, and water quality classification (Class I-V), are included in the downloaded dataset.
  2. Dataset retrieval and file specification
    1. Ensure data reproducibility by consolidating and sharing the processed dataset under the filename cnemc_data_2019_2024. csv. The file in the Baidu Cloud repository (https://pan.baidu.com/s/1ZXYxkCZAnx7tiOHJhuJ2Qg?pwd=u97h) enables public access and verification of all experiments.
    2. Include monitoring data from 13 provinces (Guangdong, Hubei, Jiangsu, Zhejiang, Anhui, Fujian, Jiangxi, Henan, Sichuan, Guizhou, Liaoning, Heilongjiang, and Jilin) to ensure representative coverage across diverse hydrological and climatic zones of North, South, East, West, and Plateau regions.
    3. Assign an equal number of monitoring records to each province, yielding a total of 1,832 entries collected between January 2019 and December 2024. Label each station using province-based identifiers (e.g., GD001 for Guangdong, HB001 for Hubei). For every record, include descriptive attributes such as basin, waterbody_type (Lake or Reservoir), and season (Spring, Summer, Autumn, or Winter, derived from sampling time).
    4. Add optional geolocation fields (longitude and latitude) to facilitate spatial analysis and reproducibility. Complete field definitions, data types, and units used in cnemc_2019_2024. The CSV values are summarized in Table 1.

2. Variable selection and labeling

  1. Variable selection
    1. Select variables that represent the most frequently monitored physicochemical parameters of surface water, ensuring ecological relevance and sensitivity to pollution or environmental disturbances. Specifically, include the following indicators:
      pH, reflecting the acid-base balance of water and influencing biological activity and chemical solubility
      Dissolved Oxygen (DO), a direct indicator of aquatic ecosystem health and organic pollution
      Total Phosphorus (TP) and Total Nitrogen (TN), two major nutrients linked to eutrophication processes
      Permanganate Index (CODMn), representing the oxidizable organic matter content and an indirect measure of organic pollution
      Turbidity (Tur), which reflects suspended particles and sediment load
      Electrical Conductivity (EC), indicating the concentration of dissolved ions and overall salinity
    2. Select these variables not only for their routine availability from CNEMC monitoring stations but also for their demonstrated relevance in prior studies10,11,14,17 on water quality assessment and anomaly detection.
  2. Labeling strategy
    1. Define anomaly labels to support model training and evaluation. Apply a dual-labeling strategy that combines the two complementary approaches.
    2. Regulatory or expert-based labeling: Adopt officially documented or annotated abnormal events (e.g., sudden pollutant discharges, algal blooms, or instrument failures) from the monitoring authority as ground truth anomalies.
    3. Data-driven weak labeling: Infer anomalies for monitoring intervals lacking explicit expert annotations directly from the CNEMC multivariate time-series dataset by applying a statistically guided, season-aware weak labeling framework.
    4. Structure this process into three main components: performing seasonal normalization, applying quantile-based deviation detection, and reinforcing the results through residual-based evaluation.
      1. Seasonal normalization: Normalize seasonal effects for each variable  xi,t (e.g., DO, CODMn, TP, TN, Turbidity) using the explicit season field (Spring, Summer, Autumn, Winter) provided in the CNEMC dataset. Standardize each variable within its corresponding seasonal subset, as shown in Equation (1).
        Statistical normalization formula, equation displaying standardized variable transformation.(1)
        where μi(s) and σi(s) are the mean and standard deviation of variable i during season s. This normalization compensates for systematic seasonal shifts such as reduced DO in summer or increased CODMn during the rainy season, ensuring cross-season comparability.
      2. Quantile-based weak labeling: After normalization, identify anomalies by applying robust quantile thresholds computed for each variable within the same season and province group, as shown in Equation (2).
        Statistical formula Q for data analysis; showcases lower and upper quantiles in a mathematical context.   (2)
        where Q_p (⋅) is the p-th quantile operator, Static equilibrium equations: Q_i,lower^(s), Q_i,upper^(s); symbols. is the lower and upper quantile thresholds (1st and 99th percentiles) for variable i in season s. Flag a data point as anomalous if it exceeds these bounds, as shown in Equation (3).
        Mathematical inequality symbols in static equilibrium formula; diagram illustrates constraints. (3)
        This step adaptively accounts for regional and seasonal differences, thereby avoiding false detections caused by natural hydrological fluctuations.
      3. Residual-based reinforcement: Establish a rolling 15-day median baseline to detect abrupt short-term deviations that quantile thresholds might miss, as expressed in Equation (4).
        Statistical formula for detrending with moving median; equation: r_it = x_it - median(x_i,t-15:t+15). (4)
        where ri,t is the residual deviation of variable i at time t, median(xi,t-15:t+15) is the 15-day rolling median baseline around t. Flag a data point as a residual anomaly if the absolute residual exceeds three times the seasonal standard deviation (|ri,t| > 3σi(s)). This residual reinforcement effectively captured the transient spikes caused by pollutant discharge, rainfall events, or temporary sensor faults.
      4. Combined weak-label decision: Fuse both quantile-based and residual-based anomaly indicators to assign a binary weak label yt, as defined in Equation (5).
        Static equilibrium equation, \(Y_t=1\) conditionally describes anomaly conditions in variables, formula.   (5)
        where yt=1 indicates that at least one parameter exhibits anomalous behavior at time t, y= 0 denotes normal observations across all parameters.
        Generate a set of data-driven weak annotations across all 13 provinces and five climatic regions in the CNEMC dataset using the combined labeling procedure. Integrate these labels into confidence-weighted learning by assigning a confidence weight of 0.7 to weak labels relative to expert-verified annotations with a weight of 1.0.
    5. Proportion of annotation types
      1. Use approximately 42% expert-verified annotations derived from official environmental reports, and 58% weak annotations generated from continuous monitoring data. Apply a heuristic fusion of z-score thresholding and seasonal trend decomposition (STL) to detect potential anomalies in multivariate water quality time series. The chosen annotation proportions are validated through experiments presented in Section 5.1 (Effect of annotation ratio) of the Results part. These results confirm that an empirically optimal balance occurs around a 40:60 expert-to-weak ratio, which is consistent with the actual dataset composition.
    6. Validation of weak annotation accuracy
      1. Ensure the reliability of weakly annotated samples by cross-checking a random subset of 800 weakly labeled instances with environmental experts. Record the agreement rate between weak annotations and expert judgments, which should reach approximately 87.5%. Remove samples with low anomaly confidence (< 0.6) or disagreement with the expert validation set from the training data.
      2. Maintain the retained weak annotations at an effective accuracy above 90%. Examine the reliability of weak annotations and their influence on model performance, where controlled experiments confirm that preserving weak-label accuracy above 90% effectively prevents training bias and ensures stable predictive behavior.
    7. Bias mitigation
      1. During training, apply a confidence-weighted learning strategy to mitigate potential bias introduced by weak annotations. Define the loss function as shown in Equation (6).
        Logarithmic loss formula; mathematical symbol; educational; data analysis; statistical relevance. (6)
        where yi∈{0,1} denotes the ground-truth label of the i-th sample, pi represents the model’s predicted probability, wi is the weight assigned to each sample, and N is the total number of samples.
      2. Determine the sample weight wi based on the source and confidence level of the label, as shown in Equation (7).
        Weighted annotation equation, diagram, showing expert and weak annotations differentiation. (7)
        Here, ci∈[0,1] denotes the confidence score of the i-th annotation, and α,β are the global weighting coefficients for expert and weak labels, respectively. Empirical analysis demonstrated that setting α=1.0 and β=0.7 achieves the best trade-off between performance and stability, as this weighting effectively suppresses residual noise from weak labels while maintaining sufficient contribution from their broader coverage.
      3. Select seven physicochemical parameters (pH, DO, TP, TN, CODMn, Tur, and EC) as the core variables for anomaly detection. Use these indicators to comprehensively represent nutrient status, organic pollution, oxygen availability, and ionic composition of surface water. Provide a detailed description of each variable.

3. Data quality control and preprocessing

  1. Establish a hierarchical data quality control and preprocessing pipeline to ensure the reliability and modeling applicability of multi-source water quality monitoring data. Sequentially perform time alignment, missing value imputation, anomaly detection, scale normalization, and windowed sample construction. Dynamically select and combine appropriate methods according to the specific characteristics of the data.
  2. Time alignment and resampling: Align all monitoring station sequences to a unified 15 min temporal resolution to account for unsynchronized timestamps. For irregularly sampled points, apply linear interpolation between adjacent observations according to Equation (8). Ensure that the subsequent windowed samples are constructed on a consistent temporal grid.
    Linear interpolation method; equation for estimating values between data points; mathematical concept. (8)
  3. Missing value processing
    1. Categorize missing values based on the length of consecutive gaps into short-term missing (<6 consecutive points, i.e., <1.5 h) and long-term missing (≥6 consecutive points), and different strategies were applied accordingly.
    2. Apply Kalman filtering and smoothing to perform dynamic estimation for long-term missing intervals (≥ 6 consecutive points). Model each water quality variable xt (e.g., DO, TN, CODMn) using a discrete linear state-space formulation, as shown in
      Equations (9) to (11).
      State space equations, xₜ=Axₜ₋₁+wₜ, yₜ=Hxₜ+vₜ, mathematical formula, dynamic system analysis. (9)
      Kalman filter equation, Bayesian estimate, state prediction update, algorithm diagram. (10)
      Kalman filter equation, statistical estimation, formula, predictive error minimization. (11)
      where xt is the latent (true) state of the water quality variable at time t, yt is the corresponding observed value; A is the state transition coefficient (empirically set to 0.95) to reflect a high temporal correlation in 15 min observations, H is the observation matrix (set to 1 for direct measurements),  w∼ N(0,Q) and v∼ N(0,R) are the zero-mean Gaussian process and measurement noise, respectively; Q = (0.05σx)2 and R=(0.10σx)2, where σx is the standard deviation of the variable within a 7-day sliding window.
    3. Configure the filter to remain sensitive to short-term variability while suppressing random measurement noise. Initialize the initial state Static equilibrium equation ΣFx=0 diagram; symbols indicate force balance in systems. using the first available non-missing observation and set the initial covariance P0|0 to σ²x; variance symbol; represents dispersion in statistical data analysis.. Remove the entire segment if the missing interval exceeds 24 h (96 records) to prevent error accumulation from long-term extrapolation.
  4. Anomaly detection and correction
    1. Identify and correct anomalies in two sequential steps: hard constraints (physical limits) and soft constraints (gradient limits and quantile winsorization).
      1. Hard constraints (Physical limits): Discard measurements that fall outside physically plausible ranges (e.g.,pH∉[0,14],DO>20 mg/L).
      2. Soft constraints (Gradient limits + Quantile winsorization): Flag a data point as suspicious if the absolute change rate between two consecutive observations exceeds an empirically defined gradient threshold |x- xt-1 | > θ. Set θ=3σ_xΔt-1, where σ x denotes the standard deviation of the variable over a 24 h sliding window, and Δt = 15 min represents the sampling interval. Correct extreme values using a Winsorization procedure, as expressed in Equation (12).
        Equation illustrating statistical quantile function, showing calculations for threshold values. (12)
        where Qα and Q1-α denote the 1% and 99%, respectively.
        The procedure first eliminates impossible values through hard constraints, then flags abnormal observations based on gradient thresholds, and finally smooths the residual deviations using quantile-based winsorization. This hierarchical approach ensured both the physical validity and statistical stability of the cleaned dataset.
  5. Normalization
    1. Different water quality indicators have different units and values. To eliminate scale differences and prevent certain variables from dominating the model training process, apply z-score normalization.
  6. Window sample construction
    1. Transform the time series into fixed length sliding window samples to preserve the temporal dependencies. Given window length W and step size S, construct the input samples according to Equation (13).
      Time series analysis equation in diagram format for forecasting using lag variables.  (13)
      Set W=96 (i.e., 24 h with a 15 min interval) and S=1 to generate samples sequentially using a point-by-point sliding window.

4. Attention-Gated Liquid Neural Network (AG-LNN)

NOTE: The overall architecture of the proposed Attention-Gated Liquid Neural Network (AG-LNN) is illustrated in Figure 2. The model integrates multisource water quality inputs, an attention-based gating mechanism, an LNN with adaptive time constants, and a readout-decoding stage with interpretability outputs. This design allows the network to dynamically capture complex temporal dependencies while remaining robust to noise and non-uniform sampling.

  1. Multi-source input layer: Refer to the leftmost part of Figure 2 to visualize the multi-source water quality monitoring data {xτ}, where each vector xτ∈RC represents measurements of C physicochemical variables (e.g., pH, DO, TN, TP, CODMn, Turbidity, EC) at time τ. Segment the input sequences into fixed-length sliding windows of size W, as formulated in Equation (14).
    Time series equation, Xt={xt}t=-w+1t; matrix algebra concept; data prediction analysis.   (14)
  2. Input attention gate: Apply an attention gate, as illustrated in the lower-left block of Figure 2, to emphasize informative variables and suppress noisy fluctuations. Compute the attention weights according to Equation (15).
    Attention mechanism equations; αt = σ(Wa[ht-1;xt]+ba), describing neural network process. (15)
    where ατ denotes channel-level importance at time τ. This mechanism ensures that variables that are highly correlated with abnormal changes (e.g., DO and CODMn) receive greater weights.
  3. Time-constant gate
    1. Modulate the liquid time constant using the aggregated attention signal, as illustrated in the top block of Figure 2, and formulate it according to Equation (16).
      Complex mathematical formula; lambda decay rate equation, involving exponential and summation terms. (16)
      where, λbase is the baseline time constant controlling the intrinsic memory of each liquid neuron; DNA editing process; ΣFx=0 formula; experiment setup; gene modification method analysis. denotes the mean attention weight across C channels at timestep τ; β is a sensitivity coefficient determining how strongly attention influences temporal responsiveness.
    2. When DNA editing process; ΣFx=0 formula; experiment setup; gene modification method analysis. is high, λτ decreases, prompting the network to accelerate its response and capture short-lived anomalies better. Impose bound constraints on λτ to stabilize the training. 
    3. Ensure numerical stability and prevent exploding or vanishing dynamics by imposing bound constraints on the time constant λτ. Set λτ ∈ [λminmax] = [0.5,2.0]. Clip any values outside this range to the nearest bound during training to maintain controlled adaptive behavior under varying environmental conditions. Setting λ = 1.0 yields optimal precision and convergence stability.
  4. Liquid neural layer
    1. Employ a Liquid Neural Network (LNN) to perform continuous-time modeling of the time series, and express its dynamic formulation as shown in Equation (17).
      Dynamic system equation: h(t)=-λ(·)⊙h+Aσ(h)+Bẋ(t)+b. Mathematical formula analysis. (17)
      where ḣ(t) denotes the hidden state vector; λ(⋅) represents the learnable time constant, modulated by attention; σ(∙) is the nonlinear activation function (ReLU); A and B are learnable weight matrices; x̃(t) is the normalized input vector; b is the bias term. This equation ensures that the network dynamics evolve with both inputs and states, while the time constant λ(⋅) remains learnable and context dependent. 
    2. For numerical computation, use the explicit Euler integration method for discretization, as shown in Equation (18).
      Recurrent neural network equation, formula for hidden state update, mathematical notation. (18)
      Here, Δτ represents the discrete time step (integration interval) between successive observations, computed using Equation (19).
      Δ_τ=(tτ - tτ-1)/Tnorm (19)
      where tτ and tτ-1 are the timestamps (in minutes) of consecutive measurements and Tnorm = 15 min corresponds to the nominal sampling period in the CNEMC monitoring data. Thus, Δτ = 1 for regular 15 min intervals, whereas Δτ > 1 or Δτ < 1 reflects irregular sampling caused by missing or dense observations. This approach naturally handles irregular sampling while maintaining interpretability with respect to the underlying physical dynamics. 
  5. Readout and anomaly scoring
    1. After completing the hidden state update, employ a readout layer in the AG-LNN to generate the one-step-ahead prediction, as expressed in Equation (20).
      Recurrent neural network equation, \(\hat{x}_{\tau+1}=W_oh_\tau+c\), symbol representation. (20)
      where Wo and c denote the output projection matrix and bias vector, respectively.
    2. Compute the residual as the anomaly score based on the discrepancy between the predicted and observed values, as shown in Equation (21).
      Static equilibrium equation, Sτ=||x̂τ+1−xτ+1||2, formula, used in mathematical analysis. (21)
    3. Apply a quantile-based adaptive thresholding strategy to determine whether an observation corresponds to an anomaly.
    4. Define the anomaly threshold θx for each water quality variable using the 99th percentile of the residuals in the training set, as formulated in Equation (22).
      Anomaly detection equation; statistical threshold comparison; formula for data analysis methods.   (22)
      ​where σs denotes the standard deviation of the residual sequence, and γ = 0.2 is a fixed safety coefficient compensating for natural diurnal variations. 
    5. This design corresponds approximately to a 1% exceedance probability, consistent with standard environmental anomaly definitions. During inference, the network outputs only the residual sequence {sτ}, for anomaly determination, perform post-hoc according to Equations (14)–(15). This separation design is consistent with the overall study framework, ensuring that the model focuses on feature extraction and anomaly measurement rather than directly participating in threshold setting. 
  6. Training objectives and regularization
    1. During training, minimize the prediction error while simultaneously applying additional regularization on both the attention weights and the time constants to prevent overfitting and numerical instability. The loss function is expressed by Equation (23).
      Optimization equation with regularization terms; diagram for sparse, entropy, or L2 methods. (23)
    2. Apply Regα through entropy regularization -∑ατ log ατ or the L1-norm to avoid attention collapse. Apply Regλ by penalizing Δλτ = λτ - λτ-1, constraining drastic fluctuations in the time constant, and adding penalties when it exceeds the predefined upper and lower bounds. This approach was used to maintain the flexibility of the AG-LNN while ensuring stability during training.
  7. Forward computation and interpretability output
    1. Simplify the forward computation process of AG-LNN into the following chain structure, as shown in Equation (24).
      Neural network architecture equation showing input gate, time constant, liquid update process. (24)
    2. During both training and inference, continuously record the attention weights ατ and the liquid time constants λτ, and use them to generate interpretability results, namely attention heatmaps and liquid time constant curves. Use these visualizations to highlight how the model focuses on different variables and time scales, thereby enhancing the interpretability of the method. 

5. Training procedure

  1. Data partitioning: Divide the multi-source water quality time series chronologically into training, validation, and testing subsets using a 70%/15%/15% split. Ensure robustness by selecting the test set to include known abnormal periods while keeping it strictly non-overlapping with the training data to prevent temporal leakage.
  2. Training details
    1. Solve the continuous dynamics in the liquid layer using a stabilized explicit Euler scheme. For comparison, test a closed-form discretization following the referenced formulation20,21.
    2. Attention warm-up schedule: Clamp the attention weights to a near-uniform value (≈ 1.0) during the first 10 epochs to stabilize the gradient flow. After epoch 10, gradually anneal the attention to its learnable state by linearly releasing the weight updates over the next 5 epochs (scaling factor = 0.8). Use this warm-up strategy to prevent unstable oscillations at the start of training and to ensure smooth convergence.
    3. Optimizer and learning-rate scheduler: Optimize the model parameters using the Adam optimizer with β1 = 0.9, β2 = 0.999, ε = 1 x 10⁻⁸. Set the initial learning rate to 1 x 10⁻³ and control it using a cosine-annealing schedule (Tmax = 50 epochs, Minimum Learning Rate = 1 x 10⁻⁵). Choose batch sizes between 32 and 128, depending on the GPU memory capacity. Apply this gradual scheduling to ensure stable adaptation of continuous-time dynamics without abrupt learning-rate shifts.
    4. Early stopping and reproducibility settings: Terminate training early if the validation metric (AU-PR or F1) does not improve for 10 consecutive epochs (patience = 10). Repeat each experiment 3x using fixed random seeds (42, 73, and 101) to ensure reproducibility. Set the maximum number of epochs to 100 and retain the checkpoint with the best validation AU-PR for testing.
  3. Hardware and software environment
    1. Perform all experiments on a Linux server equipped with NVIDIA Tesla V100 GPUs (32 GB memory) and dual Intel Xeon Gold 6230 CPUs with 256 GB RAM. Implement the model in Python 3.9 using PyTorch 2.0 as the deep learning framework, and use auxiliary libraries including NumPy 1.23, SciPy 1.9, and scikit-learn 1.2 for preprocessing and evaluation. Containerize all experiments using Docker 23.0 and manage them on Ubuntu 20.04 LTS to ensure reproducibility and portability of results. Refer to Table of materials for detailed specifications of all hardware devices and software tools to guarantee clarity and replicability.

Access restricted. Please log in or start a trial to view this content.

Results

Loading...
$$\rightleftharpoonup{xx}$$ $$\longleftharp{xx}$$, $$\longrightharp{xx}$$,

Overall performance comparison

Table 2 presents the comparative results of the different baseline models and the proposed AG-LNN for the water quality anomaly detection task. Among the traditional unsupervised baselines, Isolation Forest22 and One-Class SVM23 achieved only moderate precision and recall, reflecting their limited ability to capture the temporal dependencies inherent in multi-source water quality da...

Access restricted. Please log in or start a trial to view this content.

Discussion

Loading...
$$\rightleftharpoonup{xx}$$ $$\longleftharp{xx}$$, $$\longrightharp{xx}$$,

This study introduces an Attention-Gated Liquid Neural Network (AG-LNN), a novel architecture for water quality anomaly detection that combines continuous-time liquid dynamics with attention-based gating mechanisms. The liquid neural component of an AG-LNN is inspired by Liquid Time-constant Networks (LTCs), which model time series with learnable, input-dependent time constants20. However, AG-LNN extends beyond standard LTCs by integrating two additional gates: an input attention gate, which empha...

Access restricted. Please log in or start a trial to view this content.

Disclosures

Loading...
$$\rightleftharpoonup{xx}$$ $$\longleftharp{xx}$$, $$\longrightharp{xx}$$,

The authors have no conflicts of interest.

Acknowledgements

Loading...
$$\rightleftharpoonup{xx}$$ $$\longleftharp{xx}$$, $$\longrightharp{xx}$$,

This research was supported by the 2024 Characteristic Innovation Project for Colleges and Universities in Guangdong Province Water Quality Monitoring and Early Warning System Based on Wireless Sensor Network (Project Number: 2024KTSCX304), the 2024 School-level Scientific Research Project of Guangzhou Nanyang Polytechnic College Water Tank Management System Based on Internet of Things (Project Number: NY-2024KYZD-01), the 2022 Guangdong Province Key Area Special Project (New Generation Electronic Information) Online Prediction, Early Warning and Linkage Prevention and Control System for Aquaculture Based on HarmonyOS (Project Number: 2022ZDZX1081), and 2021 Guangdong Province Vocational Colleges High-level Professional Group Construction Project Big Data Technology Professional Group (Project Number: GSPZYQ2020089).

Access restricted. Please log in or start a trial to view this content.

Materials

List of materials used in this article
NameCompanyCatalog NumberComments
256 GB DDR4 RAMSamsungM393A4K40DB3High-capacity memory for handling large multivariate time-series datasets
CUDA 11.6NVIDIAN/AGPU acceleration toolkit for PyTorch
Intel Xeon Gold 6330 CPU (2.0GHz, 28 cores)IntelBX80708-6330Used as the main computation server for model training
Matplotlib 3.4, Seaborn 0.11Open SourceN/AVisualization of experimental results
NumPy 1.21, Pandas 1.3Open SourceN/AData preprocessing and feature engineering
NVIDIA A100 GPU (40GB)NVIDIA900-21001-0000-001Accelerated training of AG-LNN with CUDA support
Python 3.9Python Software FoundationN/AMain programming language for implementation
PyTorch 1.12Meta AIN/ADeep learning framework used for building AG-LNN
Scikit-learn 0.24Open SourceN/AEvaluation metrics and baseline models
Ubuntu 20.04 LTS OSCanonicalN/AOperating system for the computational environment

References

Loading...
$$\rightleftharpoonup{xx}$$ $$\longleftharp{xx}$$, $$\longrightharp{xx}$$,
  1. Wu, J., Wang, Z. A Hybrid Model for Water Quality Prediction Based on an Artificial Neural Network, Wavelet Transform, and Long Short-Term Memory. Water. 14 (4), 610(2022).
  2. Nazari, M., Kerachian, R. Optimal Operation of Reservoirs Considering Water Quantity and Quality Aspects: A Systematic State-of-the-Art Review. Water Resour Manage. 38 (15), 5911-5944 (2024).
  3. Das, S. K., et al. Calibration, Validation and Uncertainty Analysis of a SWAT Water Quality Model. Appl Water Sci. 14 (4), 86(2024).
  4. Mutlu, E., et al. Water Quality Assessment of Şehriban Stream (Kastamonu, Türkİye) from a Multi-Statistical Perspective. Int J Environ Anal Chem. 104 (19), 8229-8245 (2024).
  5. Hassan, A., Samy, G., Hegazy, M., Balah, A., Fathy, S. Statistical Analysis for Water Quality Data Using ANOVA (Case Study-Lake Burullus Influent Drains). Ain Shams Eng J. 15 (4), 102652(2024).
  6. Fang, S., Deitch, M. J., Gebremicael, T. G., Angelini, C., Ortals, C. J. Identifying Critical Source Areas of Non-Point Source Pollution to Enhance Water Quality: Integrated SWAT Modeling and Multi-Variable Statistical Analysis to Reveal Key Variables and Thresholds. Water Res. 253, 121286(2024).
  7. Wang, M., et al. Anomaly Detection in Multidimensional Time Series for Water Injection Pump Operations Based on LSTMA-AE and Mechanism Constraints. Sci Rep. 15 (1), 2020(2025).
  8. Zhao, X. Water Quality Anomaly Detection Research Based on GRU-PINN Model. E3S Web ConfEDP Sci. 628, 01003(2025).
  9. El-Shafeiy, E., Alsabaan, M., Ibrahem, M. I., Elwahsh, H. Real-Time Anomaly Detection for Water Quality Sensor Monitoring Based on Multivariate Deep Learning Technique. Sensors. 23 (20), 8613(2023).
  10. Chadalavada, S., et al. Gated LNN: Gated Liquid Neural Networks for Accurate Water Quality Index Prediction and Classification. IEEE Access. 13, 69500-69512 (2025).
  11. Zhang, Y., et al. Accurate Prediction of Water Quality in Urban Drainage Network with Integrated EMD-LSTM Model. J Cleaner Prod. 354, 131724(2022).
  12. Wang, L., Dong, H., Cao, Y., Hou, D., Zhang, G. Real-Time Water Quality Detection Based on Fluctuation Feature Analysis with the LSTM Model. J Hydroinfo. 25 (1), 140-149 (2023).
  13. Arepalli, P. G., Naik, K. J. A Deep Learning-Enabled IoT Framework for Early Hypoxia Detection in Aqua Water Using Light Weight Spatially Shared Attention-LSTM Network. J Supercomput. 80 (2), 2718-2747 (2024).
  14. Zhang, M., Zhang, Z., Wang, X., Liao, Z., Wang, L. The Use of Attention-Enhanced CNN-LSTM Models for Multi-Indicator and Time-Series Predictions of Surface Water Quality. Water Resour Manage. 38 (15), 6103-6119 (2024).
  15. Long, J., Lu, C., Lei, Y., Chen, Z. Y., Wang, Y. Application of an Improved LSTM Model Based on FECA and CEEMDAN VMD Decomposition in Water Quality Prediction. Sci Rep. 15 (1), 12847(2025).
  16. Xie, L., et al. A Novel Operational Water Quality Mobile Prediction System with LSTM-Seq2Seq Model. Environ Model Software. 185, 106290(2025).
  17. Wu, X., Chen, M., Zhu, T., Chen, D., Xiong, J. Pre-Training Enhanced Spatio-Temporal Graph Neural Network for Predicting Influent Water Quality and Flow Rate of Wastewater Treatment Plant: Improvement of Forecast Accuracy and Analysis of Related Factors. Sci Total Environ. 951, 175411(2024).
  18. Wan, H., Xiang, L., Cai, Y., Xie, Y., Xu, R. Temporal and Spatial Feature Extraction Using Graph Neural Networks for Multi-Point Water Quality Prediction in River Network Areas. Water Res. 281, 123561(2025).
  19. Mu, T., et al. ST-GPINN: A Spatio-Temporal Graph Physics-Informed Neural Network for Enhanced Water Quality Prediction in Water Distribution Systems. NPJ Clean Water. 8 (1), 74(2025).
  20. Liquid Time-Constant Networks. Hasani, R., Lechner, M., Amini, A., Rus, D., Grosu, R. Proc AAAI Conf Artif Intell, 35, 7657-7666 (2021).
  21. A Method for Stochastic Optimization. Adam, K. D. B. J. Int Conf Learning Representat ICLR, 5 (6), 1(2015).
  22. Mehrabian, A., Pahlevan, N. Identifying Anomalies in Surface Water Quality Using Isolation Forest. AGU Fall Meeting Abstracts. 2019, EP54C-09(2019).
  23. Ananias, P. H. M., Negri, R. G. Anomalous Behaviour Detection Using One-Class Support Vector Machine and Remote Sensing Images: A Case Study of Algal Bloom Occurrence in Inland Waters. Int J Digital Earth. 14 (7), 921-942 (2021).
  24. Kahn, C. The Value Proposition for Likelihood-of-Failure Modeling. J Am Water Works Assoc. 113 (1), 30-38 (2021).
  25. Gao, Z., et al. A Novel Multivariate Time Series Prediction of Crucial Water Quality Parameters with Long Short-Term Memory (LSTM) Networks. J Contaminant Hydrol. 259, 104262(2023).
  26. Mohan Raj, K., Vairavel, K. S. Quality Index Metrics with Bi-GRU-Based Water Quality Prediction. Energy Sourc Part A Recov Utilizat Environ Effects. 46 (1), 171-187 (2024).
  27. Yang, H., Yin, X., Hong, L., Jiang, K., Zhang, X. Research on Water Quality Parameter Prediction Model Based on TCN. Open Access Library J. 11 (4), 1-10 (2024).
  28. Lin, Y., et al. Transformer-Based Water Quality Forecasting with Dual Patch and Trend Decomposition. IEEE Internet Things J. 12 (8), 10987-10997 (2024).
  29. Buchhorn, K., Santos-Fernandez, E., Mengersen, K., Salomone, R. Graph Neural Network-Based Anomaly Detection for River Network Systems. F1000 Res. 12, 991(2024).
  30. Li, Z., Liu, H., Zhang, C., Fu, G. Real-Time Water Quality Prediction in Water Distribution Networks Using Graph Neural Networks with Sparse Monitoring Data. Water Res. 250, 121018(2024).
  31. Gcad: Anomaly Detection in Multivariate Time Series from the Perspective of Granger Causality. Liu, Z., Gao, M., Jiao, P. Proc AAAI Conf Artif Intell, 39, 19041-19049 (2025).
  32. Li, R., et al. Multi-Dimensional Spectrum Prediction Using Closed-Form Continuous-Time Neural Network With Graph Attention. IEEE Transact Vehicular Technol Early Access. , 1-5 (2025).
  33. Tandra, N., Kuppan, P., Arunachalam, K. P., Loganathan, G. A Hybrid Model of Prairie Dog Optimization and Closed-Form Continuous-Time Neural Networks for next Generation Lithium-Ion and Sodium-Ion Batteries. Int J Chem Reactor Eng. 23 (9), 1075-1087 (2025).
  34. Li, X., et al. A Closed-Form Continuous-Depth Neural-Based Hybrid Difference Features Re-Representation Network for RUL Prediction. Reliability Eng Sys Safety. 253, 110540(2025).
  35. Cantini, C., Rolland-Piegue, E., Schmitter, D. Exact Implementation of Closed-Form Liquid Neural Networks With Arbitrary Precision. IEEE Signal Proc Lett. 32 (2025), 921-925 (2025).
  36. Event-Driven Dynamic Attention for Multi-Object Tracking on Neuromorphic Hardware. Aitsam, M., Davies, S., Di Nuovo, A. Proc Comp Vis Pattern Recognit Conf, 2025, 5055-5062 (2025).
  37. Chen, Z., et al. Bridging Quantized Artificial Neural Networks and Neuromorphic Hardware. arXiv. , (2025).
  38. Kim, Y., Lee, C. W., Jang, H. W. Neuromorphic Hardware for Artificial Sensory Systems: A Review. J Electron Mater. 54 (5), 3609-3650 (2025).
  39. Abreu, S., Shrestha, S. B., Zhu, R. J., Eshraghian, J. Neuromorphic Principles for Efficient Large Language Models on Intel Loihi 2. arXiv. , (2025).
  40. Analyzing Energy Consumption of Loihi 2 Neuromorphic Chip in a Self-Driving Use-Case. Nagy, Á, Szabó, R., Toka, L. 2025 10th Int Conf Smart Sustainable Tech, , 1-6 (2025).

Access restricted. Please log in or start a trial to view this content.

Reprints and Permissions

Request permission to reuse the text or figures of this JoVE article

Request Permission

Tags

Attention MechanismTime SeriesMultivariate CorrelationDissolved OxygenPermanganate IndexEdge DeploymentModel Interpretability

Related Articles