Engineering in Agriculture, Environment and Food
Online ISSN : 1881-8366
ISSN-L : 1881-8366
A pig abnormal behavior monitoring model based on YOLOv5 and attention mechanism
Yafei YANGLi WANG Denghui LIGuoqiang WANG
Author information
JOURNAL OPEN ACCESS FULL-TEXT HTML

2026 Volume 19 Issue 2 Pages 105-110

Details
Abstract

An intelligent monitoring model based on YOLOv5 and an attention mechanism is proposed to improve automatic identification of abnormal pig behaviors in farming environments. A dataset containing pig fighting, abnormal feeding, and reduced activity behaviors was constructed and enhanced through data augmentation. By integrating a channel attention mechanism into YOLOv5s, the model improves feature extraction and detection performance for small and occluded targets. Experimental results show that the improved model achieves 95.24 % detection accuracy and 91 FPS, outperforming Faster R-CNN, YOLOv3, and the original YOLOv5s. The model demonstrates strong robustness, stability, and computational efficiency under complex conditions, providing effective technical support for intelligent livestock health management and precision farming applications.

1. Introduction

With the scaling and intensification of modern animal husbandry, livestock health management is facing increasingly severe challenges. In pig farming, abnormal behaviors such as fighting, feeding disorders, and abnormal activity patterns (Yang, 2024; Yin, 2015) reflect animal welfare and indicate potential risks such as disease transmission, overcrowding, or environmental stress. Traditional manual inspection methods have limitations, including subjectivity, poor real-time monitoring, and high labor intensity, which cannot meet modern farming demands for precision and intelligent management (Han et al., 2018). Therefore, developing an efficient and stable automated system to identify and alert abnormal pig behaviors is of great significance for improving farming efficiency and animal health.

In recent years, deep learning technologies, especially object detection algorithms based on convolutional neural network (CNN), have been extensively applied in image recognition of agriculture and animal husbandry. The YOLO (you only look once) series has become a hotspot in video surveillance and behavior recognition due to its end-to-end detection framework, high accuracy, and real-time performance (Liu et al., 2024; Zhao, 2024). As the latest lightweight representative of this series, YOLOv5 has demonstrated excellent performance in multiple livestock monitoring tasks. However, in practical farming, traditional detection methods still have difficulty in detecting small targets, significant occlusion interference, and insufficient behavioral feature extraction due to dense pig herds, similar body postures, and complex environmental backgrounds (Qin et al., 2016). Therefore, optimization is required.

The Attention Mechanism, originally developed in natural language processing, simulates human ‘focusing’ behavior by prioritizing the most relevant and meaningful information (Bressers, 1993; Dai et al., 2022; Scolari et al., 2011; Wu et al., 2019). This can improve the models’ ability to identify critical regions and salient features of images. Attention dimensions can be categorized into channel attention such as SE module, ECA module, spatial attention such as SAM module, and combined mechanisms that combine CBAM and CoordAtt (Chi et al., 2021; Nasirahmadi et al., 2017). These modules can independently or collaboratively adjust feature map weights and spatial positions, making forward propagation focus on target areas while suppressing redundant information. In object detection, targets often have scale variations, complex backgrounds, or occlusions, traditional convolutional operations may lead to insufficient feature extraction, especially in detecting small objects or local behavioral features (Ammar et al., 2022; Niioka et al., 2018; Yuan et al., 2023). Attention mechanism dynamically adjusts regional feature importance during multi-scale fusion or backbone network processing. It allows these models to adaptively enhance representation of critical abnormal behavior areas such as pig head, legs, and interaction zones, thereby improving the discriminative power and accuracy of feature representation.

