Method for predicting and judging diarrhea risk grade of suckling piglet

Through multi-parameter monitoring and dynamic prediction of random forest models, combined with image acquisition calibration and color temperature compensation algorithm, the problem of lagging prediction of diarrhea risk in piglets in the existing technology is solved, and accurate warning and early prevention and control of diarrhea risk of piglets is achieved, and prediction accuracy and management efficiency are improved.

CN120544893APending Publication Date: 2025-08-26GUANGXI NONGKEN YONGXIN ANIMAL HUSBANDRY GRP XINXING CO LTD
View PDF 0 Cites 2 Cited by

Patent Information

Application Number
CN202510653294.6
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2025-05-21
Publication Date
2025-08-26

AI Technical Summary

Technical Problem

In the prior art, the risk prediction of diarrhea in lactation piglets relies on single environmental indicator monitoring or empirical observation, and lacks multi-dimensional data correlation, resulting in lag in early warning, making it difficult to achieve accurate grading and active prevention and control of risk levels.

Method used

Through multi-parameter monitoring equipment, environmental parameters and physiological indicators are collected in real time, combined with the random forest model, environmental control strategies are dynamically adjusted, excretion behavior trigger image acquisition, standard color card calibration and color temperature compensation algorithm are used to eliminate ambient light and image deformation interference, and the model generalization ability is improved by using pre-pruning strategies and dynamic Gini threshold adjustment. Abnormal data are identified by using Hampel filters to ensure the reliability of model input.

Benefits of technology

Accurate early warning of the risk of diarrhea in piglets has been achieved, the cost of manual intervention is reduced, the efficiency of breeding management is improved, the accuracy of image analysis and model prediction stability is significantly improved, the warning time is advanced to 72 hours before the onset of symptoms, and the incidence of diarrhea is reduced by 28%.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure SMS_1
    Figure SMS_1
Patent Text Reader

Abstract

The invention discloses a method for predicting and judging the diarrhea risk grade of suckling piglets, and belongs to the technical field of piglet epidemic disease prevention and control. Aiming at the problems that traditional piglet diarrhea prediction depends on manual observation, multi-dimensional data relevance is insufficient, early warning lags and the like, a multi-parameter monitoring device is arranged in a piglet breeding environment to collect environment data in real time, and an excretion behavior detection module is used for triggering an excrement image collection device to obtain a high-quality image; and inputting multi-source data into a random forest model for risk level prediction by combining regular weight measurement and blood detection in a specific time period after environment adjustment. The system dynamically adjusts pig environment parameters according to a prediction result, after spraying, heating compensation is started to maintain humidity and control ammonia concentration, and closed-loop feedback regulation is formed. According to the method, through multi-modal data fusion and model iterative optimization, early-stage accurate early warning of diarrhea risks is realized, the method is suitable for intelligent management of a large-scale pig farm, the diarrhea occurrence rate can be effectively reduced, and the breeding benefits are improved.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] The present invention relates to the technical field of piglet disease prevention and control, and more specifically, to a method for predicting and judging the risk level of diarrhea in suckling piglets. Background Art

[0002] In large-scale pig farming, diarrhea in suckling piglets has long plagued the industry, with its morbidity and mortality rates directly impacting farming profitability. Existing technologies for predicting piglet diarrhea risk primarily rely on single environmental indicator monitoring or empirical observation. These technologies suffer from deficiencies such as insufficient correlation between multi-dimensional data and delayed early warnings, making it difficult to accurately stratify risk levels and proactively prevent and control them.

[0003] First, traditional environmental monitoring methods typically use independent threshold controls for basic parameters like temperature and humidity, but lack a systematic analysis of the dynamic changes in ammonia concentration and the synergistic effects of temperature and humidity. Studies have shown that when environmental parameters are on the verge of critical thresholds, small fluctuations in a single indicator, while within conventional control ranges, can compound with other factors (such as ammonia accumulation from retained feces), leading to intestinal stress reactions. However, existing equipment often uses fixed threshold alarm mechanisms that fail to identify these complex environmental risks, resulting in the failure to provide timely warnings for approximately 23% of subclinical cases.

[0004] Secondly, existing fecal matter detection methods often rely on manual, scheduled inspections, which suffer from low observation frequency and poor sample representativeness. Piglet defecation is intermittent and random, and manual collection can easily miss critical time windows. More significantly, visual assessment of fecal morphology is significantly affected by ambient lighting and fecal distribution. Approximately 35% of blurred or occluded images are misidentified as normal, resulting in an accuracy rate of less than 62% for identifying early features of diarrhea (such as changes in fecal viscosity). Furthermore, weight monitoring often involves weekly weighing, which makes it difficult to capture subtle weight fluctuations caused by short-term digestive dysfunction.

[0005] Conventional blood tests often use fixed sampling cycles (e.g., weekly), overlooking the timeliness of physiological responses after environmental interventions. Experimental data show that 48-72 hours after environmental parameter adjustments is a critical window for changes in blood cortisol levels. However, existing technologies fail to capture approximately 40% of stress response data due to inappropriate sampling time points. Furthermore, a standardized model for the combined analysis of white blood cell counts and cortisol levels has yet to be established, making it difficult to accurately quantify the strength of the association between environmental stress and immunosuppression.

[0006] Existing early warning models often use linear regression or single decision tree algorithms, which have limited capabilities for integrating and processing heterogeneous data from multiple sources. For example, the high-frequency sampling data from temperature sensors (once per minute) and the low-frequency data from blood tests (once per week) have significant time scale differences, making it difficult for traditional models to effectively extract feature correlations across time dimensions. Studies have shown that such models have an error rate of up to 28% for moderate diarrhea risk and are unable to distinguish between temporary diarrhea caused by environmental factors and pathogenic diarrhea.

[0007] The fundamental reasons for the above problems are that the nonlinear relationship between environmental parameters, physiological indicators and behavioral characteristics has not been fully analyzed, the time synchronization and quality controllability of multimodal data are difficult to guarantee, and the feedback mechanism between dynamic environmental regulation and biological response lacks a quantitative basis. Especially in terms of ammonia concentration control, traditional ventilation strategies often ignore the humidity compensation mechanism, resulting in a sharp increase in humidity (over 70%) during the spray cooling process, which aggravates ammonia volatilization and forms a vicious cycle. How to establish an effective correlation model for cross-scale data and formulate a dynamic control strategy based on it has become a technical bottleneck that has not been broken through in this field for a long time. Background technology: In large-scale pig farming, diarrhea in suckling piglets has long plagued the industry, with its morbidity and mortality rates directly impacting farming profitability. Existing technologies for predicting piglet diarrhea risk primarily rely on single environmental indicator monitoring or empirical observation. These technologies suffer from deficiencies such as insufficient correlation between multi-dimensional data and delayed early warnings, making it difficult to accurately stratify risk levels and proactively prevent and control them.

[0008] First, traditional environmental monitoring methods typically use independent threshold controls for basic parameters like temperature and humidity, but lack a systematic analysis of the dynamic changes in ammonia concentration and the synergistic effects of temperature and humidity. Studies have shown that when environmental parameters are on the verge of critical thresholds, small fluctuations in a single indicator, while within conventional control ranges, can compound with other factors (such as ammonia accumulation from retained feces), leading to intestinal stress reactions. However, existing equipment often uses fixed threshold alarm mechanisms that fail to identify these complex environmental risks, resulting in the failure to provide timely warnings for approximately 23% of subclinical cases.

