Water quality detection method and system based on multimodal data fusion and intelligent optimization
Through multi-modal data fusion and intelligent optimization technology, heterogeneous federated learning models and hybrid generative artificial intelligence models are constructed to solve the problems of inaccurate detection results and insufficient adaptive capabilities of existing water quality detection systems, achieving high-precision, Real-time water quality monitoring and management.
Patent Information
- Application Number
- CN202410985710.8
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2024-07-23
- Publication Date
- 2024-10-11
- Estimated Expiration
- 2044-07-23
AI Technical Summary
The existing water quality detection system lacks intelligence, has a single detection mode, and cannot adapt to environmental changes, resulting in inaccurate detection results and reduced performance.
Using methods based on multi-modal data fusion and intelligent optimization, by building a heterogeneous federated learning model of convolutional neural networks and spiking neural networks, combined with a hybrid generative artificial intelligence model, we can predict changes in water quality parameters and perform root cause analysis to achieve Multi-level integration and privacy protection of data.
It improves the accuracy and real-time performance of water quality detection, enhances the adaptive capability and flexibility of the system, ensures data privacy and security, and realizes the intelligence and automation of the entire process.
Smart Images

Figure CN118518842B_ABST
Abstract
Description
Technical Field
[0001] The present invention relates to the technical field of environmental monitoring, and in particular to a water quality detection method and system based on multimodal data fusion and intelligent optimization. Background Art
[0002] As an important part of environmental monitoring, water quality testing has always been a key direction for the industry to develop in terms of automation and intelligence. Although traditional wet chemical analysis water quality automatic detectors perform well in specific scenarios, they face the following technical defects:
[0003] Lack of intelligence in flow path editing: Although the existing system allows users to edit flow path programs, it lacks intelligent optimization suggestions based on historical data and current conditions, making it difficult to quickly adapt and improve detection accuracy in different application scenarios.
[0004] Limitation of single detection mode: Most detectors can only detect a single or limited number of factors, which makes it difficult to meet the diverse detection needs of laboratories, increasing equipment costs and operational complexity.
[0005] Lack of adaptive optimization capabilities: Most systems are unable to dynamically adjust detection parameters based on real-time detection results and environmental changes, resulting in performance degradation in complex or changing environments. Summary of the invention
[0006] In view of this, the present application provides a water quality detection method and system based on multimodal data fusion and intelligent optimization, which solves the problems of inaccurate detection results, single detection mode and lack of adaptive optimization in the prior art.
[0007] The present application provides a water quality detection method based on multimodal data fusion and intelligent optimization, the method comprising the following steps:
[0008] Collecting and cleaning multimodal data, the multimodal data including flow path parameters, environmental conditions and water quality test results;
[0009] fusing the cleaned multimodal data;
[0010] Build and train heterogeneous federated learning models of convolutional neural networks and spiking neural networks;
[0011] Build a hybrid generative AI model for water quality testing;
[0012] Inputting the fused multimodal data into the heterogeneous federated learning model to predict changes in water quality parameters under different environmental conditions and different time periods, wherein the water quality parameters include one or more combinations of pH value, dissolved oxygen, conductivity, turbidity, ammonia nitrogen, total phosphorus, and heavy metals;
[0013] The fused multimodal data is input into the hybrid generative artificial intelligence model to perform root cause analysis of abnormal water quality parameters.
[0014] Optionally, build and train heterogeneous federated learning models of convolutional neural networks and spiking neural networks, including:
[0015] Construct convolutional neural network (CNN) model and spiking neural network (SNN) model;
[0016] Developing a heterogeneous federated learning framework to enable the CNN model and the SNN model to be distributedly trained under the heterogeneous federated learning framework;
[0017] Using an improved federated average FedAvg algorithm to aggregate the CNN model and the SNN model to form the heterogeneous federated learning model;
[0018] The differential privacy mechanism is integrated into the heterogeneous federated learning framework.
[0019] Optionally, a convolutional neural network (CNN) model and a spiking neural network (SNN) model are constructed, including:
[0020] Designing a CNN model, the CNN model includes multiple convolutional layers, multiple pooling layers and a fully connected layer, the multiple convolutional layers are used to extract local features of short-term changes in water quality parameters, the multiple pooling layers are used to reduce data dimensions; the fully connected layer is used to integrate the local features and output a final prediction result;
[0021] An SNN model is designed, wherein the SNN model includes an input layer, one or more hidden layers and an output layer, and each layer is composed of LIF neurons. The LIF neurons integrate input signals over time and generate pulse outputs when a threshold is reached.
[0022] Optionally, the fused multimodal data is input into the heterogeneous federated learning model to predict the changes of water quality parameters under different environmental conditions and different time periods, including:
[0023] Inputting the multimodal data into the CNN model to output the variation of water quality parameters with environmental conditions;
[0024] Inputting the multimodal data into the SNN model to output the change of water quality parameters over time period;
[0025] The improved federated average FedAvg algorithm is used to fuse the changes of the water quality parameters with environmental conditions and with time, so as to predict the changes of water quality parameters under different environmental conditions and different time periods.
[0026] Optionally, build a hybrid generative AI model in the field of water quality testing, including:
[0027] Select a pre-trained large language model LLM, and fine-tune the large language model;
[0028] Performing knowledge distillation on the fine-tuned large language model to form multiple local models;
[0029] A dynamic switching strategy is formulated to dynamically switch to the large language model or one of the local models according to the complexity of the task.
[0030] Optionally, the fine-tuned large language model is subjected to knowledge distillation to form multiple local models, including:
[0031] The fine-tuned large language model is subjected to knowledge distillation to form a water quality parameter prediction model, anomaly detection model, pollution source identification model and treatment suggestion generation model, wherein:
[0032] The water quality parameter prediction model is used to predict future water quality parameter values using historical data;
[0033] The anomaly detection model is used to identify abnormal values or patterns in the water quality parameters;
[0034] The pollution source identification model is used to infer pollution sources based on water quality data;
[0035] The treatment suggestion generation model is used to provide treatment suggestions according to current water quality conditions.
[0036] Optionally, a dynamic switching strategy is formulated to dynamically switch to the large language model or one of the local models according to task complexity, including:
[0037] A dynamic switching strategy is formulated to determine whether the large language model needs to be activated according to the complexity of the task and the depth of the required analysis, including:
[0038] For a single query or local data analysis task, the local model is used for processing;
[0039] For multi-source query and analysis tasks of cross-domain knowledge, the large language model is used for processing.
[0040] Optionally, fusing the cleaned multimodal data includes:
[0041] Design a multi-level data fusion architecture, wherein the multi-level data fusion architecture includes data-level fusion, feature-level fusion, and decision-level fusion;
[0042] Uncertainty modeling based on evidence theory DST;
[0043] Based on the multi-level data fusion architecture and the uncertainty modeling, the cleaned multimodal data is fused.
[0044] Optionally, uncertainty modeling is performed based on the evidence theory DST, including:
[0045] defining an evidence framework, the evidence framework including all sets of hypotheses;
[0046] Calculate initial probability assignments for multi-sensor data;
[0047] Construct Dempster combination rules to integrate multi-source evidence;
[0048] Develop decision rules to make decisions based on fusion results;
[0049] Define fuzzy sets and membership functions;
[0050] Design a fuzzy rule base to describe the relationship between sensor data and water quality parameters;
[0051] Use Mamdani or Sugeno method to implement fuzzy reasoning;
[0052] A defuzzification algorithm is used to convert the fuzzy output into an exact value.
[0053] The embodiment of the present application also provides a water quality detection system based on multimodal data fusion and intelligent optimization, which is used to implement the above-mentioned water quality detection method based on multimodal data fusion and intelligent optimization. The water quality detection system includes a flow path editing module, an intelligent module, a control module, a flow path module and a multimodal data fusion module, wherein:
[0054] The flow path editing module includes a human-computer interaction unit, a parameter data processing unit, a flow path data processing unit, an algorithm data processing unit and a data transmission unit;
[0055] The intelligent module is used to construct and train a heterogeneous federated learning model of a convolutional neural network and a spiking neural network; construct a hybrid generative artificial intelligence model in the field of water quality detection; input the fused multimodal data into the heterogeneous federated learning model to predict the changes of water quality parameters under different environmental conditions and different time periods; input the fused multimodal data into the hybrid generative artificial intelligence model to perform root cause analysis of abnormal water quality parameters;
[0056] The multimodal data fusion module is used to collect and clean multimodal data, wherein the multimodal data includes flow path parameters, environmental conditions and water quality test results, and fuse the cleaned multimodal data;
[0057] The control module includes a human-computer interaction interface, a file manager, and a flow path actuator;
[0058] The flow path module includes a chemical reaction pool, a photoelectric detection unit, a temperature increasing unit, a temperature decreasing unit, a reagent buffer unit, a quantitative pump, a liquid path selection valve, a bubble leakage detector and a reagent storage unit.
[0059] An embodiment of the present application also provides a computer device, comprising: at least one processor; and a memory communicatively connected to the at least one processor; wherein the memory stores instructions executable by the at least one processor, and the instructions are executed by the at least one processor so that the at least one processor can execute the above-mentioned method of water quality detection based on multimodal data fusion and intelligent optimization.
[0060] An embodiment of the present application also provides a computer-readable storage medium, which stores computer instructions, and the computer instructions are used to enable a computer to execute the above-mentioned water quality detection method based on multimodal data fusion and intelligent optimization.
[0061] An embodiment of the present application also provides a computer program product, including computer instructions, characterized in that when the computer instructions are executed by a processor, the steps of the above-mentioned method for water quality detection based on multimodal data fusion and intelligent optimization are implemented.
[0062] This application has the following technical effects:
[0063] Multimodal data fusion: By collecting and fusing multimodal data such as flow path parameters, environmental conditions and water quality test results, data utilization is improved, making water quality test results more comprehensive and accurate.
[0064] Real-time prediction capability: By utilizing heterogeneous federated learning models and combining the advantages of CNN and SNN, it is possible to effectively predict changes in water quality parameters under different environmental conditions and time periods, thus improving the real-time and prediction capabilities of water quality detection.
[0065] Intelligent analysis: By building a hybrid generative artificial intelligence model in the field of water quality testing, intelligent root cause analysis of abnormal water quality parameters is achieved, greatly improving the efficiency of problem diagnosis and resolution.
[0066] Privacy protection: The differential privacy mechanism is integrated into the heterogeneous federated learning framework to effectively protect the privacy security of sensitive data.
[0067] Flexible adaptability: Adopting dynamic switching strategy, the appropriate model is selected according to the complexity of the task, which not only ensures the processing capability of complex tasks, but also improves the processing efficiency of simple tasks.
[0068] High-precision fusion: The multi-level data fusion architecture and uncertainty modeling based on evidence theory are used to improve the fusion accuracy of multi-source heterogeneous data.
[0069] System integration optimization: Through the organic combination of flow path editing module, intelligent module, control module and flow path module, the whole process of water quality detection is intelligent and automated. BRIEF DESCRIPTION OF THE DRAWINGS
[0070] In order to more clearly illustrate the disclosed embodiments in the embodiments of the present application, the drawings required for use in the description of the embodiments will be briefly introduced below. Obviously, the drawings in the following description are only some embodiments of the present application. For those skilled in the art, other drawings can be obtained based on these drawings without paying any creative work.
[0071] Figure 1 A schematic diagram of a water quality detection method based on multimodal data fusion and intelligent optimization provided in an embodiment of the present application;
[0072] Figure 2 A schematic diagram of the architecture of a water quality detection system based on multimodal data fusion and intelligent optimization provided by an embodiment;
[0073] Figure 3 This is a schematic diagram of the structure of a flow path editing module in one embodiment;
[0074] Figure 4 This is a schematic diagram of the control module structure in one embodiment;
[0075] Figure 5 This is an example diagram of the flow path module structure in one embodiment;
[0076] Figure 6 A schematic diagram of the architecture of a computer device provided by an embodiment. DETAILED DESCRIPTION
[0077] The embodiments of the present disclosure are described in detail below with reference to the accompanying drawings.
[0078] It should be clear that the following embodiments of the present disclosure are described by specific specific examples, and those skilled in the art can easily understand other advantages and effects of the present disclosure from the contents disclosed in this specification. Obviously, the described embodiments are only a part of the embodiments of the present disclosure, rather than all of the embodiments. The present disclosure can also be implemented or applied through other different specific embodiments, and the details in this specification can also be modified or changed in various ways based on different viewpoints and applications without departing from the spirit of the present disclosure. It should be noted that the following embodiments and features in the embodiments can be combined with each other in the absence of conflict. Based on the embodiments in the present disclosure, all other embodiments obtained by ordinary technicians in the field without making creative work are within the scope of protection of the present disclosure.
[0079] It should be noted that various aspects of the embodiments within the scope of the appended claims are described below. It should be apparent that the aspects described herein may be embodied in a wide variety of forms, and any specific structure and / or function described herein is merely illustrative. Based on the present disclosure, it should be understood by those skilled in the art that an aspect described herein may be implemented independently of any other aspect, and two or more of these aspects may be combined in various ways. For example, any number of aspects described herein may be used to implement the device and / or practice the method. In addition, other structures and / or functionalities other than one or more of the aspects described herein may be used to implement this device and / or practice this method.
[0080] It should also be noted that the illustrations provided in the following embodiments are only schematic illustrations of the basic concept of the present disclosure. The illustrations only show components related to the present disclosure rather than being drawn according to the number, shape and size of components in actual implementation. In actual implementation, the type, quantity and proportion of each component may be changed arbitrarily, and the component layout type is also more complicated.
[0081] Additionally, in the following description, specific details are provided to facilitate a thorough understanding of the examples. However, it will be understood by those skilled in the art that the aspects described may be practiced without these specific details.
[0082] Embodiment 1
[0083] like Figure 1 As shown, an embodiment of the present invention provides a method for water quality detection based on multimodal data fusion and intelligent optimization, including:
[0084] S1: collecting and cleaning multimodal data, wherein the multimodal data includes flow path parameters, environmental conditions and water quality test results;
[0085] Specifically, the embodiment of the present invention uses a variety of different types of sensors to perform multimodal data collection, and the flow path parameter collection includes:
[0086] Flow rate: Use ultrasonic flow meter or electromagnetic flow meter to measure water flow rate in real time.
[0087] Pressure: Monitor the water pressure changes in the pipe through the pressure sensor.
[0088] Temperature: Measure water temperature using a thermocouple or RTD (resistance temperature detector).
[0089] Flow rate: The amount of water per unit time is recorded by a flow meter.
[0090] Environmental condition collection includes:
[0091] Ambient Temperature: Use a temperature sensor to measure the temperature of the air surrounding the body of water.
[0092] Humidity: The humidity in the air is recorded via a humidity sensor.
[0093] Light Intensity: Use a light sensor to measure the light intensity received by the water surface.
[0094] Air Pressure: Monitor changes in atmospheric pressure with a barometer.
[0095] Water quality test results collection:
[0096] pH: Use a pH electrode to measure the acidity or alkalinity of water.
[0097] Dissolved oxygen: The dissolved oxygen content in water is measured by a dissolved oxygen sensor.
[0098] Conductivity: A conductivity meter measures the ability of water to conduct electricity.
[0099] Turbidity: A turbidity meter is used to measure the turbidity of water.
[0100] Ammonia nitrogen: Determine the ammonia nitrogen content by ion selective electrode or spectrophotometry.
[0101] Total phosphorus: The total phosphorus content was determined by ammonium molybdate spectrophotometry.
[0102] Heavy metals: Use atomic absorption spectrophotometer to determine the content of heavy metals such as lead and mercury.
[0103] For the above data, data cleaning is required. Data cleaning is a key step to ensure data quality, including the following main processes:
[0104] Outlier handling:
[0105] Use the Z-score method: Calculate the Z-score of each data point, and if |Z|>3, it is considered an outlier.
[0106] Z = (X * μ) / σ, where X is the data point, μ is the mean, and σ is the standard deviation.
[0107] Using the IQR (Interquartile Range) method: Calculate Q1 (25th percentile) and Q3 (75th percentile).
[0108] If X < Q1 - 1.5 * IQR or X > Q3 + 1.5 * IQR, it is considered an outlier.
[0109] For the detected outliers, you can choose to delete them or replace them using an interpolation method.
[0110] Missing value handling:
[0111] Time series data: Use linear interpolation or spline interpolation to fill in the missing values.
[0112] Categorical data: Use the mode to fill in the missing values.
[0113] Numerical data: You can use the mean or median to fill in, or use more complex methods such as K-Nearest Neighbor (KNN) interpolation.
[0114] Data standardization:
[0115] Min - Max standardization: Scale the data to the [0, 1] interval.
[0116] X_norm = (X - X_min) / (X_max - X_min)
[0117] Z - score standardization: Convert the data to a distribution with a mean of 0 and a standard deviation of 1.
[0118] X_norm = (X - μ) / σ
[0119] Noise reduction:
[0120] Mean filtering: Use a sliding window to calculate the mean value to reduce random noise.
[0121] Median filtering: It is especially effective for removing impulse noise.
[0122] Kalman filtering: Suitable for processing time series data, and can perform denoising and prediction simultaneously.
[0123] Data consistency check:
[0124] Unit consistency: Ensure that all data uses the same unit system.
[0125] Time consistency: Ensure that the timestamps of all data are synchronized.
[0126] Logical consistency: Check whether the data conforms to expected logical relationships, such as the inverse relationship between dissolved oxygen and temperature.
[0127] After data cleaning, the data needs to be stored and managed. Specifically:
[0128] You can choose a time series database (such as InfluxDB or TimescaleDB) to store large amounts of time series data, and use a relational database (such as PostgreSQL) to store structured metadata and configuration information.
[0129] Through the above detailed data collection and cleaning process, the embodiment of the present invention can obtain high-quality, reliable multimodal data, laying a solid foundation for subsequent data fusion and analysis. These cleaned data will be used to train machine learning models to predict water quality parameters and detect anomalies, thereby achieving more accurate and intelligent water quality monitoring and management.
[0130] S2: fusing the cleaned multimodal data;
[0131] S2 effectively integrates multimodal data from different sources to obtain more comprehensive and accurate water quality information. It includes the following sub-steps:
[0132] S2.1: Design a multi-level data fusion architecture
[0133] The multi-level data fusion architecture includes three levels: data-level fusion, feature-level fusion, and decision-level fusion. This hierarchical architecture can process data at different levels and improve the efficiency and accuracy of fusion.
[0134] Data-level fusion:
[0135] Purpose: To directly fuse the original data, which is applicable to data of the same type and scale.
[0136] method:
[0137] a) Weighted average: weighted average of the same type of data from multiple sensors.
[0138] Fusion result = Σ(w i * x i ) / Σw i , where w i is the weight, x i is the sensor data.
[0139] b) Kalman filtering: It is suitable for the fusion of time series data and can perform prediction and correction at the same time.
[0140] State equation: x(k) = Ax(k-1) + Bu(k) + w(k)
[0141] Observation equation: z(k) = Hx(k) + v(k)
[0142] where x is the state vector, u is the control vector, z is the observation vector, w and v are the process noise and observation noise respectively.
[0143] Feature-level fusion:
[0144] Purpose: Extract the features of each modal data and then fuse them in the feature space.
[0145] method:
[0146] a) Principal Component Analysis (PCA): Dimensionality reduction and extraction of main features.
[0147] Solve the eigenvalue equation of the covariance matrix: (C-λ)v = 0
[0148] where C is the covariance matrix, λ is the eigenvalue, and v is the eigenvector.
[0149] b) Autoencoder: Automatically extract features using neural networks.
[0150] Encoder: h = f(Wx + b)
[0151] Decoder: x' = g(W'h + b')
[0152] Where x is the input, h is the hidden layer representation, and x' is the reconstructed output.
[0153] c) Feature concatenation: directly concatenate feature vectors of different modes.
[0154] Fusion features = [feature1, feature2, ..., featuren]
[0155] Decision-level fusion:
[0156] Purpose: Make decisions on each modality data separately and then fuse these decision results.
[0157] method:
[0158] a) Voting mechanism: majority voting or weighted voting.
[0159] Final decision = argmax(Σw i * vote i ), where w i is the weight, vote i It is a vote for each decision.
[0160] b) Dempster-Shafer theory: decision fusion based on evidence theory (see S2.2 for details).
[0161] S2.2: Uncertainty modeling based on evidence theory DST
[0162] Dempster-Shafer theory (DST) is a mathematical tool for dealing with uncertainty and incomplete information, and is particularly suitable for multi-source information fusion.
[0163] S2.2.1: Define the evidence framework
[0164] The evidence framework Θ contains all sets of mutually exclusive and complete hypotheses.
[0165] For example, for water quality rating, Θ = {Excellent, Good, Fair, Poor}
[0166] S2.2.2: Compute initial probability assignments for multi-sensor data
[0167] A basic probability assignment (BPA) is assigned to each sensor data, indicating the support for each hypothesis.
[0168] m: 2Θ → [0,1], satisfying m(∅) = 0 and Σm(A) = 1, A ⊆ Θ
[0169] S2.2.3: Construct Dempster combination rules to integrate multi-source evidence
[0170] Fusion of BPA from multiple sensors using Dempster combination rule.
[0171] m 1,2 (A) = (m1⊕ m2)(A) = Σ(X∩Y=A) m1(X)m2(Y) / (1-K)
[0172] Where K = Σ(X∩Y=∅), m1(X)m2(Y) represents the degree of conflict.
[0173] The following is a specific example to illustrate the contents of S2.2.1-S2.2.3:
[0174] For a certain water quality parameter (such as pH value), the embodiment of the present invention may define the following hypothesis set:
[0175] Θ = {normal, slightly acidic, slightly alkaline}
[0176] This framework includes all water quality states. The embodiment of the present invention also needs to consider all combinations of these states to form a power set:
[0177] 2^Θ = {∅, {normal}, {acidic}, {alkaline}, {normal, acidic}, {normal, alkaline}, {acidic, alkaline}, {normal, acidic, alkaline}}
[0178] For each sensor or detection method, embodiments of the present invention need to define a basic probability assignment (BPA) function, which assigns belief degrees to elements in a power set.
[0179] The present embodiment has a pH sensor with a reading of 6.8. The present embodiment will assign probabilities as follows:
[0180] m({normal}) = 0.7
[0181] m({acidic}) = 0.2
[0182] m({normal, slightly acidic}) = 0.1
[0183] This means that the sensor has 70% confidence that the water quality is normal, 20% confidence that the water quality is acidic, and 10% uncertainty (normal or acidic).
[0184] Dempster's combination rule allows embodiments of the present invention to combine evidence from multiple sources (i.e., multiple BPAs). Assuming that the embodiment of the present invention has two evidence sources m1 and m2, the combination rule is as follows:
[0185] (m1⊕m2)(A) = (1 / K) * Σ(m1(B) * m2(C)), where B∩C=A, A≠∅
[0186] K = 1 - Σ(m1(B) * m2(C)), where B∩C=∅
[0187] K is a normalization factor used to handle conflicting information.
[0188] When implementing this step, the embodiment of the present invention requires:
[0189] 1. Write a function to calculate the combination of two BPAs.
[0190] 2. Design an algorithm to handle the sequential combination of more than two sources of evidence.
[0191] 3. Implement conflict handling mechanisms, especially when K is close to 1 (high conflict).
[0192] S2.2.4: Develop decision rules to make judgments based on fusion results
[0193] The embodiment of the present invention needs to make decisions based on the fused BPA. Common decision rules include:
[0194] 1. Maximum confidence rule: Choose the hypothesis with the greatest confidence.
[0195] Maximum confidence rule: choose the hypothesis with the highest confidence.
[0196] Bel(A) = Σm(B), B ⊆ A
[0197] 2. Maximum likelihood rule: Select the hypothesis with the highest likelihood.
[0198] Maximum likelihood rule: choose the hypothesis with the highest likelihood.
[0199] Pl(A) = 1 Bel(Ā)
[0200] 3. Interval probability optimization criterion: Make balanced decisions based on both confidence and likelihood.
[0201] In the context of water quality testing, embodiments of the present invention may adopt a more conservative approach, for example:
[0202] If the confidence of any harmful state (such as "acidic" or "alkaline") exceeds a certain threshold, a warning is issued.
[0203] A weighted decision rule was used to assign different weights to different water quality parameters according to their importance.
[0204] By implementing uncertainty modeling based on the Dempster-Shafer theory, the water quality detection system of the embodiment of the present invention will be able to:
[0205] Efficiently handle uncertain and conflicting information from multiple sensors.
[0206] Explicitly represent the uncertainty of the system rather than forcing precise probability estimates that are inaccurate.
[0207] Take into account incomplete and conflicting evidence when making decisions.
[0208] Provide more reliable and robust assessments of water quality status, especially in the face of incomplete or inconsistent data.
[0209] This approach will significantly improve the reliability and adaptability of water quality detection systems, enabling them to better handle complex actual monitoring environments.
[0210] S2.2.5: Define fuzzy sets and membership functions
[0211] Fuzzy logic is a method of processing approximate reasoning, especially suitable for processing imprecise, ambiguous or subjective information. In the water quality detection system, fuzzy logic can help this solution better deal with the imprecision of sensor data and the subjectivity of water quality assessment.
[0212] The water quality parameters are divided into different fuzzy sets.
[0213] For example, pH can be classified as "acidic", "neutral", and "alkaline".
[0214] Define the membership function μA(x) to indicate the degree to which element x belongs to the fuzzy set A.
[0215] Specifically,
[0216] First, this scheme needs to define fuzzy sets and corresponding membership functions for key parameters in water quality detection.
[0217] 1. Determine key water quality parameters: such as pH, dissolved oxygen, turbidity, conductivity, etc.
[0218] 2. Define language variables for each parameter: for example, for pH value, you can define "acidic", "neutral", "alkaline".
[0219] 3. Design membership functions: Create membership functions for each linguistic variable. These functions define the degree to which a specific value belongs to a fuzzy set.
[0220] For example, for pH value, this scheme defines the following membership function:
[0221] - μacidity(x) = 1, if x ≤ 5
[0222] = (7-x) / 2,if 5 <x<7
[0223] = 0,if x ≥ 7
[0224] - μneutral(x) = 0,if x ≤ 5 or x ≥ 9
[0225] = (x-5) / 2,if 5 <x<7
[0226] = 1,if 7 ≤ x ≤ 7.5
[0227] = (9-x) / 1.5, if 7.5 <x<9
[0228] - μAlkalinity(x) = 0, if x ≤ 7
[0229] = (x-7) / 2,if 7 <x<9
[0230] = 1,if x ≥ 9
[0231] S2.2.6: Design a fuzzy rule base to describe the relationship between sensor data and water quality parameters
[0232] Design IF-THEN rules based on expert knowledge and historical data. For example: IF pH is low AND dissolved oxygen is high THEN water quality is good
[0233] Specifically,
[0234] In this step, the solution needs to create a fuzzy rule base, which describes the relationship between different water quality parameters and their impact on the overall water quality. These rules are usually in the form of IF-THEN.
[0235] For example:
[0236] 1. IF pH is acidic AND dissolved oxygen is low THEN water quality is poor
[0237] 2. IF pH is neutral AND dissolved oxygen is high AND turbidity is low THEN water quality is good
[0238] 3. IF conductivity is high OR turbidity is high THEN water quality is questionable
[0239] These rules should be formulated by domain experts and adjusted and optimized according to actual conditions.
[0240] S2.2.7: Implement fuzzy reasoning using Mamdani or Sugeno methods
[0241] The fuzzy inference engine is the core of the whole system, responsible for converting input data into output through fuzzy rules. This solution can choose Mamdani or Sugeno method to implement this engine.
[0242] Mamdani Method:
[0243] Fuzzy Input
[0244] Rule Evaluation
[0245] Aggregate Output
[0246] Defuzzification
[0247] Sugeno method:
[0248] The output is either a linear combination of the input variables or a constant.
[0249] Fuzzy Input
[0250] Applying the fuzzy operator
[0251] Applying the Implication Method
[0252] Weighted average output
[0253] The choice of method depends on the specific application. The Mamdani method is more intuitive and suitable for human-computer interaction; the Sugeno method is more computationally efficient and suitable for optimization and adaptive techniques.
[0254] S2.2.8: Use defuzzification algorithms to convert fuzzy outputs into precise values
[0255] This solution requires converting the fuzzy output back into an accurate value or decision. Common defuzzification methods include:
[0256] 1. Center of Average Method (COA): Calculate the centroid of the output fuzzy set.
[0257] 2. Maximum Membership Method (MOM): Select the output value with the maximum membership.
[0258] 3. Weighted average method: The output is weighted averaged according to the membership value.
[0259] In the water quality testing system, this solution will use the following methods:
[0260] Center of gravity method (COG): y* = ∫yμ(y)dy / ∫μ(y)dy
[0261] Maximum membership method (MOM): y* = argmax(μ(y))
[0262] S2.3: Fusion of cleaned multimodal data based on multi-level data fusion architecture and uncertainty modeling
[0263] In this step, the embodiment of the present invention combines the methods of S2.1 and S2.2 to achieve efficient fusion of multimodal data. The specific process is as follows:
[0264] Data-level fusion:
[0265] The same type of sensor data is initially fused using weighted averaging or Kalman filtering.
[0266] Use DST to handle data-level uncertainty and calculate the initial BPA.
[0267] Feature-level fusion:
[0268] Use PCA or autoencoder to extract features of each modality data.
[0269] Apply DST in feature space to handle feature uncertainty.
[0270] The Dempster combination rule is used to fuse features from different modalities.
[0271] Decision-level fusion:
[0272] Fuzzy rule reasoning is applied to each modal data separately.
[0273] Use DST to fuse the decision results of each modality.
[0274] Apply defuzzification algorithm to get the final accurate decision.
[0275] Integration of multi-level fusion results:
[0276] The fusion results of data level, feature level and decision level are integrated again through DST.
[0277] The maximum confidence rule or maximum likelihood rule is used to obtain the final water quality assessment results.
[0278] Through this multi-level fusion architecture, the embodiment of the present invention can make full use of information at different levels, and at the same time process the uncertainty and fuzziness of the data through DST and fuzzy logic, and finally obtain a more reliable and comprehensive water quality assessment result. This method not only improves the accuracy of data fusion, but also enhances the system's adaptability to uncertainty and complex environments.
[0279] S3: Build and train heterogeneous federated learning models of convolutional neural networks and spiking neural networks;
[0280] S3.1: Construct a convolutional neural network (CNN) model and a spiking neural network (SNN) model;
[0281] S3.1 aims to design two different types of neural network models: convolutional neural network (CNN) and spiking neural network (SNN) to process multimodal data in water quality detection. These two models have their own characteristics and can effectively extract and analyze different features of water quality parameters.
[0282] S3.1.1: Design a CNN model, wherein the CNN model includes multiple convolutional layers, multiple pooling layers and a fully connected layer, wherein the multiple convolutional layers are used to extract local features of short-term changes in water quality parameters, and the multiple pooling layers are used to reduce data dimensions; the fully connected layer is used to integrate the local features and output the final prediction results;
[0283] S3.1.2: Design an SNN model, wherein the SNN model includes an input layer, one or more hidden layers and an output layer, and each layer is composed of LIF neurons, wherein the LIF neurons integrate input signals over time and generate pulse outputs when a threshold is reached.
[0284] Specifically,
[0285] S3.1.1: Design CNN model
[0286] The CNN model is mainly used to process data with spatial or temporal local correlation, such as short-term changes in water quality parameters. The structure of CNN is as follows:
[0287] 1. Input layer:
[0288] Input shape: [batch size, time steps, number of features]
[0289] For example: [32, 24, 10] means a batch size of 32, a 24-hour time series, and 10 features at each time point (such as pH, dissolved oxygen, etc.)
[0290] The input layer defines the basic structure of the data. In water quality monitoring, the input is usually a three-dimensional tensor represented as [batch size, time step, number of features]. For example, [32, 24, 10] means that 32 samples are processed per batch, each sample contains 24 hours of time series data, and each time point has 10 features (such as pH value, dissolved oxygen, etc.). This structure allows the model to process multiple samples at the same time, improving training efficiency.
[0291] 2. Convolutional Layer:
[0292] Purpose: Extract local characteristics of short-term changes in water quality parameters
[0293] Structure: multiple convolutional layers, each layer contains multiple convolution kernels
[0294] Convolution operation: F(i,j) = (I * K)(i,j) = Σ Σ I(m,n)K(im,jn)
[0295] Activation function: ReLU, f(x) = max(0, x)
[0296] Sample code:
[0297] ```Python
[0298] conv1 = Conv1D(filters=64, kernel_size=3, activation='relu')(input_layer)
[0299] conv2 = Conv1D(filters=128, kernel_size=3, activation='relu')(conv1)
[0300] ```
[0301] The convolution layer is the core of CNN and is used to extract local features of short-term changes in water quality parameters. It contains multiple convolution kernels (or filters), each of which slides on the input data to perform a convolution operation. The convolution operation can be expressed as F(i,j) = (I * K)(i,j) = Σ Σ I(m,n)K(im,jn), where I is the input and K is the convolution kernel. This operation can capture local patterns, such as sudden changes in water quality parameters or specific time patterns.
[0302] In the example, the embodiment of the present application uses two convolutional layers, the first layer has 64 filters, the second layer has 128 filters, and the size of each filter is 3. This setting allows the network to extract more complex features layer by layer. The activation function ReLU (f(x) = max(0, x)) is used to introduce nonlinearity, enabling the network to learn more complex patterns.
[0303] 3. Pooling layer:
[0304] Purpose: Reduce data dimension and number of parameters
[0305] Type: Max Pooling
[0306] Operation: Take the maximum value in a fixed-size window
[0307] Sample code:
[0308] ```Python
[0309] pool1 = MaxPooling1D(pool_size=2)(conv2)
[0310] ```
[0311] The main purpose of the pooling layer is to reduce the dimension of the data and the number of parameters, thereby controlling overfitting and improving computational efficiency. Max Pooling is a commonly used pooling method that takes the maximum value within a fixed-size window. In the example, the embodiment of the present application uses a pooling window of size 2, which means that the size of the feature map will be halved, but important feature information will be retained.
[0312] 4. Fully connected layer:
[0313] Purpose: Integrate local features and output the final prediction results
[0314] Structure: One or more fully connected layers, the number of neurons in the last layer is equal to the number of predicted targets
[0315] Sample code:
[0316] ```Python
[0317] flatten = Flatten()(pool1)
[0318] fc1 = Dense(128, activation='relu')(flatten)
[0319] output = Dense(num_classes, activation='softmax')(fc1)
[0320] ```
[0321] The fully connected layer receives the features extracted by the convolution and pooling layers and combines them to make the final prediction. It contains one or more densely connected layers, each with a certain number of neurons. In the example, the embodiment of the present application uses a hidden layer of 128 neurons, followed by an output layer with the number of neurons equal to the number of categories of the predicted target. The fully connected layer allows the model to learn the global relationship between features.
[0322] 5. Output layer:
[0323] Activation function:
[0324] Classification problem: softmax, σ(z)i = exp(zi) / Σ exp(zj)
[0325] Regression Problem: Linear Activation
[0326] The design of the output layer depends on the type of task. For classification problems (such as water quality grade classification), the embodiment of the present application uses a softmax activation function (σ(z)i = exp(zi) / Σ exp(zj)), which converts the output into a probability distribution. For regression problems (such as prediction of specific parameter values), the embodiment of the present application uses a linear activation function.
[0327] 6. Loss Function:
[0328] Classification problem: cross entropy, L = -Σ yi log(ŷi)
[0329] Regression problem: Mean squared error, MSE = 1 / n Σ (yi - ŷi)²
[0330] The loss function measures the difference between the model prediction and the actual value. For classification problems, the embodiments of the present application usually use the cross entropy loss (L = -Σ yi log(ŷi)), which can effectively handle multi-class problems. For regression problems, the mean square error (MSE = 1 / n Σ (yi - ŷi)²) is a common choice, which directly measures the square difference between the predicted value and the true value.
[0331] 7. Optimizer:
[0332] The optimizer is responsible for updating the model parameters to minimize the loss function. The Adam optimizer is a popular choice because it combines the advantages of AdaGrad and RMSProp. Adam adaptively adjusts the learning rate of each parameter, which is particularly effective when dealing with sparse gradients or noisy data.
[0333] Example of a complete CNN model structure:
[0334] ```Python
[0335] model = Sequential([
[0336] Conv1D(64, 3, activation='relu', input_shape=(24, 10)),
[0337] Conv1D(128, 3, activation='relu'),
[0338] MaxPooling1D(2),
[0339] Conv1D(128, 3, activation='relu'),
[0340] Conv1D(256, 3, activation='relu'),
[0341] GlobalAveragePooling1D(),
[0342] Dropout(0.5),
[0343] Dense(128, activation='relu'),
[0344] Dense(num_classes, activation='softmax') ])
[0346] ```
[0347] The complete CNN model structure example shows how to combine these components into a complete network. The model includes multiple convolutional layers, interspersed with pooling operations, and finally a fully connected layer. It is worth noting that the embodiment of the present application also adds a Dropout layer (with a dropout rate of 0.5), which is a regularization technique that prevents overfitting by randomly "turning off" some neurons during training. Global average pooling (GlobalAveragePooling1D) is used instead of the traditional flattening operation, which can greatly reduce the number of parameters while maintaining performance.
[0348] This CNN structural design allows the model to effectively learn the temporal dependencies and local patterns of water quality data. By stacking multiple convolutional layers, the model can gradually build feature representations from simple to complex. The pooling layer helps the model obtain a certain degree of translation invariance, enabling it to detect specific patterns regardless of their specific location in the time series. Finally, the fully connected layer integrates these learned features to make the final water quality assessment or prediction.
[0349] This structure is particularly suitable for processing water quality monitoring data because it can capture short-term water quality change patterns (through convolutional layers) while also understanding the significance of these changes on a longer time scale (through deeper network layers). This enables the model to detect sudden water quality changes, identify periodic patterns, and predict future water quality trends, thereby providing powerful decision support for water quality management.
[0350] S3.1.2: Design SNN model
[0351] Spiking Neural Network (SNN) is an artificial neural network that mimics the working mode of biological nervous system. In water quality monitoring applications, SNN is particularly suitable for processing continuous time series data and can capture the dynamic changes of water quality parameters over time. The following is the detailed structure and working principle of the SNN model:
[0352] 1. Input layer:
[0353] Convert continuous values to pulse trains
[0354] Coding method: rate coding or time coding
[0355] The main task of the input layer is to convert continuous water quality parameter data into discrete pulse sequences. This process simulates the way biological neurons convert analog signals into digital pulses. There are two commonly used encoding methods:
[0356] Rate encoding: The larger the input value, the higher the frequency of the generated pulses. This method is simple and intuitive, and is suitable for expressing the intensity of water quality parameters.
[0357] Time encoding: The input value determines the time when the first pulse is generated. This method can represent time information more accurately and is suitable for capturing rapid changes in water quality parameters.
[0358] In water quality monitoring, the embodiments of the present application will select different encoding methods according to the characteristics of different parameters. For example, for slowly changing pH values, rate encoding is used; while for suddenly changing dissolved oxygen content, time encoding is more suitable.
[0359] 2. Hidden Layer:
[0360] The hidden layer consists of LIF (Leaky Integrate-and-Fire) neurons, which simulate the basic properties of biological neurons. The dynamics of LIF neurons can be described by the following differential equation:
[0361] dV / dt = -(V - Vrest) / τm + RI(t) / τm
[0362] Where V is the membrane potential, Vrest is the resting potential, τm is the membrane time constant, R is the membrane resistance, and I(t) is the input current.
[0363] This equation describes how a neuron accumulates input signals (integration) and releases a spike (firing) when a threshold is reached. In water quality monitoring, this mechanism allows the network to integrate the input water quality parameters over time, thereby capturing the cumulative effect of the parameter over time.
[0364] 3. Output layer:
[0365] The output layer is also composed of LIF neurons, but its decoding method is task-dependent. Common decoding methods include:
[0366] Pulse counting: Count the number of pulses within a certain time window. This is suitable for classification tasks, such as determining water quality levels.
[0367] Time to First Pulse: Records the time when the first pulse occurs. This is suitable for tasks that require a fast response, such as early detection of a sudden increase in contamination.
[0368] In a water quality monitoring system, the embodiments of the present application will select different decoding methods according to different monitoring objectives.
[0369] 4. Neuron update rules:
[0370] The update of neurons is the core operation of SNN, which determines how the network processes and transmits information. The update rules are as follows:
[0371] If V>= Vthreshold:
[0372] Generate pulse
[0373] V = Vreset
[0374] otherwise:
[0375] V = V + dV
[0376] This rule simulates the "all or nothing" characteristic of biological neurons. When the membrane potential accumulates to the threshold, the neuron emits a pulse and resets the membrane potential. This mechanism enables SNN to effectively process time series data and is very suitable for capturing sudden changes and gradual changes in water quality parameters.
[0377] 5. Training Algorithm:
[0378] Training SNNs is a challenge because the impulse function is not differentiable. To solve this problem, the present embodiment uses a surrogate gradient method to approximate the gradient of the impulse function. This allows the present embodiment to use a back-propagation algorithm to train the network.
[0379] Loss function: Same as CNN, choose cross entropy or mean square error depending on the problem type
[0380] Optimizer: Adam optimizer
[0381] The choice of loss function depends on the task type. For water quality classification tasks (such as water quality grade determination), the embodiment of the present application uses cross entropy loss; for regression tasks (such as specific parameter value prediction), the embodiment of the present application uses mean square error.
[0382] The optimizer selected is Adam, which can adaptively adjust the learning rate and help deal with sparse gradients or noise in water quality data.
[0383] Example of Python implementation of SNN model (using snnTorch library):
[0384] ```Python
[0385] import snntorch as snn
[0386] from snntorch import surrogate
[0387] class SNNModel(nn.Module):
[0388] def __init__(self, num_inputs, num_hidden, num_outputs):
[0389] super().__init__()
[0390] # Initialize layers
[0391] self.fc1 = nn.Linear(num_inputs, num_hidden)
[0392] self.lif1 = snn.Leaky(beta=0.9)
[0393] self.fc2 = nn.Linear(num_hidden, num_outputs)
[0394] self.lif2 = snn.Leaky(beta=0.9)
[0395] def forward(self, x):
[0396] # Initialize hidden state
[0397] mem1 = self.lif1.init_leaky()
[0398] mem2 = self.lif2.init_leaky()
[0399] # Record output
[0400] spk2_rec = []
[0401] mem2_rec = []
[0402] for step in range(num_steps):
[0403] cur1 = self.fc1(x)
[0404] spk1, mem1 = self.lif1(cur1, mem1)
[0405] cur2 = self.fc2(spk1)
[0406] spk2, mem2 = self.lif2(cur2, mem2)
[0407] spk2_rec.append(spk2)
[0408] mem2_rec.append(mem2)
[0409] return torch.stack(spk2_rec, dim=0), torch.stack(mem2_rec, dim=0)
[0410] # Initialize the model
[0411] net = SNNModel(num_inputs=10, num_hidden=128, num_outputs=num_classes)
[0412] # Define loss function and optimizer
[0413] loss_fn = nn.CrossEntropyLoss()
[0414] optimizer = torch.optim.Adam(net.parameters(), lr=1e-2)
[0415] ```
[0416] In the Python implementation example provided, the specific structure of the SNN model can be seen in the embodiment of the present application:
[0417] The model contains two fully connected layers (fc1 and fc2), each followed by a layer of LIF neurons (lif1 and lif2).
[0418] During the forward propagation process, the model processes the input for multiple time steps, simulating continuous-time information processing.
[0419] At each time step, the input first passes through the fully connected layer and then through the LIF neuron layer, generating spikes and updating the membrane potential.
[0420] The model records the pulses and membrane potential of the output layer, which can be used for subsequent decoding and analysis.
[0421] Combination of CNN and SNN models:
[0422] 1. CNN is used to extract spatial and short-term temporal features of water quality parameters.
[0423] 2. SNN is used to capture long-term temporal dependencies and process continuous time series data.
[0424] 3. The outputs of the two models can be combined through weighted averaging or more complex fusion methods to obtain the final water quality parameter prediction or classification results.
[0425] In this way, the embodiment of the present invention can make full use of the advantages of CNN in feature extraction and SNN in processing time series data, thereby improving the accuracy and real-time performance of water quality detection. This combination can also better process multimodal data, because different types of data are more suitable for processing by different types of neural networks.
[0426] S3.2: Develop a heterogeneous federated learning framework to enable the CNN model and the SNN model to be distributedly trained under the heterogeneous federated learning framework;
[0427] In S3.2, a heterogeneous federated learning framework that can accommodate both CNN and SNN models is developed to achieve distributed training. This framework can use data from multiple participants for model training while protecting data privacy, thereby improving the accuracy and robustness of water quality detection.
[0428] 1. Design principles of heterogeneous federated learning framework:
[0429] a) Model heterogeneity: Supports models with two different architectures: CNN and SNN.
[0430] b) Data privacy protection: Ensure that the original data does not leave the local device.
[0431] c) Communication efficiency: Minimize the amount of data transferred during model updates.
[0432] d) Model performance: Ensure that the model performance after federated learning is not lower than that of centralized learning.
[0433] 2. Framework structure:
[0434] a) Central server: responsible for coordinating the training process and aggregating model updates.
[0435] b) Local client: Each participant runs a local CNN or SNN model.
[0436] c) Communication module: responsible for secure communication between the client and the server.
[0437] d) Model conversion module: realizes parameter mapping between CNN and SNN models.
[0438] 3. Parameter mapping of heterogeneous models:
[0439] In order to enable CNN and SNN models to work together in the same federated learning framework, it is necessary to establish a parameter mapping relationship between the two models.
[0440] a) Mapping from CNN to SNN:
[0441] Map the convolution kernel weights of CNN to the synaptic weights of SNN.
[0442] Convert the bias term of CNN to the initial potential of SNN neurons.
[0443] The weights are adjusted using normalization techniques to ensure that the activation pattern of SNN is similar to that of CNN.
[0444] b) Mapping from SNN to CNN:
[0445] Map the synaptic weights of the SNN back to the convolution kernel weights of the CNN.
[0446] The threshold information of SNN neurons is converted into activation function parameters of CNN.
[0447] Sample code (partial mapping from CNN to SNN):
[0448] ```Python
[0449] def cnn_to_snn_mapping(cnn_model, snn_model):
[0450] for cnn_layer, snn_layer in zip(cnn_model.layers, snn_model.layers):
[0451] if isinstance(cnn_layer, nn.Conv2d) and isinstance(snn_layer,snn.Convolution):
[0452] snn_layer.weight.data = cnn_layer.weight.data.clone()
[0453] snn_layer.bias.data = cnn_layer.bias.data.clone() / snn_layer.threshold
[0454] ```
[0455] 4. Federated learning algorithm process:
[0456] a) Initialization:
[0457] The central server initializes the global model (can be a CNN or SNN).
[0458] Distribute the initial model to all clients.
[0459] b) Local training:
[0460] Each client trains the model (CNN or SNN) using local data for a certain number of rounds.
[0461] Calculate the model update (the difference between the new parameters and the original parameters).
[0462] c) Model update upload:
[0463] The client sends model updates (not the full model) to the server.
[0464] The privacy of individual updates is ensured using a secure aggregation protocol.
[0465] d) Global aggregation:
[0466] The server receives updates from all clients.
[0467] Updates are aggregated using the Federated Averaging Algorithm (FedAvg).
[0468] For heterogeneous models, model conversion is performed first and then aggregation.
[0469] e) Model distribution:
[0470] The server distributes the updated global model to all clients.
[0471] f) Repeat steps be until the model converges or reaches a predetermined number of rounds.
[0472] Through the above steps, the embodiment of the present invention develops a heterogeneous federated learning framework that can support both CNN and SNN models. This framework can not only handle different types of neural network models, but also effectively use distributed data for training while protecting data privacy. This is especially important for water quality detection systems because it allows different water quality monitoring sites to collaborate to improve the model without sharing raw data, thereby improving the overall water quality detection and prediction capabilities.
[0473] S3.3: using an improved federated average FedAvg algorithm to aggregate the CNN model and the SNN model to form the heterogeneous federated learning model;
[0474] The improved FedAvg algorithm aims to solve the problem of heterogeneous model aggregation and improve aggregation efficiency and model performance. The following are the specific implementation steps:
[0475] 1. Model parameter mapping:
[0476] Before aggregation, the mapping relationship between CNN and SNN model parameters needs to be established.
[0477] ```Python
[0478] def create_parameter_mapping(cnn_model, snn_model):
[0479] mapping = {}
[0480] for cnn_name, cnn_param in cnn_model.named_parameters():
[0481] for snn_name, snn_param in snn_model.named_parameters():
[0482] if cnn_param.shape == snn_param.shape:
[0483] mapping[cnn_name] = snn_name
[0484] return mapping
[0485] ```
[0486] The purpose of this step is to establish the correspondence between the parameters of the CNN and SNN models, which is the key to the federated learning of heterogeneous models. In the water quality monitoring system, different monitoring stations use different types of neural network models (CNN or SNN), so a method is needed to coordinate the parameters of these different models.
[0487] The create_parameter_mapping function traverses all parameters of the CNN and SNN models, finds parameters with the same shape, and establishes a mapping between them. This mapping allows the embodiment of the present application to correctly merge parameters from different types of models in the subsequent aggregation process.
[0488] For example, the convolutional layer weights in CNN are mapped to the synaptic weights in SNN, and the bias terms of CNN are mapped to the neuron thresholds of SNN. This mapping ensures that knowledge from different types of models can be effectively integrated during federated learning.
[0489] 2. Weight Adaptation:
[0490] Taking into account the different data quality and quantity of different clients, an adaptive weight mechanism is introduced.
[0491] ```Python
[0492] def calculate_adaptive_weights(client_performances):
[0493] total_performance = sum(client_performances)
[0494] return [perf / total_performance for perf in client_performances]
[0495] ```
[0496] In federated learning, different clients (i.e., different water quality monitoring stations) have data of different quality and quantity. The weight adaptation mechanism aims to adjust the influence of each client in the global model update according to its performance.
[0497] The calculate_adaptive_weights function calculates the relative performance weight of each client. Performance can be based on a variety of metrics, such as prediction accuracy, data volume, or data quality. In a water quality monitoring system, this means that monitoring stations with more sensors or higher quality data will have a greater influence in model updates.
[0498] This adaptive weighting mechanism ensures that the global model makes better use of high-quality data sources while not completely ignoring the contributions of smaller or poorer data quality monitoring stations.
[0499] 3. Improved FedAvg algorithm implementation:
[0500] ```Python
[0501] def improved_fedavg(global_model, client_models, client_weights,param_mapping):
[0502] global_state = global_model.state_dict()
[0503] aggregated_state = {}
[0504] for key in global_state.keys():
[0505] aggregated_state[key] = torch.zeros_like(global_state[key])
[0506] for client_model, weight in zip(client_models, client_weights):
[0507] client_state = client_model.state_dict()
[0508] for global_key in global_state.keys():
[0509] if global_key in client_state:
[0510] aggregated_state[global_key] += weight * client_state[global_key]
[0511] elif global_key in param_mapping:
[0512] client_key = param_mapping[global_key]
[0513] aggregated_state[global_key] += weight * client_state[client_key]
[0514] global_model.load_state_dict(aggregated_state)
[0515] return global_model
[0516] ```
[0517] The improved_fedavg function implements an improved version of the FedAvg algorithm, which is specially designed to handle heterogeneous models. The core idea of this algorithm is to weighted average the model parameters from different clients while taking into account the parameter mapping between models.
[0518] The function first initializes an aggregate state with the same structure as the global model. Then, it iterates over all client models and adds the client model's parameters to the aggregate state according to the parameter mapping established previously. This process takes into account the weight of the parameters, ensuring that more important or better performing client models have a greater impact.
[0519] In a water quality monitoring system, this means that models from different monitoring stations can effectively share their knowledge, even if they use different types of neural networks. For example, a monitoring station using CNN is good at detecting short-term water quality change patterns, while a monitoring station using SNN is better at capturing long-term water quality trends. With this improved FedAvg algorithm, the system can combine the advantages of both.
[0520] 4. Heterogeneous model aggregation strategy:
[0521] For layers in CNN and SNN models that do not completely correspond, the following strategy is adopted:
[0522] a) For convolutional layers and fully connected layers, weight averaging is performed directly.
[0523] b) For SNN-specific neuron parameters (such as thresholds), a weighted average method is used.
[0524] c) For layers that cannot be directly mapped, the original parameters of the global model are retained.
[0525] ```Python
[0526] def aggregate_heterogeneous_layers(cnn_layers, snn_layers, weights):
[0527] aggregated_layers = {}
[0528] for key in cnn_layers.keys():
[0529] if key in snn_layers:
[0530] aggregated_layers[key] = sum(w * m[key]for w, m in zip(weights, [cnn_layers, snn_layers]))
[0531] else:
[0532] aggregated_layers[key] = cnn_layers[key]
[0533] for key in snn_layers.keys():
[0534] if key not in cnn_layers:
[0535] aggregated_layers[key] = snn_layers[key]
[0536] return aggregated_layers
[0537] ```
[0538] Among them, the aggregate_heterogeneous_layers function implements a complex strategy to deal with layers that do not completely correspond in CNN and SNN models. The purpose of this strategy is to maximize knowledge transfer while maintaining the integrity of the model.
[0539] For layers that exist in both CNN and SNN (such as some fully connected layers), the function directly performs weighted averaging.
[0540] For layers that only exist in one model (such as convolutional layers of CNN or special neuron parameters of SNN), the function retains the original parameters.
[0541] This strategy allows the system to remain flexible when integrating different types of water quality monitoring models. For example, it can combine the advantages of CNN in spatial feature extraction and SNN in time series processing to create a more comprehensive water quality monitoring model.
[0542] 5. Model performance evaluation and selection:
[0543] After each round of aggregation, the performance of the aggregated model is evaluated and compared with the performance of a single model (CNN or SNN) to select the optimal model.
[0544] ```Python
[0545] def evaluate_and_select_model(aggregated_model, cnn_model, snn_model,test_data):
[0546] models = [aggregated_model, cnn_model, snn_model]
[0547] performances = [evaluate_model(model, test_data) for model in models]
[0548] best_model = models[np.argmax(performances)]
[0549] return best_model
[0550] The evaluate_and_select_model function evaluates the performance of the aggregated model after each round of federated learning and compares it with the individual CNN and SNN models. This step ensures that the federated learning process always moves in the direction of improving the overall performance.
[0551] In a water quality monitoring system, this step can help determine which model structure (aggregate model, CNN, or SNN) performs best in a specific situation. For example, CNN performs better when detecting sudden changes in water quality, while SNN has an advantage when predicting long-term water quality trends. By selecting the model with the best performance, the system can flexibly adjust its strategy according to different monitoring needs.
[0552] S3.4: Integrating differential privacy mechanisms into heterogeneous federated learning frameworks
[0553] The integration of differential privacy mechanisms aims to protect the data privacy of participants while maintaining the learning ability of the model. The following are the specific implementation steps:
[0554] 1. Define your privacy budget:
[0555] Privacy budget is a core concept in the differential privacy framework, which is used to quantify and control the amount of private information that is allowed to be leaked during data analysis. In the federated learning of water quality monitoring systems, this step is crucial because it ensures that the data privacy of each monitoring site participating in the learning is protected.
[0556] Specifically, we set the overall privacy budget ε and δ, and allocate a privacy budget for each round of training.
[0557] ```Python
[0558] class PrivacyBudget:
[0559] def __init__(self, total_epsilon, total_delta, num_rounds):
[0560] self.epsilon_per_round = total_epsilon / num_rounds
[0561] self.delta_per_round = total_delta / num_rounds
[0562] ```
[0563] The PrivacyBudget class defines the overall privacy budget (ε and δ) and distributes it evenly to each training round. ε controls the strength of privacy protection, while δ is the upper limit of the probability of privacy leakage. In water quality monitoring, this means that even if an attacker obtains the model, it is impossible to accurately infer the specific water quality data of a specific monitoring site.
[0564] For example, if the total privacy budget ε=1.0, δ=10 -5 , the training rounds are 100, then ε=0.01 and δ=10 in each round -7 This ensures that even after multiple rounds of training, the cumulative risk of privacy leakage remains controllable.
[0565] 2. Implement Gaussian mechanism:
[0566] Add Gaussian noise when the client updates the model parameters.
[0567] The Gaussian mechanism is a method of achieving differential privacy, which protects privacy by adding random noise to real data or calculation results. In the water quality monitoring system, this means that each monitoring station will first add noise to the parameters when uploading its local model update.
[0568] ```Python
[0569] def add_gaussian_noise(parameters, sensitivity, epsilon, delta):
[0570] sigma = np.sqrt(2 * np.log(1.25 / delta)) * sensitivity / epsilon
[0571] noise = torch.randn_like(parameters) * sigma
[0572] return parameters + noise
[0573] ```
[0574] The add_gaussian_noise function calculates the appropriate noise standard deviation σ based on the given privacy parameters (ε and δ), and then generates and adds Gaussian noise. This process ensures that even if an attacker obtains the model update, the precise value of the original water quality data cannot be accurately inferred.
[0575] For example, for sensitive water quality parameters (such as heavy metal content), adding noise will slightly change their values but will not significantly affect the overall water quality assessment results.
[0576] 3. Gradient Clipping:
[0577] Gradient clipping is an important technique to control the sensitivity of model updates. In water quality monitoring systems, data distributions at different sites vary greatly, resulting in significant differences in gradient values. Gradient clipping can prevent abnormally large gradient values from leaking too much information.
[0578] Limit the L2 norm of the gradient to control sensitivity.
[0579] ```Python
[0580] def clip_gradients(gradients, max_norm):
[0581] total_norm = torch.norm(torch.stack([torch.norm(grad) for grad ingradients]))
[0582] clip_coef = max_norm / (total_norm + 1e-6)
[0583] if clip_coef<1:
[0584] return [grad * clip_coef for grad in gradients]
[0585] return gradients
[0586] ```
[0587] The clip_gradients function calculates the total L2 norm of all gradients and scales them when they exceed a specified threshold. This ensures that the contribution of each monitoring station is limited to a controllable range, preventing abnormal data from a single station from having too much influence on the global model.
[0588] 4. Client-side differential privacy training:
[0589] Integrate differential privacy mechanisms during client-side training.
[0590] ```Python
[0591] def train_with_privacy(model, data, optimizer, privacy_budget, max_grad_norm):
[0592] for batch in data:
[0593] optimizer.zero_grad()
[0594] loss = compute_loss(model, batch)
[0595] loss.backward()
[0596] gradients = [p.grad for p in model.parameters()]
[0597] clipped_gradients = clip_gradients(gradients, max_grad_norm)
[0598] for param, grad in zip(model.parameters(), clipped_gradients):
[0599] noisy_grad = add_gaussian_noise(grad, max_grad_norm, privacy_budget.epsilon_per_round, privacy_budget.delta_per_round)
[0600] param.grad = noisy_grad
[0601] optimizer.step()
[0602] ```
[0603] This step integrates the differential privacy mechanism into the local training process of each water quality monitoring site. The train_with_privacy function applies gradient clipping and noise addition at each parameter update.
[0604] In a water quality monitoring system, this means that each site protects the privacy of its data when training its local model. For example, if a site detects unusually high levels of a pollutant, this information is not leaked in its original form, but rather influences the model update in a privacy-preserving way.
[0605] 5. Privacy Accounting:
[0606] Track how your privacy budget is being used to ensure you stay within your total budget.
[0607] ```Python
[0608] class PrivacyAccountant:
[0609] def __init__(self, total_epsilon, total_delta):
[0610] self.total_epsilon = total_epsilon
[0611] self.total_delta = total_delta
[0612] self.used_epsilon = 0
[0613] self.used_delta = 0
[0614] def update(self, epsilon, delta):
[0615] self.used_epsilon += epsilon
[0616] self.used_delta += delta
[0617] def check_budget(self):
[0618] return self.used_epsilon<= self.total_epsilon and self.used_delta<=self.total_delta
[0619] ```
[0620] The privacy accounting mechanism tracks the usage of the privacy budget throughout the training process. The PrivacyAccountant class records the privacy budget that has been used and provides methods to check whether the total budget has been exceeded.
[0621] In the long-term operation of the water quality monitoring system, this mechanism ensures that the system does not accumulate too much privacy risk due to long-term data collection and model updates. For example, if the system finds that the privacy budget is about to be exhausted, it can pause model updates or increase the noise level to maintain privacy protection.
[0622] 6. Server-side aggregation & privacy protection:
[0623] Consider privacy protection measures when aggregating model updates on the server side.
[0624] ```Python
[0625] def private_fedavg(global_model, client_updates, privacy_accountant):
[0626] aggregated_update = {}
[0627] for key in global_model.state_dict().keys():
[0628] updates = [update[key] for update in client_updates]
[0629] mean_update = torch.mean(torch.stack(updates), dim=0)
[0630] noisy_update = add_gaussian_noise(mean_update, sensitivity=1.0,epsilon=privacy_accountant.epsilon_per_round, delta=privacy_accountant.delta_per_round)
[0631] aggregated_update[key] = noisy_update
[0632] privacy_accountant.update(privacy_accountant.epsilon_per_round,privacy_accountant.delta_per_round)
[0633] for key in global_model.state_dict().keys():
[0634] global_model.state_dict()[key] += aggregated_update[key]
[0635] return global_model
[0636] ```
[0637] The private_fedavg function implements the privacy-preserving federated averaging algorithm on the server side. It not only aggregates the model updates from various water quality monitoring stations, but also adds additional noise in the aggregation process.
[0638] This step ensures that even if the server is compromised, the attacker cannot accurately infer the contribution of a single site from the aggregated results. For example, if the water quality in a certain area suddenly deteriorates, this information will be incorporated into the global model in a privacy-preserving way without directly revealing which specific site detected the problem.
[0639] 7. Adaptive Privacy Budget Allocation:
[0640] Dynamically adjust privacy budget allocation based on model performance and privacy requirements.
[0641] ```Python
[0642] def adaptive_privacy_budget_allocation(initial_budget, model_performance, round_num, total_rounds):
[0643] if model_performance>threshold and round_num <total_rounds / 2:
[0644] return initial_budget * 0.8# Reduce the privacy budget
[0645] elif model_performance<threshold and round_num> total_rounds / 2:
[0646] return initial_budget * 1.2# Increase privacy budget
[0647] return initial_budget
[0648] ```
[0649] The adaptive_privacy_budget_allocation function dynamically adjusts the privacy budget based on model performance and training progress. This adaptive approach allows the system to balance privacy protection and model performance at different stages.
[0650] In a water quality monitoring system, this means that when a potential water quality crisis is detected, the system can temporarily increase the privacy budget to obtain a more accurate model update. Conversely, during periods of stable water quality, the system can strengthen privacy protection. This flexibility enables the system to find a balance between protecting privacy and responding to water quality changes in a timely manner.
[0651] Through the above steps, the embodiment of the present invention implements an improved federated averaging algorithm, which can effectively aggregate the two heterogeneous models of CNN and SNN, and integrate the differential privacy mechanism into the federated learning framework. This method not only solves the problem of heterogeneous model aggregation, but also maintains the learning ability of the model while protecting the data privacy of the participants.
[0652] In a water quality monitoring system, this approach allows different monitoring sites (using different types of models) to collaborate securely and jointly improve water quality detection and prediction models without leaking sensitive local data. This is critical for building a large-scale, efficient, and privacy-preserving water quality monitoring network.
[0653] S4: Building a hybrid generative AI model for water quality testing;
[0654] S4.1: Select a pre-trained large language model LLM, and fine-tune the large language model;
[0655] 1. Choose a pre-trained Large Language Model (LLM):
[0656] Selecting an appropriate pre-trained large language model is a critical first step in building an efficient water quality monitoring system. This selection requires balancing multiple factors to ensure that the model can effectively handle complex tasks related to water quality.
[0657] a) Model size: In the field of water quality monitoring, models need to understand and process complex scientific concepts and environmental data. Therefore, it is important to choose a model that is large enough to ensure that it can capture the complexity and nuances of water quality data. For example, the model should be able to distinguish between different types of pollutants and their impact on water quality. However, the model should not be too large, otherwise it cannot be deployed in resource-constrained environments, such as remote monitoring stations.
[0658] b) Pre-training data: Ideally, pre-training data should contain a large amount of scientific and environmental related text. This is particularly important for water quality monitoring, as the model needs to understand professional terms, chemical formulas, environmental regulations, etc. For example, the model should be able to understand the meaning of terms such as "dissolved oxygen" and "biochemical oxygen demand" and their importance in water quality assessment.
[0659] c) Multilingual capability: Water quality issues are global, so the model needs to be able to handle reports and literature in multiple languages. This enables the system to integrate water quality data and research results from different countries and regions, providing a more comprehensive analysis.
[0660] d) Open source availability: Selecting open source models allows researchers and developers to customize and optimize them for specific water quality monitoring needs. For example, the model can be adjusted for water quality characteristics in a specific region or for a specific type of pollutant.
[0661] Based on these considerations, the following model can be selected in the embodiment of the present invention:
[0662] BERT (Bidirectional Encoder Representations from Transformers)
[0663] RoBERTa (A Robustly Optimized BERT Pretraining Approach)
[0664] ALBERT (A Lite BERT for Self-supervised Learning of LanguageRepresentations)
[0665] For example, the embodiment of the present invention selects the BERT-base model:
[0666] ```Python
[0667] from transformers import BertForSequenceClassification, BertTokenizer
[0668] model_name = 'bert-base-uncased'
[0669] tokenizer = BertTokenizer.from_pretrained(model_name)
[0670] model = BertForSequenceClassification.from_pretrained(model_name,num_labels=num_water_quality_classes)
[0671] ```
[0672] The BERT-base model chosen in this example is a good starting point. It strikes a good balance between scale and performance, the pre-training data covers a wide range of fields, has a strong ability to process English text, and is open source. In water quality monitoring, BERT can be used for a variety of tasks, such as water quality report classification, key information extraction, water quality trend prediction, etc.
[0673] 2. Fine-tune the large language model:
[0674] The fine-tuning process consists of the following steps:
[0675] a) Prepare water quality related datasets:
[0676] Collect text data such as water quality reports, scientific literature, and expert analysis.
[0677] Annotate data such as water quality level, pollution type, treatment recommendations, etc.
[0678] This step is critical to the final performance of the model. The dataset should include various types of water quality reports, scientific literature, and expert analysis. For example, it can include water quality reports for rivers, lakes, and groundwater, research literature on different types of pollutants, and analysis and suggestions from water quality experts for different situations. Data annotations include water quality grades (such as excellent, good, and poor), pollution types (such as organic pollution and heavy metal pollution), and corresponding treatment recommendations. Such a dataset will enable the model to learn to identify water quality problems and provide corresponding solutions.
[0679] b) Data preprocessing:
[0680] The preprocessing step converts the raw text into a format that the model can understand. In the context of water quality monitoring, this involves handling special scientific symbols, chemical formulas, or numerical ranges. For example, a statement such as "pH value is 7.5±0.2" needs to be encoded correctly. The implementation of the WaterQualityDataset class ensures that the data can be processed efficiently in batches, which is important for processing large amounts of water quality monitoring data.
[0681] Construct input features (such as water quality parameters) and labels.
[0682] ```Python
[0683] def preprocess_data(texts, labels):
[0684] encodings = tokenizer(texts, truncation=True, padding=True, max_length=512)
[0685] dataset = WaterQualityDataset(encodings, labels)
[0686] return dataset
[0687] class WaterQualityDataset(torch.utils.data.Dataset):
[0688] def __init__(self, encodings, labels):
[0689] self.encodings = encodings
[0690] self.labels = labels
[0691] def __getitem__(self, idx):
[0692] item = {key: torch.tensor(val[idx]) for key, val inself.encodings.items()}
[0693] item['labels'] = torch.tensor(self.labels[idx])
[0694] return item
[0695] def __len__(self):
[0696] return len(self.labels)
[0697] ```
[0698] This code defines the data preprocessing process:
[0699] The preprocess_data function takes in the raw text and labels and uses a pre-trained tokenizer to convert the text into a sequence of numbers that the model can understand. truncation=True and max_length=512 ensure that all inputs are truncated or padded to the same length, which is important when dealing with variable-length water quality reports.
[0700] The WaterQualityDataset class is a custom dataset class that inherits from the PyTorch Dataset class. The purpose of this class is to organize the encoded data and labels into a format that is easy to process in batches.
[0701] The __init__ method initializes the dataset.
[0702] The __getitem__ method defines how to get a single data sample. It converts the encoded text and the corresponding label into a PyTorch tensor.
[0703] The __len__ method returns the size of the dataset.
[0704] This structure allows the model to efficiently process large amounts of water quality data, whether short-term water quality parameters or long-term water quality reports.
[0705] c) Set fine-tuning parameters:
[0706] Learning rate, batch size, number of training rounds, etc.
[0707] ```Python
[0708] from transformers import TrainingArguments
[0709] training_args = TrainingArguments(
[0710] output_dir='. / results',
[0711] num_train_epochs=3,
[0712] per_device_train_batch_size=16,
[0713] per_device_eval_batch_size=64,
[0714] warmup_steps=500,
[0715] weight_decay=0.01,
[0716] logging_dir='. / logs', )
[0718] ```
[0719] The parameter settings need to be adjusted according to the characteristics of the water quality monitoring task. For example, if the task is to identify sudden changes in water quality, a higher learning rate and a smaller batch size are required to quickly adapt to new patterns. On the contrary, if the task is to understand long-term water quality trends, more training rounds and larger batch sizes are required.
[0720] The above code sets the hyperparameters for training:
[0721] output_dir='. / results': Specifies where model checkpoints and other output files are saved.
[0722] num_train_epochs=3: Set the number of training rounds. For water quality monitoring tasks, this value needs to be adjusted according to the size and complexity of the dataset.
[0723] per_device_train_batch_size=16: Set the training batch size for each device (GPU / CPU).
[0724] per_device_eval_batch_size=64: Set the batch size for evaluation, which can usually be larger than that for training.
[0725] warmup_steps=500: The number of steps for warming up the learning rate, which helps stabilize the model in the early stages of training.
[0726] weight_decay=0.01: Weight decay parameter to prevent overfitting.
[0727] logging_dir='. / logs': specifies the location where the log files are saved.
[0728] The setting of these parameters is crucial to the performance of the model in water quality monitoring tasks and needs to be adjusted according to the specific characteristics of water quality data.
[0729] d) Fine-tuning process:
[0730] Train the model using the prepared dataset.
[0731] ```Python
[0732] from transformers import Trainer
[0733] trainer = Trainer(
[0734] model=model,
[0735] args=training_args,
[0736] train_dataset=train_dataset,
[0737] eval_dataset=eval_dataset )
[0739] trainer.train()
[0740] ```
[0741] During fine-tuning, the model learns to apply its general language understanding capabilities to specific water quality monitoring tasks. For example, the model learns to associate descriptions such as "high turbidity" and "cloudy water" with specific water quality issues.
[0742] The above code implements the fine-tuning process of the model:
[0743] Create a Trainer object, which encapsulates the entire training process.
[0744] model: the pre-trained model initialized previously.
[0745] args: The training parameters defined previously.
[0746] train_dataset: training dataset.
[0747] eval_dataset: Evaluation dataset.
[0748] trainer.train() starts the training process, during which the model gradually adjusts its parameters to better suit tasks related to water quality monitoring.
[0749] This training process automatically handles details such as gradient calculation, parameter updates, and learning rate scheduling, allowing researchers to focus on optimizing model performance.
[0750] e) Evaluation and Optimization:
[0751] Evaluate model performance on the validation set.
[0752] Adjust hyperparameters or add task-specific layers as needed.
[0753] ```Python
[0754] eval_results = trainer.evaluate()
[0755] print(f"Evaluation results: {eval_results}")
[0756] ```
[0757] This code evaluates the model:
[0758] trainer.evaluate() evaluates the model performance on the evaluation dataset.
[0759] The evaluation results are printed out, including indicators such as accuracy and loss value.
[0760] In water quality monitoring tasks, these evaluation results include performance indicators of the model in identifying different water quality levels, pollution types, or predicting water quality trends. Based on these results, researchers can decide whether they need to further adjust the model architecture, update the training data, or modify the training parameters to improve the model's performance on specific water quality monitoring tasks.
[0761] The evaluation phase verifies the model's performance on actual water quality monitoring tasks. This includes testing whether the model can accurately classify water quality levels, correctly identify pollution types, or provide reasonable treatment recommendations. Based on the evaluation results, further optimization is required, such as adjusting the model architecture, adding additional layers specific to water quality, or adjusting the training dataset.
[0762] Through this process, the BERT model, originally used for general language understanding, is transformed into an intelligent system specifically for water quality monitoring. This system is able to understand complex water quality reports, identify potential water quality issues, and provide data-based recommendations. For example, it can analyze long-term water quality monitoring data, identify pollution trends, predict water quality changes, and even recommend optimal water quality improvement measures. This AI-driven approach can significantly improve the efficiency and accuracy of water quality monitoring and provide strong decision-making support for water resource management.
[0763] S4.2: performing knowledge distillation on the fine-tuned large language model to form multiple local models;
[0764] The goal of knowledge distillation is to transfer the knowledge of a large LLM into smaller and more specialized models for use in resource-constrained settings.
[0765] 1. Design teacher model and student model:
[0766] In this step, the embodiment of the present application defines a teacher model (fine-tuned BERT) and a student model (smaller DistilBERT). The teacher model is the large model that the embodiment of the present application fine-tuned in S4.1, and the student model is the small model that the embodiment of the present application hopes to transfer knowledge to.
[0767] Teacher model: the fine-tuned BERT model.
[0768] Student model: A smaller model such as DistilBERT or a custom small Transformer.
[0769] ```Python
[0770] from transformers import DistilBertForSequenceClassification,DistilBertTokenizer
[0771] teacher_model = model# Fine-tuned BERT model
[0772] student_model = DistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased', num_labels=num_water_quality_classes)
[0773] student_tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
[0774] ```
[0775] This code initializes the teacher model (fine-tuned BERT) and the student model (DistilBERT). This embodiment of the application uses the pre-trained DistilBERT model and sets the number of output categories to match the water quality classification task of this embodiment of the application. This lays the foundation for the knowledge distillation process.
[0776] 2. Prepare the distillation dataset:
[0777] Use a large amount of unlabeled water quality related text data.
[0778] This can include both original training data and additional unlabeled data.
[0779] The distillation process requires a lot of data. The present application embodiment uses text data related to water quality, including labeled training data and additional unlabeled data. These data need to be preprocessed to adapt to the input format of the teacher and student models.
[0780] ```Python
[0781] def prepare_distillation_data(texts):
[0782] teacher_encodings = tokenizer(texts, truncation=True, padding=True,max_length=512)
[0783] student_encodings = student_tokenizer(texts, truncation=True, padding=True, max_length=512)
[0784] return teacher_encodings, student_encodings
[0785] ```
[0786] The prepare_distillation_data function converts the text data into a format that can be processed by both the teacher and student models. It encodes the text using their respective tokenizers, ensuring that the input length is consistent (maximum 512 tokens). This step ensures the consistency of the data so that knowledge can be effectively transferred from the teacher to the student.
[0787] 3. Define the distillation loss function:
[0788] Combining soft target loss (KL divergence between student model output and teacher model output) and hard target loss (cross entropy between student model output and true label).
[0789] The core of the distillation process is to define a suitable loss function. This function combines two parts: soft target loss (KL divergence between the student model output and the teacher model output) and hard target loss (cross entropy between the student model output and the true label).
[0790] ```Python
[0791] import torch.nn.functional as F
[0792] def distillation_loss(student_logits, teacher_logits, labels, temp=2.0, alpha=0.5):
[0793] soft_targets = F.softmax(teacher_logits / temp, dim=-1)
[0794] soft_prob = F.log_softmax(student_logits / temp, dim=-1)
[0795] soft_targets_loss = F.kl_div(soft_prob, soft_targets, reduction='batchmean') * (temp**2)
[0796] hard_loss = F.cross_entropy(student_logits, labels)
[0797] return alpha * soft_targets_loss + (1 - alpha) * hard_loss
[0798] ```
[0799] The distillation_loss loss function balances two goals: allowing the student model to learn the soft output of the teacher model (through KL divergence) while also maintaining accurate predictions of the true label (through cross entropy). The temperature parameter temp controls the "softness" of the soft target, while the alpha parameter balances the weight of the two losses. This approach allows the student model to learn not only the correct answer, but also the uncertainty and generalization ability of the teacher model.
[0800] 4. Implement the knowledge distillation training loop:
[0801] With the loss function, the embodiment of the present application can now implement the actual distillation process. This process involves training for multiple epochs, and the entire data set is processed in each epoch.
[0802] ```Python
[0803] def distill_knowledge(teacher_model, student_model, train_dataloader,optimizer, num_epochs):
[0804] for epoch in range(num_epochs):
[0805] for batch in train_dataloader:
[0806] teacher_outputs = teacher_model(**batch)
[0807] student_outputs = student_model(**batch)
[0808] loss = distillation_loss(student_outputs.logits, teacher_outputs.logits, batch['labels'])
[0809] optimizer.zero_grad()
[0810] loss.backward()
[0811] optimizer.step()
[0812] print(f"Epoch {epoch+1} / {num_epochs}, Loss: {loss.item()}")
[0813] ```
[0814] The distill_knowledge function performs the core process of knowledge distillation. In each training step, the embodiment of the present application will:
[0815] Pass the same batch of data through both the teacher and student models.
[0816] Compute the loss using the distillation_loss function defined previously.
[0817] The parameters of the student model are updated through back-propagation. This process allows the student model to gradually learn the knowledge of the teacher model while maintaining computational efficiency.
[0818] 5. Distill multiple specialized local models:
[0819] Multiple specialized models can be distilled for different water quality detection tasks or different geographical areas.
[0820] ```Python
[0821] tasks = ['ph_prediction', 'pollution_classification', 'treatment_recommendation']
[0822] local_models = {}
[0823] for task in tasks:
[0824] task_specific_student = DistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased', num_labels=task_specific_num_labels[task])
[0825] task_specific_data = prepare_task_specific_data(task)
[0826] task_specific_optimizer = AdamW(task_specific_student.parameters(),lr=5e-5)
[0827] distill_knowledge(teacher_model, task_specific_student, task_specific_data, task_specific_optimizer, num_epochs=3)
[0828] local_models[task] = task_specific_student
[0829] ```
[0830] This code creates and trains a specialized student model for each defined task. The present embodiment prepares specific data for each task and uses the same distill_knowledge function for knowledge distillation. This approach allows the present embodiment to create a series of small, specialized models, each focusing on a specific aspect of water quality monitoring.
[0831] 6. Evaluate the distilled model:
[0832] Finally, the embodiment of the present application needs to evaluate each distilled model to ensure that they have achieved the expected performance level. Therefore, the performance of each local model is evaluated on a test set of a specific task.
[0833] ```Python
[0834] def evaluate_local_model(model, test_dataloader):
[0835] model.eval()
[0836] total_accuracy = 0
[0837] num_batches = len(test_dataloader)
[0838] with torch.no_grad():
[0839] for batch in test_dataloader:
[0840] outputs = model(**batch)
[0841] predictions = torch.argmax(outputs.logits, dim=-1)
[0842] total_accuracy += (predictions == batch['labels']).float().mean()
[0843] return total_accuracy / num_batches
[0844] for task, model in local_models.items():
[0845] task_specific_test_data = prepare_task_specific_test_data(task)
[0846] accuracy = evaluate_local_model(model, task_specific_test_data)
[0847] print(f"Accuracy for {task}: {accuracy}")
[0848] ```
[0849] This evaluation process tests each specialized model using task-specific test data. The present embodiment calculates the accuracy of each model, which enables the present embodiment to evaluate the effectiveness of knowledge distillation and ensure that each local model can effectively perform its specific task.
[0850] Through these six steps, the embodiment of the present application successfully transfers the knowledge of the large language model to multiple small, specialized models. These local models retain most of the performance of the large model while greatly reducing the demand for computing resources. This approach enables the water quality detection system of the embodiment of the present application to operate efficiently in a variety of environments, from resource-limited edge devices to more powerful central servers.
[0851] The above six steps can be specifically expressed as:
[0852] 1. Design teacher model and student model:
[0853] In this step, the embodiment of the present application first selects a pre-trained large language model (such as BERT) as the teacher model. This model has been fine-tuned for water quality related tasks in S4.1. For the student model, the embodiment of the present application selects a smaller model architecture, such as DistilBERT. The structure of the student model is smaller than the teacher model, but it still needs to maintain sufficient complexity to capture key information. When initializing the student model in the embodiment of the present application, random initialization or pre-trained weights can be used. The key is to ensure that the output layer of the student model matches the specific task of the embodiment of the present application (such as water quality classification).
[0854] 2. Prepare the distillation dataset:
[0855] Data preparation is the key to successful knowledge distillation. The embodiment of the present application collects a large amount of text data related to water quality, including labeled training data and unlabeled additional data. These data need to be cleaned and preprocessed, including noise removal, standardized format, etc. Then, the embodiment of the present application uses the tokenizer of the teacher model and the student model to encode the text. This step needs to pay attention to the truncation of long texts and the padding of short texts to ensure that the length of all inputs is consistent. The embodiment of the present application also needs to ensure the diversity of the data, covering various water quality conditions and language expressions, in order to improve the generalization ability of the student model.
[0856] 3. Define the distillation loss function:
[0857] The distillation loss function is the core of the whole process. The embodiments of the present application usually combine two losses: soft target loss and hard target loss. Soft target loss uses Kullback-Leibler (KL) divergence to measure the difference between the output probability distribution of the student model and the output of the teacher model. Here, the embodiment of the present application introduces a temperature parameter to "soften" the probability distribution, which is usually set to a value greater than 1 (such as 2 or 4). The hard target loss is the cross entropy between the output of the student model and the true label. The embodiment of the present application uses a weight parameter α to balance the two losses, and α is usually set between 0.5 and 0.8. This combined loss function allows the student model to learn not only the correct answer, but also the uncertainty estimate of the teacher model.
[0858] 4. Implement the knowledge distillation training loop:
[0859] The training loop is the actual execution phase of the entire distillation process. The embodiment of the present application iterates the entire data set through multiple epochs. In each training step, the embodiment of the present application first passes a batch of data through the teacher model to obtain the teacher's prediction. Then, the embodiment of the present application passes the same data to the student model. Using the loss function defined above, the embodiment of the present application calculates the loss between the output of the student model and the output of the teacher model, as well as the loss between the student model and the true label. The parameters of the student model are then updated through backpropagation. This process requires careful adjustment of the learning rate and other optimizer parameters to ensure that the student model can learn effectively without overfitting. The embodiment of the present application can also implement learning rate scheduling strategies, such as linear decay or cosine annealing, to optimize the training process.
[0860] 5. Distill multiple specialized local models:
[0861] In order to adapt to the special needs of different water quality detection tasks or geographical areas, the embodiment of the present application can train multiple specialized student models. First, the embodiment of the present application defines a series of specific tasks, such as pH value prediction, pollution classification, treatment suggestion generation, etc. For each task, the embodiment of the present application prepares specific training data sets, which should reflect the particularity of the task. Then, the embodiment of the present application initializes a new student model instance and uses the same teacher model for knowledge distillation. This process is repeated for each task, and the distillation parameters (such as temperature, α value) are fine-tuned each time to adapt to the needs of the specific task. This approach allows the embodiment of the present application to create a series of small, efficient, and task-optimized models.
[0862] 6. Evaluate the distilled model:
[0863] Finally, the embodiment of the present application needs to comprehensively evaluate the performance of each distilled model. The embodiment of the present application prepares an independent test set for each specialized model, and these test sets should reflect the data distribution in the actual application scenario. The evaluation process includes calculating standard indicators such as accuracy, precision, recall, and F1 score. For regression tasks (such as pH prediction), the embodiment of the present application will use the root mean square error (RMSE) or the mean absolute error (MAE). The embodiment of the present application should also compare the performance of the student model with the teacher model on the same task to ensure the effectiveness of knowledge transfer. In addition, the embodiment of the present application can test the inference speed and resource consumption (such as memory usage, CPU / GPU occupancy) to confirm the practicality of the student model in a resource-constrained environment. Finally, the embodiment of the present application also needs to conduct some actual scenario tests to evaluate the performance of the model in a real water quality monitoring environment.
[0864] Through these steps, the embodiment of the present invention successfully selected a large language model suitable for water quality detection tasks, fine-tuned it to adapt to specific water quality-related tasks, and generated multiple specialized small local models through knowledge distillation. These local models can be more effectively deployed in resource-constrained environments, such as various water quality monitoring sites, while retaining most of the performance advantages of large LLMs.
[0865] This method enables the water quality detection system of the embodiment of the present invention to use advanced natural language processing technology to understand and analyze complex water quality reports, generate accurate water quality assessments, and provide targeted processing suggestions, greatly improving the intelligence level and practicality of the system.
[0866] Exemplarily, the fine-tuned large language model is subjected to knowledge distillation to form a water quality parameter prediction model, an anomaly detection model, a pollution source identification model, and a treatment suggestion generation model, wherein:
[0867] The water quality parameter prediction model is used to predict future water quality parameter values using historical data;
[0868] The anomaly detection model is used to identify abnormal values or patterns in the water quality parameters;
[0869] The pollution source identification model is used to infer pollution sources based on water quality data;
[0870] The treatment suggestion generation model is used to provide treatment suggestions according to current water quality conditions.
[0871] S4.3: formulating a dynamic switching strategy to dynamically switch to the large language model or one of the local models according to task complexity;
[0872] Specifically, a dynamic switching strategy is formulated to determine whether the large language model needs to be activated according to the complexity of the task and the depth of the required analysis, including:
[0873] For a single query or local data analysis task, the local model is used for processing;
[0874] For multi-source query and analysis tasks of cross-domain knowledge, the large language model is used for processing.
[0875] It should be noted that in S4.3, an intelligent dynamic switching strategy is designed to switch between the local model and the large language model according to the complexity of the task and the depth of the required analysis. The core of this strategy is to optimize the use of system resources while ensuring the processing quality. The specific implementation includes the following key aspects:
[0876] 1. Task complexity assessment:
[0877] Design a scoring system to quantify the complexity of the task. This system considers multiple factors, such as the length of the query, whether it contains professional terms, whether it involves cross-domain knowledge, whether it requires information from multiple data sources, etc. Each factor is assigned a certain weight, and finally a complexity score is obtained.
[0878] 2. Analyze the in-depth needs assessment:
[0879] Assess the depth of analysis required for the query. This includes determining whether a detailed explanation is required, whether predictions or extrapolations are involved, whether historical data comparisons are required, whether comprehensive reports need to be generated, etc. Again, these factors are quantified into a depth score.
[0880] 3. Model selection decision:
[0881] The decision of which model to use is based on the complexity and depth scores. A threshold is set, and when the total score is below a certain value, the local model is used, and when it is above a certain value, it switches to the large language model. In the middle range, different specialized local models are selected according to the specific situation.
[0882] 4. Dynamic switching implementation:
[0883] Create a manager to handle switching between models. This manager receives queries, evaluates their complexity and depth, and then selects an appropriate model to handle. If the selected model is different from the currently used model, a switch operation is triggered.
[0884] 5. Optimize switching efficiency:
[0885] Implement model preloading and caching mechanisms to reduce latency during switching. Frequently used models can be preloaded into memory or GPU for fast switching.
[0886] 6. Continuous Learning and Adaptability:
[0887] Add a feedback mechanism to record the performance of each model in processing different types of queries. Based on this historical data, the system can dynamically adjust the selection criteria and continuously optimize the switching strategy.
[0888] 7. Special Circumstances:
[0889] For certain types of queries, such as emergency situations or routine reports, specific models can be specified to be used, bypassing the normal evaluation process.
[0890] 8. Parallel processing capabilities:
[0891] For particularly complex queries, the system can enable multiple models at the same time, process the query in parallel, and then combine the results of each model to get the final answer.
[0892] The specific switching strategies are as follows:
[0893] For single queries or local data analysis tasks, such as daily water quality parameter queries, simple trend analysis, etc., the system will choose to use local models. These models are specially trained to handle such common tasks quickly and efficiently.
[0894] For multi-source queries and complex analysis tasks that span domain knowledge, such as in-depth analysis that requires comprehensive knowledge from multiple domains, such as environmental science, chemistry, and biology, the system will activate the large language model, which has a broader knowledge base and stronger reasoning capabilities and can handle such complex tasks.
[0895] Through this dynamic switching strategy, the water quality detection system can flexibly switch between tasks of different complexity and depth, ensuring both the ability to handle complex tasks and the rapid response to daily tasks. This approach greatly improves the system's intelligence level and resource utilization efficiency, enabling it to adapt to the needs of various water quality detection and analysis scenarios.
[0896] S5: inputting the fused multimodal data into the heterogeneous federated learning model to predict the changes of water quality parameters under different environmental conditions and different time periods, wherein the water quality parameters include one or more combinations of pH value, dissolved oxygen, conductivity, turbidity, ammonia nitrogen, total phosphorus, and heavy metals;
[0897] S5.1: Inputting the multimodal data into the CNN model to output the variation of the water quality parameters with environmental conditions;
[0898] S5.2: inputting the multimodal data into the SNN model to output the change of the water quality parameter over a time period;
[0899] S5.3: Use the improved FedAvg algorithm to integrate the changes in the water quality parameters with environmental conditions and with time to predict the changes in the water quality parameters under different environmental conditions and different time periods.
[0900] The specific instructions are as follows:
[0901] S5 and its sub-steps describe how to use a heterogeneous federated learning model to predict the changes in water quality parameters under different conditions. This process combines the advantages of CNN and SNN models and integrates information from multiple data sources through federated learning. The following is a detailed description of this process:
[0902] First, S5 aims to use the multimodal data fused in the previous steps to predict the changes in water quality parameters under various conditions through a heterogeneous federated learning model. This process involves distributed data processing and model training, ensuring data privacy and model comprehensiveness.
[0903] S5.1: Feeding multimodal data into CNN models
[0904] In this sub-step, the system inputs the fused multimodal data into the CNN model. The CNN model is particularly good at processing data with spatial correlation, so it is mainly used to analyze the relationship between water quality parameters and environmental conditions.
[0905] The process includes:
[0906] 1. Data preprocessing: Convert data related to environmental conditions (such as temperature, humidity, light, etc.) into a format suitable for CNN processing.
[0907] 2. Model input: Input the preprocessed data into the CNN model.
[0908] 3. Feature extraction: CNN extracts key features between environmental conditions and water quality parameters through its convolutional and pooling layers.
[0909] 4. Output generation: The model outputs the prediction results of water quality parameters as environmental conditions change.
[0910] S5.2: Feeding multimodal data into SNN models
[0911] This sub-step is about time series analysis. The spiking neuron characteristics of the SNN model make it particularly suitable for processing time-related data.
[0912] The process includes:
[0913] 1. Time series preprocessing: Organize water quality data in chronological order, which involves data standardization and time window setting.
[0914] 2. Pulse encoding: Convert continuous time series data into pulse sequences that SNN can process.
[0915] 3. Model processing: The SNN model processes these pulse trains to capture the changing patterns of water quality parameters over time.
[0916] 4. Results decoding: Decoding the output of the SNN into understandable predictions of water quality parameters over time.
[0917] S5.3: Fusion of prediction results using the improved FedAvg algorithm
[0918] The purpose of this step is to combine the prediction results of the CNN and SNN models to form a comprehensive prediction of water quality parameter changes.
[0919] The process includes:
[0920] 1. Local model update: Each participant (different water quality monitoring sites) uses local data to train CNN and SNN models.
[0921] 2. Model parameter upload: Participants send model updates (not raw data) to the central server.
[0922] 3. Improved FedAvg aggregation: The central server uses an improved federated averaging algorithm to aggregate model updates from different participants. This improved version can handle the parameters of both CNN and SNN heterogeneous models.
[0923] 4. Global model update: The aggregated parameters are used to update the global model.
[0924] 5. Model distribution: The updated global model is distributed back to each participant.
[0925] 6. Forecast Generation: Use the updated global model to generate comprehensive forecasts of water quality parameters under different environmental conditions and time periods.
[0926] The advantages of this approach are:
[0927] The advantages of CNN in spatial feature extraction and SNN in time series analysis are fully utilized.
[0928] Through federated learning, information from multiple data sources is integrated to improve the comprehensiveness and accuracy of predictions.
[0929] Data privacy is protected because the original data does not need to leave the local area.
[0930] Ability to generate comprehensive forecasts that consider both environmental conditions and time factors, providing comprehensive decision support for water quality management.
[0931] S6: Input the fused multimodal data into the hybrid generative artificial intelligence model to perform root cause analysis of abnormal water quality parameters.
[0932] The goal of this step is to use advanced hybrid generative AIGC models (large and small models) to conduct in-depth root cause analysis of abnormal water quality parameters. This process not only identifies anomalies, but also provides the causes of the anomalies, providing key insights for water quality management. The following is a detailed description of this step:
[0933] 1. Data preparation and input:
[0934] Use the multimodal data fused in the previous steps.
[0935] Converting data into a format suitable for processing by hybrid generative models involves preprocessing steps such as data standardization and encoding.
[0936] 2. Anomaly Detection:
[0937] The anomaly detection capability of the model was used to identify water quality parameters that deviated from the normal range.
[0938] This involves a combination of statistical methods (such as Z-score analysis) and machine learning techniques (such as the isolation forest algorithm).
[0939] 3. Contextual information integration:
[0940] Collect contextual information related to abnormal parameters, such as recent environmental changes, human activity records, upstream water system conditions, etc.
[0941] 4. Cause and effect analysis:
[0942] The reasoning ability of the model is used to analyze the causal relationship between abnormal parameters and various factors.
[0943] This involves the application of Bayesian networks or other causal inference techniques.
[0944] 5. Knowledge base query:
[0945] Query the model's built-in knowledge base of water quality science to find historical cases or scientific explanations similar to the current anomaly.
[0946] This step utilizes the powerful knowledge retrieval capabilities of the large language model.
[0947] 6. Hypothesis Generation:
[0948] Based on the above analysis, the model generates several hypotheses that lead to anomalies.
[0949] Each hypothesis should include potential causes, mechanisms of effect, and evidence.
[0950] 7. Hypothesis Verification:
[0951] The model attempts to verify each hypothesis, which involves requests for additional data or suggestions for simulation experiments.
[0952] This step reflects the model's creative thinking ability.
[0953] 8. Confidence Assessment:
[0954] Conduct a confidence assessment for each root cause hypothesis, taking into account factors such as the strength of evidence and the rationality of the hypothesis.
[0955] Use probabilistic models or fuzzy logic to quantify confidence.
[0956] 9. Result generation:
[0957] Generates a detailed root cause analysis report including:
[0958] a) Detailed description of abnormal parameters
[0959] b) Root causes, sorted by confidence
[0960] c) A detailed explanation and supporting evidence for each reason
[0961] d) Potential impact assessment
[0962] e) Recommended directions for further investigation or corrective actions
[0963] Through this complex process, the hybrid generative AI model is able to provide in-depth and comprehensive root cause analysis of abnormal water quality parameters. This analysis not only helps to quickly identify and solve water quality problems, but also provides valuable insights for long-term water quality management and policy making. The generative nature of the model enables it to handle new and unprecedented situations, while its knowledge-based reasoning capabilities ensure the scientific nature and interpretability of the analysis. This approach greatly enhances the intelligence level of the water quality monitoring system, making it a powerful tool for water resource management.
[0964] Embodiment 2
[0965] like Figure 2 As shown, the embodiment of the present application also provides a water quality detection system 20 based on multimodal data fusion and intelligent optimization, including:
[0966] Flow path editing module 21, intelligent module 22, control module 23, flow path module 24 and multimodal data fusion module 25, wherein:
[0967] The flow path editing module 21 includes a human-computer interaction unit, a parameter data processing unit, a flow path data processing unit, an algorithm data processing unit and a data transmission unit;
[0968] like Figure 3 As shown, exemplarily, the module includes:
[0969] The flow path editing module 21 realizes the compilation and interpretation function from natural language to machine language, and encapsulates the complex software design and hardware circuit control and describes them in natural language.
[0970] (1) Human-computer interaction unit: user-oriented editing interface
[0971] ①Parameter interaction interface: basic software parameter configuration, basic instrument function parameter configuration;
[0972] ②Flow path interactive interface: flow path program configuration;
[0973] ③Algorithm interaction interface: algorithm program configuration;
[0974] ④Log display: user operation action display and operation status display.
[0975] (2) Parameter data processing unit: performs parameter data processing;
[0976] ①Parameter setting converter: parameter data conversion and verification;
[0977] ②Parameter memory: parameter storage
[0978] (3) Flow path data processing unit: flow path data processing;
[0979] ①Flow path editor: convert the written flow path natural language into machine code;
[0980] ② Flow path interpreter: interprets flow path machine code into natural language;
[0981] ③Flow path file storage: store the edited flow path synthesis .lab file or the flow path synthesis .lab file exported by the instrument;
[0982] (4) Algorithm data processing unit: algorithm data processing;
[0983] ①Algorithm editor: convert the written mathematical formula into machine code;
[0984] ②Algorithm interpreter: interprets the algorithm machine code into mathematical formulas;
[0985] ③ Algorithm file storage: add the edited algorithm synthesis .bin file or the algorithm synthesis .bin file exported by the instrument for storage;
[0986] (5) Data transmission unit: performs data transmission and transmission process verification with the control module;
[0987] ①Parameter uploader and downloader: control unit parameter export and import;
[0988] ②Flow path file upload and downloader: control the flow path program export and import of the control unit;
[0989] ③Algorithm file upload and downloader: control the export and import of the algorithm program of the control unit;
[0990] (6) Operation log monitor: monitors the flow path editing module operations and outputs the operation results;
[0991] The intelligent module 22 is used to construct and train a heterogeneous federated learning model of a convolutional neural network and a spiking neural network; construct a hybrid generative artificial intelligence model in the field of water quality detection; input the fused multimodal data into the heterogeneous federated learning model to predict the changes of water quality parameters under different environmental conditions and different time periods; input the fused multimodal data into the hybrid generative artificial intelligence model to perform root cause analysis of abnormal water quality parameters;
[0992] The multimodal data fusion module 25 is used to collect and clean the multimodal data, the multimodal data including flow path parameters, environmental conditions and water quality test results, and fuse the cleaned multimodal data;
[0993] The control module 23 includes a human-computer interaction interface, a file manager, and a flow path actuator;
[0994] For example, the module is as follows Figure 4 As shown, the control module includes:
[0995] (1) Embedded software layer: embedded hardware driver, implementation of various instrument operation logic and algorithms;
[0996] ① Human-computer interaction interface: instrument human-computer interaction realizes instrument basic parameter setting, test data query, etc.;
[0997] ② File management: file management of instrument flow path, algorithm program, test data, etc.;
[0998] ②Communication monitoring: monitor the communication between the flow path module;
[0999] ③Flow path actuator: executes the flow path program;
[1000] ④Algorithm executor: executes the algorithm program;
[1001] ⑤Task scheduler: communication, human-computer interaction, flow execution, algorithm execution task scheduling;
[1002] ⑥ Operation log monitor: monitor the operation status of the control module and flow path module;
[1003] ⑦ Real-time system RTOS: embedded real-time system;
[1004] (2) Embedded hardware layer: control circuit, detection circuit, operation circuit, etc.;
[1005] ①Microprocessor: microprocessor;
[1006] ②Digital-to-analog conversion circuit: digital quantity to analog quantity is used to detect light source drive
[1007] ③Analog-to-digital conversion circuit: Analog-to-digital circuit is used to convert analog signals into digital signals.
[1008] ④I / O control circuit: used to drive various switch quantity controls of flow path modules
[1009] ⑥General interface circuit: 485, I2C, 232, SPI, etc. and flow path editing module, flow path editing module communication circuit
[1010] ⑦External storage circuit: SD card, used for file storage
[1011] ⑧Clock circuit: hardware system clock circuit;
[1012] ⑨Power management circuit: provides various power supplies and management required by the control module and flow path module;
[1013] The flow path module 24 includes a chemical reaction pool, a photoelectric detection unit, a temperature increasing unit, a temperature decreasing unit, a reagent buffer unit, a quantitative pump, a liquid path selection valve, a bubble leakage detector and a reagent storage unit.
[1014] For example, the module is as follows Figure 5 As shown, the flow path module is used to realize the instrument reagent flow path, chemical reaction and photoelectric detection functions, which includes:
[1015] ①Chemical reaction cell, photoelectric detection unit: chemical reaction, measurement signal detection;
[1016] ② Heating unit: Heating of the chemical reaction cell heating wire;
[1017] ③ Cooling unit: chemical reaction pool fan cooling;
[1018] ④ Reagent cache unit: pre-use reagent cache area;
[1019] ⑤ Dosing pump: extract and discharge reagent metering and power device;
[1020] ⑥Liquid path selection valve: switch different night paths;
[1021] ⑦ Bubble leakage detector: detect the operating status of the flow module
[1022] ⑧Communication and control interface: communicate with the control module and receive control module instructions;
[1023] ⑨ Reagent storage unit: to store reagents required for testing instruments;
[1024] Embodiment 3
[1025] The present application also provides a computer device, such as Figure 6 As shown, the computer device includes:
[1026] at least one processor; and,
[1027] a memory communicatively connected to the at least one processor; wherein,
[1028] The memory stores instructions that can be executed by the at least one processor, and the instructions are executed by the at least one processor so that the at least one processor can execute the above-mentioned water quality detection method based on multimodal data fusion and intelligent optimization.
[1029] An embodiment of the present application also provides a computer-readable storage medium, which stores computer instructions, and the computer instructions are used to enable a computer to execute the above-mentioned water quality detection method based on multimodal data fusion and intelligent optimization.
[1030] An embodiment of the present application also provides a computer program product, including computer instructions, characterized in that when the computer instructions are executed by a processor, the steps of the water quality detection method based on multimodal data fusion and intelligent optimization are implemented.
[1031] Each module in the water quality detection system based on multimodal data fusion and intelligent optimization can be implemented in whole or in part by software, hardware and their combination. Each module can be embedded in or independent of the processor in the computer device in the form of hardware, or can be stored in the memory of the computer device in the form of software, so that the processor can call and execute the operations corresponding to each module above.
[1032] In one embodiment, a computer device is also provided. The computer device is the water quality detection system based on multimodal data fusion and intelligent optimization mentioned in the above method embodiment. Its internal structure diagram can be as follows: Figure 6 As shown. The computer device includes a processor, a memory, an input / output interface (I / O for short) and a communication interface. The processor, the memory and the input / output interface are connected via a system bus, and the communication interface is connected to the system bus via the input / output interface.
[1033] Among them, the processor of the computer device is used to provide computing and control capabilities, and can be a general-purpose processor, a central processing unit, a graphics processor, a digital signal processor, a programmable logic unit, a data processing logic unit based on quantum computing, etc., but is not limited thereto. The processor may include one or more processors, for example, one or more central processing units (CPUs). When the processor is a CPU, the CPU may be a single-core CPU or a multi-core CPU. The processor may also include one or more dedicated processors, and the dedicated processor may include a GPU, an FPGA, etc., for accelerated processing. The processor is used to call the program code and data in the memory and execute the steps in the above method embodiment. For details, please refer to the description in the method embodiment, which will not be repeated here.
[1034] The memory of the computer device includes, but is not limited to, non-volatile storage media and internal memory. Non-volatile memory may include read-only memory (ROM), magnetic tape, floppy disk, flash memory, optical memory, high-density embedded non-volatile memory, resistive random access memory (ReRAM), magnetic random access memory (MRAM), ferroelectric random access memory (FRAM), phase change memory (PCM), graphene memory, etc. Volatile memory may include random access memory (RAM) or external cache memory, etc. As an illustration and not limitation, RAM may be in various forms, such as static random access memory (SRAM) or dynamic random access memory (DRAM). The non-volatile storage medium stores an operating system, a computer program, and a database. The internal memory provides an environment for the operation of the operating system and computer program in the non-volatile storage medium.
[1035] The input / output interface of the computer device is used to exchange information between the processor and external devices.
[1036] The communication interface of the computer device is used to communicate with an external terminal via a network connection.
[1037] When the computer program is executed by a processor, a method for seafloor geological imaging is implemented.
[1038] In the several embodiments provided in the present application, it should be understood that the disclosed devices and methods can be implemented in other ways. For example, the division of each unit / module is only a logical function division, and there may be other division methods in actual implementation, for example, multiple units or components can be combined or integrated into another system, or some features can be ignored or not executed. The mutual coupling, direct coupling, or communication connection shown or discussed can be through some interfaces, indirect coupling or communication connection of systems or units, which can be electrical, mechanical or other forms.
[1039] The units described as separate components may or may not be physically separated, and the components shown as units may or may not be physical units, that is, they may be located in one place or distributed on multiple network units. Some or all of the units may be selected according to actual needs to achieve the purpose of the solution of this embodiment.
[1040] In the above embodiments, it can be implemented in whole or in part by software, hardware, firmware or any combination thereof. When implemented using software, it can be implemented in whole or in part in the form of a computer program product. The computer program product includes one or more computer instructions. When the computer program instructions are loaded and executed on a computer, the process or function according to the embodiment of the present application is generated in whole or in part. The computer can be a general-purpose computer, a special-purpose computer, a computer network, or other programmable system. The computer instructions can be stored in a computer-readable storage medium or transmitted through the computer-readable storage medium. The computer instructions can be transmitted from a website site, computer, server or data center to another website site, computer, server or data center by wired (e.g., coaxial cable, optical fiber, digital subscriber line (DSL)) or wireless (e.g., infrared, wireless, microwave, etc.) mode. The computer-readable storage medium can be any available medium that can be accessed by a computer or a data storage device such as a server or data center that includes one or more available media integrated. The available medium may be a read-only memory (ROM), or a random access memory (RAM), or a magnetic medium, such as a floppy disk, a hard disk, a tape, a disk, or an optical medium, such as a digital versatile disc (DVD), or a semiconductor medium, such as a solid state disk (SSD), etc.
[1041] The system of the embodiments of the present disclosure can execute the method provided by the embodiments of the present disclosure, and the implementation principles are similar. The actions performed by each module in the system of each embodiment of the present disclosure correspond to the steps in the method of each embodiment of the present disclosure. For the detailed functional description of each module of the system, please refer to the description in the corresponding method shown in the previous text, which will not be repeated here.
[1042] The above is only an optional implementation method for some implementation scenarios of the present disclosure. It should be pointed out that for ordinary technicians in this technical field, without departing from the technical concept of the scheme of the present disclosure, other similar implementation methods based on the technical ideas of the present disclosure are also within the protection scope of the embodiments of the present disclosure.
Claims
1. A water quality detection method based on multimodal data fusion and intelligent optimization, It is characterized in that The method comprises the following steps: Collecting and cleaning multimodal data, the multimodal data including flow path parameters, environmental conditions and water quality test results; fusing the cleaned multimodal data; Build and train heterogeneous federated learning models of convolutional neural networks and spiking neural networks; Build a hybrid generative AI model for water quality testing; Inputting the fused multimodal data into the heterogeneous federated learning model to predict changes in water quality parameters under different environmental conditions and different time periods, wherein the water quality parameters include one or more combinations of pH value, dissolved oxygen, conductivity, turbidity, ammonia nitrogen, total phosphorus, and heavy metals; Inputting the fused multimodal data into the hybrid generative artificial intelligence model to perform root cause analysis of abnormal water quality parameters; The step of fusing the cleaned multimodal data includes: Design a multi-level data fusion architecture, wherein the multi-level data fusion architecture includes data-level fusion, feature-level fusion, and decision-level fusion; Uncertainty modeling based on evidence theory DST; Based on the multi-level data fusion architecture and the uncertainty modeling, fusing the cleaned multimodal data; Among them, uncertainty modeling based on evidence theory DST includes: defining an evidence framework, the evidence framework including all sets of hypotheses; Calculate initial probability assignments for multi-sensor data; Construct Dempster combination rules to integrate multi-source evidence; Develop decision rules to make decisions based on fusion results; Define fuzzy sets and membership functions; Design a fuzzy rule base to describe the relationship between sensor data and water quality parameters; Use Mamdani or Sugeno method to implement fuzzy reasoning; Use defuzzification algorithm to convert fuzzy output into precise value; Among them, the heterogeneous federated learning models of convolutional neural networks and spiking neural networks are constructed and trained, including: Construct convolutional neural network (CNN) model and spiking neural network (SNN) model; Developing a heterogeneous federated learning framework to enable the CNN model and the SNN model to be distributedly trained under the heterogeneous federated learning framework; Using an improved federated average FedAvg algorithm to aggregate the CNN model and the SNN model to form the heterogeneous federated learning model; Integrate the differential privacy mechanism into the heterogeneous federated learning framework; Among them, the convolutional neural network CNN model and the pulse neural network SNN model are constructed, including: Designing a CNN model, the CNN model includes multiple convolutional layers, multiple pooling layers and a fully connected layer, the multiple convolutional layers are used to extract local features of short-term changes in water quality parameters, the multiple pooling layers are used to reduce data dimensions; the fully connected layer is used to integrate the local features and output a final prediction result; Designing an SNN model, wherein the SNN model includes an input layer, one or more hidden layers and an output layer, and each layer is composed of LIF neurons, wherein the LIF neurons integrate input signals over time and generate pulse outputs when a threshold is reached; The fused multimodal data is input into the heterogeneous federated learning model to predict the changes of water quality parameters under different environmental conditions and different time periods, including: Inputting the multimodal data into the CNN model to output the variation of water quality parameters with environmental conditions; Inputting the multimodal data into the SNN model to output the change of water quality parameters over time period; Using an improved federated average FedAvg algorithm to fuse the changes of the water quality parameters with environmental conditions and with time, so as to predict the changes of the water quality parameters under different environmental conditions and different time periods; Among them, the construction of a hybrid generative artificial intelligence model in the field of water quality detection includes: Select a pre-trained large language model LLM, and fine-tune the large language model; Performing knowledge distillation on the fine-tuned large language model to form multiple local models; Formulate a dynamic switching strategy to dynamically switch to the large language model or one of the local models according to task complexity; The fine-tuned large language model is subjected to knowledge distillation to form multiple local models, including: The fine-tuned large language model is subjected to knowledge distillation to form a water quality parameter prediction model, anomaly detection model, pollution source identification model and treatment suggestion generation model, wherein: The water quality parameter prediction model is used to predict future water quality parameter values using historical data; The anomaly detection model is used to identify abnormal values or patterns in the water quality parameters; The pollution source identification model is used to infer pollution sources based on water quality data; The treatment suggestion generation model is used to provide treatment suggestions based on current water quality conditions; Wherein, formulating a dynamic switching strategy to dynamically switch to the large language model or one of the local models according to task complexity includes: A dynamic switching strategy is formulated to determine whether the large language model needs to be activated based on the complexity of the task and the depth of the required analysis, including: For a single query or local data analysis task, the local model is used for processing; For multi-source query and analysis tasks of cross-domain knowledge, the large language model is used for processing.
2. A water quality detection system based on multimodal data fusion and intelligent optimization, It is characterized in that For realizing the water quality detection method based on multimodal data fusion and intelligent optimization as described in claim 1, the water quality detection system comprises a flow path editing module, an intelligent module, a control module, a flow path module and a multimodal data fusion module, wherein: The flow path editing module includes a human-computer interaction unit, a parameter data processing unit, a flow path data processing unit, an algorithm data processing unit and a data transmission unit; The intelligent module is used to construct and train a heterogeneous federated learning model of a convolutional neural network and a spiking neural network; construct a hybrid generative artificial intelligence model in the field of water quality detection; input the fused multimodal data into the heterogeneous federated learning model to predict the changes of water quality parameters under different environmental conditions and different time periods; input the fused multimodal data into the hybrid generative artificial intelligence model to perform root cause analysis of abnormal water quality parameters; The multimodal data fusion module is used to collect and clean multimodal data, wherein the multimodal data includes flow path parameters, environmental conditions and water quality test results, and fuse the cleaned multimodal data; The control module includes a human-computer interaction interface, a file manager, and a flow path actuator; The flow path module includes a chemical reaction pool, a photoelectric detection unit, a temperature increasing unit, a temperature decreasing unit, a reagent buffer unit, a quantitative pump, a liquid path selection valve, a bubble leakage detector and a reagent storage unit.
Citation Information
Patent Citations
Mixing system with artificial neural network and impulsive neural network
CN105095961A
Hybrid computing system of artificial neural network and impulsive neural network
CN105095966A
Water quality degradation event detection method based on multi-modal data fusion
CN116166966A
Federal learning-based power data anomaly detection method
CN116451117A
Distributed false news detection system based on federal learning
CN116775865A
Cited By
Deep learning-based water quality anomaly detection method and system
CN121881167A
