About Us Advertise Careers Contact Us Privacy Policy Community Guidelines
Locating… 13°C English WhatsApp Alerts Email Alerts
BREAKING NEWS
SpaceX now fundamentally an "infrastructure company," senior official says UK Government Investment Secures More Than 25% Stake in SaxaVord AI agents test and improve robot code in virtual worlds before deployment CCIA Report Highlights Satellite Connectivity’s Potential to Expand Internet Access and Drive Economic Growth Four half centuries carry new-look Pakistan to 281-5 against Sri Lanka in 1st test - Seattle Post-Intelligencer Winter could cut electric air taxi range by up to 22%, simulations suggest Advanced coating can alter a drone's radar signature A single AI model simulates the behavior of many substances, from sliding sand to folding proteins New body-actuation interface for faster movement initiation while maintaining user control Astronauts Across Generations Share the Stage
SRI LANKA NEWS

Machine learning-based prediction of subclinical mastitis in large-scale dairy herds using a locally established somatic cell count threshold - Nature

Lanka Hit News • Apr 28, 2026 · 6mo ago • 52 min read
Share:

Thank you for visiting nature.com. You are using a browser version with limited support for CSS. To obtain the best experience, we recommend you use a more up to date browser (or turn off compatibility mode in Internet Explorer). In the meantime, to ensure continued support, we are displaying the site without styles and JavaScript.

You have full access to this open access article

This study aims to establish a somatic cell count threshold to identify cows with subclinical mastitis (SCM) and to develop a machine learning model to predict the incidence of SCM using individual cow data, milk production and composition data. Milk samples were collected from a total of 2420 lactating cows from three large scale dairy herds (A: n = 1002; B: n = 898; and C: n = 520), for California Mastitis Test (CMT), Somatic Cell Count (SCC) determination, and milk composition analysis. Information on individual cows and their milk production was obtained from farm records. The diagnostic SCC threshold was identified on the basis of CMT scores using the Youden’s index. Two methodological approaches were employed: Method one with all variables (M1) and Method two with four selected variables (M2) to select the most appropriate models for predicting SCM. The SCC threshold yielding the highest Youden’s index was 353,000 cells/mL. For M1, XGBoost, an efficient gradient boosting ML algorithm that handles complex, nonlinear relationships in data, showed the highest accuracy (77.3%). Milk conductivity consistently emerged as the most influential predictor across nearly all the algorithms, followed by lactation number (Lac. No.), and milk density. In M2, the overall performance decreased, with CatBoost, a gradient boosting algorithm which handles categorical variables efficiently, achieving the highest accuracy (70.8%). Lac. No. and testday milk yield (Testday MY) were the most important predictors in M2. Overall, the results show that integrating a SCC threshold of 353,000 cells/mL together with key predictors such as milk conductivity enables machine learning models to support practical and reliable basis for early detection of subclinical mastitis in dairy herds.

Subclinical mastitis (SCM) is a significant production-related disease in dairy cows that is associated with decreased milk yield and diminished milk quality 1 . SCM is characterized by elevated somatic cell counts (SCC) in milk; however, it presents without visible abnormalities in milk or the udder and without detectable clinical signs in cows 2 . In addition to reduced milk production and quality, SCM leads to substantial economic losses due to increased treatment costs, additional labor, milk discarding following treatment, and premature culling 3 , 4 , 5 . In Sri Lanka, during the third quarter of 2023, mastitis cases were reported across all nine provinces of the country, totaling 3702 cases, a 6.7% increase compared with the same period in the previous year 6 . In response, the Department of Animal Production and Health (DAPH) has implemented a mastitis control program through veterinary investigation offices in each district, providing field and laboratory mastitis identification tests, microbial culture, isolation and antibiotic susceptibility testing. Early detection of SCM remains essential for effective mastitis control in the country.

Establishing a threshold level for SCC is critical for distinguishing infected cows from uninfected cows. A SCC less than 200,000 cells/mL of milk is considered indicative of a healthy quarter, whereas counts equal to and exceeding 200,000 cells/mL strongly suggest the presence of infection 7 , 8 , 9 . However, it has been also reported that the first lactation cows typically exhibit mastitis at a lower SCC 10 . Global studies have reported varying SCC threshold values for SCM identification 11 , 12 , 8 , and specific SCC threshold information applicable to Sri Lanka is lacking. Thus, establishing a SCC threshold to identify SCM in Sri Lankan dairy cows is essential. In large Sri Lankan dairy herds, the SCC for individual cows is not recorded during milk collection. Instead, the California Mastitis Test (CMT) is routinely conducted in these herds. The CMT is a rapid, cow-side test in which a reagent (detergent) lyses somatic cells in milk and the released DNA and protein cause a formation of a gel. The strength of the gel is scored visually and is used as an indirect indicator of SCC and SCM.

Machine learning (ML), a branch of artificial intelligence, encompasses methods that allow machines (computers) to automatically perform tasks on the basis of data and experience without explicit programming. ML is often considered a valuable decision-support tool, especially in situations where conventional algorithms are challenging or infeasible to apply 13 . Machine learning models range from simple approaches, through intermediate methods, to advanced techniques. Logistic regression (LR), a simplified form of the generalized linear model, performs binary classification by applying a binomial family with a logit link and can accommodate both numerical and categorical predictors 14 . Decision trees (DT) identify patterns by recursively partitioning data based on the most informative attributes 15 , 16 , while random forests (RF) enhance predictive performance by aggregating the results of multiple randomly generated trees 17 . K-nearest neighbors (KNN) classifies animals by comparing them to the most similar cases in the feature space, though its performance is often surpassed by ensemble methods 18 . Support vector machines (SVM) has also been used effectively for mastitis detection, demonstrating high accuracy and sensitivity when somatic cell count is used as an indicator 19 . Neural networks (NN) learn complex, non-linear relationships through interconnected computational layers that mimic biological neural processing 19 . More advanced ensemble models such as XGBoost and CatBoost apply gradient boost strategies to capture intricate interactions among physiological, production, and behavioral variables with CatBoost offering particular advantages for handling categorical data 20 , 21 . Naïve Bayes (NB), despite its simplifying independence assumptions, remains a fast, efficient method capable of producing reliable results even with limited datasets. Collectively, these machine learning approaches offer complementary strengths for predicting subclinical mastitis in dairy cows 22 .

Studies have shown that ML algorithms can effectively predict udder health status, aiding in decision-making for dairy farmers 9 . An example of an ML application in mastitis prediction is MasPA, an open-source software that uses the random forest algorithm to assess mastitis risk in cattle 23 . Different data sources have been utilized in developing ML models for SCM, including AMS (Automatic Milking Systems) sensor data 11 , 23 and SCC 9 . To date, no studies have investigated data relevant to the Sri Lankan context. Therefore, the present study aimed to establish an SCC threshold for identifying cows with SCM based on CMT scores and to develop a machine learning model that can predict the incidence of subclinical mastitis using the estimated SCC threshold. The model considers individual cow data, milk production, milk composition, and the SCC, which are tailored to the Sri Lankan dairy sector.

Several threshold values between 353,000 and 550,000 cells/mL were associated with the highest Youden’s index of 0.81. To minimize the false negative diagnoses, where SCM cases might go undetected, the threshold with the highest sensitivity within this range, 353,000 cells/mL was selected as the threshold. This value ensures a greater likelihood of identifying cows positive for SCM while maintaining diagnostic accuracy. Considering the above threshold, the overall prevalence of SCM was 39.8% on the three farms studied.

The descriptive statistics of the individual cow data and milk composition data are presented in Tables 1 and 2 .