Although YOLOv5 has high detection speed and simple structure, it faces challenges in processing intensive pig farming environments with severe occlusion or complex backgrounds, including insufficient feature extraction and unclear object boundaries. Combined attention modules with the backbone network such as CSPDarknet or neck layer such as FPN + PAN of YOLOv5 (Bai et al., 2024), this approach can improve the sensitivity of the shallow network to local information and the integration quality of deep semantic features. Therefore, semantic understanding of abnormal behaviors and the accuracy of target localization are strengthened (Vivek et al., 2024). On this basis, an intelligent detection model that combines YOLOv5 with an enhanced attention mechanism is proposed for pig anomaly behavior. Experimental verification is conducted by constructing a video dataset that covers typical behaviors such as combat, abnormal eating, and reduced activity, as well as combined with data augmentation and feature optimization methods. This aims to provide technical support and theoretical foundations for developing intelligent, automated livestock health management systems.

2. Materials and methods

2.1. Data collection and classification

To develop a pig abnormal behavior monitoring model suitable for real-world farming, this study collected daily behavioral videos from swine herds and manually annotated key action sequences. The video capture adopts a top-view installation method, with a high-definition infrared network camera installed above each pigsty stall. The size of a single stall is (3.0 × 2.5) m (length × width). The camera was fixed on the top crossbeam of the pigsty, with an installation height of 2.5 m. The lens was vertically downward using the overhead shooting method, with an installation angle of 0–5 ° (relative to the vertical direction). This small angle deviation is mainly used to fine tune the center of the picture, avoiding obstruction of local areas by material troughs or fences. A single standard field is covered and photographed. Each camera corresponds to an independent field, and there is no multiple field splicing or cross regional shooting. The data was collected 24 h a day, with a focus on behavioral differences between daytime active periods and nighttime resting periods. A 30-day video collection period yielded about 120 h of raw footage. The capture equipment adopts a high-definition infrared network camera (resolution [1,920 × 1,080], frame rate 25 fps).

Based on expert veterinary recommendations and farming practices, abnormal behaviors are categorized into three types (Table 1). Using the LabelImg annotation tool, frame-by-frame labeling to obtain YOLO-compatible annotation files (including category labels and bounding box coordinates) (Khairwa et al., 2024). To enhance model generalization, data augmentation techniques including brightness adjustment, image rotation, scale scaling and random occlusion are applied. A total of about 8,500 image samples were obtained, including 2,950 for fighting, 2,850 for abnormal eating, and 2,700 for reduced activity. To avoid data leakage caused by the similarity of consecutive frames in the video data, the dataset was divided into segments based on the video time series. According to the video collection date and time period, the video segments collected at different time periods were divided into training, validation, and testing sets. The same continuous video segments only appear in one subset. On this basis, the ratio of training set, validation set, and testing set is 7:2:1 (Guo, 2018).

Table 1 Characteristics of abnormal behavior in pig herds

Category of conduct Description Characteristic performance
Fighting behavior Rapid running, body collisions, biting and other aggressive behavior occurred between the pigs. Intense movement, frequent physical contact, regional aggregation
Feeding abnormalities Pigs had shorter feeding time, lower feeding frequency or failed to feed. Stand for a long time without eating, and frequently approach the trough and leave
Activity decreased Pigs lie down for long periods of time or respond slowly. The posture remains unchanged and the movement trajectory is significantly reduced

2.2. Data preprocessing

To improve the model's ability to recognize abnormal behaviors of pigs in complex scenarios and alleviate the training difficulties caused by sample imbalance, illumination difference and occlusion interference, the original image data set is cleaned to unify the size and convert the format before model training.

2.2.1. Image cleaning and screening

Since the original images originate from real-time monitoring videos of actual pig farms, the factors such as lighting conditions, equipment vibrations, occlusion interference, and camera blind spots may result in some substandard image quality. This study uses the variance Laplacian algorithm to quantitatively assess the image clarity and conducts second-order derivative calculations on grayscale values. When the Laplacian variance falls below the threshold (set at 60 in experiments), the image is deemed blurry. After removing these images, inter-frame difference algorithm (Frame Difference) and perceptual hash algorithm (pHash) are used to evaluate image similarity and eliminate duplicate frames with a similarity above 0.95. Finally, video frames that do not meet the three behavioral criteria: fighting, abnormal feeding behavior, or reduced activity, are excluded (Zhu, 2018). For instance, images showing pigs standing with unclear movements or excessive background noise are considered invalid samples.