[0009] Secondly, existing fecal matter detection methods often rely on manual, scheduled inspections, which suffer from low observation frequency and poor sample representativeness. Piglet defecation is intermittent and random, and manual collection can easily miss critical time windows. More significantly, visual assessment of fecal morphology is significantly affected by ambient lighting and fecal distribution. Approximately 35% of blurred or occluded images are misidentified as normal, resulting in an accuracy rate of less than 62% for identifying early features of diarrhea (such as changes in fecal viscosity). Furthermore, weight monitoring often involves weekly weighing, which makes it difficult to capture subtle weight fluctuations caused by short-term digestive dysfunction.

[0010] Conventional blood tests often use fixed sampling cycles (e.g., weekly), overlooking the timeliness of physiological responses after environmental interventions. Experimental data show that 48-72 hours after environmental parameter adjustments is a critical window for changes in blood cortisol levels. However, existing technologies fail to capture approximately 40% of stress response data due to inappropriate sampling time points. Furthermore, a standardized model for the combined analysis of white blood cell counts and cortisol levels has yet to be established, making it difficult to accurately quantify the strength of the association between environmental stress and immunosuppression.

[0011] Existing early warning models often use linear regression or single decision tree algorithms, which have limited capabilities for integrating and processing heterogeneous data from multiple sources. For example, the high-frequency sampling data from temperature sensors (once per minute) and the low-frequency data from blood tests (once per week) have significant time scale differences, making it difficult for traditional models to effectively extract feature correlations across time dimensions. Studies have shown that such models have an error rate of up to 28% for moderate diarrhea risk and are unable to distinguish between temporary diarrhea caused by environmental factors and pathogenic diarrhea.

[0012] The root cause of these problems lies in the lack of fully understood nonlinear relationships between environmental parameters, physiological indicators, and behavioral traits. Temporal synchronization and quality controllability of multimodal data are difficult to ensure, and there is a lack of quantitative evidence for the feedback mechanism between dynamic environmental control and biological responses. In particular, regarding ammonia concentration control, traditional ventilation strategies often overlook humidity compensation mechanisms. This leads to a rapid increase in humidity (over 70%) during spray cooling, exacerbating ammonia volatilization and creating a vicious cycle. Establishing an effective correlation model for cross-scale data and formulating dynamic control strategies based on this model has long been a technical bottleneck in this field. Summary of the Invention

[0013] An object of the present invention is to solve at least the above problems and to provide at least the advantages which will be described hereinafter.

[0014] One objective of this invention is to address the problem that traditional piglet diarrhea prediction relies on manual observation, making it difficult to accurately obtain environmental parameters and physiological indicators in real time, leading to delayed intervention. By leveraging multi-parameter monitoring equipment and a random forest model, this invention dynamically optimizes environmental conditions, improving the timeliness and accuracy of diarrhea risk prediction.

[0015] One objective of this invention is to address the issues with existing image acquisition being susceptible to interference from ambient light and deformation of liquid areas, which can affect detection results. This invention uses defecation-triggered image acquisition, standard color card calibration, and a color temperature compensation algorithm to eliminate interference from ambient light and image deformation, thereby improving the accuracy of stool morphology classification.

[0016] One objective of this invention is to address the issues with standard color charts being susceptible to the corrosive environment of piggeries and the inability of fixed thresholds to adapt to changes in lighting. This invention utilizes a polyvinyl chloride-coated color chart, combined with dynamic HSV threshold adjustment, to ensure long-term, stable color calibration.

[0017] One purpose of this invention is to address the issues of traditional cameras being easily damaged in humid environments and unstable fill light intensity that affects image analysis. This invention utilizes a waterproof bracket, a stainless steel motor, and precise fill light control to ensure device reliability and image acquisition quality.

[0018] One purpose of this invention is to address the prediction bias caused by insufficient depth or overfitting of traditional models. This invention improves the model's generalization ability and prediction accuracy through a pre-pruning strategy, dynamic Gini threshold adjustment, and a combination of multiple decision trees.

[0019] One purpose of the present invention is to solve the problem of decision tree aging and high memory usage after long-term use of the model. The present invention ensures the real-time performance of the model and optimizes memory usage efficiency by activating tree group screening and LRU caching mechanism.

[0020] One purpose of this invention is to address the problem of large scale differences in multi-source data and the impact of redundant features on model efficiency. This invention improves feature quality and model training speed through standardization, PCA dimensionality reduction, and time decay factor optimization.

[0021] One purpose of this invention is to address the problem of traditional outlier detection being prone to misjudgment, which affects data accuracy. This invention uses a Hampel filter combined with a confidence threshold to accurately identify and correct outlier data, ensuring the reliability of model input.

[0022] One purpose of the present invention is to address the lack of model adaptability when the weights of environmental and physiological parameters on diarrhea change. The present invention uses layered attenuation and real-time correlation monitoring to dynamically adjust feature weights and improve model prediction stability.

[0023] One purpose of this invention is to address the difficulty in detecting performance degradation after long-term model operation. By updating the validation set and controlling the AUC-ROC threshold, this invention promptly detects model drift and triggers optimization, ensuring sustained and stable prediction results.

[0024] The present invention provides a method for predicting and judging the risk level of diarrhea in suckling piglets, comprising the following steps: setting a multi-parameter monitoring device in a piglet breeding environment to collect environmental parameters in real time, wherein the environmental parameters include the temperature, humidity and ammonia concentration in the pig house; using an excretion behavior detection module to monitor the excretion behavior of the piglets, and when an excretion event is detected, triggering a feces image acquisition device to collect piglet feces images, and performing a quality assessment on the collected feces images to exclude blurred or blocked images; regularly measuring the weight of the piglets to obtain weight fluctuation data; collecting blood samples from the piglet's ear vein 48-72 hours after the environment is adjusted, detecting the number of white blood cells and cortisol content in the blood, and obtaining to blood test data; the collected environmental parameters, fecal images, weight fluctuation data and blood test data are used as input features and input into the trained random forest model to predict the diarrhea risk level; according to the predicted diarrhea risk level, the corresponding environmental control instructions are generated to adjust the temperature, humidity and ventilation environmental conditions of the pig house. After the adjustment, if the spraying operation is performed, the heating compensation needs to be started to maintain the humidity ≤ 65%, and the ammonia concentration control threshold is adjusted to 10-15ppm; 48-72 hours after the environment adjustment, the above-mentioned data are collected again and input into the random forest model again for risk level assessment to dynamically adjust the environmental control strategy.

[0025] Preferably, the collected stool image is preprocessed, and the defecation behavior detection signal is used to trigger image acquisition to ensure that the liquid area is not deformed. Then, the image is color calibrated using a standard color card, and a color temperature compensation algorithm is added to the color calibration. The HSV threshold is dynamically adjusted according to the ambient light sensor data; the calibrated image is converted to the HSV color space, and the proportion of the liquid area in the stool image is calculated; according to the proportion of the liquid area, combined with the preset threshold range, the morphology of the stool is classified as a feature of diarrhea risk assessment.

[0026] Preferably, in the step of color calibrating the image using a standard color card, the standard color card is coated with polyvinyl chloride to prevent corrosion, and the calibration frequency is once every 4 hours. At the same time, a color temperature compensation algorithm is added to dynamically adjust the threshold range of the HSV color space based on the ambient light color temperature data monitored in real time by the ambient light sensor to eliminate the influence of ambient light of different color temperatures on image color recognition.

[0027] Preferably, the feces image acquisition device includes a liftable bracket and an image acquisition camera, the liftable bracket has an IP65 waterproof rating, its motor is made of stainless steel and is rust-proofed, and the fill light intensity during image acquisition is 200±50Lux.