Pearson correlation analysis revealed high correlations (|r| > 0.8), particularly between farm and Jersey-Friesian breed population ( r = 0.843) and between average daily milk yield over the preceding seven days [Avg (7 days) Daily MY] and testday milk yield (Testday MY) ( r = 0.893). Variation Inflation Factor analysis further confirmed severe multicollinearity (VIF ≥ 10) among multiple breed related categories, while farm. Avg (7 days) Daily MY, and Testday MY exhibited high multicollinearity (5 ≤ VIF < 10) (Table 3 ). Condition index analysis also indicated severe multicollinearity (Condition Index ≥ 30), and the first eigenvalue (4.7464) suggested that 4–5 variables such as Avg (7 days) Daily MY, Testday MY, and possibly farm or breed clustered tightly, reflecting substantial redundancy. Based on these findings all breed-related variables and farm were excluded from subsequent analyses. However, Avg (7 days) Daily MY and testday MY were retained, as these measures are routinely accessible, testday MY being the most accurate, and Avg (7 days) Daily MY capturing longer term SCC trends in large scale dairy herds.

The performance of the evaluated ML models, run for the test set, was assessed across multiple classification metrics, as presented in Fig. 1 . The highest accuracy was observed with the XGBoost model, with a value of 0.77.3, indicating that it correctly classified 77.3% of SCM cases, followed closely by CatBoost (75.9%), RF (75.5%), SVM (74.8.%), LR (73.8%) and NN (73.4%). NB yielded the lowest accuracy (55.5%), indicating limited predictive power compared with the other models. The precision peaked at 0.784, reflecting the ability of the SVM model to minimize false positives. Significantly outperforming other models in this metric, the highest recall was recorded for the NB model at 0.896, showing its effectiveness in identifying actual positive instances. For the F1 score, which provides a harmonic mean of precision and recall, NN ranked the highest at 0.689, suggesting a well-rounded performance with gradual improvement over time. Across all models, NB achieved the highest negative predictive value (NPV) of 0.826, meaning that when the model predicted a cow to be healthy, this prediction was correct 82.6% of the time, followed by NN (NPV = 0.808) and XGBoost (NPV = 0.781). Among all the models evaluated, XGBoost exhibited the most consistent and well-rounded performance across all the metrics, particularly excelling in accuracy while maintaining strong precision and F1 scores. The NB model showed surprising strength in terms of the recall and NPV despite its lower accuracy and precision. These results collectively indicate that XGBoost is likely the best overall model for this classification task, with CatBoost and NN serving as strong alternatives depending on which metric is prioritized. Two ensemble strategies: a weighted probability blend and a union rule approach were explored to investigate whether the high recall of NB could be combined with the accuracy of XGBoost to produce a more clinically useful model. This ensemble produced an accuracy of 0.719, precision of 0.708, recall of 0.505, F1 of 0.590, NPV of 0.724, and AUPRC of 0.731, a substantial decline compared to standalone models, indicating that blending the probability outputs of the two models suppressed rather than preserved the accuracy and recall of standalone models.

The comparison of accuracy, precision, recall, F1 and negative predictive value (NPV) for nine predictive models [logistic regression (LR), decision tree (DT), random forest (RF), k-nearest neighbors (KNN), support vector machine (SVM), neural network (NN), XGBoost, CatBoost and Naïve Bayes (NB)], run on the testing set, in prediction of subclinical mastitis in method 1 (M1).

Overall, the train–test gaps indicated no major overfitting, demonstrating model stability. LR showed balanced behavior, with training (72.4%), cross-validation (72.2%), and test accuracy (73.8%) all closely aligned. The DT showed a moderate drop from training accuracy (73.5%) to cross-validation and test performance (both 69.0%). RF displayed stronger learning capacity, achieving 78.3% on training and maintaining good generalization with 72.8% cross-validation accuracy and 75.5% on the test set. KNN showed higher training accuracy (78.5%) but lower cross-validation (69.7%) and test (69.9%) performance, reflecting sensitivity to data variability. SVM demonstrated excellent consistency, with nearly matched training (71.7%) and cross-validation (71.5%) accuracy and improved generalization on the test set (74.8%). NN also generalized well, with training (74.0%), cross-validation (72.8%), and test accuracy (73.4%) showing minimal divergence.

Among ensemble methods, XGBoost achieved the highest training accuracy (85.6%) while maintaining strong cross-validation (74.1%) and the highest test accuracy (77.3%), indicating effective learning without harmful overfitting. CatBoost followed closely, achieving 78.9% on training, 74.7% on cross-validation, and 75.9% on the test set. NB, as expected for a simple probabilistic model, showed lower overall performance, with training (53.3%), cross-validation (58.9%), and test accuracy (55.5%) remaining consistent.

Overall, the progression from training to cross-validation to test results confirms that the models exhibit strong generalization, with XGBoost, CatBoost, RF, SVM, and NN performing particularly well across all evaluation stages.

The area under the curve (AUC) metric quantifies each model’s ability to distinguish between positive and negative classes. In contrast, the area under the precision-recall curve (AUPRC) quantifies each model’s ability to retrieve positive cases with high precision across different classification thresholds. AUPRC metrics are more informative and are useful when dealing with imbalanced datasets, where accuracy alone can be misleading. As shown in Figs. 2 and 3 , when run on the test set, CatBoost demonstrated the highest AUC and AUPRC (0.812 and 778, respectively), indicating superior discriminating ability in balancing true positive rates against false positive rates. XGBoost followed closely with an AUC of 0.804 and AUPRC of 0.775 confirming the strength of gradient boosting methods for this classification task. KNN (AUC = 0.712; AUPRC = 667) demonstrated the lowest discriminative power among the evaluated models. The curves visually confirmed these rankings, with CatBoost and XGBoost consistently achieving higher true positive rates while maintaining lower false positive rates across most threshold values. Overall, ensemble methods (particularly boosting algorithms) emerged as the most effective approaches for these classification tasks, with CatBoost providing the optimal balance of sensitivity and specificity.

Comparing Receiver Operating Characteristic (ROC) curves of nine machine learning models [logistic regression (LR), decision tree (DT), random forest (RF), k-nearest neighbors (KNN), support vector machine (SVM), neural network (NN), XGBoost, CatBoost and Naïve Bayes (NB)], run on the testing set, in prediction of subclinical mastitis in method 1 (M1).

Comparing Precision-Recall curves of nine machine learning models [logistic regression (LR), decision tree (DT), random forest (RF), k-nearest neighbors (KNN), support vector machine (SVM), neural network (NN), XGBoost, CatBoost and Naïve Bayes (NB)], run on the testing set, in prediction of subclinical mastitis in method 1 (M1).

On the basis of all the ML models analyzed, conductivity (mS/cm) consistently emerged as the most significant predictor for the detection of SCM (Fig. 4 ). This finding was particularly pronounced in all the models, where conductivity demonstrated substantially higher importance scores than the other features did. The second most important feature was the lactation number (Lac. No.) followed by milk density (density). The NB model uniquely prioritized testday MY as its primary feature, suggesting that different algorithms may identify complementary indicators of infection. The ensemble methods (RF, XGBoost and CatBoost) showed more balanced feature importance distributions than single models such as DT and SVM did, suggesting that they leveraged multiple indicators more effectively.

The performance of the models of M2 was evaluated across multiple classification metrics similar to those of M1 (Fig. 5 ). The accuracy across the models, run on test set, ranged from 0.629 to 0.708, with the CatBoost model achieving the highest accuracy of 70.8%, followed by LR at 70.6% and RF at 70.0%. In terms of precision, which quantifies the proportion of true positive predictions among all positive predictions, the SVM performed best at 69.9%, closely followed by the LR at 69.8% and the CatBoost at 69.1%. These similar values indicate comparable effectiveness in minimizing false positives across these three models. Recall, the model’s ability to identify actual positive instances, ranging from 0.373 to 0.642, with the NB and NN models clearly outperforming others at 64.2%. This represents a significant advantage in capturing positive cases, although all the models showed relatively low recall overall. The F1 score peaked at 0.600 with the NN model, followed by NB at 0.593. NN also achieved the highest NPV in M2 at 0.738, followed by NB at 0.733. Overall, while CatBoost delivered the best accuracy and strong precision, the NN model demonstrated the highest recall, F1 score and NPV.

