A pesticide residue prediction method based on an LSTM variant
The pesticide residue prediction method based on LSTM variants solves the problems of long detection cycle, high cost and poor real-time performance in existing technologies, and realizes efficient and convenient monitoring and prediction of pesticide residues, which is suitable for rapid response agricultural production.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- GUIZHOU UNIV
- Filing Date
- 2024-10-21
- Publication Date
- 2026-04-21
AI Technical Summary
Existing pesticide residue detection methods suffer from problems such as long detection cycles, high costs, insufficient nonlinear modeling capabilities, limited adaptability to multivariate data, and poor real-time performance, making it difficult to achieve real-time monitoring and prediction of pesticide residues.
A pesticide residue prediction method based on LSTM variants is adopted. By removing the output activation function and introducing a direct output channel of cell state, a three-layer stacked LSTM variant model is constructed. Combined with a dynamic threshold adjustment mechanism, it is deployed on edge devices for real-time prediction. Data processing is optimized by normalization and sliding window slicing techniques.
It significantly improves the ability to capture nonlinear changes in pesticide residues, enables personalized adaptability and real-time prediction for a variety of pesticides, reduces computational resource consumption, and is suitable for fast-response agricultural scenarios.
Smart Images

Figure CN119359084B_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of pesticide residue detection and prediction technology, specifically to a pesticide residue prediction method based on LSTM variants. Background Technology
[0002] Pesticides are widely used in modern agriculture to increase crop yields and control pests and diseases, but their residues remain a significant challenge to food safety and environmental pollution. Current pesticide residue detection methods primarily rely on laboratory analytical methods such as gas chromatography, high-performance liquid chromatography, and mass spectrometry. While these methods offer high precision, they suffer from drawbacks such as long detection cycles, high costs, and the need for specialized operation, making it difficult to achieve real-time monitoring and prediction of pesticide residues.
[0003] To overcome the limitations of traditional detection methods, a series of time series forecasting techniques based on machine learning and deep learning have emerged in recent years. These techniques can model historical data and predict future residual trends. However, existing forecasting techniques mainly suffer from the following problems:
[0004] Insufficient nonlinear modeling capability: Traditional time series models (such as ARIMA, SARIMA, etc.) often show limitations when dealing with complex pesticide residue changes, making it difficult to capture the nonlinear changes in residues after application, resulting in low prediction accuracy.
[0005] Limited adaptability to multivariate data: Pesticide residue variations are influenced by a variety of factors, including temperature, humidity, soil conditions, application concentration, and rainfall. Most existing models struggle to effectively model pesticide residues under multivariate conditions, particularly lacking the ability to respond to short-term residue fluctuations after application.
[0006] Poor real-time performance: Traditional forecasting models usually rely on cloud computing for data processing and model inference, which not only increases network transmission latency, but may also affect the timeliness of forecasts due to network instability, failing to meet the needs of rapid response in agricultural production.
[0007] Given the above issues, LSTM (Long Short-Term Memory) networks, as a deep learning model capable of capturing long-term dependencies, have demonstrated good performance in time series prediction. However, standard LSTM still suffers from insufficient nonlinear processing capabilities and limited model generalization ability when dealing with complex time series such as pesticide residues. Furthermore, existing LSTM models generally require high computational resources, making them difficult to deploy in the field. Therefore, this paper proposes a pesticide residue prediction method based on an LSTM variant. Summary of the Invention
[0008] The purpose of this invention is to provide a pesticide residue prediction method based on an LSTM variant. Through structural optimizations such as removing the output activation function and introducing a direct cell state output channel, the method significantly improves the ability to capture nonlinear changes in pesticide residues. Furthermore, the model can achieve real-time prediction on edge devices and adapts to different pesticide residue standards through a dynamic threshold adjustment mechanism, greatly improving the accuracy, real-time performance, and applicability of the prediction. This innovative residue prediction method overcomes the limitations of existing technologies and can provide agricultural producers with an efficient and convenient pesticide residue management solution to address the problems mentioned in the background section.
[0009] To solve the above-mentioned technical problems, the technical solution adopted by the present invention is as follows:
[0010] A pesticide residue prediction method based on LSTM variants.
[0011] Time series data were obtained from the target farmland samples, including application frequency, application concentration, farmland moisture, soil temperature, soil pH, crop growth stage, and climate change factors.
[0012] Normalization and missing value imputation are used to ensure the integrity of time series data;
[0013] Time series data can be transformed into input-output pairs using the sliding window slicing technique;
[0014] Construct and train a deep learning model based on an LSTM variant to output whether the predicted pesticide residue level meets safety standards.
[0015] Preferred: The LSTM variant is further specified to remove the output activation function to adapt to nonlinear changes in pesticide residue concentration, directly pass the cell state to the next time step, thereby more accurately capturing the complex temporal dependencies in the pesticide degradation process.
[0016] Preferred: The preprocessing of time series data is optimized for residual changes in the short term after application, with a focus on processing data within 48 hours after application, and a high-frequency sampling strategy is adopted to capture the rapid degradation characteristics of pesticides.
[0017] Preferably, the LSTM variant employs a three-layer stacked structure, with each layer containing at least 128 hidden units, and introduces a variable-length cell state maintenance mechanism to enhance adaptability to pesticide residue fluctuations.
[0018] Preferred: Normalization uses a specific residue standardization factor to adjust the data to a distribution pattern that matches the specific physical and chemical properties of the target pesticide, so that the model can more accurately understand the residue characteristics of pesticides under different environmental conditions.
[0019] Preferably, the window length of the sliding window slice is dynamically adjusted according to crop type, soil type and specific pesticide physicochemical properties, and a shorter time step is set in the key degradation stage after application to enhance the model's ability to respond to residue dynamics.
[0020] Preferred: The model training process uses the Adam optimizer with an initial learning rate of 0.001, and a regularization term with a time decay factor is introduced to ensure the robustness of the model when dealing with pesticide residue prediction tasks.
[0021] Preferred: The evaluation phase of the model uses a pesticide residue-specific loss function for optimization. The loss function comprehensively considers the deviation between the predicted residue value and the actual detected value, the toxicity threshold of the pesticide, and the toxicological characteristics of different pesticides in crops and the environment.
[0022] Preferred method: The data preprocessing process is optimized for specific pesticide residue standards, and a dynamic threshold adjustment strategy is adopted to meet the legal residue standards of different pesticides.
[0023] Preferably, the sliding window slices adopt an overlapping strategy, and the sliding step size is dynamically adjusted according to the half-life of different pesticides to better adapt to the degradation rate and residue change pattern of pesticides.
[0024] Preferred method: The cross-validation used during model training employs a data segmentation method specific to pesticide residue scenarios to ensure that both the training and test datasets include time points before, after, and during the degradation period.
[0025] Preferred approach: The hidden layer of the model introduces a pesticide degradation-specific attention mechanism to enhance the model's ability to perceive residual changes within a specific time step.
[0026] Preferred method: The model quantization adopts mixed precision training technology, which reduces the consumption of computing resources by converting some calculations to 16-bit floating-point numbers, and ensures the accuracy of pesticide residue prediction results at important thresholds.
[0027] Preferred: When the model is deployed to edge devices, it integrates a real-time data processing module, including continuous monitoring of sensor data, dynamic prediction, and residual exceedance alarm functions.
[0028] Preferred: Edge devices can achieve regular model updates and integration of new pesticide residue data through wireless synchronization with the central database, thereby improving the model's adaptability to new pesticides and its prediction accuracy.
[0029] Due to the adoption of the above technical solution, the technical progress achieved by this invention compared to the prior art is as follows:
[0030] 1. This invention provides a pesticide residue prediction method based on an LSTM variant. By removing the output activation function of the LSTM and directly outputting the data at the cell state, the method enhances the ability to capture nonlinear changes in pesticide residues. Compared to traditional LSTM or other time-series models (such as ARIMA and GRU), this LSTM variant is more suitable for handling rapid changes and long-term dependence of pesticide residue concentrations, especially for dynamic residue conditions within 48 hours after application.
[0031] 2. This invention provides a pesticide residue prediction method based on LSTM variants. By introducing a dynamic threshold adjustment mechanism, it can be personalized according to the physicochemical properties of specific pesticides and legal residue standards (such as EU MRL, EPA Tolerance, etc.). This flexibility not only improves the applicability to multiple pesticides but also accurately detects residue exceedances, significantly enhancing the adaptability to pesticide residue prediction in various scenarios. Traditional models typically use fixed thresholds, making them difficult to apply accurately in multi-pesticide scenarios.
[0032] 3. This invention provides a pesticide residue prediction method based on LSTM variants. By deploying the LSTM variant model on edge devices, real-time data processing and prediction are achieved. Edge devices can not only quickly process newly collected data on-site but also immediately issue alarms when residue exceedances are detected, improving detection and response efficiency. This distributed real-time processing mode reduces network transmission latency, significantly shortening prediction and response times, making it more suitable for agricultural scenarios requiring rapid response.
[0033] 4. This invention provides a pesticide residue prediction method based on LSTM variants. It adopts a sliding window overlap strategy and mixed precision training technology, which improves data utilization and optimizes the consumption of computing resources. The sliding window slicing process can fully cover the details in the time series, while the mixed precision training reduces the memory occupation and computational burden in the model inference process, making this invention more efficient and cost-effective.
[0034] 5. This invention provides a pesticide residue prediction method based on LSTM variants. Traditional time series prediction models usually require high computing resources to process complex long-term series, while this invention can achieve high-precision prediction on relatively low-configuration edge devices.
[0035] 6. This invention provides a pesticide residue prediction method based on LSTM variants. In the data preprocessing and model training stages, it combines the physicochemical properties of specific pesticides (such as imidacloprid) and their residue patterns in specific crops (such as rice). Through specialized residue normalization factors and time-series feature extraction methods, the prediction accuracy of the model in specific pesticide application scenarios is improved. Compared to existing general residue prediction models, this invention provides customized processing for the characteristics of different pesticides, significantly improving applicability and prediction accuracy.
[0036] 7. This invention provides a pesticide residue prediction method based on LSTM variants. Through an online update mechanism of a central server, the LSTM variant model can be dynamically adjusted and optimized as new pesticides are introduced and data accumulates. This adaptive capability ensures the long-term effectiveness of the model and avoids the limitation of frequent manual retraining of the model in existing technologies. Attached Figure Description
[0037] Figure 1 This is a framework diagram of the pesticide residue prediction method based on LSTM variants of the present invention;
[0038] Figure 2 This is a comparison chart of data before and after normalization in this invention;
[0039] Figure 3 This is a diagram illustrating the effect of missing value filling in this invention.
[0040] Figure 4 This is a diagram illustrating the effect of the sliding window slicing of the present invention.
[0041] Figure 5 This is a schematic diagram of the input-output data flow of the LSTM variant of the present invention;
[0042] Figure 6 This is a comparison chart of the predicted value and the dynamic threshold of the present invention;
[0043] Figure 7 This is a visual illustration of the real-time predicted data stream of the present invention. Detailed Implementation
[0044] The present invention will be further described in detail below with reference to embodiments:
[0045] like Figure 1As shown, this invention provides a pesticide residue prediction method based on an LSTM variant. It obtains time-series data from a target farmland sample, including application frequency, application concentration, farmland humidity, soil temperature, soil pH, crop growth stage, and climate change factors. Normalization and missing value imputation are used to ensure the integrity of the time-series data. A sliding window slicing technique is used to transform the time-series data into input-output pairs. A deep learning model based on an LSTM variant is constructed and trained to output whether the predicted pesticide residue level meets safety standards.
[0046] The following description is based on an example:
[0047] Example 1
[0048] like Figure 1-7 As shown, this invention provides a pesticide residue prediction method based on LSTM variants, including: time series data acquisition and preprocessing, model construction and training based on LSTM variants, dynamic threshold adjustment and model optimization, model deployment and real-time prediction on edge devices, and model updating and adaptive optimization. Through a series of optimization measures, the prediction model can more accurately and efficiently adapt to the residue characteristics of specific pesticides under different environmental conditions.
[0049] 1. Time series data acquisition and preprocessing
[0050] Multi-parameter sensor nodes were deployed in the target farmland environment to monitor and collect time-series data related to pesticide application in real time, including temperature, humidity, soil pH, rainfall, wind speed, and historical pesticide residue concentrations. The data collection frequency was set to once every 15 minutes to capture rapid changes in pesticide residues after application.
[0051] The preprocessing steps are as follows:
[0052] Normalization: The collected data is standardized using Z-score to ensure that the mean of the model input is 0 and the standard deviation is 1, which facilitates the model's sensitivity and adaptability to the data.
[0053] Missing value imputation: Missing values are imputed using interpolation, historical averages, or K-nearest neighbors (KNN) to ensure data continuity and integrity. The imputation method should be dynamically adjusted based on the specific data collection conditions.
[0054] Sliding window slicing: Time series data is sliced using a sliding window technique. The window length is set to 5 to 20 time steps based on the physicochemical properties of the target pesticide, with each time step corresponding to a 15-minute time span. An overlapping strategy is used during the sliding process, with a step size of 1 time step, to improve data utilization and model training effectiveness.
[0055] Appendix Figures 2 to 4It demonstrates the effects of processing raw data, from data acquisition to normalization, missing value imputation, and sliding window slicing.
[0056] 2. Model Construction and Training Based on LSTM Variants
[0057] The model employs a variant of the LSTM architecture, specifically an LSTM with the output activation function removed, to better adapt to nonlinear changes in pesticide residue concentration. The model structure is as follows:
[0058] A three-layer stacked LSTM variant structure: each layer contains 128 hidden units and introduces a Dropout mechanism (with a value of 0.2) to prevent overfitting, while passing cell state through the direct output channel to improve the ability to capture long-term dependencies.
[0059] Optimizer selection: The Adam optimizer is used with an initial learning rate of 0.001, and is dynamically adjusted during training using an exponential decay strategy to ensure a balance between convergence speed and stability.
[0060] Specific loss function: Optimization is performed using a loss function specific to pesticide residues. The loss function takes into account the deviation between predicted and actual values and introduces weighted terms of pesticide toxicological properties and degradation rate to improve adaptability to different pesticide residues.
[0061] Cross-validation: The generalization ability of the model is evaluated by five-fold cross-validation. Each fold of validation data includes data before application, after application, and during the degradation period to ensure the prediction accuracy of the model at different degradation stages.
[0062] Appendix Figure 5 The changes in input feature values and output predicted values at hidden units and time steps are displayed in the form of a three-dimensional heatmap.
[0063] 3. Dynamic threshold adjustment and model optimization
[0064] To adapt to different legal residue standards for pesticides, the system introduces a dynamic threshold adjustment mechanism. The specific steps are as follows:
[0065] Based on the physical and chemical properties of the target pesticide, a residue threshold, such as EU MRL or EPATolerance, is set before training and is used as a key focus during model training.
[0066] When the model outputs predicted values, it marks and alarms for cases that exceed the threshold, ensuring that users receive accurate reminders and decision-making basis at the safety threshold.
[0067] Appendix Figure 6 A two-dimensional line graph is used to show the changing trends of model predictions and dynamic thresholds at different time steps.
[0068] 4. Model Deployment and Real-Time Prediction on Edge Devices
[0069] The LSTM variant model is deployed on edge devices to enable real-time prediction of field data. The specific steps are as follows:
[0070] Hardware configuration: Edge devices use multi-core processors and high-performance memory, support mixed-precision computing, and calculate some model parameters using 16-bit floating-point numbers to improve inference speed and reduce resource consumption.
[0071] Data processing module: The device integrates a data processing module responsible for real-time monitoring and analysis of sensor data. The data is normalized and processed using a sliding window slicing method before being input into the LSTM variant model.
[0072] Real-time prediction and alarm: After receiving new input data, the model outputs prediction results in real time and determines whether to trigger the alarm function based on the set residual threshold. If the residual level is detected to be excessive, the device will upload the alarm information to the central monitoring system via wireless network.
[0073] Appendix Figure 7 The dynamic changes of input feature values and model output predictions over time steps are compared using a two-dimensional line graph.
[0074] 5. Model updating and adaptive optimization
[0075] To ensure the adaptability of the LSTM variant model to novel pesticides, the system supports online updates and dynamic optimization of the model. The specific steps are as follows:
[0076] Data synchronization: Edge devices regularly upload data collected on-site to the central database, and at the same time retrieve the latest pesticide residue data from the database.
[0077] Retraining: The LSTM variant model is retrained on a central server, with parameter optimization and architecture adjustments made using new pesticide residue data to ensure the model remains up-to-date.
[0078] Model push: The trained new model is pushed to edge devices via wireless network to enable real-time updates and improvements to on-site predictions.
[0079] Example 2: Imidacloprid residue prediction based on LSTM variants in paddy fields
[0080] This example demonstrates the prediction of imidacloprid residues in a paddy field environment. Imidacloprid is an insecticide widely used in rice cultivation, but its residues in paddy fields have a significant impact on both rice safety and the aquatic environment. Through analysis and modeling of collected data, this example specifically describes how an LSTM variant can predict imidacloprid residues in a paddy field scenario.
[0081] 1. Data Acquisition and Preprocessing
[0082] Sensor nodes were deployed in the rice paddies to collect the following data:
[0083] Temperature (°C): e.g., daily minimum 20°C, maximum 30°C;
[0084] Humidity (%): such as between 70% and 90%;
[0085] Soil pH value: such as between 5.5 and 6.5;
[0086] Rainfall (mm): varies from 0 to 50 mm per day;
[0087] Application concentration (mg / L): e.g., 10 to 30 mg / L;
[0088] Historical imidacloprid residual concentration (mg / L): Initial value was 10 mg / L.
[0089] The specific steps are as follows:
[0090] Normalization: Perform Z-score normalization on all data so that the mean of each feature is 0 and the standard deviation is 1.
[0091] Missing value imputation: Missing values are imputed using linear interpolation. If temperature data for a certain moment is missing, it is imputed by averaging the values of the two preceding and following measurements.
[0092] The corresponding pseudocode is as follows:
[0093] import numpy as np
[0094] from sklearn.preprocessing import StandardScaler
[0095] # Data Collection
[0096] data = {
[0097] "temperature": [25, 26, np.nan, 28, 29],
[0098] "humidity": [80, 82, 83, np.nan, 85],
[0099] "soil_ph": [6.0, 5.9, 6.1, 6.2, 6.1],
[0100] "rainfall": [10, 20, 15, 5, 0],
[0101] "imidacloprid_conc": [15, 18, np.nan, 12, 10]
[0102] }
[0103] # Normalization
[0104] scaler = StandardScaler()
[0105] normalized_data = scaler.fit_transform(np.array(list(data.values())).T)
[0106] # Fill in missing values
[0107] for i, feature in enumerate(normalized_data.T):
[0108] if np.isnan(feature).any():
[0109] # Linear interpolation
[0110] valid_idx = np.where(~np.isnan(feature))[0]
[0111] filled_feature = np.interp(np.arange(len(feature)), valid_idx, feature[valid_idx])
[0112] normalized_data[:, i] = filled_feature
[0113] 2. Sliding window slicing and LSTM variant model training
[0114] The sliding window is set to 48 hours (192 time steps), with each time step being 15 minutes.
[0115] A variant of LSTM with three stacked layers, each containing 128 hidden units, was used, with the Dropout value set to 0.2.
[0116] The optimizer used is Adam, with an initial learning rate of 0.001;
[0117] The generalization performance of the model was evaluated using 5-fold cross-validation.
[0118] The corresponding pseudocode is as follows:
[0119] import tensorflow as tf
[0120] # Sliding window slice
[0121] window_size = 192
[0122] stride = 1
[0123] def create_windows(data, window_size, stride):
[0124] windows = []
[0125] for i in range(0, len(data) - window_size, stride):
[0126] windows.append(data[i:i + window_size])
[0127] return np.array(windows)
[0128] windowed_data = create_windows(normalized_data, window_size, stride)
[0129] # LSTM variant model construction
[0130] model = tf.keras.Sequential([
[0131] tf.keras.layers.LSTM(128, return_sequences=True, dropout=0.2,input_shape=(window_size, windowed_data.shape[2])),
[0132] tf.keras.layers.LSTM(128, return_sequences=True, dropout=0.2),
[0133] tf.keras.layers.LSTM(128, dropout=0.2),
[0134] tf.keras.layers.Dense(1, activation=None) # No output activation function )
[0136] # Model training
[0137] model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001), loss='mean_squared_error')
[0138] history = model.fit(windowed_data, epochs=20, validation_split=0.2)
[0139] import tensorflow as tf
[0140] # Sliding window slicing
[0141] window_size = 192
[0142] stride = 1
[0143] def create_windows(data, window_size, stride):
[0144] windows = []
[0145] for i in range(0, len(data) - window_size, stride):
[0146] windows.append(data[i:i + window_size])
[0147] return np.array(windows)
[0148] windowed_data = create_windows(normalized_data, window_size, stride)
[0149] # Construction of LSTM variant model
[0150] model = tf.keras.Sequential(
[0151] tf.keras.layers.LSTM(128, return_sequences=True, dropout=0.2,input_shape=(window_size, windowed_data.shape[2])),
[0152] tf.keras.layers.LSTM(128, return_sequences=True, dropout=0.2),
[0153] tf.keras.layers.LSTM(128, dropout=0.2),
[0154] tf.keras.layers.Dense(1, activation=None) # No output activation function )
[0156] # Model training
[0157] model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001), loss='mean_squared_error')
[0158] history = model.fit(windowed_data, epochs=20, validation_split=0.2)
[0159] import tensorflow as tf
[0160] # Sliding window slicing
[0161] window_size = 192
[0162] stride = 1
[0163] def create_windows(data, window_size, stride):
[0164] windows = []
[0165] for i in range(0, len(data) - window_size, stride):
[0166] windows.append(data[i:i + window_size])
[0167] return np.array(windows)
[0168] windowed_data = create_windows(normalized_data, window_size, stride)
[0169] # Build the LSTM variant model
[0170] model = tf.keras.Sequential(
[0171] tf.keras.layers.LSTM(128, return_sequences=True, dropout=0.2,input_shape=(window_size, windowed_data.shape[2])),
[0172] tf.keras.layers.LSTM(128, return_sequences=True, dropout=0.2),
[0173] tf.keras.layers.LSTM(128, dropout=0.2),
[0174] tf.keras.layers.Dense(1, activation=None) # No output activation function
[0176] # Model training
[0177] model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001), loss='mean_squared_error')
[0178] history = model.fit(windowed_data, epochs=20, validation_split=0.2)
[0179] 3. Dynamic threshold adjustment and real-time prediction
[0180] The safety threshold for imidacloprid is set at 5 mg / L. If the predicted value exceeds the threshold when the model makes its predictions, an alarm mechanism will be triggered to remind the user to take preventive measures.
[0181] # Dynamic threshold setting
[0182] threshold = 5.0 mg / L
[0183] # Real-time prediction and alarm mechanism
[0184] predictions = model.predict(windowed_data)
[0185] for i, pred in enumerate(predictions):
[0186] if pred > threshold:
[0187] print(f"Alert: High imidacloprid residue detected at step{i}, value: {pred} mg / L")
[0188] 4. Model Deployment on Edge Devices
[0189] Edge devices are installed in rice paddies, integrating real-time monitoring and processing modules for sensor data, and LSTM variant models are deployed to achieve real-time prediction and alarm functions on-site.
[0190] Hardware configuration: Edge devices are equipped with multi-core processors and 2GB of memory, supporting 16-bit mixed-precision computing to improve inference speed and resource efficiency;
[0191] Data processing: The device collects and preprocesses data every 15 minutes, using the aforementioned normalization and sliding window slicing methods;
[0192] Real-time prediction: After receiving new input data, the model outputs prediction results in real time. If residual levels are detected to be excessive, the device will upload alarm information to the central monitoring system via wireless network.
[0193] import time
[0194] # Edge device data processing and real-time prediction
[0195] def edge_device_prediction(new_data):
[0196] new_data = scaler.transform(new_data) # Data normalization
[0197] window = create_windows(new_data, window_size, stride)
[0198] pred = model.predict(window)
[0199] if pred[-1] > threshold:
[0200] print(f"Alert: Imidacloprid residue exceeded threshold: {pred[-1]} mg / L")
[0201] # Upload alarm information to the central monitoring system
[0202] upload_to_server(pred[-1])
[0203] # Simulated Real-Time Data Acquisition and Processing
[0204] while True:
[0205] new_data = np.random.rand(1, 5) # Simulate newly collected data
[0206] edge_device_prediction(new_data)
[0207] time.sleep(900) # Collect data every 15 minutes
[0208] The above embodiments describe in detail the whole process of predicting and applying imidacloprid residues in paddy field environments, covering the implementation of data acquisition, preprocessing, model training, real-time prediction and alarm functions.
[0209] In summary, the advantages of this invention are:
[0210] 1. Specifically adapted to the time-series characteristics of pesticide residues
[0211] This invention enhances the ability to capture nonlinear changes in pesticide residues by removing the output activation function of the LSTM and directly outputting the data at the cellular level. Compared to traditional LSTM or other time-series models (such as ARIMA and GRU), this LSTM variant is more suitable for handling rapid changes and long-term dependence of pesticide residue concentrations, especially for dynamic residue conditions within 48 hours after application.
[0212] 2. Dynamic threshold adjustment for flexibility in handling different pesticides.
[0213] This invention introduces a dynamic threshold adjustment mechanism, enabling personalized settings based on the physicochemical properties of specific pesticides and legal residue standards (such as EU MRL, EPA Tolerance, etc.). This flexibility not only improves applicability to a variety of pesticides but also allows for accurate detection of residue exceedances, significantly enhancing the adaptability to pesticide residue prediction in various scenarios. In contrast, traditional models typically use fixed thresholds, making them difficult to apply accurately in multi-pesticide scenarios.
[0214] 3. Real-time prediction and alarm functions on edge devices
[0215] Unlike existing models that rely on cloud computing, this invention achieves real-time data processing and prediction by deploying a variant LSTM model on edge devices. These edge devices can not only rapidly process newly acquired data on-site but also immediately issue alerts when residual levels exceed limits, improving detection and response efficiency. This distributed real-time processing mode reduces network transmission latency, significantly shortening prediction and response times, making it more suitable for agricultural scenarios requiring rapid response.
[0216] 4. Efficient use of data and optimization of computing resources
[0217] This invention employs a sliding window overlap strategy and mixed-precision training technology, which improves data utilization while optimizing computational resource consumption. The sliding window slicing process can comprehensively cover the details in the time series, while mixed-precision training reduces memory usage and computational burden during model inference, making this invention more efficient and cost-effective.
[0218] 5. Traditional time series forecasting models typically require high computing resources to process complex long-term series, while this invention can achieve high-precision forecasting on relatively low-configuration edge devices.
[0219] 6. Optimization modeling for specific pesticides
[0220] This invention combines the physicochemical properties of specific pesticides (such as imidacloprid) and their residue patterns in specific crops (such as rice) during the data preprocessing and model training stages. Through specialized residue standardization factors and time-series feature extraction methods, the prediction accuracy of the model in specific pesticide application scenarios is improved. Compared to existing general residue prediction models, this invention provides customized processing for the characteristics of different pesticides, significantly improving applicability and prediction accuracy.
[0221] 7. Online model updates and adaptive capabilities
[0222] Through an online update mechanism on a central server, the LSTM variant model can be dynamically adjusted and optimized as new pesticides are introduced and data accumulates. This adaptive capability ensures the long-term effectiveness of the model and avoids the limitation of requiring frequent manual retraining in existing technologies.
[0223] The present invention has been described in detail above. However, modifications or improvements can be made to it, which will be obvious to those skilled in the art. Therefore, any modifications or improvements that do not depart from the spirit of the present invention are within the scope of protection of the present invention.
Claims
1. A pesticide residue prediction method based on LSTM variants, characterized in that: Time series data were obtained from the target farmland samples, including application frequency, application concentration, farmland moisture, soil temperature, soil pH, crop growth stage, and climate change factors. Normalization and missing value imputation are used to ensure the integrity of time series data; Time series data can be transformed into input-output pairs using the sliding window slicing technique; Construct and train a deep learning model based on an LSTM variant to output whether the predicted pesticide residue level meets safety standards; The LSTM variant is further specified to remove the output activation function to adapt to nonlinear changes in pesticide residue concentration, directly pass the cell state to the next time step, thereby more accurately capturing the complex temporal dependencies in the pesticide degradation process; The LSTM variant employs a three-layer stacked structure, with each layer containing at least 128 hidden units, and introduces a variable-length cell state maintenance mechanism to enhance adaptability to pesticide residue fluctuations. The normalization process uses a specific residue normalization factor to adjust the data to a distribution pattern that matches the specific physical and chemical properties of the target pesticide, so that the model can more accurately understand the residue characteristics of pesticides under different environmental conditions. The data preprocessing process is optimized for specific pesticide residue standards and adopts a dynamic threshold adjustment strategy to meet the legal residue standards of different pesticides. The window length of the sliding window slice is dynamically adjusted according to crop type, soil type and specific pesticide physicochemical properties, and a shorter time step is set in the key degradation stage after application to enhance the model’s response to residue dynamics. The sliding window slice adopts an overlapping strategy, and the sliding step length is dynamically adjusted according to the half-life of different pesticides to better adapt to the degradation rate and residue change pattern of pesticides. The model is trained using the Adam optimizer with an initial learning rate of 0.
001. A regularization term with a time decay factor is introduced to ensure the model's robustness in pesticide residue prediction tasks. The cross-validation used during model training employs a pesticide residue scenario-specific data segmentation method to ensure that both the training and test datasets contain time points before, after, and during the degradation period. The model's hidden layers incorporate a pesticide degradation-specific attention mechanism to enhance the model's ability to perceive residue changes within a specific time step.
2. The pesticide residue prediction method based on LSTM variants according to claim 1, characterized in that: The preprocessing of the time series data is optimized for residual changes in the short term after pesticide application, with a focus on processing data within 48 hours after application. A high-frequency sampling strategy is used to capture the rapid degradation characteristics of pesticides.
3. The pesticide residue prediction method based on LSTM variants according to claim 1, characterized in that: The evaluation phase of the model uses a pesticide residue-specific loss function for optimization. The loss function comprehensively considers the deviation between the predicted residue value and the actual detected value, the toxicity threshold of the pesticide, and the toxicological characteristics of different pesticides in crops and the environment.
4. The pesticide residue prediction method based on LSTM variants according to claim 1, characterized in that: The model employs mixed-precision training technology for quantization, which reduces computational resource consumption by converting some calculations to 16-bit floating-point numbers and ensures the accuracy of pesticide residue prediction results at key thresholds. When the model is deployed to edge devices, it integrates a real-time data processing module, including continuous monitoring of sensor data, dynamic prediction, and residue exceedance alarm functions.
5. The pesticide residue prediction method based on LSTM variants according to claim 4, characterized in that: The edge device enables regular model updates and integration of new pesticide residue data through wireless synchronization with the central database, thereby improving the model's adaptability to new pesticides and its prediction accuracy.
Citation Information
Patent Citations
Pesticide residue measurement method based on LightGBM-XGBoost integrated learning
CN116957164A
Multi-sample detection system applied to food pesticide residue detection
CN117390499A