[0028] Preferably, the construction process of the random forest model includes: collecting historical piglet breeding data, including environmental parameters, fecal image features, weight fluctuation data and blood test data, and corresponding diarrhea incidence as training samples; using a random sampling method to select some samples from the training samples, and randomly selecting some features to construct multiple decision trees, the maximum depth of the decision tree is set to 9 layers, but a pre-pruning strategy is adopted, and the split is terminated when the number of node samples is <10; the dynamic Gini threshold formula is modified to 0.2+0.02×depth; multiple decision trees are combined into a random forest model, and the prediction results of multiple decision trees are comprehensively analyzed to obtain the final diarrhea risk level prediction result.

[0029] Preferably, the prediction process of the random forest model also includes: adopting an activated tree group screening mechanism, increasing the time decay factor, and selecting decision trees trained within 72 hours to participate in the prediction; adopting LRU cache to eliminate the derivative features that have not been used for the longest time to manage the memory usage of the model.

[0030] Preferably, the method further includes the steps of processing and screening the input features: standardizing the various types of collected data so that data with different features have the same scale; introducing a feature screening mechanism to retain features with a cumulative variance contribution rate ≥ 95% through PCA dimensionality reduction; adjusting the cortisol-derived feature time decay factor α = 0.85, and verifying its lagged correlation with diarrhea risk through clinical data.

[0031] Preferably, the collected data is processed for outliers, and a Hampel filter is used for outlier detection. The filter window is adjusted to 4 hours to match the piglet excretion interval, and the outlier marker increases the confidence threshold, and the replacement operation is triggered only when there are three consecutive outlier points.

[0032] Preferably, during the training and prediction process of the random forest model, the importance of features is dynamically updated: the dynamic feature importance update adds hierarchical attenuation, the environmental parameter attenuation coefficient β=0.8^(current tree depth-1), and the physiological parameter attenuation coefficient β=0.9^(current tree depth-1); a real-time correlation threshold is introduced, and the feature importance update is triggered when the absolute value of the Spearman coefficient changes by >0.2 compared with the mean.

[0033] Preferably, the method further includes the steps of monitoring and controlling the stability of the random forest model: adjusting the validation set update frequency to once every 12 hours; setting the AUC-ROC change rate threshold to 3%, and retraining or adjusting the model when the AUC-ROC change rate of the model exceeds the threshold.

[0034] The present invention has at least the following beneficial effects: through the multi-dimensional data fusion of environmental parameters, physiological indicators and image analysis, combined with the dynamic prediction of the random forest model, accurate early warning of piglet diarrhea risk is achieved, reducing the cost of manual intervention and improving breeding management efficiency. Excretion behavior triggers image acquisition combined with color card calibration and color temperature compensation to effectively eliminate ambient light interference and liquid area deformation, ensure the accuracy of fecal morphology classification, and provide a reliable basis for diarrhea risk assessment. The polyvinyl chloride coated color card is corrosion-resistant and, combined with dynamic HSV threshold adjustment, adapts to the complex lighting conditions of the pig house, ensures long-term stable color recognition effect, and improves the consistency of image analysis. The waterproof bracket, stainless steel motor and precise fill light design ensure long-term stable operation of the equipment in humid and corrosive environments, while optimizing image acquisition quality and reducing data errors caused by hardware failures. The pre-pruning strategy and dynamic Gini threshold adjustment avoid overfitting of the decision tree, and the combination of multiple decision trees enhances the robustness of the model, significantly improving the accuracy and stability of diarrhea risk prediction. The activation of tree group screening and LRU cache mechanism ensures that the model uses the latest training data, while reducing the memory occupied by redundant features, improving prediction speed and system resource utilization. Standardization, PCA dimensionality reduction, and time decay factor optimization effectively reduce data dimensions while retaining key information, shortening model training time and enhancing the correlation between features and diarrhea risk. The Hampel filter, combined with the confidence threshold, accurately identifies and corrects abnormal data, avoids prediction bias due to accidental errors, and improves data quality and model input reliability. The layered decay and real-time correlation monitoring mechanism enable the model to automatically adapt to the dynamic changes in the impact of environmental and physiological parameters on diarrhea, maintaining the timeliness and accuracy of the prediction results. High-frequency validation set updates and AUC-ROC threshold control promptly detect model performance drift and trigger optimization, ensuring the stability and reliability of the prediction effect in long-term operation.

[0035] Other advantages, objectives and features of the present invention will be reflected in part from the following description and will be understood by those skilled in the art through study and practice of the present invention. DETAILED DESCRIPTION

[0036] The present invention is described in further detail below so that those skilled in the art can implement the invention with reference to the description.

[0037] It should be understood that terms such as “having”, “including” and “comprising” used herein do not preclude the existence or addition of one or more other elements or combinations thereof.

[0038] It should be noted that the experimental methods described in the following embodiments are conventional methods unless otherwise specified, and the reagents and materials can be obtained from commercial channels unless otherwise specified.

[0039] A method for predicting and judging the risk level of diarrhea in suckling piglets comprises the following steps: Multi-parameter monitoring equipment is installed in the piglet breeding environment to collect environmental parameters in real time, including temperature, humidity, and ammonia concentration in the pig house. The excretion behavior detection module monitors the piglets' excretion behavior. When an excretion event is detected, the feces image acquisition device is triggered to collect piglet feces images. The collected feces images are then quality-assessed to exclude blurred or obscured images. The piglets' weight is regularly measured to obtain weight fluctuation data. Between 48 and 72 hours after environmental adjustment, blood samples were collected from the piglets' ear veins to test the number of white blood cells and cortisol levels in the blood to obtain blood test data; The collected environmental parameters, stool images, weight fluctuation data, and blood test data were used as input features and fed into the trained random forest model to predict the diarrhea risk level; Based on the predicted diarrhea risk level, corresponding environmental control instructions are generated to adjust the temperature, humidity, and ventilation environmental conditions of the pig house. If spraying operations are performed after the adjustment, heating compensation must be activated to maintain humidity ≤ 65%, and the ammonia concentration control threshold is adjusted to 10-15ppm; within 48-72 hours after the environmental adjustment, the above-mentioned data are re-collected and re-entered into the random forest model for risk level assessment to dynamically adjust the environmental control strategy.

[0040] The multi-parameter monitoring system can be configured with a DS18B20 temperature sensor, an SHT31 humidity sensor, and an MQ-135 ammonia sensor. These sensors can be installed at the center of the pig house, on the wall 1.2 meters above the floor, and 0.8 meters above the piglet activity area. Alternatively, the ammonia sensor can be moved below the farrowing crib or at the edge of the defecation area to improve detection accuracy. The defecation behavior detection module can utilize an OPB742 infrared sensor, combined with a pressure sensor matrix to enhance defecation behavior recognition accuracy. The feces image capture device can utilize an IP65 waterproof Basler acA2000-50gm industrial camera, adjustable from 0.5 to 1.5 meters via a PBC Linear ZL-16 electric actuator. The fill light uses a LitraTorchPro LED ring light with an intensity setting of 200 ± 50 Lux. Piglet weight can be measured using a DIGI 1500 series electronic weighing platform, installed in a fixed location in the nursing area, daily in the morning on an empty stomach. Blood samples are collected using a 23G sterile BD Micro-Fine needle from the ear vein, with 2 ml of whole blood drawn and stored in EDTA-anticoagulant tubes. White blood cell counts can be performed using the Mindray BC-2800 automated hematology analyzer. Cortisol is measured using an ELISA kit (ZIKER Biotech) at a detection wavelength of 450 nm, with an intra-assay CV of ≤5%. Model input features include: temperature (°C), humidity (%), ammonia concentration (ppm), proportion of liquid feces (%), weight change rate (% / day), white blood cell count (×10^9 / L), and cortisol concentration (ng / mL). Model parameters were set as follows: 100 decision trees, a maximum depth of 9 layers, a minimum number of samples per node split of 10, and a Gini threshold formula of 0.2 + 0.02 × depth.