Overall weights of milk production, composition parameters and cow factors in prediction of subclinical mastitis based on nine machine learning models [logistic regression (LR), decision tree (DT), random forest (RF), k-nearest neighbors (KNN), support vector machine (SVM), neural network (NN), XGBoost, CatBoost and Naïve Bayes (NB)], run on the testing set, in method 1 (M1).

The comparison of accuracy, precision, recall, F1 and negative predictive value (NPV) for nine predictive models [logistic regression (LR), decision tree (DT), random forest (RF), k-nearest neighbors (KNN), support vector machine (SVM), neural network (NN), XGBoost, CatBoost and Naïve Bayes (NB)], run on the testing set, in prediction of subclinical mastitis in method 2 (M2).

The performance of the M2 models was evaluated across training, cross-validation, and test sets using methodology consistent with M1. Training set performance showed moderate variation across models. KNN achieved the highest training accuracy (73.2%), followed by XGBoost (75.7%) and RF (71.4%). CatBoost reached 69.7% training accuracy, while DT achieved 70.5%. Simpler models showed more conservative training performance: LR (67.8%), SVM (66.5%), NN (65.5%), and NB (62.4%).

Cross-validation performance ranged from 59.6% to 67.7%. The LR model achieved the highest cross-validation accuracy (67.7%), followed by NB (67.1%) and NN (66.7%). SVM demonstrated stable performance at 66.5%, while RF and CatBoost both achieved 65.9%. XGBoost reached 63.9%, DT 63.0%, and KNN showed the lowest cross-validation performance at 59.6%. Notably, several models showed superior test performance compared to cross-validation, indicating effective generalization rather than overfitting.

The ROC and Precision-Recall curve comparison for the M2 revealed important differences in their discriminative abilities (Figs. 6 and 7 ). The AUC metric showed that XGBoost achieved the highest performance with an AUC of 0.732, closely followed by RF an AUC of 0.730 and CatBoost with an AUC of 0.728. As far as AUPRC is concerned, RF achieved the highest AUPRC of 0.672, followed closely by CatBoost with an AUPRC of 0.667, indicating that gradient boosting methods retained their relative advantage even under the conditions of this dataset. KNN clearly underperformed with the lowest AUC of 0.641 and AUPRC of 0.534 approaching random classification in some regions of the curve. The visual representation confirmed that XGBoost, CatBoost, and RF maintain the most favorable balance between sensitivity and specificity across different threshold values. Overall, XGBoost and RF emerges as the most effective models for this particular classification task, with CatBoost being next, demonstrating better discrimination ability.

Comparing receiver operating characteristic (ROC) curves of nine machine learning models [logistic regression (LR), decision tree (DT), random forest (RF), k-nearest neighbors (KNN), support vector machine (SVM), neural network (NN), XGBoost, CatBoost and Naïve Bayes (NB)], run on the testing set, in prediction of subclinical mastitis in method 2 (M2).

Comparing precision-recall curves of nine machine learning models [logistic regression (LR), decision tree (DT), random forest (RF), k-nearest neighbors (KNN), support vector machine (SVM), neural network (NN), XGBoost, CatBoost and Naïve Bayes (NB)], run on the testing set, in prediction of subclinical mastitis in method 2 (M2).

In M2, the comparative analysis of feature importance across multiple ML models is shown in Fig. 8 . Lac. No. emerged as a particularly influential feature in several models (LR, SVM, XGBoost, CatBoost and NB). However, the magnitude of this dominance varied substantially between models, from overwhelming in SVM to more balanced in ensemble methods. In contrast, tree-based models including DT and RF prioritized milk production metrics with Avg (7 days) Daily MY and Testday MY. Similarly, the KNN model assigned the greatest importance to Avg (7 days) Daily MY. Days in milk (DIM) consistently ranked as the least important feature across most models, with the exception of KNN where it surpassed Lac. No. However, its relative contribution varied from negligible in SVM to modest in ensemble methods such as XGBoost and CatBoost. This variation in feature importance across algorithms highlights the value of employing multiple modeling approaches when analyzing dairy production data. The ensemble methods (RF, XGBoost, catBoost) demonstrated more balanced feature utilization overall, suggesting that they may capture more complex interactions between animal characteristics and production metrics than simple algorithms do.

Overall weights of lactation number, testday milk yield, average (7 days) daily milk yield and days in milk in prediction of subclinical mastitis based on nine machine learning models [logistic regression (LR), decision tree (DT), random forest (RF), k-nearest neighbors (KNN), support vector machine (SVM), neural network (NN), XGBoost, CatBoost and Naïve Bayes (NB)], run on the testing set, in method 2 (M2).

The aim of the current study was to establish a threshold somatic cell count to identify cows affected with SCM and to develop a model to predict SCM in dairy cows using ML techniques. Given the high prevalence of subclinical mastitis in dairy cows the application of SCC as a diagnostic screening tool for detecting SCM at the individual cow level is highly relevant for both dairy farmers and veterinarians. However, a SCC threshold for accurately identifying SCM in dairy cows has not been established in the country. This study demonstrated how predictive models can be applied to identify subclinical mastitis, with the goal of determining which model provides the most accurate predictions. The outcome of this from this study revealed the importance of the EC of milk as a predictor for early subclinical mastitis detection.

The primary objective of selecting an appropriate threshold for defining SCM is to identify cows that are positive for SCM. Employing lower threshold values enhances the sensitivity of detection, thereby reducing the likelihood of false negative results. Conversely, applying higher thresholds increases the specificity of the test, which minimizes the occurrence of false positive diagnoses 24 . Various somatic cell count thresholds have been proposed across different countries for the identification of SCM in dairy cows. A commonly accepted cow level SCC threshold is 200,000 cells /mL, which is widely used to indicate intramammary infections at the individual cow level 25 . However, a lower threshold (100,000 cells/mL) has also been suggested to detect intramammary infections in lactating dairy cows in Bangladesh where mastitis pathogens are abundant 8 and in a Hessian dairy cow population in Germany 26 . Similarly, higher threshold levels such as 150,000 cells/mL in South African dairy herds 27 , 250,000 cells/mL in Ireland 28 or 300,000 cells/mL in Belgium 29 have been reported. Considering these regional variations in somatic cell count thresholds, we were motivated to establish an appropriate threshold relevant to the Sri Lankan context. In the present study, the optimal SCC threshold for identifying subclinical mastitis was 353,000 cells/mL, which is slightly higher than the thresholds reported in previous studies. At this threshold, the sensitivity and specificity were 91.7% and 88.8%, respectively. The sensitivity achieved was notably greater than those reported by Sumon et al. 8 and Sargeant et al. 30 , who reported sensitivities of 53.1% and 57.4%, respectively, using a lower threshold of 100,000 cells/mL. While the specificity in the current study was lower than that reported by Sumon et al. 8 i.e. 95.7%, which probably had daily observations of milk yield, milk component measurement, and SCC, it exceeded the specificity reported by Sargeant et al. 30 , which was 72.3%. A comparable study by Souza et al. 31 , which employed a higher SCC threshold (> 500,000 cells/mL) for composite milk samples, reported a lower Youden index (0.536) and sensitivity and specificity values of 65.7% and 87.9%, respectively. Considering the above findings, a SCC threshold of 353,000 cells/mL may be deemed an appropriate benchmark for identifying SCM in large commercial dairy herds of Sri Lanka. The somatic cell count threshold identified in this study is higher than the internationally accepted threshold of 200,000 cells/mL. This difference may be attributed to several context-specific factors. One possible explanation is the prevalence of chronic intramammary infections caused by pathogens such as Staphylococcus aureus , which generally cause the greatest increase of SCC at the herd level 32 . A previous study conducted within the same herds identified Staphylococcus aureus as the most prevalent pathogen 33 . Additionally, tropical environmental conditions characterized by high temperature and humidity may increase environmental pathogen load and result in continuous immune stimulation, thereby elevating SCC even in clinically normal cows. Furthermore, variations in farm management practices, including milking hygiene and housing conditions, may contribute to increased background SCC levels. Collectively, these factors may shift the optimal diagnostic threshold upward, making a higher SCC cut-off. Consequently, a higher threshold may more accurately distinguish truly infected cows from physiologically normal ones under these conditions. However, this adjustment also carries a potential risk, as cows with mild subclinical mastitis (those with SCC levels between 200,000 and 353,000 cells/mL) may go undetected and untreated, thereby serving as reservoirs of infection within the herd. Furthermore, this proposed threshold may not be equally suitable for first-lactation cows, as they often develop mastitis at comparatively lower SCC, suggesting that a lower SCC cutoff may be more appropriate for this group 10 .