2.2.2. Image size standardization

In object detection, inconsistent input image sizes will increase computation of models and reduce the efficiency of feature extraction. The YOLOv5 series models default to a (640 × 640) pixel input size. This chapter uses proportional scaling combined with edge padding (letterbox) to standardize original images. For edges in scaled images smaller than (640 × 640) pixels, symmetrical padding using gray (RGB values 114, 114, 114) or black is applied to maintain central alignment. The padding process utilizes the cv2.copyMakeBorder() function from the OpenCV library (Li et al., 2024).

2.2.3. Annotation format conversion

In this study, the LabelImg tool is used to complete the initial annotation of image targets, and outputs Pascal VOC format (.xml) files. Each file contains image names, size information, and positional data for multiple object bounding boxes. To apply these annotations to the YOLOv5 training framework, the bounding box parameters (xmin, ymin at the top-left corner and xmax, ymax at the bottom-right corner) in Pascal VOC format are converted into five required components for YOLO. All coordinates have been normalized based on the width and height of images, generating a value range of 0–1. The calculation method is as follows (Wen et al., 2024).

  
x c e n = x max + x min 2 × I w (1)
  
y c e n = y max + y min 2 × I h (2)
  
W n o r = x max x min I w (1)
  
H n o r = y max y min I h (4)

Where xcen and ycen is the center of x and y coordinate, Iw and Ih is the image width and height, and Wnor and Hnor is the normalized width and height.

To accommodate the YOLOv5 training framework, all behavioral categories should be converted into corresponding numerical labels. T three abnormal behavior classes are defined: fighting behavior (Class 0), feeding abnormalities (Class 1), and reduced activity (Class 2). Each transformed image corresponds to one entry in a.txt file, with filenames matching the image files. Each row contains annotation information for a specific target.

2.3. Basic detection network: YOLOv5s

YOLOv5 is a deep learning algorithm based on one-stage object detection, with the advantages of fast speed, high accuracy, and easy deployment. The overall architecture mainly consists of Backbone, Neck, and Head (Fig. 1), which enhances the network’s ability to focus on key features by integrating convolutional block attention module (CBAM). The attention mechanism module based on the backbone network (Backbone) and feature fusion module (Neck) can enhance the performance of the model in complex background and small object detection.

Fig. 1 Schematic diagram of the YOLOv5s network architecture

In the Backbone section, the channel attention of CBAM first weights the channel dimensions of the feature map to enhance attention to important features. Then, the spatial attention module further focuses on key behavioral areas such as the pig’s head and torso by spatially weighting local regions. In the Neck section, the feature maps refined by CBAM are further fused to improve the expression ability of multi-scale features (Gao et al., 2024) and enhance detection accuracy. In addition, edges are added automatically after the input image is scaled proportionally to (640 × 640), maintaining the image structure unchanged.

2.4. Introduction of attention mechanism and improvement strategy

In practical livestock farming, recognition of pig herd behaviors will face complex backgrounds, occlusion of targets, dense small objects, and diverse postures. Although YOLOv5s has strong feature extraction and multi-scale detection capabilities, its ability is limited in key areas of abnormal behaviors. Especially in fine-grained action discrimination (such as feeding abnormalities and stationary behaviors), the response areas of the model lack sufficient concentration, leading to missed detections or misjudgments.