[0041] The Gini Index is a measure of node purity in a decision tree; smaller values ​​indicate higher node purity. Traditionally, the Gini threshold is fixed (e.g., 0.3), but deeper nodes are more likely to overfit to local noise. The Gini threshold formula of this invention achieves the following goals by dynamically adjusting the threshold: Shallow nodes (low depth): Set a lower threshold (0.2-0.3) to allow more splits to capture global features.

[0042] Deep nodes (high depth): The threshold increases linearly (for example, the threshold is 0.38 when depth = 9) to suppress overfitting to noise.

[0043] Dynamic threshold formula: Reduces tree complexity by limiting the splitting ability of deep nodes.

[0044] Pre-pruning condition (terminating splitting when the number of node samples is <10): further prevent overfitting.

[0045] Experimental verification: When tested on historical data (n=5000), the overfitting rate of the dynamic threshold model was reduced from 18% to 6% compared to the fixed threshold (0.3), and the AUC-ROC of the validation set was improved by 0.07.

[0046] Environmental control equipment includes: Ranco ETC-1000 thermostat to control heating plate / air cooler, Hygrostat HC2000 humidity controller to link humidifier / dehumidifier, and ammonia concentration is adjusted by Tjernlund 2000 series ventilation fan. The infrared heater Chromalox HDX-1500 is used for post-spray heating compensation to maintain humidity ≤65%. More specifically, an atomizing nozzle is used to reduce the amount of water sprayed per time (such as spraying 3 grams of water per cubic meter) to avoid excessive humidity increase. A humidity sensor is installed for real-time monitoring, and the water spraying function is automatically paused after the spray is triggered. When the humidity exceeds 65%, the infrared heater (such as 5 kW power) is automatically started and the temperature is gradually raised to 28-30°C. The heaters need to be evenly distributed to avoid excessively high local temperatures. Heating is turned on at the same time The ventilation system is activated to exhaust high-humidity air and control the ammonia concentration to 10-15 ppm. The ventilation rate is dynamically adjusted based on the ammonia sensor data.

[0047] The sensor is fixed in position, the X-Rite ColorChecker calibration color card is automatically calibrated every 4 hours, and the camera focus is adjusted to clearly image the fecal area. Environmental parameters are recorded every 5 minutes, and defecation behavior triggers image acquisition, which is synchronously marked with a timestamp. Body weight is measured at a fixed time daily, and blood samples are collected 60 hours after environmental adjustment. The model is trained using historical data (n=5000 times), and the validation set is divided into chronological order and updated every 12 hours. The prediction results are output as low, medium, and high risk levels. Parameters are adjusted according to the risk level (such as starting the air cooler in the event of high temperature risk), and heating compensation is started immediately after spraying to ensure that the ammonia concentration is maintained at 10-15ppm. This technical solution uses real-time multi-dimensional data collection and dynamic analysis to provide early warning of diarrhea risk in piglets, with an average warning time of 72 hours before symptoms appear. Environmental parameter control accuracy has been improved to ±0.5°C for temperature, ±3% for humidity, and ±2ppm for ammonia concentration, reducing the incidence of diarrhea by 28%. The model's area under the AUC-ROC curve reached 0.92, a 19% improvement over traditional single-parameter warning methods.

[0048] Furthermore, after collecting the piglet feces image, the method further includes: The collected fecal images are preprocessed, and the defecation behavior detection signal is used to trigger image acquisition to ensure that the liquid area is not deformed. The image is then color-calibrated using a standard color chart. A color temperature compensation algorithm is added to the color calibration, and the HSV threshold is dynamically adjusted based on the ambient light sensor data. Convert the calibrated image to the HSV color space and calculate the proportion of liquid area in the feces image; The stool morphology is classified according to the proportion of liquid area and the preset threshold range as a feature for diarrhea risk assessment.

[0049] The image acquisition device utilizes an industrial-grade camera, coupled with a PBC Linear ZL-16 electric actuator, for height adjustment from 0.5 to 1.5 meters. A standard color chart, made of PVC coating, is mounted in a fixed position within the camera's field of view and rotated and calibrated every four hours using a NEMA 17 stepper motor. The color temperature compensation algorithm dynamically adjusts the HSV threshold range based on real-time data from a BH1750 ambient light sensor. A laser rangefinder (Keyence LK-G30) was mounted on the camera bracket to measure the coordinates of the piglet's excretion location in real time (accuracy ±2 mm). An inverse kinematics algorithm was used to adjust the motorized pan / tilt (Panasonic WV-SP800, 0.01° accuracy) to align the camera's optical axis perpendicularly to the feces area.

[0050] A liquid lens (Varioptic VCM-D-12) with dynamic focusing and laser triangulation ensures a depth of field of 0.3-1.2 meters. The fill light has been upgraded to an LED matrix (Luminus SBT-90, 5500K color temperature), controlled by PWM (2000Hz frequency) to achieve a fill light intensity of 500±50 Lux.

[0051] When defecation was detected, a high-speed camera (Basler acA640-740um, 740fps) was activated, capturing 10 frames at 50ms intervals and simultaneously timestamping them. The diffusion velocity of the liquid region was analyzed using the Farneback algorithm, and the first three frames of diffusion were selected for morphological analysis.

[0052] Sobel edge detection is applied to the captured image, and the standard deviation (σ) of the gradient amplitude at the edge of the liquid region is calculated. If σ < 15, the image is considered undeformed; otherwise, a second acquisition is triggered. Experimental data shows that this method reduces the deformation rate of the liquid region from 18% to 4.2%.

[0053] Three cameras (spaced 60° apart) were deployed for stereoscopic imaging, reconstructing the three-dimensional shape of feces through triangulation. A Poisson reconstruction algorithm was used to eliminate single-viewpoint distortion, keeping the error in liquid area volume measurement within ±3%.

[0054] Image processing was performed using the OpenCV library. First, noise was reduced using Gaussian blur (kernel size 5×5), followed by Canny edge detection to locate fecal regions. After conversion to HSV color space, liquid regions were extracted using the Otsu thresholding method. When calculating the liquid region percentage, morphological closing (kernel size 3×3) was used to eliminate noise points. The liquid region percentage thresholds were set as follows: ≤30% for normal stool, 30%-60% for mushy stool, and ≥60% for watery stool. The morphological classification model is based on the support vector machine (SVM) algorithm, using the RBF kernel function with penalty parameters C=1.0 and γ=0.1. The training sample consisted of 1,000 annotated images (500 normal and 500 diarrhea images), using a 5-fold cross-validation approach. Classification results were spatiotemporally aligned with environmental parameters, weight fluctuation, and other features within a 2-hour time window after collection, and spatially matched to the corresponding individual piglets. Liquid area percentage data were filtered with a sliding average (30-minute window) before input into the model to mitigate the impact of transient fluctuations. The excretion sensor and camera are fixed in position, and the color card calibration device is kept 0.3 meters away from the camera to ensure that the calibration area covers the entire imaging range. After the excretion event is triggered, the system automatically captures five consecutive frames of images, evaluates image quality using the entropy method, and retains clear images with an entropy value ≥80. Every four hours, the color card rotation is triggered, a calibration image is captured, the HSV mean and variance of the standard color block are calculated, and the threshold range (such as H±10, S±15, V±20) is dynamically updated. The calibrated image is segmented, and the percentage of pixels in the liquid area is calculated. If the percentage exceeds the threshold, it is marked as a suspected diarrhea sample. The morphological classification results are logically ANDed with other parameters (such as the current ammonia concentration ≥15ppm and the temperature ≥28°C) to generate a composite risk signature.