The application of ML algorithms has introduced advanced data-driven approaches for analysing complex datasets of dairy production systems. These methods have shown considerable potential in improving decision support tools, particularly for the early detection and prediction of mastitis. Various ML techniques have been employed to detect both clinical and subclinical mastitis and these models are capable of capturing complex, nonlinear relationships among variables, thereby improving diagnostic accuracy and facilitating timely interventions 34 , 35 , 36 , 37 , 38 , 11 , 9 . In the present study, we attempted to predict the SCM status of cows on the day of data collection using individual cow data, milk production data and composition data. Generally, several evaluation metrics such as accuracy, precision, recall, F1 score and NPV, are used to evaluate the performance of ML methods. Accuracy, one of the most commonly used metrics, represents the number of correct predictions made by the model over the total number of predictions 9 , 11 . However, accuracy alone may not be sufficient to evaluate model performance. If it aims to minimize false negatives or false positives, evaluation on the basis of metrics such as recall or precision, respectively, may be needed. Furthermore, the F1 score which is the harmonic mean of both precision and recall, is useful for obtaining the model with the best performance 39 , 40 . In addition to standard classification metrics described above, NPV quantifies the probability that a cow classified as healthy by the model is genuinely free of SCM, which is of particular practical relevance in a farm management context. In the current study, considering accuracy and precision, XGBoost and SVM appeared to be the best models, respectively, NB showed the best performance in terms of recall and NPV, while NN was the best model for F1, in identifying the SCM in M1. In M2, CatBoost and SVM demonstrated the best accuracy and strong precision, respectively, the NN and NB models showed superior recall and NN model showed the highest NPV and F1 score, suggesting that those might be the better choices for applications where identifying positive cases is critical. In contrast, Cavero, et al. 38 reported that the performance of the NN was suboptimal, likely because the available input features lacked sufficient mastitis related information for early detection of mastitis. The models of M2 generally exhibited moderate accuracy and precision but showed limitations in recall and F 1, suggesting challenges with imbalanced classes or detecting positive cases. The highest prediction accuracies in the present study were 77.3% and 70.8% for M1 and M2, respectively. These values are relatively low compared with those of previous studies. A possible explanation for these comparatively lower accuracies could be the limited dataset size, differences in data quality, herd variabilities and variation in the definitions of SCM. Bobbo et al. 9 reported more than 75% prediction accuracies for all the best performing models: the NN, RF, linear discriminant analysis and generalized linear model. An accuracy of 84.9% was reported by Ebrahimi et al. 11 for the gradient boosted tree model based on milking parameters. SCM was detected with an accuracy of 81% using SVM or RF models in a study conducted by Motohashi et al. 41 in Japan. To identify cows positive for clinical mastitis during the first lactation and for the daily continuous prediction of the onset of clinical mastitis, it has been reported that the RF algorithm has performed better than XGBoost algorithm, with 71% and 85% accuracy, respectively 36 . Recall (sensitivity) reflects the model’s ability to correctly identify cows with subclinical mastitis. In the context of subclinical mastitis detection, false negatives are of greater concern than false positives, as undetected infected cows may proceed to clinical mastitis, contribute to disease persistence and transmission within the herd. Although false positives may lead to unnecessary testing or minor additional costs, their impact is relatively limited compared to false negatives. Therefore, greater emphasis should be placed on recall in evaluating the model. The observed high recall of NB (0.896) suggests that the model is effective as a screening tool for early detection of subclinical mastitis in large scale dairy herds. The highest precision score reported in the current study was greater than that of the study reported by Bobbo et al. in 2021 9 (0.706) for SVM and lower than the scores reported by Ebrahami et al. in 2019 11 for all the models tested. With relevance to NPV, the highest value obtained in the current study (0.826) is comparable to the value (0.846) reported by Bobbo et al. in 2021 9 . Recall and F1 scores of many models reported in the current study are greater than those reported in previous studies, highlighting the significance of the selected models in enhancing the prediction of SCM in large-scale dairy systems 11 , 42 . Continued infection in affected cows may result in a reduction in milk yield of approximately 10–20% during the remaining lactation period. Based on field estimates, we have estimated that the economic impact of a false negative mastitis case could range from LKR 20,000–40,000 per cow primarily due to reduced milk production. Previous findings have indicated that milk loss accounts for the majority (94%) of the total economic losses associated with clinical mastitis 43 . In the Sri Lankan context, additional costs may include treatment and labour expenses. In contrast, the economic consequences of false positive cases are likely to be minimal, largely limited to labour costs associated with additional handling or testing, which are negligible compared to the substantial losses incurred due to false negatives.

The AUC is another widely used metric for the evaluation of classification problems, and it has the advantages of being independent of the outcome rate, as does Matthew’s correlation coefficient (MCC) 9 . In the present dataset, in M1, CatBoost demonstrated the highest AUC of 0.812. Ebrahimi et al. 11 reported a higher AUC value of 0.826 for the DT model and Ullomi 44 reported lower AUC values than did the current study (0.686).

The performance of the ML models was evaluated via several metrics, and the results revealed that the models with the best performance included all the collected parameters (M1). The models with selected parameters (M2) presented lower values for accuracy, precision, recall, F1 and NPV. This finding is in agreement with that of Bobbo et. al. 9 , who reported that all 15 selected features were relevant in predicting the outcome and recursive feature elimination revealed that the accuracy increased with increasing number of features included. Most of the dairy farms do not have automated milk recording systems and do not measure the milk composition or other features in individual cows. Therefore, we intended to develop a prediction model for SCM that considers mostly available features such as Lac. No., DIM, Avg (7 days) Daily MY and Testday MY (M2).

In M1, which was based on all the parameters analyzed, conductivity emerged as the most significant predictor for the detection of the SCM across nearly all the algorithms. Ebrahimi et al. 11 also reported that electrical conductivity has the highest weight in the prediction of SCM. In another study of feature selection, the selected top eight features were related to electrical conductivity 41 . These findings align with the established knowledge that the electrical conductivity of milk increases with mastitis due to elevated ion concentrations resulting from inflammatory processes. This multifeatured approach provides a more comprehensive detection system than does relying on a single parameter 45 . This comprehensive analysis supports development of multiparameter screening tools for dairy farmers, with electrical conductivity serving as the primary but not exclusive indicator for SCM detection.

The Lac. No. has emerged as a particularly influential feature in several models, suggesting that the physiological maturity and reproductive history of dairy animals play fundamental roles in production outcomes. Further, the results of the present study agree with a previous study that reported associations between parity 33 and SCM. In contrast, tree-based models include prioritized milk production metrics, with Testday MY ranking the highest. This pattern indicates that recent production history may contain more relevant information for these algorithms than may animal characteristics. These discrepancies between linear and nonlinear models suggest that different mathematical approaches capture distinct aspects of the complex relationships within dairy production data.

This variation in feature importance across algorithms highlights the value of employing multiple modeling approaches when analyzing dairy production data. The ensemble methods (Random Forest, XGBoost and CatBoost) demonstrated more balanced feature utilization overall, suggesting they may capture more complex interactions between animal characteristics and production metrics than simpler algorithms do. These findings emphasize that model selection significantly influences which factors are identified as most predictive in dairy herd disease prediction.