To enhance the model’s focus on abnormal behavior regions, a lightweight attention mechanism module in the YOLOv5s backbone network and feature fusion network is introduced. The CBAM is adopted as an enhancement module in the backbone network and Neck structure (Li et al., 2024). At the same time, feature information is modeled significantly in channel and spatial dimensions. Compared with attention mechanisms that only focus on channel relationships (SE and ECA), CBAM introduces a spatial attention module based on channel attention. It can explicitly characterize the spatial distribution characteristic blocks of key regions in the feature map. This module sequentially executes two sub-modules to guide the network in extracting key regions and salient features of images from the perspectives of ‘channel dimension’ and ‘spatial dimension’ to improve the target perception capability of the model.

The working principle is shown in Fig. 2. The CBAM module adopts a serial cascade structure design of channel attention and spatial attention (Wen et al., 2024). Assuming the input feature map is FR C × H × W, the channel attention module takes F as input and obtains channel level statistical information through global average pooling and global maximum pooling. The channel attention weights Mc(F) is generated by shared multi-layer perceptron (MLP) and Sigmoid activation function, and weighted channel by channel with the original features to obtain the channel-enhanced feature map F ′ = Mc(F) ⨂ F. Then the spatial attention module takes the output feature F ′of the channel attention module as input to conduct maximum pooling and average pooling on the channel dimension respectively. Two two-dimensional feature maps are obtained and concatenated in the spatial dimension. After (7 × 7) convolution and sigmoid activation, the spatial attention weight Ms(F ′) is generated, and F ′ is weighted element by element to obtain the final output feature F ″ = Ms(F ′) ⨂ F ′. The spatial attention module does not operate independently of the channel attention module, but focuses on key spatial positions based on the enhanced features of the channel attention. They work together to achieve joint modeling of key regions of abnormal behaviors.

Fig. 2 Schematic diagram of CBAM working principle

2.5. Improvement of the model structure framework

The refined YOLOv5s architecture comprises four core components: the input module, backbone network, Neck feature fusion network, and output detection head (Head), as shown in Fig. 3. The model processes (640 × 640) images by extracting semantic features through Focus and multi-layer BottleneckCSP modules, and enhances multiscale perception through SPP modules. The Neck structure combines CBAM attention mechanism to amplify anomaly detection capabilities through feature concatenation and deep fusion. The tri-scale detection head ultimately identifies and locates behavioral targets of different sizes. This architecture strikes a balance between detection accuracy and computational efficiency, making it suitable for real-time anomaly monitoring in complex swine herd scenarios.

Fig. 3 Improved YOLOv5s model structure framework diagram

3. Results and analysis

To validate the effectiveness of this anomaly detection model based on YOLOv5s and CBAM attention mechanism, it is compared with the original YOLOv5s, YOLOv3, and Faster R-CNN. The improved model using actual piggery test data. The experiments were conducted on a NVIDIA RTX 3080 GPU-equipped Ubuntu system using PyTorch 1.11 framework with official YOLOv5 training code. As shown in Table 2, the training set, validation set, and test set are proportionally divided (7:2:1), including 8,500 annotated images covering three behavioral categories: ‘fighting’, ‘abnormal feeding’, and ‘reduced activity’.

Table 2 Experimental training parameters

Parameter categories Setting values
Input image size 640 × 640
Batch size 16
Initial learning rate 0.001
Optimizer SGD
Loss function CIoU Loss + BCE Loss
Number of training rounds 300 epochs
Anchor box generation Adaptive clustering is generated

3.1. Comparison of detection indicators

The performance metrics of different models are shown in Table 3. Key evaluation indicators in the test set include mAP@0.5 (average precision), precision, recall, and FPS (frames per second). The results showthat compared with other models, the precision and recallof this model is improved by 4.92 % and 4.28 % respectively. Although the CBAM module slightly reduces FPS by 2 frames per second, it can still maintain real-time detection (Wen et al., 2024).

Table 3 Comparison of detection performance between different models