[0055] In this technical solution, through defecation behavior triggering and color card calibration, image efficiency increased from 65% to 92%, and the error rate of liquid area detection decreased from 18% to 5%. The morphological classification model achieved an accuracy of 91.2% with a Kappa coefficient of 0.83, significantly improving the 62% accuracy of manual judgment. The Spearman correlation coefficient between the proportion of liquid areas and diarrhea incidence reached 0.78 (p < 0.01), which, as a risk characteristic, increased the model's AUC-ROC by 0.15. In a validation study of 1,000 piglets, the 48-hour advance warning accuracy reached 89%, a 27% improvement over traditional methods.

[0056] Furthermore, in the step of using a standard color card to calibrate the image color, the standard color card is coated with polyvinyl chloride to prevent corrosion, and the calibration frequency is once every 4 hours. At the same time, a color temperature compensation algorithm is added to dynamically adjust the threshold range of the HSV color space based on the ambient light color temperature data monitored in real time by the ambient light sensor to eliminate the influence of different color temperature ambient light on image color recognition.

[0057] The standard color chart is available in the X-Rite ColorChecker Classic, a 1.5mm thick polyvinyl chloride (PVC)-coated material with a 0.1mm thick epoxy resin protective layer. It is resistant to the corrosive environment of piggeries with ammonia concentrations ≤ 20ppm. The chart measures 10cm x 15cm and contains 24 standard color patches, including a neutral grayscale patch (18% reflectance) for white balance calibration.

[0058] The calibration device, driven by a stepper motor, automatically rotates the color chart to preset angles (0°, 90°, 180°, and 270°) every four hours, capturing three calibration images after each rotation. An ambient light sensor, mounted next to the camera, monitors light intensity and color temperature in real time, transmitting this data to the main control unit via the I2C bus. The color temperature compensation algorithm is based on a polynomial regression model. The input is the ambient light color temperature (K), and the output is the adjustment coefficient for each HSV channel. For example, when the color temperature is greater than 5500K, the H channel threshold increases by 5% and the S channel threshold decreases by 8%; when the color temperature is less than 4000K, the V channel threshold increases by 12%. The dynamic adjustment formula is: HSV adjusted =HSV base ×(1+α×Δ T ); Where ΔT is the difference between the current color temperature and the reference color temperature (5000K), and α is the channel sensitivity coefficient (H: 0.002, S: -0.003, V: 0.0015).

[0059] The training process of the polynomial regression model parameters with dynamic adjustment of HSV thresholds includes the following steps: 1) Calibration Data Collection, Standard Color Chart: An X-Rite ColorChecker Classic (24 color patches) was used, with calibration images automatically captured every four hours. Ambient Light Data: A BH1750 sensor was used to record color temperature (K) and light intensity (Lux) in real time.

[0060] Data volume: 100 sets of calibration images at different color temperatures (3000K-6500K) were collected, each set containing the HSV values ​​of 24 color blocks.

[0061] 2) Model training and parameter fitting, input variable: ambient light color temperature (T).

[0062] Output variables: Adjustment coefficients (ΔH, ΔS, ΔV) for each HSV channel.

[0063] Polynomial regression model: Δ H =0.002×( T −5000); Δ S=−0.003×( T −5000); Δ V =0.0015×( T −5000); Fitting method: The least squares method is used to optimize the coefficients, with the goal of minimizing the mean square error (MSE) between the theoretical and actual values ​​of the calibration color patch.

[0064] A color chart is fixed 0.3 meters in front of the camera. A stepper motor is connected to the color chart bracket, and the ambient light sensor is integrated with the camera. Every four hours, the stepper motor is triggered to rotate the color chart. The system captures a calibration image and calculates the HSV mean and standard deviation of each color block. Based on the current color temperature data, a compensation algorithm is applied to adjust the HSV threshold range. For example, when a color temperature of 4500K is detected, the H channel threshold range is adjusted from 20-40 to 22-42. After each calibration, a standard sample with a known liquid area ratio (e.g., 50%) is captured to verify the segmentation accuracy of the adjusted threshold. The PVC coating extends the life of color cards from 3 months to 12 months, maintaining a color difference ΔE < 1.5 even in an ammonia concentration of 15 ppm. Dynamic threshold adjustment reduces the error rate in liquid area detection from 17% to 6% at different color temperatures, and improves color recognition consistency by 41% when the color temperature fluctuates by ±1000K. Experimental data shows that using this technology increases the accuracy of stool image color classification from 82% to 94%, and reduces the misclassification rate of the diarrhea warning model by 19%.

[0065] Furthermore, the feces image acquisition device includes a liftable bracket and an image acquisition camera. The liftable bracket has an IP65 waterproof rating, its motor is made of stainless steel and is rust-proofed, and the fill light intensity during image acquisition is 200±50Lux.

[0066] For adjustable brackets, choose the PBC Linear ZL-16 series electric actuator, which has a travel range of 0.5-1.5 meters, a maximum load of 50 kg, and an IP65 protection rating. The bracket body is constructed of 304 stainless steel, coated with an epoxy resin anti-corrosion coating (thickness ≥ 50 μm), and the motor housing is constructed of SUS316 stainless steel, proven to withstand 1000 hours of salt spray testing without corrosion. The image acquisition camera is a Basler acA2000-50gm industrial camera paired with a Navitar 12×Zoom 6000 lens and IP67 waterproof rating. The fill light is a LitraTorch Pro LED ring light with a color temperature of 5500K. The light intensity is adjustable to 200±50 Lux using a PWM signal (frequency 200Hz). The camera and fill light are connected via a waterproof connector and a polyurethane-sheathed shielded cable. The bracket is installed 1.8 meters above the piglet farrowing bed and secured to the ceiling with expansion bolts. The camera's horizontal viewing angle is adjustable to 45°, and the vertical viewing angle covers a height range of 0.5-1.2 meters. The fill light angle is set at 30° to the camera's optical axis to ensure uniform illumination of the manure area. The bracket's lifting speed is set to 5 mm / s to avoid image blur caused by rapid movement. Secure the electric actuator to the ceiling, adjusting the horizontal error to ≤0.5°. Connect the 24V DC power supply and control signal cables. Use the client software to set camera parameters (exposure time 5-10ms, gain 0-10dB), and adjust the lens focal length to achieve a fecal area resolution of ≥0.5mm / pixel. Use a illuminance meter (such as a Konica Minolta T-10) to measure light intensity at various heights (0.5-1.5 meters). Adjust the PWM duty cycle to maintain a stable light intensity of 200±50 lux. Run the camera continuously for 2000 hours in a 90% humidity environment, verifying that the motor temperature rise on the bracket is ≤30°C and that there is no condensation inside the camera. The IP65 protection rating ensures the device remains operational during spray cleaning. Salt spray testing shows an annual corrosion rate of less than 0.01mm for stainless steel components. Precise fill light control reduces image brightness standard deviation to less than 15%, improving liquid area detection accuracy from 78% to 91%. The adjustable bracket design accommodates varying excretion heights in piglets of varying ages, minimizing image obstruction caused by viewing angle deviation and reducing false positives by 23%. In a trial involving 500 piglets, the device achieved an average trouble-free operating time of 8,700 hours, more than three times longer than traditional fixed brackets.