The traditional methods of SCM detection such as CMT and SCC, are widely used; they are relatively low-tech, moderate-cost and effective, but can be time-consuming, subjective, or require lab facilities. The ML approach uses existing farm data and once developed and implemented, can provide rapid, low-cost predictions with consistent accuracy and potential for earlier detection, although initial investments are needed. In Sri Lanka, CMT is widely used for screening SCM, but it is subjective and influenced by the person. SCC is more objective but less accessible for most of the dairy farmers. Well trained ML models can achieve accuracy levels comparable to those of CMT and approach the SCC level performance, especially when trained with high quality farm specific data. ML also offers greater consistency as it avoids human interpretation bias. The developed ML model will be deployed in large scale dairy farmers through integration into farm management software if available or as a mobile application for farm managers enabling on-farm decision making. It will also be necessary to collect input data such as individual cow data, milk production data and milk composition data regularly. Implementation requires basic digital infrastructure, including a computer or smartphone and internet access. When the cost benefit analysis is considered, although an initial investment is needed, early detection of SCM ultimately results in a greater return on investment through improved health and productivity of cows.

A key limitation of this study is the relatively small number of data and herds included, coupled with the fact that the enrolled herds do not fully represent the local smallscale dairy herds. Consequently, the proposed SCC threshold for SCM may not be broadly generalizable. It is likely that model performance would decline when applied to herds that operate under different management systems and environmental conditions, given that the model was trained on a limited and specific dataset. To overcome current limitations, data quality can be improved by standardizing collection methods and expanding datasets through the inclusion of several farms. Model generalizability can be enhanced via external validation, transfer learning, and the inclusion of farmspecific context features. The pipeline can be strengthened with automated feature selection, continuous model monitoring, and scheduled retraining.

The current study identified an optimal somatic cell count threshold of 353,000 cells/mL for detecting SCM in Sri Lankan dairy cows. Additionally, the application of ML techniques provides a promising avenue for developing predictive models for SCM. Among the tested algorithms, XGBoost and CatBoost exhibited the highest performance in terms of accuracy and AUC, respectively whereas other models, such as NB, NN, and SVM, presented strengths across different evaluation metrics. M1, in which the models trained on all the available features in the dataset outperformed the reduced-feature method (M2), reinforcing the importance of comprehensive data collection in improving the predictive accuracy. Electrical conductivity has emerged as the most consistent and influential predictor across models, validating its utility as a key indicator of SCM. Given the limited access to automated data collection in many Sri Lankan dairy farms the development of simplified, yet effective, ML models hold significant potential for practical implementation. Overall, this study highlights the value of integrating diagnostic thresholds with data-driven ML tools for enhancing mastitis detection and control strategies in the local dairy industry.

The study was designed as a cross sectional epidemiological investigation and the individual cow was considered the experimental unit. Three commercial dairy herds located in the Nuwaraeliya district of the Central Province of Sri Lanka were included in the study. Herds were selected on the basis of the accessibility of data and willingness to participate in the study. A total of 2420 lactating cows (A: n = 1002; B: n = 898; and C: n = 520), with Lac. No. ranging from 1 to 7, were included over a six-month period from December 2022 to May 2023. The cows were primarily Holstein-Friesian, Ayrshire, and their crosses, housed in free-stall barns and managed under an intensive system (cows were kept in barns for 24 h while supplying feed). Each herd was milked three times daily using machine milking, with average milk yields of 17, 27, and 30 L per cow across the three farms. All the cows were provided cut-and-carry feed along with supplemental concentrates, vitamins, and mineral mixtures tailored to their production levels. Cows displaying visible udder or milk abnormalities, clinical mastitis, or other diseases at the time of examination were excluded from the study. All eligible lactating cows present in the selected herds during the study period were included.

Two 15 mL centrifuge tubes were prepared one with potassium dichromate preservative for somatic cell count analysis, and one without the preservative for pH and milk composition measurements for each composite milk sample collected. The preservative solution was prepared, employing safety precautions, by dissolving I g of potassium dichromate in 5.05 mL of deionized water. Fifty microliters of this mixture were dispensed into each tube at room temperature and allowed to air dry in a ventilated area at room temperature (20–25 °C) for 5–6 days. The tubes were labeled with cow ID using waterproof markers.

Each farm was visited during the noon milking period for sample and data collection. Before the milk samples were collected, the teats were thoroughly washed with a 0.5% iodine solution, wiped clean, and dried using sterile towels. Next, the teats were disinfected with 70% ethanol-soaked cotton to ensure aseptic conditions. The first few streams of milk were discarded to remove potential contaminants. Composite foremilk samples (30 ml) were then aseptically collected from all quarters into sterilized pre-labeled plastic cups. CMT was performed onsite immediately after collection. The samples were subsequently divided into two portions: one aliquot was transferred to a 15 ml centrifuge tube containing potassium dichromate as a preservative, while the other was placed in a preservative-free centrifuge tube. Both samples were mixed thoroughly, labeled, and stored in a cool box with ice packs to maintain low temperatures during transport to the Laboratory of Dairy Technology, Department of Animal Science, Faculty of Agriculture, University of Peradeniya. The transport process was completed within 5 h of collection to ensure sample integrity. In the laboratory, the samples were stored at 4 °C until analysis, during which they were thawed at room temperature. Data from individual cows, including breed, Lac. No., DIM, Avg (7 days) Daily MY and Testday MY, were retrieved from the farm’s digital record-keeping system. Herd and management-related information was gathered through interviews with farm managers via a pretested, structured questionnaire.

All experimental procedures involving cows were conducted in full compliance with the ethical guidelines established by the Ethics Review Committee, Faculty of Veterinary Medicine and Animal Science. Approval for the study was obtained prior to commencement, ensuring adherence to internationally accepted standards for animal welfare and research ethics on animal experimentation (Proposal ID - VERC-23-02). All methods were carried out in accordance with relevant institutional guidelines and regulations for animal care and use. This study is reported in accordance with the ARRIVE guidelines.

CMT was used to detect cows with SCM 46 . The test was conducted by adding 3 mL of CMT reagent to 3 mL of milk in each well of the CMT paddle. The paddle was then rotated gently in a horizontal circular motion for 60 s to thoroughly mix the reagent with the milk and allow gel formation; The results were assessed on the basis of the observed changes in the mixture’s consistency and scored according to the following criteria: 0 (negative): normal consistency with no gel formation, 1 (trace/positive): slight gel formation with a purplish-gray colour, 2 (positive): light but persistent gel formation with a purple-gray colour, 3 (positive): immediate thickening, forming a viscous cluster at the bottom of the well, and 4 (positive): thick gel with a consistency similar to egg white and a dark purple color 1 , 47 . Cows with a CMT score of ≥ 1 were classified as having SCM. To reduce variability in scoring and ensure consistency, all CMT tests were performed by the second author, who was trained in the procedure.

After thawing, the pH of each milk sample was measured using a calibrated pH meter. The composition of milk, including fat, protein, lactose, solid-non-fat (SNF), density, conductivity, salt content and freezing point was analyzed using a LACTOSCAN SP milk analyzer (Milkotronic Ltd). All analyses were conducted following the manufacturer’s instructions, with regular calibration and maintenance of the equipment to ensure reliable results.

SCC was determined using a LACTOSCAN SCC analyzer (Milkotronic Ltd.) following the manufacturer’s protocol. The milk samples were first equilibrated to room temperature before being placed in a water bath at 40 °C for 20 min. The samples were then cooled to 20 °C to optimize dye interactions. After cooling, the milk was thoroughly mixed using a vortex mixer for uniform dispersion of somatic cells. One hundred microliters of milk were carefully pipetted into prelabeled Eppendorf tubes containing Sofia Green dye. The milk-dye mixture was vortexed for 10 s to ensure homogeneity and allowed to stand for one minute to facilitate dye-cell binding. Subsequently, 8 µL of the prepared sample was precisely pipetted onto the measurement chips. The chips were inserted into the LACTOSCAN SCC device, and SCC were automatically recorded from the digital display.