Model mAP@0.5 (%) Precision (%) Recall (%) FPS (frames/s)
YOLOv3 86.42 84.78 81.26 42
Faster R-CNN 88.15 86.33 83.96 15
YOLOv5s 90.32 88.20 85.47 91
YOLOv5s-CBAM 95.24 92.87 89.75 89

3.2. Analysis of small target and occlusion detection capability

In swine behavior monitoring, abnormal behaviors are usually manifested as localized movements in small areas, such as rapid collisions during fights or subtle head movements during feeding abnormalities. These targets have the smallest image area, have a short duration, are easily obstructed by other pigs or background interference, posing challenges to traditional detection models. To evaluate the adaptability of the improved modelto small targets and occluded scenarios, this study defines the samples in the test set with target areas less than 5 % of the image size as ‘small target samples’, and calculates mAP@0.5 of each model on this subset. As shown in Table 4, the accuracy of YOLOv5s-CBAM in small target detection can improve by about 7.2 % than YOLOv5, significantly higher than YOLOv3. This indicates that the attention mechanism can effectively enhance the model’s focus on detailed regions, and can more accurately capture localized behavioral changes of pigs.

Table 4 Performance evaluation of small object detection

Model Small target mAP@0.5 (%)
YOLOv3 74.6
YOLOv5s 80.1
YOLOv5s-CBAM (this paper) 87.3

3.3. Analysis of visual detection effect

The real image results of detecting abnormal behavior in pig herds using the YOLOv5s CBAM model are presented in a (2 × 2) format (Fig. 4). The behavioral categories include ‘fighting behavior’, ‘abnormal feeding behavior’, and ‘reduced activity’. Each target behavior is visualized with different colored bounding boxes. The borders of fight behavior region are concentrated in strong interaction areas such as neck and head movements. The abnormal feeding behavior box cluster indicates the area between the head and feeding trough of pigs, indicating the model has a strong capability to distinguish subtle behavioral patterns. The reduced activity category shows stationary individuals for a long time. However, this model maintains high accuracy in the detection of weak dynamic targets. In addition, the image displays post-detection processing with automatically overlaid results and category labels, indicating the end-to-end recognition capability and practical deployment effectiveness of the model. In real-world scenarios with complex backgrounds, lighting variations, and multi-object occlusions, YOLOv5s-CBAM has excellent detection robustness, without bounding box displacement, duplicationor loss. This further validates the increased attention to critical regions achieved through the attention mechanism.

Fig. 4 Visualization of abnormal behavior detection model results (after processing)

4. Conclusion and prospect

Traditional monitoring mainly relies on manual labor with low detection accuracy and real-time performance. A YOLOv5s deep learning detection model based on CBAM attention mechanism is proposed to identify abnormal pig behaviors in pig farms. Compared with the model, mAP@0.5 pf the improved YOLOv5s-CBAM model is increased from 90.32 % to 95.24 %, precision from 88.20 % to 92.87 %, and recall from 85.47 % to 89.75 %. The Recall rate under occlusion has also been significantly improved, and it can still maintain real-time detection capability of 89 FPS.

Although the YOLOv5s-CBAM model has achieved good results in identifying abnormal behaviors in pig herds, there are still some limitations. This study mainly focuses on three typical abnormal behaviors, and has not covered other sub-health behaviors such as stall pressing, head shaking, and multiple probes. In the future, the behavior labeling system can be expanded to build a multi-dimensional behavior recognition framework, and introduce cross-scenario transfer learning and multi-source data fusion methods to improve model adaptability.

Acknowledgments

Research Project at the College Level of Jiangsu Agri-animal Husbandry Vocational College (NSF2025ZR04).

Declaration of conflicting interests

The authors declare no conflicts of interest.

Notes

(URLs on references were accessed on 27 May 2026.)

References
 
© Asian Agricultural and Biological Engineering Association

This article is licensed under a Creative Commons [Attribution 4.0 International] license.
https://creativecommons.org/licenses/by/4.0/
feedback
Top