[0067] Furthermore, the construction process of the random forest model includes: Collect historical piglet breeding data, including environmental parameters, fecal image features, weight fluctuation data, blood test data, and corresponding diarrhea occurrence data as training samples; Random sampling is used to select some samples from the training samples, and some features are randomly selected to construct multiple decision trees. The maximum depth of the decision tree is set to 9 layers, but a pre-pruning strategy is used to terminate the split when the number of node samples is less than 10. The modified dynamic Gini threshold formula is 0.2 + 0.02 × depth; Multiple decision trees were combined into a random forest model, and the prediction results of multiple decision trees were comprehensively analyzed to obtain the final diarrhea risk level prediction result.

[0068] Historical breeding data can be stored in a SQLite database, containing 5,000 records with a 1:1 positive-negative sample ratio. Environmental parameters include temperature 18-32°C, humidity 40-80%, and ammonia concentration 5-30 ppm, collected every 5 minutes. Stool image feature extraction uses liquid area percentage (0-100%) and color entropy (0-255). Weight fluctuation data is calculated as a daily change rate of -5% to +3%. Blood test data is standardized using Excel spreadsheets, with white blood cell counts ranging from 5-20 × 10^9 / L and cortisol concentrations from 50-300 ng / mL. The model was built using the scikit-learn library in Python 3.8, with a set of 100 decision trees. Bootstrap sampling was used for random selection, with 80% of the samples selected for training and the remaining 20% ​​for out-of-bag validation. The feature selection ratio was set to √(n_features) = 3, meaning that 3 of the 7 input features were randomly selected for splitting. The maximum depth was 9 layers, the minimum number of samples per node split was 10, and the minimum number of samples per leaf node was 5. The dynamic Gini threshold formula was 0.2 + 0.02 × depth; for example, the threshold for layer 5 nodes was 0.3. After the decision tree was generated, the prediction results were integrated using majority voting, with output probability thresholds set at 0.6 (high risk), 0.4 (medium risk), and 0.2 (low risk). The out-of-bag error (OOB) rate was calculated to be 15.7%, and the model achieved an accuracy of 89.2% on the test set (n=1000), with an F1-score of 0.91. Feature importance was calculated using the Gini index, showing that environmental parameters (temperature and ammonia) and physiological indicators (cortisol) contributed 32% and 28%, respectively. Using the Pandas library (1.3.3), samples with more than 30% missing values ​​were deleted, and continuous variables were Z-score normalized. Features with a correlation with diarrhea ≥0.5 were selected using the Spearman correlation coefficient, retaining temperature, ammonia concentration, liquid area percentage, and cortisol concentration. 100 decision trees were trained in parallel, with the depth of each tree dynamically adjusted and splitting stopped when the number of node samples was less than 10. The area under the AUC-ROC curve was 0.92, and the Kappa coefficient was 0.84. After setting the threshold, the recall rate for high-risk predictions reached 94%. A pre-pruning strategy reduced the model's overfitting rate from 27% to 9%, and dynamic Gini threshold adjustment improved the rationality of node splitting by 23%. Random feature selection reduced the impact of inter-feature collinearity, improving model generalization by 19% compared to a single decision tree. In a validation study of 1,000 piglets, the 72-hour early warning accuracy reached 87%, a 31% improvement over traditional linear models. Memory usage was optimized to an average of 2.1MB per decision tree, and 210MB for 100 trees, making it suitable for deployment in embedded systems.

[0069] Furthermore, the prediction process of the random forest model also includes: Adopt the activation tree group screening mechanism, increase the time decay factor, and select decision trees trained within 72 hours to participate in prediction; An LRU cache is used to eliminate the least recently used derivative features to manage the memory usage of the model.

[0070] Active tree group filtering can be implemented using the Python scikit-learn library. During model training, the training timestamp is recorded for each decision tree. The time decay factor is set to 0.9, meaning that every hour, the weight of the decision tree is multiplied by 0.9^(1 / 72). The filtering criteria are: the difference between the current time and the training time is ≤ 72 hours, and the weight is ≥ 0.5. For example, the weight of a decision tree trained 72 hours ago decays to 0.9^(72 / 72) = 0.9, which meets the retention criteria. Derived feature caching can be done using the Python functools.lru_cache decorator, with a maximum cache capacity of 10,000 entries and a caching window of 24 hours. A least recently used (LRU) algorithm is used for eviction. When the cache is full, the least recently accessed features are removed. Cached features include derived variables such as the sliding average of environmental parameters and the rate of change in the proportion of liquid feces. Data is stored in NumPy arrays. The time decay factor calculation formula is: weight=α Δt Where α = 0.9, and Δt is the difference in hours between training and prediction time. When a decision tree weight is < 0.5, it is automatically eliminated, and the relevant features are removed from the cache. The cache is updated every 15 minutes, synchronized with the environmental parameter collection cycle. During the training phase, record the training timestamp and initial weight of 1.0 for each decision tree. Before each prediction, traverse all decision trees, calculate the current weight, and select those with a weight ≥ 0.5 and a training time ≤ 72 hours. Maintain a feature access record table, updating the access time each time a derived feature is used. Features that have not been used for more than 24 hours are automatically deleted. Record the cache hit rate (target ≥ 85%) and memory usage (target ≤ 500MB), and generate weekly analysis reports. Activating tree group filtering increased the proportion of decision trees trained using the latest data to 89%, improving prediction accuracy by 3.2% compared to full tree participation. LRU caching reduced memory usage from 720MB to 480MB and reduced feature access latency by 41%. In 1,000 prediction tests, average response time decreased from 320ms to 210ms, and the cache hit rate remained stable at 87%. Experimental data showed that this technology improved the model's response to sudden environmental changes by 58% and reduced the incidence of memory leaks by 62%.

[0071] Furthermore, it also includes the steps of processing and filtering the input features: Standardize all types of collected data so that data with different characteristics have the same scale; A feature screening mechanism is introduced to retain features with a cumulative variance contribution rate ≥ 95% through PCA dimensionality reduction; The cortisol-derived characteristic time decay factor α = 0.85 was adjusted, and its lagged correlation with diarrhea risk was verified by clinical data.

[0072] Data normalization can be performed using the StandardScaler or MinMaxScaler in the Python scikit-learn library (version 1.2.2). For example, continuous variables such as temperature (18-32°C) and humidity (40-80%) can be normalized using the Z-score formula: x′ = (x − μ) / σ; The percentage of liquid area (0-100%) and cortisol concentration (50-300 ng / mL) were normalized to the range of 0-1 using Min-Max. PCA dimensionality reduction can be performed using the PCA module in the scikit-learn library, with n_components set to 0.95 (preserving 95% of the variance). PCA reduces the 7-dimensional input features to three principal components, with a cumulative contribution of 96.3%. Feature selection thresholds are set to univariate variance ≥ 0.1, skewness absolute value ≤ 2, and kurtosis absolute value ≤ 7.

[0073] PCA dimensionality reduction verification: Input features and principal component contribution rates, original features (7): temperature, humidity, ammonia concentration, liquid area ratio, weight change rate, white blood cell count, cortisol concentration.

[0074] PCA results: When the cumulative variance contribution rate is ≥95%, three principal components (PC1-PC3) are retained. The specific contributions are as follows: The two loadings in PC2 were similar (0.85 vs. 0.79), indicating that they jointly characterize the stress response and are consistent with the lagged correlation with diarrhea (r = 0.68).

[0075] PC1 reflects environmental stress (temperature / ammonia), PC2 reflects physiological stress (cortisol / leukocytes), and PC3 characterizes fecal morphology.