Among the 2420 samples collected, 1661 were subjected to the CMT test to determine the SCC. The CMT could not be performed on the remaining samples because of time limitations during the milking process. Cows with a CMT score of 0 were classified as negative for SCM. In contrast, cows with a CMT score of 1 or higher, accompanied by a visibly normal udder and normal milk, were categorized as positive for SCM. For each somatic cell count value, sensitivity, specificity and Youden’s index 27 , were calculated using the formulas provided below. The SCC threshold value with the highest Youden’s index was identified as the optimal cutoff value for diagnosing SCM positive cows.

Sensitivity (Se): The proportion of infected cows whose SCC values were above the selected threshold [Eq. ( 1 )].

Specificity (Sp): The proportion of uninfected cows whose SCC values were below the selected threshold [Eq. ( 2 )].

TP = true-positive test result (infected cows above the SCC threshold).

FP = false-positive test result (uninfected cows above the SCC threshold).

TN = true-negative test result (uninfected cows below or equal to the SCC threshold).

FN = false-negative test result (infected cows below or equal to the SCC threshold).

Youden’s index (J) is a metric commonly used to determine the optimal threshold value for a diagnostic test. Typically, thresholds with high sensitivity and high specificity are preferred to balance diagnostic accuracy. However, sensitivity and specificity may not carry equal importance in every instance. For example, if false-negative results have more serious consequences than false-positive results do, a threshold value prioritizing higher sensitivity over specificity might be selected. Conversely, when avoiding false positives is critical, a threshold with comparatively higher specificity may be preferred. Youden’s index is particularly valuable for selecting a threshold that balances both sensitivity and specificity. It is calculated using the following formula [Eq. ( 3 )]:

The value of J ranges from 0 to 1. A test with excellent diagnostic performance achieves a maximum J value of 1, indicating perfect sensitivity and specificity. In contrast, a value of 0 reflects a test with no diagnostic utility. The SCC threshold value with the highest Youden’s index was identified as the optimal cutoff value for diagnosing SCM positive cows.

The descriptive statistics of the individual cow data and milk composition data were presented as mean ± SD.

The multicollinearity among the predictors were analyzed using Pearson correlation analysis, variation inflation factor analysis and condition index analysis.

The development of the ML model followed a structured workflow, including data preprocessing, exploratory data analysis (EDA), model selection via cross-validation, performance evaluation and final validation on test data. The data preprocessing pipeline included the following steps. First, initial data cleaning was performed by removing nonpredictive columns (identification number and sample number) to focus on biologically relevant features. A critical quality control step involved filtering invalid entries in the conductivity (mS/cm) feature, where 97 rows containing nonnumeric values (e.g., “out of range”) were removed. The final dataset retained 2403 samples after cleaning. Second, missing value imputations were performed. Missing values were identified for four features: Avg (7 days) Daily MY (L): 20 missing values (0.83% of samples); Testday MY (L): 71 missing values (2.95% of samples); conductivity (mS/cm): 62 (2.58% of samples); and freezing point (⁰C): 4 (0.17% of samples). Median imputation for these features was employed after verifying right-skewed distributions through exploratory analysis. The median robustness to outliers makes imputation preferable for preserving the integrity of milk yield and sensor-derived measurements. Third, in feature engineering, categorical encoding includes label encoding for the farm variable to convert farm IDs into ordinal representations and one-hot encoding for breeds to create six binary features representing cattle breeds. The column SCC (10 3 cells/mL) was replaced by diseased or not diseased considering the threshold SCC estimated in the current study. The integrity of the dataset was confirmed by identifying 0 duplicate cows postprocessing. The target variable SCM showed a 60:40 class imbalance (1446 negative vs. 957 positive cases), which informed subsequent stratification during data splitting. Fourth, for feature scaling, a dual-scaling approach, the standard scaler for freezing points (⁰C) to center the feature around zero mean (± 1 SD) and the MinMax scaler for remaining numerical features to normalize values between 0 and 1 was implemented so that no variable dominated due to larger scales. This hybrid strategy addresses the presence of negative values in freezing point measurements while maintaining consistent scaling for other physiological parameters. In this way, small differences in the freezing point were preserved relative to the overall variability instead of being squashed. Finally, the data were partitioned using an 80:20 stratified training: test split (random state = 42) to preserve class proportions. The training set included 1922 samples (1157 negative and 765 positive samples) and the test set included 481 samples (289 negative and 192 positive samples). Stratification mitigated bias in model evaluation given the observed class imbalance. The feature matrices (X train, X test) and target vectors (Y train, Y test) were stored separately, with scaling parameters derived exclusively from training data to prevent information leakage.

Summary statistics, correlation matrices, and data distribution visualizations were used to evaluate data quality, analyze feature relationships and identify potential issues necessitating further preprocessing or feature engineering. Following the EDA outcomes, a multicollinearity assessment was carried out to confirm the robustness of the predictors. Three diagnostic approaches were applied: (1) Pearson correlation analysis to assess pairwise feature associations, (2) Variance Inflation Factor (VIF) calculation to detect linear redundancy among predictors, and (3) condition index analysis derived from the eigenvalues of the correlation matrix. Based on these diagnostics, the feature set was refined by applying n-1 categorical encoding to avoid dummy variable redundancy and by removing strongly correlated variables, thereby improving model stability and ensuring more reliable coefficient estimation.

Two analytical approaches, Method 1 (M1). considering all the variables: 'Lac. No.’, ‘DIM’, ‘Avg (7 days) Daily MY’, ‘Testday MY’, ‘Fat’, ‘SNF’, ‘Density’, ‘Protein’, ‘Conductivity’, ‘pH’, ‘Freezing point’, ‘Salt’, and ‘Lactose’ and Method 2 (M2) considering a selected subset of variables: ‘Lac. No.’, ‘DIM’, ‘Avg (7 days) Daily MY’, and ‘Testday MY’ , were employed to identify the optimal ML models for predicting SCM. The latter approach was undertaken to see the possibility of developing a SCM predictive model using variables that can be readily and consistently obtained from Sri Lankan dairy herds. A set of nine algorithms, identified as high performing in previous studies was evaluated for the predictive performance 11 , 9 . These nine models were selected for model development, representing a spectrum of statistical assumptions and learning capacities. LR and NB constituted baseline linear and probabilistic classifiers, respectively, modelling relationships through weighted linear functions (LR) or conditional likelihoods (NB). DT and KNN provided interpretable, rule and distance-based approaches suitable for capturing simple decision structures. SVM incorporated kernel based optimization to delineate nonlinear decision boundaries, whereas NN employed multilayer architectures to learn hierarchical feature representations. The three ensemble methods; RF, XGBoost and CatBoost leveraged bagging or gradient boosting strategies to model complex, higher order feature interactions while enhancing predictive robustness, particularly under class imbalance. All nine algorithms were trained using identical predictors sets within each approach (M1 or M2) and underwent methodspecific hyperparameter optimisation. This included regularisation strengths for LR; smoothing parameters for NB; tree depth, minimum split requirements and number of estimators for DT, RF, XGBoost and CatBoost; kernel type, C-penalty and gamma parameters for SVM; and layer depth, neuron count, activation functions and learning rate for NN. The inherent 60:40 class imbalance was addressed by employing class weighing, oversampling or boosting-based mechanisms, depending on the model’s architecture. Predictive performance was assessed using a 5-fold stratified cross-validation framework to ensure proportional representation of SCM positive and SCM negative samples in each fold. Accuracy, precision, recall, F1 score and NPV served as performance metrics. Stratification was used to maintain the original class distribution in each fold, preserving the minority mastitis class representation and addressing potential overfitting. The 5-fold choice balances computational efficiency with reliability, providing five independent train-test splits while leveraging the full dataset, which is critical given the moderate sample size. A true positive (TP) was defined as a SCM positive sample correctly identified, whereas a false positive (FP) denoted a SCM negative sample incorrectly classified as positive. The precision is defined as follows: [Eq. ( 4 )].

