ABSTRACT
The objective was to evaluate the potential of machine learning algorithms utilizing thermal imaging and/or milk-based parameters for the identification of subclinical mastitis(SCM) in dairy cows. Holstein dairy cows (n = 194) were enrolled, and milk samples were collected from each quarter separately (n = 776 quarter-level samples) and analyzed for milk-based parameters. Four images per cow, representing all four quarters, were captured using a handheld infrared camera. Skin temperatures were extracted using Fluke Connect software, yielding 776 images for analysis. SCM was defined at the quarter level as SCC > 200,000 cells/mL, identifying 139 infected and 637 healthy quarters. The data were analyzed to test Random Forest Classifier(RFC), Logistic Regression Classifier, AdaBoost Classifier(ABC), and Naïve Bayes Classifier algorithms. The RFC models using milk features and temperature features achieved accuracy and precision scores of 0.88 and 0.88, respectively, yielding 0.90 AUC values, with high feature importance for milk lactose and SNF. Using only thermal imaging features, the ABC model yielded accuracy and precision of 0.82 and 0.67, respectively, with 0.56 AUC. We conclude that SCM prediction using machine learning algorithms is most promising when combined with thermal images and milk-based parameters. Future studies with larger datasets and refined methods for thermal image capture and analysis are warranted to validate these findings.
Introduction
Mastitis remains one of the most economically significant diseases in the dairy industry that impacts farm profitability (Hogeveen et al. 2011). It is characterized by inflammation of the mammary gland, primarily caused by bacterial infections, and can manifest as either clinical or subclinical mastitis (Bradley 2002; Jamali et al. 2018). While clinical mastitis is identifiable by visible signs such as redness, pain, swollen udders, and abnormal milk, subclinical mastitis (SCM) is more challenging to detect because of its lack of overt symptoms (Seegers et al. 2003). SCM is defined by an elevated somatic cell count (SCC) in milk, leading to reduced milk quality, decreased production, and increased treatment costs (Halasa et al. 2007). The on-farm prevalence of SCM varies widely, with studies reporting rates ranging from 20% to over 50% depending on region and management factors (Ruegg 2003; Abebe et al. 2016).
The economic impact of SCM is substantial, with estimates suggesting that it accounts for a greater portion of the total mastitis-related losses (Halasa et al. 2007; Krishnamoorthy et al. 2021). In the United States, the annual cost of mastitis to the dairy industry is estimated to be in the billions of dollars (Ruegg 2017). Therefore, early and accurate detection of SCM is critical for effective management and control. Traditional diagnostic methods, such as somatic cell counts, electrical conductivity, and the California Mastitis Test (CMT), have been widely used but have intrinsic limitations. These methods often require collecting milk samples from cows, which is time-consuming, and may not provide real-time results suitable for on-farm decision-making (Schukken et al. 2003; Ruegg 2017). Additionally, the variables measured in these techniques can be influenced by non-mastitis factors such as the stage of lactation, milking frequency, and stress, potentially leading to misdiagnosis (Schepers et al. 1997; Krishnamoorthy et al. 2021).
In recent years, interest in non-invasive technologies, and cow-level features for mastitis detection has increased (Pakrashi et al. 2023). Infrared thermography (IRT), or thermal imaging, has emerged as a promising tool for identifying inflammation in dairy cattle (Polat et al. 2010; Schaefer et al. 2004). The principle of IRT is based on detecting heat patterns; inflammation associated with mastitis increases local temperature due to enhanced blood flow and metabolic activity, which can be captured by thermal cameras (Stewart et al. 2010; Wang et al. 2022). Several studies have investigated the efficacy of IRT in detecting mastitis. As a high level of inflammation, which contributes to increased temperature, is inherent in clinical mastitis cases, the utility of temperature variables in SCM is of concern, as the inherent clinical signs are not present. Hovinen et al. (2008) demonstrated that IRT could detect clinical mastitis with high accuracy, indicating that temperature increases in affected udder quarters. With the recent rise of advanced analytics and machine learning tools, their utilization for mastitis detection is suggested. In addition to other advanced analytics tools, machine learning algorithms have been identified to detect mastitis from thermal images (Wang et al. 2022; Chu et al. 2023). These advancements highlight the potential of machine learning to process complex cow- and quarter-level data, identify subtle patterns of inflammation, and integrate multiple variables for more robust SCM detection, paving the way for automated, on-farm diagnostic systems. However, the use of milk-derived variables, IRT, and their combination in SCM prediction has not been extensively explored. The main goal of this project is to identify a strategy to use advanced analytic tools using IRT, milk-based variables and their combination for mastitis detection in dairy farms. This study aims to evaluate the potential of using infra-red imaging alone as well as in combination with milk-derived features (fat%, protein%, SNF%, lactose, and MUN) using machine learning algorithms to identify SCM in dairy cattle. By comparing and combining thermal imaging with traditional diagnostic methods and developing standardized algorithms, we seek to provide dairy farmers with an effective, non-invasive method for the early detection and management of SCM.
Materials and methods
Study population
This study was conducted at a commercial dairy farm in central Texas during February 2023, milking a rolling average of 2200 cows. The study protocol was approved by the Institutional Animal Care and Use Committee at Texas A&M AgriLife Research (IACUC #2022-026A). A total of 194 Holstein dairy cows were enrolled, with days in milk (DIM) ranging from 25 to 245 and parity 1–7. The sample size used was based on available resources, including funds and logistics, during the study period. Cows were purposively selected based on their lactation stage [Early lactation (25–70 DIM = 63; Mid (70–150) = 72; Late lactation (151–245) = 59], parity [ 1st lactation = 52; 2nd lactation = 45; > 2 = 97], and historical udder level somatic cell count (SCC) records [SCC > 200 thousands] to ensure a representation of healthy and potentially affected animals of different cow groups for the robust model development based on previous monthly herd tests. Cows with dead quarters were not used in this study. The farm was operated under standard farm management practices, with cows housed in a free-stall barn and milked twice daily in a double 24 parallel milking parlor. Cows were fed a total mixed ratio (TMR) two times a day, formulated to meet or exceed the nutritional requirements for lactating Holstein cow producing 30 kg of milk/d with 3.5% fat and 3.1% true protein.
Mastitis management on the farm
Cows on the farm were milked two times per day. Cow monitoring involved checking for clinical mastitis signs during the milking process. Cows identified with clinical mastitis were treated according to the farm protocol. All cows were monitored monthly for their milk production, milk components, and somatic cell counts (SCC) through DHIA testing. Cows with high SCC values in these tests were closely monitored for their probability of developing clinical signs of mastitis.
Milk sampling and analysis
Milk samples were collected from each udder quarter (n = 776 quarter-level samples) during the morning milking session. A 10 mL sample was obtained from each quarter using sterile techniques and stored at 4 °C until analysis. After cleaning the teat ends thoroughly using a cotton pad soaked in alcohol (70%), milk samples were collected from all quarters on the day of the dairy visit. Milk samples were submitted immediately to the Texas DHIA laboratory (Stephenville, TX). The samples were evaluated for multiple parameters, including SCC (reported as n × 1000 cells/mL), fat (%), protein (%), lactose (%), solids-not-fat (SNF, %), beta-hydroxybutyrate (BHBA, mM/L), acetone (mM/L), and milk urea nitrogen (MUN, mg/dL). The SCC was measured using a Fossomatic analyzer (Foss, Hillerød, Denmark), while other milk components were analyzed using a Bentley FTS/FCM 400 analyzer (Bentley Instruments, Chaska, MN, USA). Subclinical mastitis (SCM) was defined at the quarter level as SCC > 200,000 cells/mL, which is consistent with established thresholds in dairy research (Schukken et al. 2003).
Thermal imaging protocol
Thermal images were captured using a handheld infrared camera (Fluke TiS 75+ , Fluke Corporation, Everett, WA, USA) with a resolution of 320 × 240 pixels and a thermal sensitivity of ≤ 0.08°C. A minimum of four images per cow were taken to represent all four udder quarters, with the camera positioned approximately 0.5 meters from the cow at a 90-degree angle to the udder surface. Imaging was conducted inside the milking parlor immediately after the morning milking to minimize the influence of ambient temperature fluctuations. The temperature during thermal imaging ranged from 0.5 to 12.7 °C, with 45%–65% relative humidity measured using a HOBO temperature logger at the milking parlor. A temperature humidity index for every 30 min interval was obtained from these data using the equation: THI = Temperature – [0.55 – (0.55 × Relative Humidity/100)] × (Temperature – 58). The camera was calibrated daily to match the ambient temperature of the barn at the beginning of imaging. The emissivity was set to 0.98, which is in agreement with previous studies with dairy cattle mammary glands (Wang et al. 2022). A total of 776 thermal images were initially collected, but 10 images were discarded due to inadequate resolution or focus, leaving 766 images for analysis. Skin temperatures (maximum, minimum, and average) for each udder quarter were manually extracted after defining the respective quarter as a region of interest using Fluke Connect software (Fluke Corporation, Everett, WA, USA). The region of interest (ROI) for each udder quarter was manually defined using Fluke Connect software. The ROI extended from the teat-udder junction at the bottom to the point of attachment of the udder to the cow’s body at the top. The teat itself was excluded from the ROI to avoid variability due to its smaller surface area and inconsistent exposure. The ROI was selected to encompass the full visible surface of each quarter, and although the number of pixels varied slightly depending on the image resolution and cow positioning, care was taken to maintain consistency across samples. Additional features included Max_deviation, which is the absolute maximum temperature between the udder max temperature and the quarter max temperature. The updder maximum refers to the maximum temperature corresponding to all four images of the specific udder [max of all four quarters], while quarter maximum corresponds to the maximum temperature specific to the quarter. Other variables, ‘Min_deviation’, ‘Max_min_deviation’, and ‘Average_deviation’ were calculated similarly using the respective temperatures obtained from the thermal images [Table 1].
Table 1.
Representation of different features and their combinations used in the machine learning models in this study and their description.
| Feature Combination | Description |
|---|---|
| Milk features | Derived from quarter level milk components; Fat%, Protein %, SNF%, Lactose%, MUN |
| Max_devation | Absolute difference between udder maximum temperature and Quarter maximum temperature |
| Min_deviation | Absolute difference between udder minimum temperature and quarter minimum temperature |
| Max_min_deviation | Absolute difference between quarter maximum temperature and udder minimum temperature |
| Average_deviation | Absolute difference between udder average temperature and quarter average temperature |
| Combo_max_deviation | Milk feature + Max_deviation |
| Combo_min_deviation | Milk feature + Min_deviation |
| Combo_average_deviation | Milk feature + Average_deviation |
| Combo_max_min_deviation | Milk feature + Max_min_deviation |
| Temperature features | All deviation temperature features at quarter levels (Max, Min and Average deviations together) |
| Ambient temperature | Ambient Temperature Humidity Index at thermal imaging |
Statistical analysis
Data preprocessing
Data curation, preprocessing, and management were conducted using Microsoft Excel software. Further data processing and analysis were conducted using the Python programming framework (version 3.9) and Pandas library (version 2.2). The dataset, comprising 766 quarter-level samples with corresponding milk and temperature variables (Table 1), was loaded into the Pandas Dataframe. Visual inspection of the histogram of each variable was used to assess the normal distribution and any potential outliers (Figure 1), along with the corresponding correlation matrix. Unsupervised machine learning was used to impute missing values using the K-means imputation method as described by Raja and Thangavel (2020). This approach was selected because it provides a more robust and data-driven alternative to conventional methods such as mean or mode imputation, allowing missing values to be dynamically estimated based on relationships with other variables, such as days in milk. The proportion of missing data was minimal, comprising less than 2% of the total observations from the 776 quarter-level milk samples analyzed. Missing values were irregularly and sparsely distributed across variables, primarily arising from occasional failures in milk component analyses. The affected variables were derived from quarter-level milk components, including fat (%), protein (%), solids-not-fat (SNF, %), lactose (%), and milk urea nitrogen (MUN.
Figure 1.
Correlation heatmap (A) and histogram (B) of the predictor variables used in the study.
Machine learning model fitting
The Python programming language is well known for several libraries for machine learning algorithms, including TensorFlow, PyTorch, and Sklearn. The latest version of the Sklearn library (version 1.6) was used in this study because of its popularity and easy implementation. Random Forest Classification (RFC), Logistic Regression (LGR), Adaboost Classifier (ABC), Naïve Bayes Classifier (NAB) algorithms were tested. These algorithms were chosen because of their individual characteristics, for example, RFC is the most popular among machine learning models (Parmar et al. 2015), which works by building numerous decision trees and is resistant to outliers. LGR is well known in classical statistics for classification problems (Gladence et al. 2015). ABC is well known to combine multiple weak learners to create a strong classifier, and NAB accounts for the Bayesian modeling (Gladence et al. 2015). The models were used to predict SCM-infected quarters (SCC > 200,000; n = 139), healthy quarters (n = 637), with model performance evaluated using the accuracy, precision, recall, F1 score, and AOC-RUC. Additionally, confusion matrices and feature importance plots (where available) were generated for visual analysis. The data were split into training (80%) and testing (20%) sets, with 5-fold cross-validation along with hyperparameter searching (Table 2). A short description of the features used for prediction is provided in Table 1. A total of 24 model-feature combinations were evaluated, and the results were compiled into a summary table. Subsequently, the models were developed to predict SCM status (binary outcome: SCM vs. healthy) using three sets of input features: (1) both temperature and milk variables, (2) temperature variables, and (3) milk-derived variables only. All analyses were conducted with a significance threshold of P < 0.05 where applicable.
Table 2.
Representation of hyperparameter tuning grid with hyperparameter of interest and the values tested for each machine learning model used in this study.
| Model | Hyperparameter | Values tested |
|---|---|---|
| Random Forest | Estimator count | 50, 100, 150, 200 |
| Depth limit | None, 10, 20, 50, 100 | |
| Logistic Regression | Regularization | 0.1, 1, 10, 100 |
| Solver algorithm | lbfgs, sag, liblinear, newton-cg |
|
| AdaBoost | Estimator count | 50, 100, 150, 200 |
| Learning rate | 0.5, 1.0, 1.5, 2.0 | |
| Naïve Bayes | Smoothing factor | 1e−9, 1e−8, 1e−7, 1e−6 |
The objective function was the weighted F1 score, accounting for class imbalance. The best hyperparameters were used to instantiate the final model for further evaluation. To robustly estimate model performance, we conducted an additional 5-fold stratified cross-validation using the best model, reporting the mean and standard error (SEM) of key metrics: Accuracy, Precision, Recall, F1-Score, and Receiver Operating Characteristic – Area Under the Curve (ROC–AUC). These metrics were calculated across folds, with SEM representing the standard deviation of each metric across folds. After cross-validation, the best model was retrained on the entire training and validation set and evaluated on the held-out test set. Confusion matrices were developed to visualize classification performance. For models with built-in feature importance measures (e.g. Random Forest), feature importance plots were generated to identify key predictive variables.
Results
A total of 776 quarter-level milk samples and corresponding thermal images from 194 Holstein cows were analyzed after excluding 10 images due to poor resolution or focus. Among the 776 quarters, 139 (17%) were identified as having subclinical mastitis (SCM) based on the SCC threshold of >200,000 cells/mL, while 637 (82%) were classified as healthy. A descriptive analysis revealed that none of the temperature variables (Max, Min, and Avg) were significantly associated with SCM status (P > 0.05). However, milk variables, including fat, lactose, and SNF, were significantly lower in quarters with SCM compared to healthy quarters (Table 3).
Table 3.
Distribution of key predictor variables (mean ± SD) within cows with different subclinical mastitis statuses.
| Variables | Healthy (n = 637) | Subclinical mastitis (n = 139) |
|---|---|---|
| Max Temp (oC) | 34.49 ± 1.37 | 34.40 ± 1.40 |
| Min Temp (oC) | 30.76 ± 2.49 | 30.66 ± 2.21 |
| Avg Temp (oC) | 33.30 ± 1.57 | 33.16 ± 1.51 |
| Fat | 3.72 ± 0.92 | 2.04 ± 1.01* |
| Protein | 3.47 ± 0.48 | 3.40 ± 0.49 |
| Lactose | 4.68 ± 0.26 | 3.95 ± 0.76* |
| SNF | 9.01 ± 0.56 | 8.15 ± 1.06* |
| MUN | 13.48 ± 4.52 | 13.51 ± 4.41 |
| SCC (x1000) | 72 ± 69 | 497 ± 98* |
| Milk BHB | 0.13 ± 0.36 | 0.02 ± 0.39 |
| Milk acetone | 0.04 ± 0.03 | 0.01 ± 0.06 |
*Indicates statistically significant differences at P < 0.05.
Exploratory data analysis
The exploratory data analysis involved assessing correlations and distributions within the healthy and subclinical mastitis (SCM) populations. Figure 1(A) displays a correlation matrix heatmap, illustrating the pairwise correlation coefficients among the nine measurements. Each cell in the matrix represents the correlation between two variables, with values ranging from −1 to 1. The color gradient, ranging from blue (indicating negative correlation) to red (indicating positive correlation), visually depicts the strength and direction of these correlations. Notably, high correlations between lactose, acetone, and solids-not-fat (SNF) contents suggest their association with energy metabolism in the body. This redundancy implies that, for modeling purposes, one feature from each highly correlated pair could be removed or combined to mitigate multicollinearity without significant loss of information. Figure 1(B) presents histograms that depict the distribution of each clinical measurement across the entire dataset, emphasizing the frequency of various observed values. This observation indicates that simple linear relationships are inadequate for precise classification. Consequently, a more sophisticated approach using machine learning is crucial to address the complex interdependencies of parameters, underscoring the necessity for comprehensive diagnostic models. To assess the potential influence of ambient temperature on udder surface temperature measurements, we conducted a correlation analysis between ambient temperature and all temperature-related variables in this study. The results showed no significant correlation (r = 0.07; P > 0.05), suggesting that ambient temperature did not systematically influence the gland temperatures within the observed range. We further evaluated ambient temperature as an additional feature in all the ML models tested, which did not improve the values obtained without the feature in the model. This may be attributed to the relatively controlled sampling conditions, specifically the consistent morning time points and the relatively narrow ambient temperature range (0.5–12.7 °C). Therefore, while ambient temperature is acknowledged as a contextual factor, the data do not support it as a confounding variable in this study.
Machine learning algorithms
We evaluated Random Forest Classification (RFC), Logistic Regression (LGR), AdaBoost Classifier (ABC), and Naive Bayes (NAB) models using features derived from milk composition and thermal imaging systems to assess their potential for classifying a quarter as having subclinical mastitis (SCM). Table 4 summarizes the performance metrics of the best models evaluated using different sets of features derived from the predictor variables. Across all models, the F1 scores and ROC-AUC were used as the primary evaluation criteria. The best-performing combinations were consistently observed when using either Milk_features or temperature deviation features combined with milk features, such as Combo_max_dev, Combo_min_dev, and Combo_avge_dev. Notably, models using Milk_features yielded high F1 scores (0.87–0.88) and ROC-AUCs (0.87–0.91) across all classifiers, showing their robustness. Similarly, the models that used milk variables combined with temperature deviation features (e.g. Combo_avge_dev) also ranked among the top performers in every algorithm tested. This consistency suggests that both raw milk production metrics and temperature deviation measures are strong predictors across various classification approaches.
Table 4.
Model performance scores for the selected high-performing machine learning algorithms and feature combinations tested in the study for the identification of subclinical mastitis in dairy cows using milk features, temperature features, and a combination of milk and temperature features for different machine learning models used, namely Random Forest Classifier, Logistic Regression, AdaBoost classifier, and Naïve Bayes classifier.
| Model | Feature Combinations |
Accuracy (±SEM) | Precision (±SEM) | Recall (±SEM) | F1 Score (±SEM) | ROC-AUC (±SEM) |
|---|---|---|---|---|---|---|
| Random | Milk_features | 0.88 ± 0.01 | 0.88 ± 0.01 | 0.88 ± 0.01 | 0.87 ± 0.01 | 0.90 ± 0.02 |
| Forest | Min_deviation | 0.80 ± 0.01 | 0.70 ± 0.03 | 0.80 ± 0.01 | 0.74 ± 0.01 | 0.51 ± 0.06 |
| Classifier | Combo_max_dev | 0.87 ± 0.01 | 0.87 ± 0.02 | 0.87 ± 0.01 | 0.86 ± 0.01 | 0.90 ± 0.02 |
| Logistic | Milk_features | 0.88 ± 0.02 | 0.87 ± 0.02 | 0.88 ± 0.02 | 0.87 ± 0.01 | 0.90 ± 0.01 |
| Regression | Avg_deviation | 0.82 ± 0.00 | 0.67 ± 0.01 | 0.82 ± 0.00 | 0.74 ± 0.00 | 0.56 ± 0.03 |
| Combo_min_dev | 0.88 ± 0.02 | 0.87 ± 0.02 | 0.88 ± 0.02 | 0.87 ± 0.01 | 0.90 ± 0.01 | |
| AdaBoost | Milk_features | 0.87 ± 0.01 | 0.87 ± 0.01 | 0.87 ± 0.01 | 0.87 ± 0.01 | 0.91 ± 0.01 |
| Classifier | Average_deviation | 0.82 ± 0.00 | 0.67 ± 0.01 | 0.82 ± 0.00 | 0.74 ± 0.00 | 0.56 ± 0.01 |
| Combo_avg_dev | 0.88 ± 0.02 | 0.88 ± 0.01 | 0.88 ± 0.02 | 0.88 ± 0.01 | 0.91 ± 0.01 | |
| Naïve | Milk_features | 0.86 ± 0.01 | 0.86 ± 0.01 | 0.86 ± 0.01 | 0.86 ± 0.01 | 0.87 ± 0.02 |
| Bayes | Min_deviation | 0.81 ± 0.01 | 0.72 ± 0.05 | 0.81 ± 0.01 | 0.75 ± 0.01 | 0.49 ± 0.07 |
| Combo_avg_dev | 0.86 ± 0.01 | 0.86 ± 0.00 | 0.86 ± 0.01 | 0.86 ± 0.00 | 0.87 ± 0.02 |
When using RFC, the highest performance was observed with models using both Milk_features and Combo_max_dev, which produced an F1 score of 0.87 and 0.86, respectively. The model performance declined when only using temperature deviation features (Min_deviation, ROC-AUC: 0.51) or temperature features (Temp_features, ROC-AUC: 0.49), suggesting that Random Forest models benefit from more integrated or context-rich feature sets (Figure 2). These findings highlight the model's strength in handling complex, non-linear relationships when the input features contain sufficient predictive signals.
Figure 2.
Representation of model performance metrics (accuracy, F1 score, precision, recall, ROC-AUC) derived from different machine learning algorithms that utilized features from milk-based variables and thermal image-based variables for the detection of subclinical mastitis in dairy cows.
Algorithms based on LGR also demonstrated strong performance with Milk_features and Combo_min_dev features, both achieving an F1 score of 0.87 and an ROC-AUC of 0.90. Interestingly, models using Average_deviation feature provided a moderate F1 score (0.74) but had a relatively higher ROC-AUC (0.56) compared to similar models using deviation-based features, indicating the model's linear sensitivity to average-based metrics. Logistic regression models exhibited stable performance across all features but demonstrated peak discrimination power when used with temperature or milk-based variables.
Algorithms based on ABC yielded some of the highest ROC-AUC scores across all models, peaking at 0.91 with Milk_features, Combo_max_dev, and combo_avge_dev. The highest F1 score (0.88) was also derived from models that used combo_avge_dev, affirming the classifier's effectiveness in leveraging ensemble learning on temperature deviation metrics. The models that used deviation-based features alone performed less competitively (ROC-AUC: 0.53), suggesting that AdaBoost excels when feature interrelationships are captured more holistically. The feature importance diagram (Figure 3) demonstrates that the model prefers milk-associated features compared to the temperature-associated features.
Figure 3.
Feature importance (A) and confusion matrix diagrams (B) from the Adaboost classifier algorithm, including features of milk-based variables and thermal image-based variables. This algorithm, containing milk (lactose, protein, BHB, fat, SNF, MUN, and acetone) and average_deviation, performed best (AUC 0.91) among all other combinations of features tested for this algorithm.
Finally, the NAB algorithms, while generally lower in ROC-AUC across most features, still achieved strong F1 scores (0.86) with Milk_features, Combo_max_dev, and Combo_avge_dev. However, the NAB models had ROC-AUC values (0.87) that were slightly lower than those of AdaBoost and RFC (Figure 2). Despite its simplifying assumptions of feature independence, Naive Bayes performed comparably on key feature sets, showing that even simple models can benefit from well-structured input features. The algorithm showed more variability in the ROC-AUC across deviation features (0.49–0.50), indicating limitations when predictive relationships become non-linear or interdependent.
Discussion
The present study demonstrates the potential of combining thermal imaging with machine learning techniques for detecting subclinical mastitis (SCM) in dairy cows, with ABC models achieving an accuracy of 88% and an AUC of 0.91 when integrating milk composition and average_deviation. However, models relying solely on temperature variables yielded lower performance (accuracy 80%, AUC 0.49–0.56), underscoring the importance of incorporating milk parameters such as lactose and solids-not-fat (SNF), which emerged as major predictors in feature importance analyses.
The use of infrared thermography (IRT) for detecting mastitis in dairy cows has been extensively explored in peer-reviewed literature, with several studies demonstrating its effectiveness for both clinical and subclinical forms of the disease. For instance, Machado et al. (2021) evaluated IRT for SCM detection in dairy cows housed in compost barn systems, finding that thermal images from the front quarters of the udder were particularly effective, with strong correlations between udder temperature and the somatic cell count (SCC) (R² up to 0.97 for the right fore udder temperature). Similarly, Sathiyabarathi et al. (2018) reported that IRT can serve as an early indicator of mastitis by detecting temperature differentials between the body and udder skin surfaces, with udder temperatures in SCM-affected cows being significantly higher than those in healthy cows, typically ranging from 35 to 38 °C. We were not able to detect a statistically significant association of udder temperature variables with SCM status (P > 0.05). The numerically higher temperature values in healthy quarters could be due to unbalanced treatment groups, with a high number of healthy quarters contributing to a wider range in readings. This observation justified the use of advanced analytics in our study to identify a relationship that would not be detected using classical statistical approaches. Previous studies (Sathiyabarathi et al. 2018) align with the current study's finding that the minimum udder temperature is a significant indicator, though the reported temperatures in this study (30–34 °C) are notably lower. This may be potentially due to the difference in measurement instruments, temperature extraction methods, or farm conditions when the temperature variables are taken. The thermal images were taken in this study during relatively cooler times of the day and particularly during the colder months of the year, which could lead to the overall smaller readings in both healthy and sick animals throughout the study period.
The ROC-AUC metric, which measures a model's ability to distinguish between classes, reveals that the ABC model consistently outperformed others when using Milk Features, and temperature deviation features (with ROC-AUCs of approximately 0.91), while all models perform poorly (ROC-AUC of ~0.55) with temperature-derived deviation features alone. This disparity arises from the algorithms' internal mechanisms: RFC leverages ensemble learning through bootstrapped decision trees, effectively capturing non-linear relationships and interactions present in the milk production data and combined features, which likely hold richer and more predictive information. LGR models, though linear, perform well when the data has strong signal-to-noise ratios and clear class separability, as seen with Milk_Features. ABC also performs decently with informative features by sequentially focusing on misclassified instances, but is more sensitive to noise and less robust with weak predictors such as isolated temperature features. Naïve Bayes, assuming feature independence, underperforms in complex feature spaces but still shows a moderate ROC-AUC with milk-based features due to their strong marginal distributions.
The integration of machine learning with thermal imaging has recently been getting more attention. Xudong et al. (2020) developed a deep learning model (EFMYOLOv3) for automatic mastitis recognition from thermal images, achieving high accuracy (96.8%) in detecting eyes and udders and 83.33% accuracy in classifying mastitis, with a sensitivity of 92.31% and specificity of 76.47%. Similarly, Wang et al. (2022) used YOLOv5 to locate cow eyes and udders, achieving 85.71% accuracy in mastitis detection, with an overall accuracy of 87.62%, a sensitivity of 96.30%, and a specificity of 84.62%. However, Wang et al. (2024) used two-stage DeepLabV3+ and YOLOv5 models, resulting in a higher accuracy of 86%, a sensitivity of 79.41%, and a specificity of 92.49% as compared to the one-stage model using only YOLOv5, indicating better performance of the models when used in combination rather than separately. A study by Chu et al. (2023) evaluated the efficacy of the YOLOv7 model to detect mastitis using ocular and udder surface temperature and reported the overall accuracy of 88.61%. The sensitivity and specificity of clinical mastitis detection were 87.50% and 94.03%, respectively, while those of subclinical mastitis detection were 81.25% and 91.94%, respectively, showing YOLOv7 as a better algorithm than YOLOv5 on the premise of ensuring detection precision (Chu et al. 2023). Zhang et al. (2023) used the CLE-UNet deep learning algorithm for the ocular surface temperature and udder skin surface temperature obtained from infrared thermal images to detect mastitis in cows and reported an accuracy of 86.67%, a sensitivity of 82.35%, and a specificity of 80%. These studies highlight the potential of advanced analytics to enhance the diagnostic capabilities of thermal imaging, aligning with the current study's use of random forest models, which achieved 88% accuracy when combining milk and temperature variables. However, the current study's RFC model using only temperature variables had a lower accuracy (80%), suggesting that temperature alone might not be sufficient, which is consistent with findings from Schaefer et al. (2022), who noted in a scoping review that IRT's effectiveness is enhanced when coupled with environmental monitoring and other diagnostic methods.
Our findings on the AUC of 56% when using the AdaBoost (boosting) algorithm with the temperature variables (maximum, minimum, and average temperature of the udder surface) only agreed closely with the findings of Santana et al. (2025). The authors reported an AUC of 53% when using the boosting algorithm (XGBoost) with the thermographic variables only (cold, hot, and average temperature of the udder) to detect subclinical mastitis. Our study identified the average temperature difference of the udder and quarter as the most important feature to detect the subclinically infected udder when using the boosting algorithm, which was similar to the result of Santana et al. (2025). However, the model performance comparisons should be conducted carefully. Elevated SCC levels and clinical mastitis detected in other studies are typically associated with increased udder surface temperatures. In our study, all cows were classified as having subclinical mastitis with no obvious clinical signs. This classification is important, as temperature changes in subclinical cases may be subtler and more variable, potentially influencing the sensitivity of IR-based detection models. The performance of our model should therefore be interpreted within the context of subclinical mastitis. When comparing our findings with those of other studies, it is essential to consider the average SCC of the animal population involved. Differences in SCC distributions may explain variations in reported temperature thresholds and detection accuracy, underscoring the need for standardized SCC reporting in IR-based mastitis research.
The findings of this study could have several implications for dairy farm management. We demonstrated that the use of ML algorithms helps detect SCM using milk-based variables without the need for SCC evaluation. This opens opportunities to explore other milk component parameters as a proxy for SCC evaluations. We demonstrated that thermal imaging had approximately 0.82% accuracy and 0.74% F1 score, which can be used in parallel or in series combinations with the milk-based test. This can be served when the tests are not available or fail. Early detection of SCM is critical for timely intervention, as untreated SCM can progress to clinical mastitis, leading to reduced milk production, compromised milk quality, and increased treatment costs (Halasa et al. 2007). Thermal imaging, being non-invasive and rapid, offers a promising alternative to traditional diagnostic methods such as the SCC or the California Mastitis Test (CMT), which often require cow restraint, milk sampling, and may not provide real-time results (Schukken et al. 2003). The developed IR-based models, as well as the improved performance of machine learning models when incorporating milk variables (e.g. lactose, SNF, BHBA, acetone, MUN), suggest that a multi-model approach used in this study enhanced detection accuracy. This is particularly relevant given the strong correlations reported in previous studies, such as Polat et al. (2010), who found IRT had a sensitivity of 95.6% and specificity of 93.6% for SCM, which is comparable to CMT. Furthermore, the results should be interpreted within the context of the study, as thermal imaging systems vary widely in design and application, ranging from stationary units to handheld devices with different technical specifications. In this study, we used a Fluke TiX580 handheld infrared thermal camera (640 × 480 resolution, ±2 °C accuracy, ≤0.05 °C sensitivity at 30 °C), which is well-suited for capturing detailed quarter-level udder temperature profiles; however, our findings are specific to this device and should not be generalized to all infrared thermography systems, as variations in resolution, calibration, and sensitivity can influence the results.
From a practical standpoint, integrating thermal imaging with machine learning could enable the development of automated, on-farm diagnostic tools. Such systems could provide real-time monitoring of udder health, allowing farmers to intervene early and reduce economic losses (Schaefer et al. 2004; Stewart et al. 2005). A study by Berry et al. (2003) found that daily variation in udder surface temperature could be used for mastitis detection, supporting the potential for continuous monitoring. However, for widespread adoption, these systems must be user-friendly, reliable, and compatible with existing farm management practices. The current study's use of ABC models demonstrates the feasibility of such integration, though further refinement is needed to match the performance of deep learning approaches, as seen in Wang et al. (2022).
Despite its contributions, the current study has some limitations that need to be discussed for the appropriate interpretation of the results. This study did not include external validation using an independent dataset from a different herd or location, which is considered the gold standard for assessing model generalizability. The sample size (194 cows) could also be considered relatively small. In general, larger datasets are needed to validate the models across diverse populations and management systems. To mitigate this limitation, we employed 5-fold cross-validation, an established approach for unbiased performance estimation when external datasets are unavailable during early development stages (Bradshaw et al. 2023). The reported udder temperatures (30 and 34 °C) are low compared to standard literature values (35–38 °C), which we consider due to the winter months and morning time points. Our goal was to minimize the variation in ambient temperature per day by taking measurements in this timeframe. This discrepancy could affect the interpretation of the results and underscores the importance of the dynamic temperature cutoff in future studies, as emphasized by Schaefer et al. (2022). Despite excluding the THI from the final model to avoid redundancy, we acknowledge that environmental conditions may influence thermal responses under more extreme or heterogeneous field settings. The controlled conditions under which images were collected may have limited the variability in THI, thereby reducing its detectable impact. Future research should evaluate the role of the THI and related environmental indices across broader climatic ranges to determine whether they enhance model robustness in less controlled production environments. While the study used machine learning models, the models did not achieve the same level of accuracy as the deep learning models reported in other studies (Chu et al. 2023); however, the model performances of the deep neural network cannot be compared with the ability of feature selection in this study. Deep neural network models are black box algorithms, where feature importance cannot be quantified, and hence it is not possible to know which features were utilized by the model for decision making. This suggests that more advanced algorithms might be better suited for this application and data use conditions, provided that proper feature engineering and validation of these features are conducted using either RFC or ABC. Further research should also consider incorporating additional data sources, such as cow behavior (e.g. lying time) or other physiological indicators (e.g. pH, electrical conductivity), to enhance the predictive power of models, as suggested by Schaefer et al. (2022). If using deep learning models, the biological relevance of the selected features used for the black box models should be assessed before using them for proper decision-making to avoid emphasis on the irrelevant features for classification. This leads to an important need for feature engineering as a part of future research.
A potential future study will include a longitudinal design of experiments to assess the long-term data collection to improve the effectiveness of thermal imaging for mastitis detection and its impact on farm management practices to capture weather and cow-level variabilities (Gayathri et al. 2024). Future research can build on our work by integrating diverse data sources, including dairy record-keeping programs, longitudinal monitoring from milking meters and robotic milkers, and external camera-based sensors like infrared thermography and RGB cameras, to develop more accurate and robust SCM detection systems that enhance early detection and improve dairy cow health and milk quality. However, the lack of predictive power in the models highlights the need for further research with larger datasets and advanced image analysis techniques, such as deep learning tools, to enhance the diagnostic accuracy of thermal imaging for SCM detection within these research conditions.
Conclusion
In conclusion, the ML models developed in this study confirm that quarter-level milk-based parameters are effective for detecting subclinical mastitis. In contrast, models relying solely on thermal imaging parameters yielded moderate predictive performance. While these findings demonstrate the potential of using thermal imaging with machine learning algorithms, particularly when integrating milk composition data, several challenges remain. Longitudinal studies that standardize recordings and ultimately validate models using larger datasets, as well as explore more advanced algorithms, are critical steps toward widespread on-farm implementation.
Disclosure statement
No potential conflict of interest was reported by the author(s).
References
- Abebe R, Hatiya H, Abera M, Megersa B, Asmare K. 2016. Bovine mastitis: prevalence, risk factors and isolation of staphylococcus aureus in dairy herds at hawassa milk shed, south Ethiopia. BMC Vet Res. 12:1–11. 10.1186/s12917-016-0905-3 [DOI] [PMC free article] [PubMed] [Google Scholar]
- Berry RJ, Kennedy AD, Scott SL, Kyle BL, Schaefer AL. 2003. Daily variation in the udder surface temperature of dairy cows measured by infrared thermography: potential for mastitis detection. Can J Anim Sci. 83(4):687–693. 10.4141/A03-012 [DOI] [Google Scholar]
- Bradley AJ. 2002. Bovine mastitis: an evolving disease. The Veterinary Journal. 164(2):116–128. 10.1053/tvjl.2002.0724 [DOI] [PubMed] [Google Scholar]
- Bradshaw TJ, Huemann Z, Hu J, Rahmim A.. 2023. A guide to cross-validation for artificial intelligence in medical imaging. Radiology: Artificial Intelligence. 5(4):e220232. [DOI] [PMC free article] [PubMed] [Google Scholar]
- Chu M, Li Q, Wang Y, Zeng X, Si Y, Liu G. 2023. Fusion of udder temperature and size features for the automatic detection of dairy cow mastitis using deep learning. Comput Electron Agric. 212:108131. 10.1016/j.compag.2023.108131 [DOI] [Google Scholar]
- Gayathri SL, Bhakat M, Mohanty TK. 2024. Seasonal assessment of mastitis using thermogram analysis in sahiwal cows. Res Vet Sci. 166:105083. 10.1016/j.rvsc.2023.105083 [DOI] [PubMed] [Google Scholar]
- Gladence LM, Karthi M, Anu VM.. 2015. A statistical comparison of logistic regression and different Bayes classification methods for machine learning. ARPN Journal of Engineering and Applied Sciences. 10(14):5947–5953. [Google Scholar]
- Halasa T, Huijps K, Østerås O, Hogeveen H. 2007. Economic effects of bovine mastitis and mastitis management: a review. Vet Q. 29(1):18–31. 10.1080/01652176.2007.9695224 [DOI] [PubMed] [Google Scholar]
- Hogeveen H, Huijps K, Lam TJGM. 2011. Economic aspects of mastitis: new developments. NZ Vet J. 59(1):16–23. 10.1080/00480169.2011.547165 [DOI] [PubMed] [Google Scholar]
- Hovinen M, et al. 2008. Detection of clinical mastitis with the help of a thermal camera. J Dairy Sci. 91(12):4592–4598. 10.3168/jds.2008-1218 [DOI] [PubMed] [Google Scholar]
- Jamali H, et al. 2018. Invited review: incidence, risk factors, and effects of clinical mastitis recurrence in dairy cows. J Dairy Sci. 101(6):4729–4746. 10.3168/jds.2017-13730 [DOI] [PubMed] [Google Scholar]
- Krishnamoorthy P, Goudar AL, Suresh KP, Roy P. 2021. Global and countrywide prevalence of subclinical and clinical mastitis in dairy cattle and buffaloes by systematic review and meta-analysis. Res Vet Sci. 136:561–586. 10.1016/j.rvsc.2021.04.021 [DOI] [PubMed] [Google Scholar]
- Machado NA, et al. 2021. Using infrared thermography to detect subclinical mastitis in dairy cows in compost barn systems. J Therm Biol. 97:102881. 10.1016/j.jtherbio.2021.102881 [DOI] [PubMed] [Google Scholar]
- Pakrashi A, et al. 2023. Early detection of subclinical mastitis in lactating dairy cows using cow-level features. J Dairy Sci. 106(7):4978–4990. 10.3168/jds.2022-22803 [DOI] [PubMed] [Google Scholar]
- Parmar C, et al. 2015. Radiomic machine-learning classifiers for prognostic biomarkers of head and neck cancer. Frontiers in oncology. 5:272. [DOI] [PMC free article] [PubMed] [Google Scholar]
- Polat B, et al. 2010. Sensitivity and specificity of infrared thermography in detection of subclinical mastitis in dairy cows. J Dairy Sci. 93(8):3525–3532. 10.3168/jds.2009-2807 [DOI] [PubMed] [Google Scholar]
- Raja PS, Thangavel SC. 2020. Missing value imputation using unsupervised machine learning techniques. Soft Computing. 24(6):4361–4392. 10.1007/s00500-019-04199-6 [DOI] [Google Scholar]
- Ruegg PL. 2003. Investigation of mastitis problems on farms. Veterinary Clinics: Food Animal Practice. 19(1):47–73. 10.1016/S0749-0720(02)00078-6 [DOI] [PubMed] [Google Scholar]
- Ruegg PL. 2017. A 100-year review: mastitis detection, management, and prevention. J Dairy Sci. 100(12):10381–10397. 10.3168/jds.2017-13023 [DOI] [PubMed] [Google Scholar]
- Santana RCM, et al. 2025. Machine learning techniques associated with infrared thermography to optimize the diagnosis of bovine subclinical mastitis. Vet Med Int. 2025(1):5585458. 10.1155/vmi/5585458 [DOI] [PMC free article] [PubMed] [Google Scholar]
- Sathiyabarathi M, et al. 2018. Infrared thermal imaging of udder skin surface temperature variations to monitor udder health status in bos indicus (Deoni) cows. Infrared Physics & Technology. 88:23–28. 10.1016/j.infrared.2017.11.028 [DOI] [Google Scholar]
- Schaefer AL, et al. 2004. Early detection and prediction of infection using infrared thermography. Can J Anim Sci. 84(1):73–80. 10.4141/A02-104 [DOI] [Google Scholar]
- Schaefer AL, McCartan B, Cook NJ, Webster J. 2022. Thermography for disease detection in livestock: a scoping review. Front Vet Sci. 9:965622. 10.3389/fvets.2022.965622 [DOI] [PMC free article] [PubMed] [Google Scholar]
- Schepers AJ, Lam TJGM, Schukken YH, Wilmink JBM, Hanekamp WJA. 1997. Estimation of variance components for somatic cell counts to determine thresholds for uninfected quarters. J Dairy Sci. 80(8):1833–1840. 10.3168/jds.S0022-0302(97)76118-6 [DOI] [PubMed] [Google Scholar]
- Schukken YH, Wilson DJ, Welcome F, Garrison-Tikofsky L, Gonzalez RN. 2003. Monitoring udder health and milk quality using somatic cell counts. Vet Res. 34(5):579–596. 10.1051/vetres:2003028 [DOI] [PubMed] [Google Scholar]
- Seegers H, Fourichon C, Beaudeau F. 2003. Production effects related to mastitis and mastitis economics in dairy cattle herds. Vet Res. 34(5):475–491. 10.1051/vetres:2003027 [DOI] [PubMed] [Google Scholar]
- Stewart M, Webster JR, Schaefer AL, Cook NJ, Scott SL. 2005. Infrared thermography as a non-invasive tool to study animal welfare. Anim Welfare. 14(4):319–325. 10.1017/S096272860002964X [DOI] [Google Scholar]
- Stewart M, Verkerk GA, Stafford KJ, Schaefer AL, Webster JR. 2010. Noninvasive assessment of autonomic activity for evaluation of pain in calves, using surgical castration as a model. J Dairy Sci. 93(8):3602–3609. 10.3168/jds.2010-3114 [DOI] [PubMed] [Google Scholar]
- Wang Y, Chu M, Kang X, Liu G. 2024. A deep learning approach combining DeepLabV3+ and improved YOLOv5 to detect dairy cow mastitis. Comput Electron Agric. 216:108507. 10.1016/j.compag.2023.108507 [DOI] [Google Scholar]
- Wang Y, Kang X, He Z, Feng Y, Liu G. 2022. Accurate detection of dairy cow mastitis with deep learning technology: a new and comprehensive detection method based on infrared thermal images. Animal. 16(10):100646. 10.1016/j.animal.2022.100646 [DOI] [PubMed] [Google Scholar]
- Xudong Z, Xi K, Ningning F, Gang L. 2020. Automatic recognition of dairy cow mastitis from thermal images by a deep learning detector. Comput Electron Agric. 178:105754. 10.1016/j.compag.2020.105754 [DOI] [Google Scholar]
- Zhang Q, Yang Y, Liu G, Ning Y, Li J. 2023. Dairy cow mastitis detection by thermal infrared images based on CLE-UNet. Animals. 13(13):2211. 10.3390/ani13132211 [DOI] [PMC free article] [PubMed] [Google Scholar]