[0076] After dimensionality reduction, the features can still distinguish environmental diarrhea from pathogenic diarrhea (e.g., high PC1 + low PC2 is environmental diarrhea, high PC2 + high PC3 is pathogenic diarrhea).

[0077] The time decay factor α=0.85, calculated as: cortisol adjusted =cortisol raw × α Δt ; Where Δt is the difference in hours between the current time and the sampling time. Clinical data validation was performed on 500 piglets with diarrhea. The Spearman correlation coefficient between adjusted cortisol concentration and diarrhea incidence was calculated (r = 0.68, p < 0.01). The highest correlation was observed after a 48-hour lag. Parameters such as temperature and humidity were standardized using StandardScaler, while parameters such as the liquid area percentage were normalized using MinMaxScaler. Principal component analysis was performed on the seven-dimensional features, and the first three principal components were selected. The eigenvector loading matrix showed that temperature (0.92), ammonia concentration (0.88), and cortisol (0.85) contributed the most. In data from 1,000 piglets, adjusting α from 0.75 to 0.95 found that α = 0.85 resulted in the largest area under the AUC-ROC curve (0.91). The three principal components after dimensionality reduction were combined with the unreduced liquid area percentage and weight change rate to form a five-dimensional input feature.

[0078] Normalization reduced feature mean to 0 and standard deviation to 1, eliminating dimensionality effects and accelerating model convergence by 37%. PCA dimensionality reduction reduced the number of features by 57%, shortening training time from 120 seconds to 45 seconds. Optimizing the time decay factor increased the lagged correlation between cortisol and diarrhea by 23%, boosting the model's accuracy in identifying delayed stress responses from 78% to 91%. In the validation set (n=2000), the model incorporating the decay factor achieved an AUC-ROC of 0.94, a 0.12 improvement over the traditional method.

[0079] Furthermore, the collected data were processed for outlier detection using a Hampel filter, the filter window was adjusted to 4 hours to match the piglet excretion interval, and the outlier markers were marked with an increased confidence threshold, triggering the replacement operation only when there were three consecutive outlier points.

[0080] The Hampel filter can be implemented using the Python scipy library, with a window length of 4 hours (i.e., 24 sampling points, assuming data is collected every 10 minutes) and a contamination ratio of 0.15. The filter parameters are calculated as follows: threshold=3×MAD; The MAD (median absolute deviation) is calculated using the numpy library. Data preprocessing includes time alignment and linear interpolation to ensure that the data frequency is consistent. The steps for outlier detection are: Apply a Hampel filter to each time series (e.g., temperature, ammonia concentration) and calculate the residuals. If the absolute value of the residual exceeds the threshold, it is marked as an outlier. Three consecutive abnormal points trigger the replacement operation, and the replacement value is the median of the previous three valid values. The confidence threshold is set to 95%, that is, the outlier mark must meet the following requirements: probability=1−Φ(MADresidual)≥0.95; where Φ is the cumulative function of the standard normal distribution. The data after the replacement operation is stored in a SQLite database, and the outlier record contains the timestamp, original value, replacement value, and confidence score. Environmental parameter data is collected from sensors every 10 minutes, totaling 24 points in a 4-hour window. A Hampel filter is applied to the data within each window, and the MAD and threshold values ​​are calculated. The data points are iterated over, and if three consecutive points exceed the threshold, a replacement is triggered. The outlier point is filled with the median of the previous three valid values, and the database record is updated. The Hampel filter increased outlier detection accuracy from 68% to 92%, reducing the false positive rate by 34%. A 4-hour window matched the piglet's excretion interval, reducing false positives due to physiological fluctuations. The confidence threshold reduced the chance noise trigger rate from 22% to 5%, improving the model input data quality by 29%. In a test of 1,000 data sets, outlier processing reduced the model's prediction error rate by 17%, and the area under the AUC-ROC curve increased by 0.09.

[0081] Furthermore, during the training and prediction process of the random forest model, the importance of features is dynamically updated: Dynamic feature importance update adds hierarchical attenuation, with environmental parameter attenuation coefficient β=0.8^(current tree depth-1) and physiological parameter attenuation coefficient β=0.9^(current tree depth-1); A real-time correlation threshold is introduced, and feature importance update is triggered when the absolute value of the Spearman coefficient changes by more than 0.2 compared with the mean.

[0082] The attenuation coefficient for environmental parameters is β = 0.8^(current tree depth - 1), for example, for the fifth-level node, β = 0.8^4 = 0.4096. The attenuation coefficient for physiological parameters is β = 0.9^(current tree depth - 1), for the fifth-level node, β = 0.9^4 = 0.6561. The attenuation coefficient can be calculated using the Python numpy library and stored in the model parameter table in the MySQL database. The real-time correlation threshold is set to a Spearman coefficient change of >0.2 relative to the mean. Correlation calculations can be performed using the pandas library, monitoring the correlation between environmental parameters (temperature, ammonia concentration) and diarrhea occurrence hourly. When the Spearman coefficient between temperature and diarrhea drops from 0.6 to 0.4, a feature importance update is triggered. The feature importance update process is: 1. Record the feature importance score (based on the Gini index) for each decision tree during training. 2. Calculate the Spearman coefficient of the current feature and diarrhea in real time and compare it with the historical mean. 3. When the change exceeds the threshold, apply the corresponding attenuation coefficient to the environmental parameters and physiological parameters. 4. The updated importance score is synchronized to all prediction nodes through the HTTP API (Flask framework). During the training phase, the initial importance score for each feature is recorded. The average for environmental parameters (temperature and ammonia) is 0.35, and the average for physiological parameters (cortisol) is 0.28. A scheduled task (such as Celery) is deployed to calculate the Spearman coefficient every hour. For example, if the correlation between ammonia concentration and diarrhea increases from 0.5 to 0.7, a change of 0.2 triggers an update. For environmental parameters, β = 0.8^(3-1) = 0.64 is applied, adjusting the importance score from 0.35 to 0.35 × 0.64 = 0.224. For physiological parameters, β = 0.9^(3-1) = 0.81 is maintained, resulting in a score of 0.28 × 0.81 = 0.2278. The adjusted importance scores are written to the database, and the new parameters are loaded when the prediction service is restarted. Layered attenuation reduced the long-term impact of environmental parameters by 38% and physiological parameters by 19%, improving the model's response to short-term environmental changes by 42%. Updates triggered by real-time correlation thresholds improved the consistency of feature importance with real-world data by 27%. Over 1,000 predictions, the model's accuracy in warning of sudden increases in ammonia concentrations increased from 79% to 94%. The area under the AUC-ROC curve stabilized at 0.93 after the update, an improvement of 0.07 compared to the fixed-weight model.

[0083] Furthermore, it also includes steps to monitor and control the stability of the random forest model: Adjust the validation set update frequency to once every 12 hours; The AUC-ROC change rate threshold is set to 3%. When the AUC-ROC change rate of the model exceeds this threshold, the model is retrained or adjusted.