The performance of all evaluated ML models was assessed across training, cross-validation, and test sets to ensure reliable predictive capability and robust generalization. Receiver operating characteristic and precision-recall curves analysis were performed and the AUC and AUPRC values were used for models’ performance comparison.

The dataset analyzed in the current study is available from the corresponding author upon reasonable request.

Gunawardana, S. et al. Risk factors for bovine mastitis in the Central Province of Sri Lanka. Trop. Anim. Health Prod. 46 (7), 1105–1112. https://doi.org/10.1007/s11250-014-0602-9 (2014).

Radostits, O. M., Gay, C. C., Hinchcliff, K. W. & Constable, P. D. Veterinary Medicine. A Textbook of the Diseases of Cattle, Sheep, Pigs, Goats and Horses 10th edn (Saunders Elsevier, 2007).

Losinger, W. C. Economic impacts of reduced milk production associated with an increase in bulk-tank somatic cell count on US dairies. J. Am. Vet. Med. Assoc. 226 , 1652–1658. https://doi.org/10.2460/javma.2005.226.1652 (2005).

Halasa, T., Huijps, K., Osteras, O. & Hogeveen, H. Economic effects of bovine mastitis and mastitis management: A review. Vet. Q. 29 , 18–31. https://doi.org/10.1080/01652176.2007.9695224 (2007).

Hogeveen, H., Huijps, K. & Lam, T. J. G. M. Economic aspects of mastitis: New developments. N Z. Vet. J. 59 (1), 16–23. https://doi.org/10.1080/00480169.2011.547165 (2011).

Veterinary, E. B. Department of Animal Production and Health, P.O. Box 13, Peradeniya, Sri Lanka. Accessed Nov. 13, 2024. https://daph.gov.lk/files/uploads/documents/downloads/Bulletine%20-2023-3rd%20Q.pdf (2023).

Bradley, A. & Green, M. Use and interpretation of somatic cell count data in dairy cows. Pract. 27 , 310–315. https://doi.org/10.1136/inpract.27.6.310 (2005).

Sumon, S. M. M. R., Parvin, M. S., Ehsan, M. A. & Islam, T. Relationship between somatic cell counts and subclinical mastitis in lactating dairy cows. Vet. World 13(8), 1709–1713, https://doi.org/10.14202/vetworld.2020.1709-1713 (2020).

Bobbo, T., Biffani, S., Taccioli, C., Penasa, M. & Cassandro, M. Comparison of machine learning methods to predict udder health status based on somatic cell counts in dairy cows. Sci. Rep. 11 , 13642. https://doi.org/10.1038/s41598-021-93056-4 (2021).

Article ADS CAS PubMed PubMed Central Google Scholar

Ut, I. D., Berean, D. I., Bogdan, L. M., Ciupe, S. & Gog Bogdan, S. Selective Dry Cow Therapy in Modern Dairy Management: Balancing Udder Health and Antimicrobial Stewardship. Vet. Sci. 12 (6), 580. https://doi.org/10.3390/vetsci12060580 (2025).

Article PubMed PubMed Central Google Scholar

Ebrahimi, M., Mohammadi-Dehcheshmeh, M., Ebrahimie, E. & Petrovski, K. R. Comprehensive analysis of machine learning models for prediction of sub-clinical mastitis: Deep Learning and Gradient-Boosted Trees outperform other models. Comput. Biol. Med. 114 , 103456. https://doi.org/10.1016/j.compbiomed.2019.103456 (2019).

Jadhav, P. V., Das, D. N., Suresh, K. P. & Shome, B. R. Threshold Somatic Cell count for delineation of subclinical mastitis cases. Vet. World . 11 (6), 789–793. https://doi.org/10.14202/vetworld.2018.789-793 (2018).

Article CAS PubMed PubMed Central Google Scholar

Anglart, D., Sandgren, C. H., Emanuelson, U. & Rönnegård, L. Comparison of methods for predicting cow composite somatic cell counts. J. Dairy. Sci. 103 (9), 8433–8442. https://doi.org/10.3168/jds.2020-18320 (2020).

Kleinbaum, D. G. & Klein, M. Logistic Regression: A Self Learning Text . (Third edition), Springer, New York, https://doi.org/10.1007/978-1-4419-1742-3 (2010).

Jamali, A. A. et al. Drug Miner: comparative analysis of machine learning algorithms for prediction of potential druggable proteins. Drug. Discov. Today . 21 , 718–724. https://doi.org/10.1016/j.drudis.2016.01.007 (2016).

Safavian, S. R. & Landgrebe, D. A. Survey of decision tree classifier methodology. IEEE Trans Syst. Man. Cybern B Cybern . 21 , 660–674. https://doi.org/10.1109/21.97458 (1991).

Article ADS MathSciNet Google Scholar

Breiman, L. Random forests. Mach. Learn. 45 , 5–32. https://doi.org/10.1023/A:1010933404324 (2001).

Bobbo, T. et al. Exploiting machine learning methods with monthly routine milk recording data and climatic information to predict subclinical mastitis in Italian Mediterranean buffaloes. J. Dairy. Sci. 106 , 1942–1952. https://doi.org/10.3168/jds.2022-22292 (2023).

Pan, L. et al. Machine Learning-based clinical mastitis detection in dairy cows using milk electrical conductivity and somatic cell count. Front. Vet. Sci. 12 , 1671186. https://doi.org/10.3389/fvets.2025.1671186 (2025).

Santana, R. C. M. et al. Machine learning techniques associated with infrared thermography to optimize the diagnosis of bovine subclinical mastitis. Vet. Med. Int. 1 https://doi.org/10.1155/vmi/5585458 (2025).

Kalkan, A., Tepeli, M. & Göde, A. Mastitis diagnosis with machine learning algorithms. Neural Comput. Appl. 37 , 12351–12372. https://doi.org/10.1007/s00521-025-11176-8 (2025).

Lewis, D. D. Naive (Bayes) at forty: the independence assumption in information retrieval. European Conference on Machine Learning. 4–15, https://link.springer.com/chapter/10.1007/BFb0026666#citeas (Springer, 1998).

Abdul Ghafoor, N., Sitkowska, B. & MasPA A machine learning application to predict risk of mastitis in cattle from AMS sensor data. Agric. Eng. 3 (3), 575–583. https://doi.org/10.3390/agriengineering3030037 (2021).

Pantoja, J. C., Hulland, C. & Ruegg, P. L. Dynamics of somatic cell counts and intramammary infections across the dry period. Prev. Vet. Med. 90 (2), 43–54. https://doi.org/10.1016/j.prevetmed.2009.03.012 (2009).

Smith, K. L., Hillerton, J. E. & Harmon, R. J. National Mastitis Council Guidelines on normal and abnormal milk based on somatic cell counts and signs of clinical mastitis. National Mastitis Council, Madison WI, 3, (2001).

Schwarz, D. et al. Somatic cell counts and bacteriological status in quarter foremilk samples of cows in Hesse, Germany—A longitudinal study. J. Dairy. Sci. 93 , 5716–5728. https://doi.org/10.3168/jds.2010-3223 (2010).

Petzer, I-M., Karzis, J., Donkin, E. F., Webb, E. C. & Etter, E. M. C. Somatic cell count thresholds in composite and quarter milk samples as indicator of bovine intramammary infection status. Onderstepoort. J. Vet. Res. 84 (1), e1–e10. https://doi.org/10.4102/ojvr.v84i1.1269 (2017).

Berry, D. P. & Meaney, W. J. Interdependence and distribution of subclinical mastitis and intramammary infection among udder quarters in dairy cattle. Prev. Vet. Med. 75 , 81–91. https://doi.org/10.1016/j.prevetmed.2006.02.001 (2006).

Deluyker, H. A., Oye, S. N. V. & Boucher, J. F. Factors affecting cure and somatic cell count after pirlimycin treatment of subclinical mastitis in lactating cows. J. Dairy. Sci. 88 , 604–614. https://doi.org/10.3168/jds.S0022-0302(05)72724-7 (2005).

