October 02, 2026
Impact of Mesomycoplasma hyopneumoniae on swine mortality using Machine Learning models
Impact of Mesomycoplasma Hyopneumoniae on Swine Mortality Using Machine Learning Models
Fabiana Carolina de Aguiar; Henrique Raymundo Gioia
DOI: 10.22167/2675-6528-202602883
Article derived from a Final Course Work (TCC), with content based on the student’s original work and adapted to the editorial format of the E&S Magazine with the support of the ResumeAI tool, an artificial intelligence solution developed by Instituto Pecege for textual synthesis and organization.
Summary
High-production swine farming faces constant challenges related to lot viability, where the interaction between pathogens and productive indicators directly impacts the industry’s profitability. Laboratory analyses to identify infectious agents such as Mesomycoplasma hyopneumoniae, the cause of enzootic pneumonia, are relevant for directing assertive interventions on farms. The objective of this study was to evaluate the importance of M. hyopneumoniae infection and zootechnical variables in mortality on growing and finishing farms, using Machine Learning models. The methodology consisted of processing a real database from an agribusiness, integrating laboratory results, production indicators, and biosecurity assessments. The data were standardized and the target variable logarithmically transformed, being analyzed by Linear Regression, Random Forest, and XGBoost algorithms. The results showed that the models captured interactions similarly, explaining approximately 35% of the mortality variability. The presence of M. hyopneumoniae and the inverted cycle threshold stood out as important sanitary indicators, while the Corrected Feed Conversion and age at slaughter were the main production indicators. The XGBoost algorithm was considered the best performing operationally due to its native ability to manage missing data. Predictive modeling acted as an effective tool in assessing mortality risks, reinforcing the need for routine laboratory diagnostics in the production cycle.
Keywords: Mortality; Predictive model; Enzootic pneumonia; Swine farming.
1. Introduction
High-production global swine farming faces continuous challenges related to lot viability, where the interaction between pathogens and productive indicators directly impacts industry profitability. Brazil ranks fourth among the world’s largest producers and exporters of pork, with the state of Santa Catarina being the largest national producer, responsible for 32.94% of production. In 2024, the states in the Southern region slaughtered 34.1 million pigs (ABPA, 2025). With the continuous expansion of production and the increasing demands of the production chain, concern is growing about the presence of diseases, which directly impact productivity and increase production costs.
In this scenario, Mesomycoplasma hyopneumoniae, the causative agent of swine enzootic pneumonia, stands out as a highly prevalent respiratory pathogen in swine herds. Its presence in the animals’ respiratory tract is characterized by dry, non-productive coughing, which can result in significant economic losses due to decreased zootechnical performance and increased medication costs. Studies indicate that M. hyopneumoniae infection can cause losses of up to 6.55 dollars per animal when more than 15% of the lung is compromised, in addition to a reduction in growth rate of seven percent to twenty percent, especially when associated with other infectious diseases (Barcellos and Guedes, 2022).
Due to the negative impacts of infectious diseases, it is essential to improve the accuracy of diagnoses and the epidemiological knowledge of pathogens of relevance in swine farming. This will allow the implementation of more effective prevention, control, and eradication measures on farms, contributing to herd health and production sustainability. The use of data for the control of infectious diseases has proven essential for the effective management of diseases in herds, as the technification of production systems has enabled disease traceability, allowing for active surveillance on farms and enabling early detection of outbreaks (Batista et al., 2007; Merca et al., 2022).
Predictive models, which use historical data and mathematical algorithms, are powerful tools for forecasting future events and behaviors, transforming data into useful predictions for decision-making. Although traditional statistical models, such as linear regression, are widely used, the application of Machine Learning (ML) has become increasingly relevant, mainly due to its ability to handle large volumes of data and non-linear relationships (van Milgen et al., 2008; Madhuri and Deshpande, 2024). Machine Learning, a subset of artificial intelligence, allows systems to learn and improve their predictions autonomously, using techniques such as neural networks and deep learning, without the need for explicit programming (Google Cloud, 2024; Madhuri and Deshpande, 2024).
In veterinary epidemiology, the use of Machine Learning, although still in its early stages, has shown great potential to improve the prediction of outbreaks and disease management in swine populations. ML models, such as Random Forest and Extreme Gradient Boosting (XGBoost), have proven effective in predicting swine disease outbreaks, such as African Swine Fever (Liang et al., 2020) and Porcine Reproductive and Respiratory Syndrome (Shamsabardeh et al., 2022). XGBoost, in particular, is considered one of the most important technologies in machine learning, being effective in large-scale datasets where classification accuracy surpasses traditional methods (Liu et al., 2022; Xu et al., 2023; Paploski et al., 2021). Furthermore, ML can be expanded to the analysis of animal welfare, a growing indicator of quality in swine production, aiding in risk prediction (Zimpel et al., 2021).
Despite the advances, the multifactorial complexity of mortality in the finishing phase suggests that the integration of laboratory diagnostics with productive indices, as observed in this study, strengthens the robustness of machine learning models in anticipating sanitary losses in swine farming (Halev et al., 2023). Thus, this study is justified by the need to improve the understanding of factors influencing mortality in swine herds, using Machine Learning approaches to identify patterns and optimize management and biosecurity strategies. The objective of this study was to evaluate, through linear regression and Machine Learning models, the importance of the presence of Mesomycoplasma hyopneumoniae on growing/finishing phase pig farms of a large agribusiness in western Santa Catarina, with the construction of the models aiming to identify production and biosecurity patterns that contribute to the occurrence of mortality.
2. Material and Methods
This work was characterized as a retrospective observational study, focused on the analysis of productive and biosecurity data on pig farms. The unit of analysis comprised mortality, daily weight gain, corrected feed conversion, and age at slaughter, in addition to the average biosecurity score. The data were collected from integrated pig productions, specifically in the growing and finishing phases, belonging to a large agribusiness located in western Santa Catarina, during the years 2024 and 2025. The biosecurity assessment of the farms was carried out using an internal “checklist”, which consisted of 41 questions.
To complement the productive and biosecurity data, laboratory diagnostic results were incorporated. Infection by Mesomycoplasma hyopneumoniae was detected using the qPCR (quantitative polymerase chain reaction) technique in samples collected on the farms during the same period. Additionally, microbiological analyses of the water supplied to the animals were included, with qualitative results indicating the presence or absence of total coliforms and Escherichia coli. The detection of the pathogen by qPCR was determined by the “Cycle Threshold” (CT) value, where lower values indicate a higher amount of genetic material. To facilitate interpretation, “inverted” CT values (40 – CT) were used, so that higher values represented a greater load of the agent.
The processing of data and the implementation of Machine Learning models were carried out using the Python programming language, with the aid of specialized libraries for analysis, as detailed in Appendix A of the original work. The dependent variable of the models was the total mortality percentage of the pig batch. To reduce asymmetry and stabilize the variance of this variable, a logarithmic transformation (log1p) was applied.
Data quality was ensured through procedures for correcting typographical errors in textual fields and verifying data consistency and type. For the explanatory variables that presented missing values, constant imputation was chosen, using SimpleImputer with fill_value = -1. This procedure was applied only to the Linear Regression and Random Forest models, as the XGBoost algorithm has native capability to manage missing data.
Seasonality, represented by months, was transformed into sine (mes_sen) and cosine (mes_cos) components to capture the continuous nature of time. The sex variable was handled through “One-Hot Encoding”, using the “get_dummies” function from the pandas library. The sex_misto batch was defined as the implicit reference category, and the sex_femea and sex_macho variables were created as “dummy” variables.
For the analysis and modeling, three algorithms with distinct architectures were selected. Linear Regression (LR) was employed as a classic statistical reference model. For the Ensemble models, Random Forest (RF) and XGBoost, the database was divided into a training set (70%) and a test set (30%), aiming to ensure generalization capacity and avoid data overfitting.
The Random Forest algorithm, based on “Bagging”, was configured with 500 decision trees, a maximum depth of 10, and the number of variables viewed by each tree set at 0.7. XGBoost, a “Boosting” algorithm, was configured with 1000 trees and a “learning rate” of 0.05, being adjusted to minimize residual error sequentially.
The validity of the linearity assumptions for the Linear Regression model was evaluated through residual analysis, using the “Quantile-Quantile Plot” (Q-Q) and the distribution plot, aiming to verify the normality of the errors. The predictive performance of the models was measured by the Coefficient of Determination (R²) and the Mean Absolute Error (MAE), complemented by the evaluation of global statistical significance via F-Statistic and its p-value. For Linear Regression, these metrics were calculated on the entire dataset, while for the Machine Learning models, they were calculated on the test set.
3. Results and Discussion
The data analysis began with a robust dataset, comprising 2,744 productive observations from 500 farms. This included 910 water quality analysis records, covering 424 properties, and 286 Mesomycoplasma hyopneumoniae analyses conducted on 188 farms. Additionally, 2,056 biosecurity assessments, corresponding to 431 farms, were incorporated. On average, each producer housed 5.48 batches during the study period, resulting in 2.74 batches of pigs slaughtered per year, demonstrating the breadth and relevance of the dataset for understanding the factors influencing mortality in swine farming.
The productive variables analyzed revealed an average mortality of 2.49%, a corrected feed conversion of 2.30 kg/kg, and a daily weight gain of 1.05 kg/day. The average age at slaughter was 98.11 days. Regarding the composition of the batches, 103 were identified as female batches, 72 as male batches, and 2,569 as mixed batches. The average biosecurity checklist score was 89.61, indicating a good overall level of compliance with sanitary practices. Laboratory results for the water showed that 719 samples were positive for total coliforms and 88 for Escherichia coli, while 191 and 822 were negative, respectively. For Mesomycoplasma hyopneumoniae, 240 results were positive and 46 negative, with an average inverted Cycle Threshold (CT) value of 26.98, reflecting the bacterial load of the pathogen.
The detection of the presence or absence of Mesomycoplasma hyopneumoniae was performed using the qPCR technique, where the Cycle Threshold (CT) value indicates the number of cycles required for the target genetic material to become detectable. Lower CT values correspond to a higher amount of the agent’s genetic material in the sample. To facilitate the interpretation of results, “inverted” CT values (40 – CT) were used, so that higher values represented a greater load of the agent, aligning with the expectation that a higher presence of the pathogen would be associated with an elevated risk of mortality.
The Linear Regression model, fitted on the entire dataset, demonstrated an explanatory capacity of approximately 38.59% of the mortality variability, as indicated by the coefficient of determination (R²). Although this capacity is considered limited for complex biological data, the overall statistical significance of the model was highly expressive (p < 0.001), confirming that the selected variables establish a mathematically solid relationship with the mortality rate. The statistical validity of the model was corroborated by the analysis of residuals, which showed an approximately normal distribution in most of the sample, with deviations at the upper extremes associated with cases of high mortality, and a unimodal and symmetric histogram, centered at zero, indicating adherence to the normality assumptions (Fávero and Belfiore, 2017).
The analysis of the coefficients obtained by the Linear Regression model revealed the strength and direction of each variable’s influence on mortality. Positive coefficients indicated variables that increase mortality, while negative coefficients pointed to factors associated with its reduction. Corrected Feed Conversion stood out with the largest positive coefficient, followed by the presence of Mesomycoplasma hyopneumoniae, age at slaughter, and bacterial load (inverted CT). These findings corroborate the literature, which associates the occurrence of the pathogen, high bacterial loads, and the prolongation of the rearing cycle with a higher risk of batch mortality (Barcellos and Guedes, 2022; Halev et al., 2023).
On the other hand, variables such as batches composed exclusively of females and seasonality (months) exhibited negative coefficients, suggesting lower mortality. Lower mortality in females may be associated with their genetic origin, which confers greater sanitary and immunological uniformity to the herd. Temporal mapping revealed a continuous seasonal pattern, with the impact on mortality reaching its lowest point between January and March, increasing in autumn and reaching its peak in winter (July to August), and then declining at the end of the year. This pattern reflects the greater vulnerability of the animals in the colder months, as also described by Barcellos and Guedes (2022).
Considering the multifactorial complexity of swine mortality and the observational nature of the study, the Random Forest (RF) model was employed for the construction of the predictive model. RF, based on the aggregation of multiple decision trees, is recognized for its ability to handle the variability and complex relationships present in observational data (Zimpel et al., 2021; Magalhães et al., 2023). Optimization via GridSearch, with restriction of the maximum tree depth and elevation of the minimum number of samples per leaf, was crucial to mitigate the phenomenon of “overfitting” and improve the generalization of the model to external data not previously observed (Halev et al., 2023).
In the Random Forest model, the Corrected Feed Conversion also stood out as the variable with the greatest impact, contributing approximately 36.6% of the predictive importance. Bacterial load (inverted CT) and Daily Weight Gain assumed prominent roles, representing about 19.4% and 11.5% of the importance, respectively. The presence of Mesomycoplasma hyopneumoniae and age at slaughter were also relevant, with 10.8% and 8.5% importance. Water microbiological quality variables and seasonality components showed individual contributions of less than 5%, reinforcing the prioritization of continuous zootechnical performance indicators and direct sanitary pressure in explaining mortality variability.
Despite the good performance of the Random Forest, the observed reduction in the coefficient of determination (R²) between the training (0.6439) and test (0.3430) sets suggested the occurrence of “overfitting” or disparities in data distribution. This limitation indicates that, although the model learned the patterns in the training data well, its generalization ability to new data may be compromised. The divergence in the hierarchy of importance between RF and Linear Regression reflects the non-linear nature of mortality, where RF, by modeling complex interactions, allocates feed conversion at the top of its predictive ranking, indicating that deviations in conversion may be critical in older or pathogen-challenged batches (Atias et al., 2025).
The XGBoost model showed similar predictive performance to Random Forest, explaining approximately 31.10% of the mortality variability in the test set (R² = 0.3110). However, XGBoost demonstrated an improvement in the accuracy of estimates by reducing the distance to the training set (R² = 0.4684). This is due to its L1/L2 regularization mechanism and the reduced learning rate (0.05), which sequentially penalized the complexity of the trees, containing the propagation of residual errors and ensuring greater stability in the transition to unobserved data (Madhuri and Deshpande, 2024).
A significant operational advantage of XGBoost is its native ability to manage missing data, eliminating the need for artificial imputation and preserving the integrity of observed information. The detection of Mesomycoplasma hyopneumoniae assumed the top importance in XGBoost, accounting for 27.3% of the algorithm’s purity gain, followed by bacterial load (inverted CT, 24.0%) and Corrected Feed Conversion (21.8%). The relevance of the outcome_mycoplasma variable, even with a considerable volume of missing data, suggests that both the presence of the pathogen and a possible selection bias in its monitoring may be associated with variations in mortality.
The comparative analysis of accumulated mortality in batches positive and negative for Mesomycoplasma hyopneumoniae, in relation to the overall average of the flock, revealed that the positive batches systematically remained above the historical average. This finding underscores the direct impact of the pathogen on flock viability and suggests that the monitoring strategy may be directed at batches that already show clinical signs, justifying the high relevance of this variable in predictive models. In contrast, the curve of negative batches predominantly oscillated near or below the general average, validating the sampling and demonstrating that the monitoring was not restricted only to problematic batches, but also included healthy batches, lending greater credibility to the models’ inferences.
The consistency of the results among the three models, despite their structural differences, reinforces the reliability of the identified variables. Linear Regression, Random Forest, and XGBoost presented similar predictive and statistical performances in their validation metrics, with the proximity of R², MAE, and the significance of the F-Statistic across all approaches. This convergence of results, especially the prominence of Corrected Feed Conversion, the presence of Mesomycoplasma hyopneumoniae, and the inverted CT, consolidates these factors as crucial risk indicators for mortality in swine farming.
Although the developed models have shown promising results in identifying production and biosecurity patterns that contribute to mortality, the multifactorial complexity of mortality in the finishing phase suggests that the inclusion of additional sanitary and management variables could further enhance predictive performance. The integration of diagnostics for other pathogens of the swine respiratory complex, such as swine influenza virus, Pasteurella multocida, and Actinobacillus pleuropneumoniae, could capture synergistic interactions that worsen the clinical picture. Furthermore, monitoring systemic and enteric agents, along with management and environmental variables such as vaccination, water intake, temperature, population density, and air quality, could refine the models’ sensitivity in early detection of deviations.
In summary, predictive modeling, particularly the XGBoost algorithm due to its ability to manage missing data, proved to be an effective tool in assessing mortality risks in swine farms. The results confirmed the importance of Mesomycoplasma hyopneumoniae infection and zootechnical indicators such as Corrected Feed Conversion and age at slaughter in explaining mortality variability, reinforcing the need for routine laboratory diagnostics and multifactorial risk management to optimize management and biosecurity strategies in the production cycle.
4. Conclusion
This study evaluated the importance of Mesomycoplasma hyopneumoniae infection and zootechnical variables in mortality on growing and finishing farms, using Machine Learning models. It was found that the Linear Regression, Random Forest, and XGBoost algorithms presented similar explanatory capacity, accounting for approximately 35% of the mortality variability. The presence of M. hyopneumoniae and the inverted cycle threshold stood out as important sanitary indicators, while the Corrected Feed Conversion and age at slaughter were identified as the main production indicators. It was observed that batches positive for M. hyopneumoniae systematically remained above the historical average mortality, evidencing the pathogen’s direct impact on flock viability. The consistency of results among the models reinforces the reliability of the identified variables, consolidating them as crucial risk factors. Predictive modeling, with the XGBoost algorithm demonstrating better operational performance due to its native capability to manage missing data, acts as an effective tool in evaluating mortality risks, offering decision support and prioritizing preventive interventions in swine farming.
Despite the advances, the explanatory capacity of the models was considered limited for the complexity of biological data, and the Random Forest model showed signs of overfitting. The multifactorial complexity of mortality in the termination phase suggests that the inclusion of additional sanitary and management variables could improve predictive performance. For future studies, the integration of diagnostics for other pathogens of the swine respiratory complex, such as swine influenza virus, Pasteurella multocida, and Actinobacillus pleuropneumoniae, is recommended in order to capture synergistic interactions. Monitoring of systemic and enteric agents, as well as management and environmental variables, including vaccination, water consumption, temperature, population density, and air quality, is also suggested. Such inclusions could refine the sensitivity of the models in the early detection of deviations that increase herd mortality, reinforcing the need for routine laboratory diagnostics and multifactorial risk management to optimize management and biosecurity strategies in the production cycle.
Bibliographic References
ABPA. 2025. Relatório Anual 2025. Associação Brasileira de Proteína Animal, São Paulo, SP, Brasil. Disponível em: https://abpa-br.org/wp-content/uploads/2025/04/ABPA.-Relatorio-Anual-2025.pdf. Acesso em: 05 nov. 2025.
Atias, D.; Ashri, S.; Goldbourt, U.; Benyamini, Y.; Gilad-Bachrach, R.; Hasin, T.; Gerber, Y.; Obolski, U. 2025. Machine learning in epidemiology: An introduction, comparison with traditional methods, and a case study of predicting extreme longevity. Annals of Epidemiology 110: 23-33.
Barcellos, D.E.S.N.; Guedes, R.M.C. 2022. Doença dos Suínos. 3ed. Edição dos autores, Porto Alegre, RS, Brasil.
Batista, L.; Pijoan, C.; Ruiz, A.; Utreta, V.; Dee, S. 2007. Assessment of transmission of Mycoplasma hyopneumoniae by personnel. Journal of Swine Health and Production 12: 75-77.
Fávero, L.P.L.; Belfiore, P.P. 2017. Manual de análise de dados: estatística e modelagem multivariada com excel, SPSS e stata. 1ed. Elsevier, Rio de Janeiro, RJ, Brasil.
Google Cloud. 2024. O que é análise preditiva e como ela funciona? Disponível em: https://cloud.google.com/learn/what-is-predictive-analytics?hl=pt-BR. Acesso em: 02 nov. 2025.
Halev, A.; Martínez-López, B.; Clavijo, M.; et al. 2023. Infection prediction in swine populations with machine learning. Scientific Reports 13: 17738.
Liang, R.; Lu, Y.; Qu, X.; et al. 2020. Prediction for global African swine fever outbreaks based on a combination of random forest algorithms and meteorological data. Transboundary and Emerging Diseases 67: 935-946.
Liu, Y.; Zhuang, Y.; Ji, B.; Zhang, G.; Rong, L.; Teng, G.; Wang, C. 2022. Prediction of laying hen house odor concentrations using machine learning models based on small sample data. Computers and Electronics in Agriculture 195: 106849.
Madhuri, S.D.; Deshpande, P.S. 2024. A review of predictive analytics: Techniques, advantages, related works and applications. Journal of Advanced Artificial Intelligence 1(3): 1-6.
Magalhães, E.S.; Zhang, D.; Wang, C.; Thomas, P.; Moura, C.A.A.; Trevisan, G.; Holtkamp, D.J.; Rademacher, C.; Silva, G.S.; Linhares, D.C.L. 2023. Comparing forecasting models for predicting nursery mortality under field conditions using regression and machine learning algorithms. Smart Agricultural Technology 5: 100280.
Merca, C.; Clemensson Lindell, I.; Ernholm, L.; Eliasson Selling, L.; Nunes, T.P.; Sjölund, M.; Dórea, F.C. 2022. Veterinary syndromic surveillance using swine production data for farm health management and early disease detection. Preventive Veterinary Medicine 205: 105659.
Paploski, I.A.D.; Bhojwani, R.K.; Sanhueza, J.M.; Corzo, C.A.; VanderWaal, K. 2021. Forecasting viral disease outbreaks at the farm-level for commercial sow farms in the U.S. Preventive Veterinary Medicine 196: 105449.
Shamsabardeh, M.; Martínez-López, B.; O’Hara, K.C. 2022. Machine Learning Framework for Porcine Reproductive and Respiratory Syndrome Outbreak Forecasting. Research Square (PREPRINT Version 1). DOI: 10.21203/rs.3.rs-1785633/v1.
Van Milgen, J.; Valancogne, A.; Dubois, S.; Dourmad, J.Y.; Sève, B.; Noblet, J. 2008. InraPorc: a model and decision support tool for the nutrition of growing pigs. Animal Feed Science and Technology 143(1-4): 387–405.
Xu, J.; Ye, J.; Zhou, S.; Xu, A. 2023. Automatic quantification and assessment of grouped pig movement using the XGBoost and YOLOv5s models. Biosystems Engineering 230: 145-158.
Zimpel, T.; Riekert, M.; Klein, A.; Hoffmann, C. 2021. Machine learning for predicting animal welfare risks in pig farming. Agricultural Engineering 76(1): [páginas não fornecidas].
Article originating from the Final Course Work of the Specialization in Data Science and Analytics of the MBA USP/Esalq
To learn more about the course, click here and access the MBX Academy platform