[0084] Validation set updates can be implemented using the Python pandas library. Historical data is divided chronologically into a training set (80%) and a validation set (20%). Updates are set every 12 hours, for example, at 12:00 AM and 12:00 PM daily, supplementing the validation set with 10% new samples from the latest data. The validation set is stored in a separate table in a MySQL database and contains environmental parameters, stool characteristics, blood markers, and diarrhea labels. AUC-ROC calculation can be done using the roc_auc_score function of the scikit-learn library (version 1.2.2). The model performance is re-evaluated after each validation set update. The rate of change threshold is set to 3%, and the calculation formula is: Rate of change = |Current AUC − Baseline AUC| / Baseline AUC × 100% When the rate of change exceeds a threshold, the model is retrained via the Celery task queue. The baseline AUC is initially set to 0.92, and the latest value is automatically saved after each subsequent update. Trigger conditions include: 1. AUC-ROC change rate ≥ 3% 2. Performance degrades after three consecutive validation set updates 3. Rare environmental parameter combinations appear in the new data (e.g., temperature > 32°C and ammonia > 25 ppm) During retraining, the original model structure was retained and only the latest 6 months of data (approximately 50,000 records) were used. The training cycle was set to 2 hours, which was shortened to 45 minutes through GPU acceleration (such as NVIDIA Tesla T4). Every day at midnight and midnight, the last 72 hours of data is extracted from the real-time database. After sorting by time, the first 80% of the data is used as the training set, and the last 20% is used as the validation set. The validation set is used to calculate the current AUC-ROC and compare it with the baseline value in the historical data. If the rate of change exceeds 3%, an alert is sent to the administrator's email address, and the model retraining process is initiated. After training is complete, the new model is deployed using a Docker container, and the old version is retained for 7 days as a rollback backup. High-frequency validation set updates increased the model's adaptability to environmental changes by 41%, reducing the AUC-ROC fluctuation range from ±8% to ±2.5%. A threshold control mechanism reduced the model's false positive rate by 15%, and timely detected and corrected model drift 23 times out of 1,000 validation runs. Experimental data showed that after implementing this technology, the model maintained an average AUC-ROC of 0.92 over six months, an improvement of 0.08 compared to the traditional fixed validation set approach, and its early warning accuracy remained stable at over 89%.

[0085] Although the embodiments of the present invention have been disclosed above, they are not limited to the applications listed in the description and implementation methods. They can be fully applied to various fields suitable for the present invention. For those familiar with the art, additional modifications can be easily implemented. Therefore, without departing from the general concept defined by the claims and the scope of equivalents, the present invention is not limited to specific details.

Claims

1. A method for predicting and judging the risk level of diarrhea in suckling piglets, characterized in that: The following steps are involved: Multi-parameter monitoring equipment is installed in the piglet breeding environment to collect environmental parameters in real time, including temperature, humidity, and ammonia concentration in the pig house. The excretion behavior detection module monitors the piglets' excretion behavior. When an excretion event is detected, the feces image acquisition device is triggered to collect piglet feces images. The collected feces images are then quality-assessed to exclude blurred or obscured images. The piglets' weight is regularly measured to obtain weight fluctuation data. Between 48 and 72 hours after environmental adjustment, blood samples were collected from the piglets' ear veins to test the number of white blood cells and cortisol levels in the blood to obtain blood test data; The collected environmental parameters, stool images, weight fluctuation data, and blood test data were used as input features and fed into the trained random forest model to predict the diarrhea risk level; Based on the predicted diarrhea risk level, corresponding environmental control instructions are generated to adjust the temperature, humidity, and ventilation environmental conditions of the pig house. If spraying operations are performed after the adjustment, heating compensation must be activated to maintain humidity ≤ 65%, and the ammonia concentration control threshold is adjusted to 10-15ppm; within 48-72 hours after the environmental adjustment, the above-mentioned data are re-collected and re-entered into the random forest model for risk level assessment to dynamically adjust the environmental control strategy.

2. The method for predicting and judging the risk level of diarrhea in suckling piglets according to claim 1, characterized in that: After collecting the piglet feces image, the method further includes: The collected fecal images are preprocessed, and the defecation behavior detection signal is used to trigger image acquisition to ensure that the liquid area is not deformed. The image is then color-calibrated using a standard color chart. A color temperature compensation algorithm is added to the color calibration, and the HSV threshold is dynamically adjusted based on the ambient light sensor data. Convert the calibrated image to the HSV color space and calculate the proportion of liquid area in the feces image; The stool morphology is classified according to the proportion of liquid area and the preset threshold range as a feature for diarrhea risk assessment.

3. The method for predicting and judging the risk level of diarrhea in suckling piglets according to claim 2, characterized in that: In the step of color calibrating the image using a standard color card, the standard color card is coated with polyvinyl chloride to prevent corrosion, and the calibration frequency is once every 4 hours. At the same time, a color temperature compensation algorithm is added to dynamically adjust the threshold range of the HSV color space based on the ambient light color temperature data monitored in real time by the ambient light sensor to eliminate the influence of ambient light of different color temperatures on image color recognition.

4. The method for predicting and judging the risk level of diarrhea in suckling piglets according to claim 3, characterized in that: The feces image acquisition device includes a liftable bracket and an image acquisition camera. The liftable bracket has an IP65 waterproof rating, its motor is made of stainless steel and is rust-proofed, and the fill light intensity during image acquisition is 200±50Lux.

5. The method for predicting and judging the risk level of diarrhea in suckling piglets according to claim 1, characterized in that: The construction process of the random forest model includes: Collect historical piglet breeding data, including environmental parameters, fecal image features, weight fluctuation data, blood test data, and corresponding diarrhea occurrence data as training samples; Random sampling is used to select some samples from the training samples, and some features are randomly selected to construct multiple decision trees. The maximum depth of the decision tree is set to 9 layers, but a pre-pruning strategy is used to terminate the split when the number of node samples is less than 10. The modified dynamic Gini threshold formula is 0.2 + 0.02 × depth; Multiple decision trees were combined into a random forest model, and the prediction results of multiple decision trees were comprehensively analyzed to obtain the final diarrhea risk level prediction result.

6. The method for predicting and judging the risk level of diarrhea in suckling piglets according to claim 5, characterized in that: The prediction process of the random forest model also includes: Adopt the activation tree group screening mechanism, increase the time decay factor, and select decision trees trained within 72 hours to participate in prediction; An LRU cache is used to eliminate the least recently used derivative features to manage the memory usage of the model.

7. The method for predicting and judging the risk level of diarrhea in suckling piglets according to claim 6, characterized in that: It also includes steps for processing and filtering input features: Standardize all types of collected data so that data with different characteristics have the same scale; A feature screening mechanism is introduced to retain features with a cumulative variance contribution rate ≥ 95% through PCA dimensionality reduction; The cortisol-derived characteristic time decay factor α = 0.85 was adjusted, and its lagged correlation with diarrhea risk was verified by clinical data.

8. The method for predicting and judging the risk level of diarrhea in suckling piglets according to claim 7, characterized in that: The collected data were processed for outlier detection using a Hampel filter. The filter window was adjusted to 4 hours to match the piglet excretion interval, and the confidence threshold was increased for outlier markers. The replacement operation was triggered only when there were three consecutive outlier points.

9. The method for predicting and judging the risk level of diarrhea in suckling piglets according to claim 5, characterized in that: During the training and prediction process of the random forest model, the importance of features is dynamically updated: Dynamic feature importance update adds hierarchical attenuation, with environmental parameter attenuation coefficient β=0.8^(current tree depth-1) and physiological parameter attenuation coefficient β=0.9^(current tree depth-1); A real-time correlation threshold is introduced, and feature importance update is triggered when the absolute value of the Spearman coefficient changes by more than 0.2 compared with the mean.

10. The method for predicting and judging the risk level of diarrhea in suckling piglets according to claim 9, characterized in that: It also includes steps to monitor and control the stability of the random forest model: Adjust the validation set update frequency to once every 12 hours; The AUC-ROC change rate threshold is set to 3%. When the AUC-ROC change rate of the model exceeds this threshold, the model is retrained or adjusted.

Citation Information

Cited By

  • Pig excrement appearance and excretion behavior fusion-based disease identification method and system

    CN122067199A

  • Disease recognition method and system based on fusion of pig feces appearance and excretion behavior

    CN122067199B