Sargeant, J. M., Leslie, K. E., Shirley, J. E., Pulkrabek, B. J. & Lim, G. H. Sensitivity and specificity of somatic cell count and California Mastitis Test for identifying intramammary infection in early lactation. J. Dairy. Sci. 84 , 2018–2024. https://doi.org/10.3168/jds.S0022-0302(01)74645-0 (2001).

Souza, F. N. et al. Somatic cell count and mastitis pathogen detection in composite and single or duplicate quarter milk samples. Pesq Vet. Bras. 36 (9), 11–818. https://doi.org/10.1590/S0100-736X2016000900004 (2016).

Sharma, N., Singh, N. K. & Bhadwal, M. S. Relationship of Somatic Cell Count and Mastitis: An Overview. Asian-Aust J. Anim. Sci. 24 (3), 429–438. https://doi.org/10.5713/ajas.2011.10233 (2011).

Ranasinghe, R. M. S. B. K., Deshapriya, R. M. C., Abeygunawardana, D. I., Rahularaj, R. & Dematawewa, C. M. B. Subclinical mastitis in dairy cows in major milk-producing areas of Sri Lanka: prevalence, as sociated risk factors, and effects on reproduction. J. Dairy. Sci. 104 , 12900–12911. https://doi.org/10.3168/jds.2021-20223 (2021).

Heald, C. W., Kim, T., Sischo, W. M., Cooper, J. B. & Wolfgang, D. R. A Computerized Mastitis Decision Aid Using Farm-Based Records: An Artificial Neural Network Approach. J. Dairy. Sci. 83 (4), 711–720. https://doi.org/10.3168/jds.S0022-0302(00)74933-2 (2000).

Sun, Z., Samarasinghe, S. & Jago, J. Detection of mastitis and its stage of progression by automatic milking systems using artificial neural networks. J. Dairy. Res. 77 (2), 168–175. https://doi.org/10.1017/S0022029909990550 (2010).

Fadul-Pacheco, L., Delgado, H. & Cabrera, V. E. Exploring machine learning algorithms for early prediction of clinical mastitis. Int. Dairy. J. 119 https://doi.org/10.1016/j.idairyj.2021.105051 (2021).

Kamphuis, C., Mollenhorst, H., Heesterbeek, J. A. P. & Hogeveen, H. Detection of clinical mastitis with sensor data from automatic milking systems is improved by using decision-tree induction. J. Dairy. Sci. 93 (8), 3616–3627. https://doi.org/10.3168/jds.2010-3228 (2010).

Cavero, D., Tölle, K. H., Henze, C., Buxadé, C. & Krieter, J. Mastitis detection in dairy cows by application of neural networks. Livest. Sci. 114 (2–3), 280–286. https://doi.org/10.1016/j.livsci.2007.05.012 (2008).

Cabot, J. H. & Ross, E. G. Evaluating prediction model performance. Surgery 174 (3), 723–726. https://doi.org/10.1016/j.surg.2023.05.023 (2023).

Gleckler, P. J., Taylor, K. E. & Doutriaux, C. Performance metrics for climate models. J. Geophys. Res. 113 https://doi.org/10.1029/2007JD008972 (2008).

Motohashi, H., Ohwada, H. & Kubota, C. Early detection method for subclinical mastitis in auto milking systems using machine learning. In IEEE 19th International Conference on Cognitive Informatics and Cognitive Computing (ICCI*CC), Beijing, China. 76–83, https://doi.org/10.1109/iccicc50026.2020.9450258 (2020).

Hyde, R. M. et al. Automated prediction of mastitis infection patterns in dairy herds using machine learning. Sci. Rep. 10 , 1–8. https://doi.org/10.1038/s41598-020-61126-8 (2020).

Samaraweera, A. M., van der Werf, J. H. J., Boerner, V. & Hermesch, S. Economic values for production, fertility and mastitis traits for temperate dairy cattle breeds in tropical Sri Lanka. J. Anim. Breed. Genet. 139 , 330–341. https://doi.org/10.1111/jbg.12667 (2022).

Ullomi, J. O. Subclinical Mastitis Detection by Machine Learning . Thesis. Centre for Bioinformatics University of Veterinary Medicine Budapest, Hungary. (2023).

Panchal, I., Sawhney, I. K., Sharma, A. K. & Dang, A. K. Classification of healthy and mastitis Murrah buffaloes by application of neural network models using yield and milk quality parameters. Comput. Electron. Agric. 127 , 242–248. https://doi.org/10.1016/j.compag.2016.06.015 (2016).

Quinn, P. J., Carter, M. E., Markey, B. & Carter, G. R. Mastitis in Clinical Veterinary Microbiology 327–335 (Elsevier Ltd, 1999). (First edition).

Kayesh, M. E. H., Talukder, M. & Anower, A. K. M. M. Prevalence of subclinical mastitis and its association with bacteria and risk factors in lactating cows of Barisal district in Bangladesh. Int. J. Biol. Res. 2 (2), 35–38. https://doi.org/10.14419/ijbr.v2i2.2835 (2014).

The cooperation of the farm managers and staff is sincerely appreciated.

The authors gratefully acknowledge the financial support provided by the University Research Council, University of Peradeniya, Sri Lanka (Grant No. MRG-199).

Informatics Institute of Technology, 57, Ramakrishna Road, Colombo, 00600, Sri Lanka

Department of Animal Science, Faculty of Agriculture, University of Peradeniya, Peradeniya, 20400, Sri Lanka

K. M. Devindi & R. M. C. Deshapriya

Artificial Intelligence for Sustainable Livestock Systems Laboratory, Department of Animal Science, Texas A&M University, College Station, TX, 77843, USA

M. P. Saiju, A. P. Ajitha & K. Kaniyamattam

Department of Basic Veterinary Sciences, Faculty of Veterinary Medicine and Animal Science, University of Peradeniya, Peradeniya, 20400, Sri Lanka

Search author on: PubMed Google Scholar

R.M.C.O.R, M.P.S., A.P.A. and K.K. developed the machine learning algorithms. R.M.C.O.R. analyzed the results. K.M.D., R.M.C.D. and R.M.S.B.K.R were involved in farm visits and data collection. K.M.D. conducted all the laboratory experiments. R.M.S.B.K.R. conceived the study, wrote the proposal, obtained the grant and supervised the project. R.M.C.O.R and R.M.S.B.K.R. wrote the manuscript. All the authors reviewed the manuscript.

Correspondence to R. M. S. B. K. Ranasinghe .

The authors declare no competing interests.

Springer Nature remains neutral with regard to jurisdictional claims in published maps and institutional affiliations.

Open Access This article is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License, which permits any non-commercial use, sharing, distribution and reproduction in any medium or format, as long as you give appropriate credit to the original author(s) and the source, provide a link to the Creative Commons licence, and indicate if you modified the licensed material. You do not have permission under this licence to share adapted material derived from this article or parts of it. The images or other third party material in this article are included in the article’s Creative Commons licence, unless indicated otherwise in a credit line to the material. If material is not included in the article’s Creative Commons licence and your intended use is not permitted by statutory regulation or exceeds the permitted use, you will need to obtain permission directly from the copyright holder. To view a copy of this licence, visit http://creativecommons.org/licenses/by-nc-nd/4.0/ .

Rathnayaka, R.M.C.O., Devindi, K.M., Saiju, M.P. et al. Machine learning-based prediction of subclinical mastitis in large-scale dairy herds using a locally established somatic cell count threshold. Sci Rep 16 , 19661 (2026). https://doi.org/10.1038/s41598-026-50467-5

DOI : https://doi.org/10.1038/s41598-026-50467-5

Anyone you share the following link with will be able to read this content:

Sorry, a shareable link is not currently available for this article.

Provided by the Springer Nature SharedIt content-sharing initiative

&copy; 2026 Springer Nature Limited

Join the Conversation