<figure><img src="image_1.png" /></figure>

HAL
open science

# Classifying active and inactive states of growing rabbits from accelerometer data using machine learning algorithms

Mónica Mora, Lucile Riaboff, Ingrid David, Juan Pablo Sánchez, Miriam Piles

► To cite this version:

Mónica Mora, Lucile Riaboff, Ingrid David, Juan Pablo Sánchez, Miriam Piles. Classifying active and inactive states of growing rabbits from accelerometer data using machine learning algorithms. Journal of Animal Science, In press. hal-04621966v2

HAL Id: hal-04621966

https://hal.science/hal-04621966v2

Submitted on 27 Jun 2024

HAL is a multi-disciplinary open access
archive for the deposit and dissemination of sci-
entific research documents, whether they are pub-
lished or not. The documents may come from
teaching and research institutions in France or
abroad, or from public or private research centers.

L'archive ouverte pluridisciplinaire HAL, est
destinée au dépôt et à la diffusion de documents
scientifiques de niveau recherche, publiés ou non,
émanant des établissements d'enseignement et de
recherche français ou étrangers, des laboratoires
publics ou privés.
# Classifying active and inactive states of growing rabbits from accelerometer data using machine learning algorithms

Mónica Mora, Lucile Riaboff, Ingrid David, Juan Pablo Sánchez, Miriam Piles

► To cite this version:

Mónica Mora, Lucile Riaboff, Ingrid David, Juan Pablo Sánchez, Miriam Piles. Classifying active and inactive states of growing rabbits from accelerometer data using machine learning algorithms. Smart Agricultural Technology, 2024, 9, pp.100675. 10.1016/j.atech.2024.100675. hal-04621966v3

HAL Id: hal-04621966

https://hal.science/hal-04621966v3

Submitted on 8 Jan 2025

HAL is a multi-disciplinary open access
archive for the deposit and dissemination of sci-
entific research documents, whether they are pub-
lished or not. The documents may come from
teaching and research institutions in France or
abroad, or from public or private research centers.

L'archive ouverte pluridisciplinaire HAL, est
destinée au dépôt et à la diffusion de documents
scientifiques de niveau recherche, publiés ou non,
émanant des établissements d'enseignement et de
recherche français ou étrangers, des laboratoires
publics ou privés.

<figure><img src="image_1.png" /></figure>
# Classifying active and inactive states of growing rabbits from accelerometer data using machine learning algorithms

Mónica Mora*, Lucile Riaboff#+§, Ingrid David#, Juan Pablo Sánchez* and Miriam Piles*

* Animal Breeding and Genetics, Institute of Agrifood Research and Technology (IRTA), Caldes de Montbui, 08140 Barcelona, Spain.

# GenPhySE, Université de Toulouse, INRAE, ENVT, 31326 Castanet Tolosan, France

+ School of Computer Science, University College Dublin, Dublin, Ireland

§ VistaMilk SFI Research Centre, Ireland

Corresponding author: monica.mora@irta.cat

## Funding

This study was part of the project PID2021-128173OR-C21 (GENEF3) and MM is a recipient of a “Formación de Personal Investigador (FPI)” associated with the research project RTI2018-097610R-I00.

## Lay Summary

This study explores how wearable accelerometers, small devices that measure acceleration, can help monitor the activity of growing rabbits. We equipped 16 rabbits with these devices and filmed them for two weeks. By watching the videos and using a special software we figure out what the rabbits were doing – things like lying down, eating, moving around, and more. These activities were grouped into two states: active or inactive. Then, this information along acceleration data was used to teach a computer
<figure><img src="image_2.png" /></figure>

<figure><img src="image_3.png" /></figure>

Check for
updates

# Classifying active and inactive states of growing rabbits from accelerometer data using machine learning algorithms

Mónica Mora<sup>a,*</sup>, Lucile Riaboff<sup>b,c,d</sup>, Ingrid David<sup>b</sup>, Juan Pablo Sánchez<sup>a</sup>, Miriam Piles<sup>a</sup>

## ARTICLE INFO

**Keywords:**

Accelerometer

Rabbit

Classification

Monitoring

Machine learning

## ABSTRACT

Using wearable accelerometers is gaining traction in research and animal production management for monitoring animal behaviour. In this study, the objective was to automatically detect rabbit activity/inactivity states from accelerometer data in growing rabbits. For that purpose, 16 animals were equipped with an accelerometer and filmed for 2 weeks. A total of 10 h of video across all the rabbits were annotated manually using the Boris software, identifying 6 classes of different behaviours: lying, eating, moving, grooming, walking and drinking which were grouped into two classes: active and inactive. Accelerometer signal and video annotations were manually synchronized. The static and dynamic components of the signal were isolated by applying a low-pass and high-pass filter and 4 additional time series were derived from these components. The signal was segmented into time windows of different sizes: 1, 3, 5, 7 and 9 s. For each window, a total of 41 features were extracted in the time and frequency domain. Different subsets of data containing an increasing number (from 5 to 25 in steps of 5) of the most informative features identified with random forest (RF) were used to train a binary classification model (inactive as a positive class). The classification performance of RF, support vector machine (SVM) and gradient boosting (GB) was evaluated. A nested cross-validation (CV) with an outer Leave-One-Animal Out CV and an inner threefold CV for hyperparameter tuning was implemented. The same resampling was implemented for each window size and each classifier so that the models were evaluated with the same data sets. The performance was evaluated on the test datasets using different metrics: precision, recall, F1 score and accuracy. Results showed that the classifiers perform very similarly. With the best configuration (window size of 9 s and with the 5 most important features) the RF model reaches a median precision of 1 (Q1=0.99, Q3=1) and a median recall of 0.93 (Q1=0.89, Q3=0.97). These results showed that the model is highly reliable in correctly classifying positive instances. Additionally, achieving a recall of 0.93 emphasizes the model's effectiveness in capturing a substantial portion of positive instances. Accelerometers combined with machine learning models therefore hold great promise for monitoring rabbit activity and for a range of applications in animal science and behaviours.

## Introduction

Monitoring livestock behaviour is crucial for promptly detecting epidemic outbreaks and/or technical and environmental issues, such as drinking trough failures and inadequate temperatures. Furthermore, the activity level has been shown to be related to feed efficiency in beef [1],

making this information valuable for inclusion in breeding programs to enhance this trait, which stands as one of the primary objectives for the majority of livestock species.

In the case of rabbits, it would be essential to monitor their behaviour. Understanding how their activity patterns relate to their health and feed efficiency could provide valuable insights for improving their

**Abbreviations:** CV, cross-validation; FN, false negative; FP, false positive; FPR, false positive rate; GB, gradient boosting; LOAOCV, leave-one-animal out cross-validation; PLF, precision livestock farming; Q, quartile; RF, random forest; ROC, receiver operating characteristics; SMOTE, synthetic minority over-sampling technique; SVM, support vector machine; TN, true negative; TP, true positive; TPR, true positive rate.

<footnote><sup>a</sup> Animal Breeding and Genetics, Institute of Agrifood Research and Technology (IRTA), Caldes de Montbui, Barcelona 08140, Spain</footnote>

<footnote><sup>b</sup> GenPhySE, Université de Toulouse, INRAE, ENVT, Castanet Tolosan 31326, France</footnote>

<footnote><sup>c</sup> School of Computer Science, University College Dublin, Dublin, Ireland</footnote>

<footnote><sup>d</sup> VistaMilk SFI Research Centre, Ireland</footnote>

<footnote>* Corresponding author.</footnote>

<footnote>E-mail address: monica.mora@irta.cat (M. Mora).</footnote>
program to recognize when the rabbits were active or not. This technology offers a reliable way to understand rabbit behavior, which could lead to better management practices in animal production.

## Teaser text

This research showcases the effectiveness of wearable accelerometers combined with machine learning in accurately monitoring rabbit inactivity levels.

## Abstract

Using wearable accelerometers is gaining traction in research and animal production management for monitoring animal behaviour. In this study, the objective was to automatically detect rabbit activity/inactivity states from accelerometer data in growing rabbits. For that purpose, 16 animals were equipped with an accelerometer and filmed for 2 weeks. A total of 10 hours of video across all the rabbits were annotated manually using the Boris software, identifying 6 classes of different behaviours: lying, eating, moving, grooming, walking and drinking which were grouped into two classes: active and inactive. Accelerometer signal and video annotations were manually synchronized.

The static and dynamic components of the signal were isolated by applying a low-pass and high-pass filter and 4 additional time series were derived from these components.

The signal was segmented into time windows of different sizes: 1, 3, 5, 7 and 9 seconds.

For each window, a total of 41 features were extracted in the time and frequency domain. Different subsets of data containing an increasing number (from 5 to 25 in steps of 5) of the most informative features identified with random forest (RF) were used to train a binary classification model (inactive as a positive class). The classification performance of RF, support vector machine (SVM) and gradient boosting (GB) was evaluated. A nested cross-validation (CV) with an outer Leave-One-Animal Out CV and an inner threefold CV for hyperparameter tuning was implemented. The
management and welfare. However, continuous monitoring of the animals by humans is time-consuming and labour-intensive, making it impossible to monitor them 24/7. Therefore, the integration of new and advanced technologies in livestock is getting highly relevant for ensuring sustainable and efficient production systems. Precision livestock farming (PLF) aims to create smart farms that use these technologies to continuously and automatically monitor the animals [2]. In the last few years, different types of sensors and devices have been proposed to achieve this goal. Among these tools, wearable sensors containing accelerometers can be employed to gather information about the activity at the individual level [3]. An accelerometer is an electromechanical device that measures acceleration forces, which is the rate of change of velocity of an object. Moving the sensor generates a voltage by applying stress to the small crystals it contains. In a tri-axial accelerometer, acceleration is measured along the three-dimensional axis (x, y and z) [4]. The data recorded by the accelerometer provides information on the animal's movements, including how often and how vigorous they are, which in turn can provide insights into animal behaviour, health conditions, pain or discomfort. Accelerometers have gained popularity due to their compact size and affordable cost, being utilised in numerous livestock applications. Above all, they have found significant applications in large animals and/or those that are outdoors [5,6]. For example, accelerometers have been employed in sows that are housed individually in gestating stalls [7]. In cattle, behaviours such as rumination, feeding time and grazing time have been the most studied based on accelerometer data [3]. However, to the best of our knowledge, wearable accelerometers have not been used yet to monitor the behaviours of rabbits. Accelerometers could then be utilized to get information on activity patterns throughout the day in their housing system and to assess the modification in behaviour related to changes in their environment, animal growth, etc. However, getting behaviours from raw accelerometer signals requires applying appropriate experimental design and analytical methods [8]. Indeed, different dynamical properties and patterns corresponding to an observed behaviour can be identified in the raw accelerometer signal. Supervised machine learning algorithms demonstrated effectiveness in classifying accelerometer signals into pre-defined behaviour categories [9,10]. To train and validate such algorithms, accelerometer signals and their corresponding observed behaviours are required. Animal behaviours can be recorded through direct observation [11,12] or with images captured by a camera [13,14]. Then, the signal is segmented into time windows. For each window, a set of statistical features is calculated. The classifier is trained using the combination of these statistical features as predictor variables and the corresponding behavioural annotations as the target. Once the model is trained, it can be applied to new accelerometer signals from new individuals to classify and monitor their behaviours. In this way, attaching an accelerometer to the rabbits would allow for obtaining individual patterns of activity, enabling their monitoring over long periods.

The present study aimed to develop and validate a model to classify active or inactive states over 15 days using accelerometer data from growing rabbits.

## Material and methods

### Ethics approval

The experimental procedures used in the research complied with the European directive 2010/63/EU and the Spanish guidelines for the care and use of animals in research (B.O.E. number 34, Real Decreto 53/2013). Animals were submitted to an experimental procedure approved by the Ethical Committee of IRTA and the Regional Government of Catalonia.

### Accelerometers

The accelerometers used in this study were the AX3 dataloggers (https://axivity.com/product/ax3). They are MEMS 3-axis accelerometers with onboard memory (512 MB), measuring 23 × 32.5 × 8.9 mm and weighing 11 g. The accelerometer has configurable sample rates (frames per second) and sensitivity (± 2 g, ± 4 g, ± 8 g and ± 16 g; 1 g = ~9.81ms⁻²) so that both can be adapted depending on the targeted activities. In the present study, the sampling rate was set up to 25 Hz and the sensitivity to ± 8 g. With this configuration, the expected battery life was 30 days. Configuration and data download were performed by connecting each AX3 to a computer using a USB port and the OmGui software. The data of each accelerometer was downloaded at the end of the follow-up period for each animal.

### Methodology

In this section, the three main steps of the methodology are described: data collection, data preprocessing and model fitting and classification (Fig. 1).

#### Step 1: data collection

The experiment was carried out at IRTA's nucleus farm at Caldes de Montbui, Spain. In this farm, the photoperiod was set to 16 light h/d (from 07:00 to 23:00h) and the environmental temperature was kept at 20 ± 2°C. The animals included in this study come from a sire line commonly used in rabbit farms. The animals were housed in groups of 6 kits in cages measuring 76 cm width x 100 cm length x 32 cm height. Each cage was equipped with an electronic feeder that allowed one rabbit to eat at a time ensuring accurate identification of the animal. The study considered a total of 16 animals belonging to 2 batches and born between November 2022 and February 2023. The observation period was from 37 to 51 days of age.

In each batch, one animal from each cage (8 cages in total) was randomly selected to be equipped with the accelerometer for 15 consecutive days. The tri-axial accelerometer was enclosed into a resistant plastic box and fixed to the rabbit's back using an elastic band (Fig. 2). All the sensors were attached in the same way for all the animals, i.e., with the same orientation. This ensured that the x-axis detected the backward-forward direction, the y-axis detected the left-right direction and the z-axis detected the down-up direction whatever the rabbit.

The rabbits were videotaped throughout the two-week experiment in each of the batches using a 2D camera placed on the top of the cages. Videos of rabbits equipped with the accelerometer were observed for at least 35 min and a maximum of 39 min (not entirely sequential). All the pre-defined behaviours that took place during that time were manually annotated by the same person according to an ethogram (Table 1) and the BORIS software [15]. In the end, animals' behaviours on various days of the experiment and at different moments of the day were annotated, resulting in a total of ~10 h of video annotations across the 16 rabbits.

Due to the lack of representation of some predefined behaviours, they were grouped according to the state of the animal as active or inactive. Thus, it was considered that the animal was active when it was moving, walking and grooming, and inactive when it was lying, eating and drinking. The last two behaviours were included in the inactive class because of the little movement of the animal's back that produced a flat signal in the accelerometer.

#### Step 2: data preprocessing

In this section, the different phases of data preprocessing after data collection are described. Four sequential operations were carried out: i) synchronization of the accelerometer signal with the behaviour annotations; ii) new time series extraction; iii) accelerometer signal segmentation into time windows; and iv) calculation of statistical features
same resampling was implemented for each window size and each classifier so that the
models were evaluated with the same data sets. The performance was evaluated on the
test datasets using different metrics: precision, recall, F1 score and accuracy. Results
showed that the classifiers perform very similarly. With the best configuration (window
size of 9 s and with the 5 most important features) the RF model reaches a median
precision of 1 (Q1=0.99, Q3=1) and a median recall of 0.93 (Q1=0.89, Q3=0.97). These
results showed that the model is highly reliable in correctly classifying positive
instances. Additionally, achieving a recall of 0.93 emphasizes the model's effectiveness
in capturing a substantial portion of positive instances. Accelerometers combined with
machine learning models therefore hold great promise for monitoring rabbit activity and
for a range of applications in animal science and behaviours.

**Keywords:** accelerometer, rabbit, classification, monitoring, machine learning

**List of abbreviations**

CV: cross-validation

FN: false negative

FP: false positive

FPR: false positive rate

GB: gradient boosting

LOAOCV: leave-one-animal out cross-validation

PLF: precision livestock farming

Q: quartile

RF: random forest
<figure><img src="image_4.png" /><figcaption>Fig. 1. Overview data processing.</figcaption></figure>

<figure><img src="image_5.png" /><figcaption>Fig. 2. Rabbit equipped with the accelerometer.</figcaption></figure>

in each of the time windows. All the codes were run with the pro-
gramming language Python v3.10.11. The main packages used were
SciPy [16] and Scikit-learn [17].

Synchronization. The time stamps of accelerometer signals and

behaviour annotations were synchronized to guarantee that the anno-
tations corresponded to the correct sequences of the accelerometer
signal. The synchronization was possible thanks to a pattern in the signal
created by shaking the accelerometer in front of the cameras before and
ROC: receiver operating characteristics

SMOTE: synthetic minority over-sampling technique

SVM: support vector machine

TN: true negative

TP: true positive

TPR: true positive rate

## Introduction

Monitoring livestock behaviour is crucial for promptly detecting epidemic outbreaks and/or technical and environmental issues, such as drinking trough failures and inadequate temperatures. Furthermore, the activity level has been shown to be related to feed efficiency in beef (Haskell et al., 2019), making this information valuable for inclusion in breeding programs to enhance this trait, which stands as one of the primary objectives for the majority of livestock species.

In the case of rabbits, it would be essential to monitor their behaviour. Understanding how their activity patterns relate to their health and feed efficiency could provide valuable insights for improving their management and welfare. However, continuous monitoring of the animals by humans is time-consuming and labour-intensive, making it impossible to monitor them 24/7. Therefore, the integration of new and advanced technologies in livestock is getting highly relevant for ensuring sustainable and efficient production systems. Precision livestock farming (PLF) aims to create smart farms that use these technologies to continuously and automatically monitor the animals (Berckmans, 2017). In the last few years, different types of sensors and devices have been proposed to achieve this goal. Among these tools, wearable sensors containing
<table><caption>**Table 1**

Definition of the different behaviours annotated.</caption><thead><tr><th>Behaviour</th><th>Classification description</th><th>State</th><th>Hours of observation</th></tr></thead><tbody><tr><td>Lying</td><td>The rabbit is lying down</td><td>inactive</td><td>5.34</td></tr><tr><td>Eating</td><td>The rabbit is inside the electronic feeder</td><td>inactive</td><td>1.75</td></tr><tr><td>Moving</td><td>The rabbit is moving without changing its position</td><td>active</td><td>1.68</td></tr><tr><td>Grooming</td><td>The rabbit is licking itself</td><td>active</td><td>0.67</td></tr><tr><td>Walking</td><td>The rabbit is moving while changing its position</td><td>active</td><td>0.14</td></tr><tr><td>Drinking</td><td>The rabbit is drinking</td><td>inactive</td><td>0.34</td></tr></tbody></table>

after the experiment. Thus, in the videos, accelerometer shaking could be observed, allowing for accelerometer timestamp synchronization with the videos. As a result of this process, a dataset was generated in which behaviour annotations for each rabbit matched the corresponding accelerometer data sequences. However, the accelerometer time drift (±1.7 s per day maximum; AX3 user guidebook: https://axivity.com/u serguides/ax3/), i.e., the fact that the accelerometer clock is not able to maintain constant precision over time, moving forward or falling behind, led to a time difference between the accelerometer time-series and the behaviour annotations, even after the synchronization process). Therefore, each continuous sequence of time series associated with annotations (~ 35-39 min) was visually inspected. Any temporal mismatch identified between the annotations and the time series was noted. The alignment was then corrected for each sequence to ensure that it was perfectly synchronised with the associated behaviour.

**New time series extraction.** From the measurements in each of the three axes (x, y and z), a fourth orientation-independent one was calculated as follows:

$$a_{\text{mag}} = \sqrt{a_x^2 + a_y^2 + a_z^2}$$

Where $a_x$, $a_y$ and $a_z$ are the acceleration on the x-axis, y-axis and z-axis, respectively. This variable is called “the magnitude”.

On the other hand, the acceleration measured by the accelerometer in the three axes may be separated into both static and dynamic acceleration. The static acceleration registers the orientation of the animal, while the dynamic gets information about the energy expended without the ‘bias’ of the gravitational force. To separate static from dynamic acceleration, filters are typically applied to the raw acceleration. In the present study, low and high-pass filters were used to get the static and the dynamic acceleration, respectively. Considering that the static component is constant and thus leads to frequencies ~ 0, usually, the cut-off frequency used is 0.3 Hz [10,18]. From the static acceleration, the angles around x (roll) and y (pitch) were calculated to estimate the accelerometer orientation following the definition presented by Rautiainen, Alam [19]. From the dynamic acceleration, the norm of the dynamic acceleration (VeDBA) and the sum of the absolute value of dynamic acceleration (OBDA) were computed. The formulas for all these features are as follows:

$$\text{pitch} = -\text{atan}\left(\frac{\text{static}_x}{\sqrt{\text{static}_y^2 + \text{static}_z^2}}\right)$$

$$\text{roll} = \text{atan2}(\text{static}_y, \text{static}_z)$$

$$\text{VeDBA} = \sqrt{\text{dynamic}_x^2 + \text{dynamic}_y^2 + \text{dynamic}_z^2}$$

$$\text{OBDA} = |\text{dynamic}_x| + |\text{dynamic}_y| + |\text{dynamic}_z|$$

**Time-windows creation.** The accelerometer signal was split into time windows of the same size. As the movement of rabbits is brief, window

sizes smaller than 10 s were created (Riaboff et al., 2022). To determine the optimal window size, various short window sizes were tested: 1, 3, 5, 7 and 9 s. Windows with a mix of both active and inactive classes were removed from the analysis. Thus, each window was associated with just one of the classes. In Table 2, for each window size, the total number of obtained windows is shown together with the number of them belonging to the inactive class.

**Features calculation.** For each time window, features were computed on each of the time series in the time and frequency domain. A total of 41 features were computed. Table 3 shows all the features obtained and their formulas. In the time domain, the features calculated were related to position parameters like the mean and median, as well as dispersion parameters like the standard deviation, the minimum, the maximum and the range. Kurtosis and skewness were also computed in the time domain. Skewness measures the lack of symmetry of the data distribution while kurtosis measures whether the data are heavy-tailed or light-tailed relative to a normal distribution. Another feature typically used is the motion variation which indicates the rate of change in the signal: a more energetic movement will lead to higher motion variation. Finally, in the frequency domain, the spectral entropy was calculated only for the magnitude axis. It refers to a measure of the random process uncertainty in the accelerometer signal frequency distribution. Only the range was computed for the pitch, roll, OBDA and VeDBA time series.

**Step 3: Model fitting and classification of the animal state from the accelerometer signal**

The goal of this step was to train a machine learning model using the features calculated in the previous step to classify the animal state (active or inactive) during every time window. The inactive class was considered as the positive class.

Three machine learning algorithms were tested and their classification performance was evaluated: Random Forest (RF) [20], Support Vector Machine (SVM) [21] and Gradient Boosting (GB) [22]. RF is an ensemble learning method combining several classification trees. Each decision tree is fitted to a set of subsamples randomly selected through a bootstrapping procedure and using randomly selected subsets of the predictor variables. The global prediction is then obtained as the majority vote across all the predictions from all trees. GB builds a series of weak decision trees, where each subsequent tree corrects the errors made by the previous ones. The final prediction is a combination of all the weak trees. On the other hand, SVM is a supervised learning algorithm, that aims to find the hyperplane that best separates different classes in the feature space. More information about these classifiers can be found in the literature cited above.

For each classifier, a nested resampling (Fig. 3) was implemented to obtain reliable performance estimates. This procedure consists of two nested resampling loops. In the outer resampling loop, a Leave-One-Animal Out Cross-Validation (LOAOCV) was carried out. In LOAOCV, the dataset is divided into n subsets, where n is the number of animals. For each iteration of the outer loop, data points corresponding to one animal are held out as the testing dataset, and the model is trained on the remaining data points, ensuring that all the data points are used for prediction. The models were thus tested with different animals than those used for model training, preventing overfitting and over-optimistic results. This approach allowed us to evaluate the predictive power of the model while considering the variability inherent in individual animals.

<table><caption>**Table 2**

Total number of windows and percentage of windows in the inactive class.</caption><thead><tr><th>Window size</th><th>Total windows</th><th>Percentage windows inactive</th></tr></thead><tbody><tr><td>1 s</td><td>24,685</td><td>0.77</td></tr><tr><td>3 s</td><td>7,471</td><td>0.80</td></tr><tr><td>5 s</td><td>4,052</td><td>0.82</td></tr><tr><td>7 s</td><td>2,676</td><td>0.86</td></tr><tr><td>9 s</td><td>1,941</td><td>0.86</td></tr></tbody></table>
accelerometers can be employed to gather information about the activity at the
individual level (Chapa et al., 2020). An accelerometer is an electromechanical device
that measures acceleration forces, which is the rate of change of velocity of an object.
Moving the sensor generates a voltage by applying stress to the small crystals it
contains. In a tri-axial accelerometer, acceleration is measured along the three-
dimensional axis (x, y and z) (Benjamin and Yik, 2019). The data recorded by the
accelerometer provides information on the animal's movements, including how often
and how vigorous they are, which in turn can provide insights into animal behaviour,
health conditions, pain or discomfort. Accelerometers have gained popularity due to
their compact size and affordable cost, being utilised in numerous livestock
applications. Above all, they have found significant applications in large animals and/or
those that are outdoors (Martiskainen et al., 2009; Shahriar et al., 2016). For example,
accelerometers have been employed in sows that are housed individually in gestating
stalls (Ringgenberg et al., 2010). In cattle, behaviours such as rumination, feeding time
and grazing time have been the most studied based on accelerometer data (Chapa et al.,
2020). However, to the best of our knowledge, wearable accelerometers have not been
used yet to monitor the behaviours of rabbits. Accelerometers could then be utilized to
get information on activity patterns throughout the day in their housing system and to
assess the modification in behaviour related to changes in their environment, animal
growth, etc. However, getting behaviours from raw accelerometer signals requires
applying appropriate experimental design and analytical methods (Riaboff et al., 2022).
Indeed, different dynamical properties and patterns corresponding to an observed
behaviour can be identified in the raw accelerometer signal. Supervised machine
learning algorithms demonstrated effectiveness in classifying accelerometer signals into
pre-defined behaviour categories (Vázquez Diosdado et al., 2015; Riaboff et al., 2020).
<table><caption>**Table 3**
Formulas of the extracted features from the acceleration data.</caption><thead><tr><th>Feature</th><th>Formula</th></tr></thead><tbody><tr><td>Average</td><td>A&#773;<sub>a</sub> = <sup>1</sup>&frasl;<sub>M</sub> &sum;<sub>i=1</sub><sup>M</sup> a<sub>i</sub></td></tr><tr><td>Median</td><td>The median of the axis within the window</td></tr><tr><td>Standard deviation</td><td>&sigma;<sub>a</sub> = &radic;(<sup>&sum;<sub>i=1</sub><sup>M</sup> (a<sub>i</sub> - A&#773;)<sup>2</sup></sup>&frasl;<sub>M</sub>)</td></tr><tr><td>Minimum</td><td>The minimum of the axis within the window</td></tr><tr><td>Maximum</td><td>The maximum of the axis within the window</td></tr><tr><td>Range</td><td>Range<sub>a</sub> = Maximum<sub>a</sub> - Minimum<sub>a</sub></td></tr><tr><td>Kurtosis</td><td>&beta;<sub>1,a</sub> = <sup>1</sup>&frasl;<sub>M</sub> &sum;<sub>i=1</sub><sup>M</sup> (<sup>a<sub>i</sub> - A&#773;<sub>a</sub></sup>&frasl;<sub>&sigma;<sub>a</sub></sub>)<sup>3</sup></td></tr><tr><td>Skewness</td><td>&beta;<sub>2,a</sub> = <sup>1</sup>&frasl;<sub>M</sub> &sum;<sub>i=1</sub><sup>M</sup> (<sup>a<sub>i</sub> - A&#773;<sub>a</sub></sup>&frasl;<sub>&sigma;<sub>a</sub></sub>)<sup>4</sup></td></tr><tr><td>Motion variation</td><td>MV = <sup>1</sup>&frasl;<sub>M</sub> (<sup>&sum;<sub>i=1</sub><sup>M-1</sup> |a<sub>x,i+1</sub> - a<sub>x,i</sub>| + &sum;<sub>i=1</sub><sup>M-1</sup> |a<sub>y,i+1</sub> - a<sub>y,i</sub>| + &sum;<sub>i=1</sub><sup>M-1</sup> |a<sub>z,i+1</sub> - a<sub>z,i</sub>|)</sup></td></tr><tr><td>Spectral entropy</td><td>H<sub>s</sub> = - &sum;<sub>k=1</sub><sup>N</sup> P<sub>k</sub> ln(P<sub>k</sub>) P<sub>k</sub> = <sup>|&lambda;<sub>k</sub>|<sup>2</sup></sup>&frasl;<sub>&sum;<sub>i=1</sub><sup>M</sup> |&lambda;<sub>i</sub>|<sup>2</sup></sub> and for the frequency &lambda;<sub>k</sub><br>where N is the number of points in the signal spectrum</td></tr></tbody></table>

Note: The formulas are depicted as a function of the acceleration along any axis denoted as a, while M is the total number of samples in the window.

In each outer training set, feature selection was carried out by selecting subsets of the most informative features using RF. The best features (i.e. the ones that contribute the most to the classification of the animal's state corresponding to every window period) were selected based on their Gini importance scores, which quantify the reduction in impurity achieved by each feature across all the decision trees. For each subset of an increasing range of the most important features (from 5 to 25, in steps of 5), a 3-fold CV was implemented in each outer training set, where one fold was used as a validation set and the remaining folds were used as an inner training set. The evaluation of this inner CV is used in a grid-search procedure to find the optimum hyperparameters of the machine learning classifiers. Each model is built and evaluated with every combination (discrete grid) of the manually specified subset of values for each hyperparameter. The discrete grid applied for each classifier is presented in Table 4. We refer to the scikit-learn library for details about hyperparameters and values [17]. Once, the optimal hyperparameters were found, the model was fitted to all training data. The output of the model is the probability that the time window belongs

to a given class. The optimal threshold for which a window is classified as inactive was calculated from the Receiver Operating Characteristics (ROC) curve directly. This curve represents the true positive rate (TPR) or recall versus the false positive rate (FPR) at each threshold setting.

$$TPR \text{ or recall} = \frac{TP}{TP + FN}$$

$$FPR = \frac{FP}{FP + TN}$$

The geometric mean or G-mean is a metric for imbalanced classification that, if optimized, will seek a balance between the TPR and the specificity, which is 1-FPR. Then, when the ROC curve is calculated, the G-mean can be calculated for each threshold:

$$G - mean = \sqrt{TPR * (1 - FPR)}$$

The optimal threshold is determined by the probability corresponding to the largest G-mean.

The same scheme and the same data split were used to compare prediction performance in the same conditions for the different window sizes and the three classifiers.

<table><caption>**Table 4**
Hyperparameters tuned for each classifier.</caption><thead><tr><th>Classifier</th><th>Hyperparameter</th><th>Discrete grid</th></tr></thead><tbody><tr><td rowspan="4">Random Forest</td><td>Number of estimators: number of trees in the forest</td><td>100, 250, 500, 800</td></tr><tr><td>Max depth: maximum depth of the tree</td><td>2, 4</td></tr><tr><td>Min samples split: the minimum number of samples required to split an internal node</td><td>2, 4</td></tr><tr><td>Min samples leaf: the minimum number of samples required to be a at leaf node</td><td>4, 8</td></tr><tr><td rowspan="3">Gradient Boosting</td><td>Number of estimators: the number of trees to perform</td><td>100, 250, 500, 800</td></tr><tr><td>Learning rate: shrinks the contribution of each tree</td><td>0.01, 0.1</td></tr><tr><td>Max depth: maximum depth of the individual trees</td><td>2, 4</td></tr><tr><td rowspan="3">Support Vector Machine</td><td>C: regularization parameter</td><td>1, 3</td></tr><tr><td>Kernel</td><td>Linear, RBF</td></tr><tr><td>Gamma: kernel coefficient</td><td>0.1, 0.4</td></tr></tbody></table>

<figure><img src="image_6.png" /><figcaption>**Fig. 3.** Nested k-fold cross-validation diagram.</figcaption></figure>
To train and validate such algorithms, accelerometer signals and their corresponding observed behaviours are required. Animal behaviours can be recorded through direct observation (Rayas-Amor et al., 2017; Rodriguez-Baena et al., 2020) or with images captured by a camera (Cornou and Lundbye-Christensen, 2010; Thompson et al., 2019).

Then, the signal is segmented into time windows. For each window, a set of statistical features is calculated. The classifier is trained using the combination of these statistical features as predictor variables and the corresponding behavioural annotations as the target. Once the model is trained, it can be applied to new accelerometer signals from new individuals to classify and monitor their behaviours. In this way, attaching an accelerometer to the rabbits would allow for obtaining individual patterns of activity, enabling their monitoring over long periods.

The present study aimed to develop and validate a model to classify active or inactive states over 15 days using accelerometer data from growing rabbits.

# Material and methods

## Ethics approval

The experimental procedures used in the research complied with the European directive 2010/63/EU and the Spanish guidelines for the care and use of animals in research (B.O.E. number 34, Real Decreto 53/2013). Animals were submitted to an experimental procedure approved by the Ethical Committee of IRTA and the Regional Government of Catalonia.

## Accelerometers

The accelerometers used in this study were the AX3 dataloggers (https://axivity.com/product/ax3). They are MEMS 3-axis accelerometers with onboard memory (512 MB), measuring 23 × 32.5 × 8.9 mm and weighing 11 g. The
## Evaluation of the models

The performance was evaluated in each of the test datasets using different metrics: recall, precision, F1 score and accuracy. The confusion matrix was also evaluated. Recall measures how often the models correctly identify inactive windows (true positive) from all the actual positive windows in the dataset. Precision measures how often the model correctly predicts inactive windows. It is defined as follows:

$$Precision = \frac{TP}{TP + FP}$$

The F1 score was computed to assess the overall performance of a classification model. This metric provides a single value that balances the recall and the precision:

$$F1 \text{ Score} = \frac{2xPrecision \times Recall}{Precision + Recall}$$

The accuracy is the proportion of correct predictions made by the model out of the total predictions made:

$$Accuracy = \frac{TP + TN}{TP + FN + TN + FP}$$

## Results

### Model performance

In this section, the performance of each classifier for each window size and each feature subset size is evaluated. It is important to note that a LOAOCV procedure was conducted in a combination of the learner, the window size and the feature subset size. Therefore, there were 16 prediction performances (one for each animal) for each combination.

For the same window size, similar results were obtained regardless of

the number of most important features (see figures in supplementary material, Figs. S1–S5). Therefore, here, we present the performance of the simplest and fastest model to train, which corresponds to the model trained using the top 5 features according to RF. The model performance of each classifier for each window size with this subset of the most important features is presented in this section.

The distribution of precision, recall and F1 score with the top 5 features depending on the window size for each machine learning model is presented in Fig. 4. The median of the precision, recall and F1 score increased as the window size increased, regardless of the machine learning model. However, the differences were not substantial. Similarly, no differences were observed among the three classifiers for the same window size. From now on, we will focus on the results obtained for each machine learning model with a window size of 9 s and the 5 top RF features. In that configuration, a median F1 score of 0.96, ranging from 0.88 to 0.99, was obtained with RF. The median (Q1, Q3) of F1 scores for the classifiers SVM and GB were 0.95 (0.90, 0.98) and 0.95 (0.93, 0.97), respectively. Regarding the precision, the median (Q1, Q3) was 1 (0.99, 1) for RF, SVM and GB. This means that 100% of the time when a window was predicted as the positive class (inactive), it truly belonged to this class. In addition, the median (Q1, Q3) recall for RF was 0.93 (0.89, 0.97). That means that 93% of the windows corresponding to inactive periods were detected by the model. The recall median (Q1, Q3) for SVM and GB was 0.91 (0.84, 0.97) and 0.92 (0.87, 0.95), respectively.

Regarding the accuracy of the model, with a window size of 9 s and the 5 top best features the median accuracy (Q1, Q3) for RF was 0.93 (0.89, 0.96), similar to the other classifiers (results not shown).

Since there is no substantial difference between the classifiers, only the confusion matrix for RF is presented (Fig. 5), showing the median values, as well as the Q1 and Q3 of the 16 folds. Regarding the positive class, i.e., inactive, 92 windows were classified as positive, all of them

<figure><img src="image_7.png" /><figcaption>Fig. 4. Distribution of precision, recall and F1 score for each model for each window size with the top 5 features. The green dot represents the mean across the 16 outer loops.</figcaption></figure>
accelerometer has configurable sample rates (frames per second) and sensitivity (+/- 2 g, +/- 4 g, +/- 8 g and +/- 16 g; 1 g =~9.81ms⁻²) so that both can be adapted depending on the targeted activities. In the present study, the sampling rate was set up to 25 Hz and the sensitivity to ± 8 g. With this configuration, the expected battery life was 30 days. Configuration and data download were performed by connecting each AX3 to a computer using a USB port and the OmGui software. The data of each accelerometer was downloaded at the end of the follow-up period for each animal.

## Methodology

In this section, the three main steps of the methodology are described: data collection, data preprocessing and model fitting and classification (Figure 1).

<figure><img src="image_2.png" /><figcaption>Figure 1. Overview data processing</figcaption></figure>
<figure><img src="image_8.png" /><figcaption>**Fig. 5.** Confusion matrix for random forest at a window size of 9 s with the top 5 more important features. The median values (Q1, Q3) of the 16 folds are depicted.</figcaption></figure>

TP. Only, 8 out of 100 inactive windows were misclassified as active windows (FN). Focusing on the negative class, out of the total of the 19 windows classified as active 42% of them belonged to the inactive class. If the active state were considered as the positive class, the median recall would be 100% (11/11+6) and the median precision of 58% (11/11+8). The most important features were the motion variation across the x, y, z and magnitude axes.

Inference of active/inactive states

The best RF model based on the F1 score was used to perform inference on the activity level of three randomly selected rabbits throughout a day. The model's input consisted of raw accelerometer signals segmented into equal-sized windows of 9 s each. The daily pattern activity of these rabbits is presented in Fig. 6. In this figure, it can be observed that the most significant activity patterns occurred during the night. This is particularly evident in individuals 1 and 3, where intense activity concludes around 5/6h in the morning and resumes around 18h.

Discussion

Our analysis aimed to train a model capable of classifying two general states of growing rabbits, active and inactive, based on accelerometer data. To find the best possible classification performance, multiple machine learning algorithms have been tested, with their respective hyperparameter tuning, on top of a variety of window sizes for the accelerometer signals.

Firstly, our study showed that accelerometers attached to the back of rabbits in cages can be used to reliably classify inactive states. With a window size of 9 s and the top 5 features, the RF model reaches a median precision of 100% and a median recall of 93%. In addition, the models were validated in a configuration where the rabbits used for model training have not been used for model testing, suggesting that the model also has a good genericity [8]. Furthermore, it is noteworthy to point out that the rabbits did not struggle to wear the sensor. It did not affect their behaviour or that of their cage mates, no fights or attempts to remove the device were appreciated. At the end of the experiment, the accelerometers were retrieved in perfect condition, with no hardware damage, making it a viable option to measure the activity of growing rabbits. To the best of our knowledge, this is the first attempt where wearable accelerometers have been used to monitor the behaviours of growing rabbits, thus highlighting the potential of such technologies in that field.

Even if the models' performance are really good, several improvements could be proposed. First, it was not possible to simultaneously test different accelerometer configurations due to the limited number of sensors at our disposal. Based on results obtained from other species and

<figure><img src="image_9.png" /><figcaption>**Fig. 6.** Daily pattern activity of three individuals.</figcaption></figure>
Step 1: data collection

The experiment was carried out at IRTA's nucleus farm at Caldes de Montbui, Spain. In this farm, the photoperiod was set to 16 light h/d (from 07:00 to 23:00h) and the environmental temperature was kept at 20 ± 2 °C. The animals included in this study come from a sire line commonly used in rabbit farms. The animals were housed in groups of 6 kits in cages measuring 76 cm width x 100 cm length x 32 cm height. Each cage was equipped with an electronic feeder that allowed one rabbit to eat at a time ensuring accurate identification of the animal. The study considered a total of 16 animals belonging to 2 batches and born between November 2022 and February 2023. The observation period was from 37 to 51 days of age.

In each batch, one animal from each cage (8 cages in total) was randomly selected to be equipped with the accelerometer for 15 consecutive days. The tri-axial accelerometer was enclosed into a resistant plastic box and fixed to the rabbit's back using an elastic band (Figure 2). All the sensors were attached in the same way for all the animals, i.e., with the same orientation. This ensured that the x-axis detected the backward-forward direction, the y-axis detected the left-right direction and the z-axis detected the down-up direction whatever the rabbit.
following the device instructions, the sampling rate was set up to 25 Hz and the sensitivity to ±8g. However, for future analyses, it would be advisable to test multiple configurations and assess which is the best one for the case study.

As for the placement, in rabbits, the most feasible option was to attach it to their backs, at the level of the rib cage, using an elastic band Fig. 2. This arrangement enables the sensor to move with the general movement of the rabbit but may fail to catch activities such as eating when there is only head movement. Thus, the signal between the animal lying down and eating can be hardly distinguished. In the case of the drinking activity, since the position of the nipple is on top of the cage, the rabbit had to stand up, which should be reflected on the accelerometer data. The decision of where to place the sensor is therefore of high relevance as it will determine which behaviours will be measured with higher precision [3]. In the literature, some work can be found where more than one accelerometer was employed, demonstrating an improvement in predicting behaviours versus the only one sensor approach [7,14]. However, in growing rabbits, this option seems difficult to achieve.

In the process of synchronization, an average gap between the camera clock and accelerometer clock was observed in each continuous sequence due to the time drift. Thus, the impact that it might have on the correspondence between the accelerometer signal and the annotated behaviours can be significant if not corrected. In this study, each continuous sequence was manually corrected to ensure a perfect match between the signal and the annotations but this is time-consuming and labour-intensive, which may make this type of study difficult to achieve. One solution to this problem of accelerometer clock drift is to equip the animals and film them for several hours (~8 h), then reset the cameras and sensors, and repeat the test the next day, since drift accumulates over time.

In the context of model training, the number of samples is also highly important. It depends on the amount of data available for each behaviour but also of the chosen window size; bigger window sizes result in smaller sample sizes and *vice versa*. Furthermore, for large window sizes, there is a greater likelihood of having several behaviours in the window and therefore, of excluding it from the dataset for the analysis. If these windows are not removed but instead the most likely class is assigned, the signal corresponding to different behaviours would be present in the same window, leading to noise. With a window size equal to 9 s, 1,941 windows were generated, 86% of them belonging to the inactive class, resulting in a class imbalance problem. For that purpose, techniques for over-sampling and under-sampling could be applied [23]. In the present study, multiple Synthetic Minority Over-sampling Technique (SMOTE) variants were tested (results not shown), nevertheless, they did not enhance the performance of the overall model. Results could be improved with additional data annotations and with a better representation of all the classes.

Multiple features were extracted from the segmented accelerometer signal, as typically done in the field to predict a variety of behaviours from accelerometer data [6,24,25]. A parallel approach can be to apply neural networks, as done by Turner, Thompson [23], to the accelerometer time series, thus avoiding knowledge-based feature extraction. They reported that neural networks outperformed classical machine learning algorithms. However, this kind of approach requires a substantial dataset size.

In the present study, the model accuracy was greater than that of the majority class proportion. Regarding the trade-off between precision and recall, with RF and a window size of 9 s, we can predict inactive behaviours with a median precision of 1 (Q1=0.99, Q3=1) and a median recall of 0.93 (Q1=0.89, Q3=0.97). As already explained, precision refers to the proportion of TP among all positive predictions and recall refers to the proportion of TP among all the actual positive cases. In this case, the model is highly reliable in correctly classifying positive instances and it is capable of detecting 93% of the positive instances. The main limitation to achieving higher recall values is that the signal in

some periods classified as inactive is similar to that obtained in some periods classified as active. This may be a consequence of multiple factors, such as having mixed data in the inactive class (the sensor might move when the animal is drinking or eating), the placement and strapping of the sensor or possible light interactions between the rabbits (the sensor is slightly hit by another rabbit). On the other hand, if the active class were considered as the positive class, we would obtain a perfect recall but a median precision of 58% due to confusion between inactive instances and active ones.

A potential use of the activity patterns obtained from accelerometers in growing rabbits would be the detection of sick animals [26,27]. These daily patterns, as shown in Fig. 6, could be useful for implementing alarm systems for intervention if a behaviour change is observed. Moreover, understanding daily activity patterns can also assist in optimizing management strategies and identifying potential stressors or environmental factors affecting animal behaviour. On the other hand, the activity pattern has been found to be related to feed efficiency in beef steers [1]. This opens the possibility of defining new or additional phenotypes that could be included in a breeding program to select for feed efficiency.

Nevertheless, some drawbacks need to be considered regarding the use of this kind of device. The accelerometer used in this study is required to be connected to the computer to download the data. That means, that the device must be removed from the animals every time this action is needed. In rabbits, this is not a significant problem because they are small animals and easy to handle. Similarly, the anchoring system was an elastic band, which is easy to put on and take off but it involves handling the animal in a way that can be stressful for it. On top of that, a long-lasting battery and Bluetooth connection that ensures storage of data on an external database are important characteristics to be included in the device without compromising its price, size and weight.

The greatest advantage of these devices compared to other systems is that they allow the individualized monitoring of animals without the need for tracking. This makes accelerometers especially useful for animals in outdoor production systems. Furthermore, the data collected by this device could be complemented with data available from other types of sensors, such as radio frequency identification tags, cameras, or microphones to improve the capabilities of the models.

## Conclusions

This is the first study where the aim was to automate the detection of active and inactive states in rabbits. The results show that, with the device configuration, algorithms and hyperparameters tested, the models presented a high level of precision, signifying that the model is highly reliable in correctly classifying positive instances. Additionally, achieving a recall of 0.93 emphasizes the model's effectiveness in capturing a substantial portion of positive instances. The results could be improved if more data were gathered to have a better representation of the classes, which would also allow distinguishing between classes. Therefore, it appears to be a valuable tool for obtaining insights into the behaviour of rabbits and the factors that influence their welfare and productive efficiency.

## Funding

This study was part of the project PID2021-128173OR-C21 (GENEF3) and MM is a recipient of a "Formacion de Personal Investigador (FPI)" associated with the research project RTI2018-097610R-I00.

## Data statement

The data that support the findings of this study are available from the corresponding author upon reasonable request.
<figure><img src="image_3.png" /><figcaption>Figure 2. Rabbit equipped with the accelerometer.</figcaption></figure>

The rabbits were videotaped throughout the two-week experiment in each of the batches using a 2D camera placed on the top of the cages. Videos of rabbits equipped with the accelerometer were observed for at least 35 minutes and a maximum of 39 minutes (not entirely sequential). All the pre-defined behaviours that took place during that time were manually annotated by the same person according to an ethogram (Table 1) and the BORIS software (Friard and Gamba, 2016). In the end, animals' behaviours on various days of the experiment and at different moments of the day were annotated, resulting in a total of ~10 hours of video annotations across the 16 rabbits.
## Ethics approval

The experimental procedures used in the research complied with the European directive 2010/63/EU and the Spanish guidelines for the care and use of animals in research (B.O.E. number 34, Real Decreto 53/2013). Animals were submitted to an experimental procedure approved by the Ethical Committee of IRTA and the Regional Government of Catalonia.

Fig. S1. Distribution of precision, recall and F1 score for each model for each subset of the most important features with a window size of 1 s. The green dot represents the mean across the 16 outer loops.

Fig. S2. Distribution of precision, recall and F1 score for each model for each subset of the most important features with a window size of 3 s. The green dot represents the mean across the 16 outer loops.

Fig. S3. Distribution of precision, recall and F1 score for each model for each subset of the most important features with a window size of 5 s. The green dot represents the mean across the 16 outer loops.

Fig. S4. Distribution of precision, recall and F1 score for each model for each subset of the most important features with a window size of 7 s. The green dot represents the mean across the 16 outer loops.

Fig. S5. Distribution of precision, recall and F1 score for each model for each subset of the most important features with a window size of 9 s. The green dot represents the mean across the 16 outer loops.

## CRediT authorship contribution statement

**Mónica Mora:** Writing – original draft, Methodology, Formal analysis, Conceptualization. **Lucile Riaboff:** Writing – review & editing, Supervision, Methodology, Formal analysis. **Ingrid David:** Writing – review & editing, Supervision, Conceptualization. **Juan Pablo Sánchez:** Funding acquisition. **Miriam Piles:** Writing – review & editing, Supervision, Methodology, Funding acquisition, Conceptualization.

## Declaration of competing interest

The authors declare that they have no known competing financial interests or personal relationships that could have appeared to influence the work reported in this paper.

## Acknowledgements

We would like to thank Oscar Perucho for their contribution to data recording and animal care during the experiment. We would like to express our gratitude to Padraig Cunningham for his valuable grammar review contributions.

## Supplementary materials

Supplementary material associated with this article can be found, in the online version, at doi:10.1016/j.atech.2024.100675.

## Data availability

Data will be made available on request.

## References

[1] M.J. Haskell, J.A. Rooke, R. Roehe, S.P. Turner, J.J. Hyslop, A. Waterhouse, C. A. Duthie, Relationships between feeding behaviour, activity, dominance and feed efficiency in finishing beef steers, Appl. Anim. Behav. Sci. 210 (2019) 9–15, https://doi.org/10.1016/j.applanim.2018.10.012.

[2] D. Berckmans, General introduction to precision livestock farming, Anim. Front. 7 (2017) 6–11, https://doi.org/10.2527/af.2017.0102.

[3] J.M. Chapa, K. Maschat, M. Iwersen, J. Baumgartner, M. Drillich, Accelerometer systems as tools for health and welfare assessment in cattle and pigs–a review, Behav. Process. 181 (2020) 104262, https://doi.org/10.1016/j.beproc.2020.104262.

[4] M. Benjamin, S. Yik, Precision livestock farming in swine welfare: a review for swine practitioners, Animals 9 (2019), https://doi.org/10.3390/ani9040133.

[5] P. Martiskainen, M. Järvinen, J.P. Skön, J. Tiiriikainen, M. Kolehmainen, J. Mononen, Cow behaviour pattern recognition using a three-dimensional accelerometer and support vector machines, Appl. Anim. Behav. Sci. 119 (2009) 32–38, https://doi.org/10.1016/j.applanim.2009.03.005.

[6] M.S. Shahriar, D. Smith, A. Rahman, M. Freeman, J. Hills, R. Rawnsley, D. Henry, G. Bishop-Hurley, Detecting heat events in dairy cows using accelerometers and unsupervised learning, Comput. Electron. Agric. 128 (2016) 20–26, https://doi.org/10.1016/j.compag.2016.08.009.

[7] N. Ringgenberg, R. Bergeron, N. Devillers, Validation of accelerometers to automatically record sow postures and stepping behaviour, Appl. Anim. Behav. Sci. 128 (2010) 37–44, https://doi.org/10.1016/j.applanim.2010.09.018.

[8] L. Riaboff, L. Shalloo, A.F. Smeaton, S. Couvreur, A. Madouasse, M.T. Keane, Predicting livestock behaviour using accelerometers: a systematic review of processing techniques for ruminant behaviour prediction from raw accelerometer data, Comput. Electron. Agric. 192 (2022) 106610, https://doi.org/10.1016/j.compag.2021.106610.

[9] J.A. Vázquez Diosdado, Z.E. Barker, H.R. Hodges, J.R. Amory, D.P. Croft, N.J. Bell, E.A. Codling, Classification of behaviour in housed dairy cows using an accelerometer-based activity monitoring system, Anim. Biotelem. 3 (2015) 15, https://doi.org/10.1186/s40317-015-0045-8.

[10] L. Riaboff, S. Poggi, A. Madouasse, S. Couvreur, S. Aubin, N. Bédère, E. Goumand, A. Chauvin, G. Plantier, Development of a methodological framework for a robust prediction of the main behaviours of dairy cows using a combination of machine learning algorithms on accelerometer data, Comput. Electron. Agric. 169 (2020) 105179, https://doi.org/10.1016/j.compag.2019.105179.

[11] D.S. Rodriguez-Baena, F.A. Gomez-Vela, M. García-Torres, F. Divina, C. D. Barranco, N. Daz-Diaz, M. Jimenez, G. Montalvo, Identifying livestock behavior patterns based on accelerometer dataset, J. Comput. Sci. 41 (2020) 101076, https://doi.org/10.1016/j.jocs.2020.101076.

[12] A.A. Rayas-Amor, E. Morales-Almaráz, G. Licona-Velázquez, R. Veyra-Alberto, A. García-Martínez, C.G. Martínez-García, R.G. Cruz-Monterrosa, G.C. Miranda-de la Lama, Triaxial accelerometers for recording grazing and ruminating time in dairy cows: an alternative to visual observations, J. Vet. Behav. 20 (2017) 102–108, https://doi.org/10.1016/j.jweb.2017.04.003.

[13] C. Cornou, S. Lundbye-Christensen, Classification of sows' activity types from acceleration patterns using univariate and multivariate models, Comput. Electron. Agric. 72 (2010) 53–60, https://doi.org/10.1016/j.compag.2010.01.006.

[14] R.J. Thompson, S. Matthews, T. Plötz, I. Kyriazakis, Freedom to lie: how farrowing environment affects sow lying behaviour assessment using inertial sensors, Comput. Electron. Agric. 157 (2019) 549–557, https://doi.org/10.1016/j.compag.2019.01.035.

[15] O. Friard, M. Gamba, BORIS: a free, versatile open-source event-logging software for video/audio coding and live observations, Methods Ecol. Evol. 7 (2016) 1325–1330, https://doi.org/10.1111/2041-210X.12584.

[16] Jones, E., T. Oliphant, and P. Peterson. 2001. SciPy: open source scientific tools for python.

[17] F. Pedregosa, G. Varoquaux, A. Gramfort, V. Michel, B. Thirion, O. Grisel, M. Blondel, P. Prettenhofer, R. Weiss, V. Dubourg, J. Vanderplas, A. Passos, D. Cournapeau, M. Brucher, M. Perrot, É. Duchesnay, Scikit-learn: machine learning in python, J. Mach. Learn. Res. 12 (2011) 2825–2830.

[18] D. Smith, A. Rahman, G.J. Bishop-Hurley, J. Hills, S. Shahriar, D. Henry, R. Rawnsley, Behavior classification of cows fitted with motion collars: decomposing multi-class classification into a set of binary problems, Comput. Electron. Agric. 131 (2016) 40–50, https://doi.org/10.1016/j.compag.2016.10.006.

[19] H. Rautiainen, M. Alam, P.G. Blackwell, A. Skarin, Identification of reindeer fine-scale foraging behaviour using tri-axial accelerometer data, Mov. Ecol. 10 (2022) 40, https://doi.org/10.1186/s40462-022-00339-0.

[20] L. Breiman, Random forests, Mach. Learn. 45 (2001) 5–32.

[21] N. Cristianini, E. Ricci, Support vector machines, in: M.Y. Kao (Ed.), Encyclopedia of Algorithms, editor, Springer US, Boston, MA, 2008, pp. 928–932.

[22] J. Friedman, Greedy function approximation: a gradient boosting machine, Ann. Stat. 29 (2000), https://doi.org/10.1214/aos/1013203451.

[23] K.E. Turner, A. Thompson, I. Harris, M. Ferguson, F. Sohel, Deep learning based classification of sheep behaviour from accelerometer data with imbalance, Inf. Process. Agric. (2022), https://doi.org/10.1016/j.inpa.2022.04.001.

[24] L. Lush, R.P. Wilson, M.D. Holton, P. Hopkins, K.A. Marsden, D.R. Chadwick, A. J. King, Classification of sheep urination events using accelerometers to aid improved measurements of livestock contributions to nitrous oxide emissions, Comput. Electron. Agric. 150 (2018) 170–177, https://doi.org/10.1016/j.compag.2018.04.018.

[25] S. Pandey, U. Kalwa, T. Kong, B. Guo, P.C. Gauger, D.J. Peters, K.J. Yoon, Behavioral monitoring tool for pig farmers: ear tag sensors, machine intelligence, and technology adoption roadmap, Animals 11 (2021), https://doi.org/10.3390/ani11092665 (Basel).

[26] I. Dittrich, M. Gertz, J. Krieter, Alterations in sick dairy cows' daily behavioural patterns, Heliyon 5 (2019) e02902, https://doi.org/10.1016/j.heliyon.2019.02.002.

[27] L.A. González, B.J. Tolkamp, M.P. Coffey, A. Ferret, I. Kyriazakis, Changes in feeding behavior as possible indicators for the automatic monitoring of health disorders in dairy cows, J. Dairy Sci. 91 (2008) 1017–1028, https://doi.org/10.3168/jds.2007-0530.
<table><caption>Table 1. Definition of the different behaviours annotated.</caption><thead><tr><th>Behaviour</th><th>Classification description</th><th>State</th><th>Hours of observation</th></tr></thead><tbody><tr><td>Lying</td><td>The rabbit is lying down</td><td>inactive</td><td>5.34</td></tr><tr><td>Eating</td><td>The rabbit is inside the electronic feeder</td><td>inactive</td><td>1.75</td></tr><tr><td>Moving</td><td>The rabbit is moving without changing its position</td><td>active</td><td>1.68</td></tr><tr><td>Grooming</td><td>The rabbit is licking itself</td><td>active</td><td>0.67</td></tr><tr><td>Walking</td><td>The rabbit is moving while changing its position</td><td>active</td><td>0.14</td></tr><tr><td>Drinking</td><td>The rabbit is drinking</td><td>inactive</td><td>0.34</td></tr></tbody></table>

Due to the lack of representation of some predefined behaviours, they were grouped according to the state of the animal as active or inactive. Thus, it was considered that the animal was active when it was moving, walking and grooming, and inactive when it was lying, eating and drinking. The last two behaviours were included in the inactive class because of the little movement of the animal's back that produced a flat signal in the accelerometer.

## Step 2: data preprocessing

In this section, the different phases of data preprocessing after data collection are described. Four sequential operations were carried out: i) synchronization of the accelerometer signal with the behaviour annotations; ii) new time series extraction; iii) accelerometer signal segmentation into time windows; and iv) calculation of statistical features in each of the time windows. All the codes were run with the programming language Python v3.10.11. The main packages used were SciPy (Jones et al., 2001) and Scikit-learn (Fabian Pedregosa Gaël Varoquaux, 2011).
**Synchronization.** The time stamps of accelerometer signals and behaviour annotations were synchronized to guarantee that the annotations corresponded to the correct sequences of the accelerometer signal. The synchronization was possible thanks to a pattern in the signal created by shaking the accelerometer in front of the cameras before and after the experiment. Thus, in the videos, accelerometer shaking could be observed, allowing for accelerometer timestamp synchronization with the videos. As a result of this process, a dataset was generated in which behaviour annotations for each rabbit matched the corresponding accelerometer data sequences. However, the accelerometer time drift (±1.7 seconds per day maximum; AX3 user guidebook: https://axivity.com/userguides/ax3/), i.e., the fact that the accelerometer clock is not able to maintain constant precision over time, moving forward or falling behind, led to a time difference between the accelerometer time-series and the behaviour annotations, even after the synchronization process). Therefore, each continuous sequence of time series associated with annotations (~ 35-39 minutes) was visually inspected. Any temporal mismatch identified between the annotations and the time series was noted. The alignment was then corrected for each sequence to ensure that it was perfectly synchronised with the associated behaviour.

**New time series extraction.** From the measurements in each of the three axes (x,y and z), a fourth orientation-independent one was calculated as follows:

$$a_{\text{mag}} = \sqrt{a_x^2 + a_y^2 + a_z^2}$$

Where $a_x$, $a_y$ and $a_z$ are the acceleration on the x-axis, y-axis and z-axis, respectively. This variable is called “the magnitude”.

On the other hand, the acceleration measured by the accelerometer in the three axes may be separated into both static and dynamic acceleration. The static acceleration registers
the orientation of the animal, while the dynamic gets information about the energy expended without the ‘bias’ of the gravitational force. To separate static from dynamic acceleration, filters are typically applied to the raw acceleration. In the present study, low and high-pass filters were used to get the static and the dynamic acceleration, respectively. Considering that the static component is constant and thus leads to frequencies ~ 0, usually, the cut-off frequency used is 0.3 Hz (Smith et al., 2016; Riaboff et al., 2020). From the static acceleration, the angles around x (roll) and y (pitch) were calculated to estimate the accelerometer orientation following the definition presented by Rautiainen et al. (2022). From the dynamic acceleration, the norm of the dynamic acceleration (VeDBA) and the sum of the absolute value of dynamic acceleration (OBDA) were computed. The formulas for all these features are as follows:

$$ pitch = -atan\left(\frac{static_x}{\sqrt{static_y^2 + static_z^2}}\right) $$

$$ roll = atan2(static_y, static_z) $$

$$ VeDBA = \sqrt{dynamic_x^2 + dynamic_y^2 + dynamic_z^2} $$

$$ OBDA = |dynamic_x| + |dynamic_y| + |dynamic_z| $$

*Time-windows creation.* The accelerometer signal was split into time windows of the same size. As the movement of rabbits is brief, window sizes smaller than 10 seconds were created (Riaboff et al., 2022). To determine the optimal window size, various short window sizes were tested: 1, 3, 5, 7 and 9 seconds. Windows with a mix of both active and inactive classes were removed from the analysis. Thus, each window was associated with just one of the classes. In Table 2, for each window size, the total number of
obtained windows is shown together with the number of them belonging to the inactive class.

<table><caption>Table 2. Total number of windows and percentage of windows in the inactive class.</caption><thead><tr><td>Window size</td><td>Total windows</td><td>Percentage windows inactive</td></tr></thead><tbody><tr><td>1 s</td><td>24,685</td><td>0.77</td></tr><tr><td>3 s</td><td>7,471</td><td>0.80</td></tr><tr><td>5 s</td><td>4,052</td><td>0.82</td></tr><tr><td>7 s</td><td>2,676</td><td>0.86</td></tr><tr><td>9 s</td><td>1,941</td><td>0.86</td></tr></tbody></table>

*Features calculation.* For each time window, features were computed on each of the time series in the time and frequency domain. A total of 41 features were computed. Table 3 shows all the features obtained and their formulas. In the time domain, the features calculated were related to position parameters like the mean and median, as well as dispersion parameters like the standard deviation, the minimum, the maximum and the range. Kurtosis and skewness were also computed in the time domain. Skewness measures the lack of symmetry of the data distribution while kurtosis measures whether the data are heavy-tailed or light-tailed relative to a normal distribution. Another feature typically used is the motion variation which indicates the rate of change in the signal: a more energetic movement will lead to higher motion variation. Finally, in the frequency domain, the spectral entropy was calculated only for the magnitude axis. It refers to a measure of the random process uncertainty in the accelerometer signal frequency distribution. Only the range was computed for the pitch, roll, OBDA and VeDBA time series.
<table><caption>Table 3. Formulas of the extracted features from the acceleration data.</caption><thead><tr><th>Feature</th><th>Formula</th></tr></thead><tbody><tr><td>Average</td><td>A&#773;<sub>a</sub> = <sup>1</sup>&frasl;<sub>M</sub> &sum;<sub>i=1</sub><sup>M</sup> a<sub>i</sub></td></tr><tr><td>Median</td><td>The median of the axis within the window</td></tr><tr><td>Standard deviation</td><td>&sigma;<sub>a</sub> = &radic;(<sup>&Sigma;<sub>i=1</sub><sup>M</sup> (a<sub>i</sub> - A&#773;)<sup>2</sup></sup>&frasl;<sub>M</sub>)</td></tr><tr><td>Minimum</td><td>The minimum of the axis within the window</td></tr><tr><td>Maximum</td><td>The maximum of the axis within the window</td></tr><tr><td>Range</td><td>Range<sub>a</sub> = Maximum<sub>a</sub> - Minimum<sub>a</sub></td></tr><tr><td>Kurtosis</td><td>&beta;<sub>1,a</sub> = <sup>1</sup>&frasl;<sub>M</sub> &sum;<sub>i=1</sub><sup>M</sup> (<sup>a<sub>i</sub> - A&#773;<sub>a</sub></sup>&frasl;<sub>&sigma;<sub>a</sub></sub>)<sup>3</sup></td></tr><tr><td>Skewness</td><td>&beta;<sub>2,a</sub> = <sup>1</sup>&frasl;<sub>M</sub> &sum;<sub>i=1</sub><sup>M</sup> (<sup>a<sub>i</sub> - A&#773;<sub>a</sub></sup>&frasl;<sub>&sigma;<sub>a</sub></sub>)<sup>4</sup></td></tr><tr><td>Motion variation</td><td>MV = <sup>1</sup>&frasl;<sub>M</sub> (<sup>&sum;<sub>i=1</sub><sup>M-1</sup> |a<sub>x,i+1</sub> - a<sub>x,i</sub>|</sup>&frasl;<sub>&sum;<sub>i=1</sub><sup>M-1</sup> |a<sub>y,i+1</sub> - a<sub>y,i</sub>| + &sum;<sub>i=1</sub><sup>M-1</sup> |a<sub>z,i+1</sub> - a<sub>z,i</sub>|</sup>)</td></tr><tr><td>Spectral entropy</td><td>H<sub>s</sub> = - &sum;<sub>k=1</sub><sup>N</sup> P<sub>k</sub> ln(P<sub>k</sub>) P<sub>k</sub> = <sup>|&lambda;<sub>k</sub>|<sup>2</sup></sup>&frasl;<sub>&Sigma;<sub>i</sub>|&lambda;<sub>i</sub>|<sup>2</sup></sub> and for the frequency &lambda;<sub>k</sub> where N is the number of points in the signal spectrum</td></tr></tbody></table>

Note: The formulas are depicted as a function of the acceleration along any axis denoted as a, while M is the total number of samples in the window.
Step 3: Model fitting and classification of the animal state from the accelerometer
signal

The goal of this step was to train a machine learning model using the features calculated
in the previous step to classify the animal state (active or inactive) during every time
window. The inactive class was considered as the positive class.

Three machine learning algorithms were tested and their classification performance was
evaluated: Random Forest (RF) (Breiman, 2001), Support Vector Machine (SVM)
(Cristianini and Ricci, 2008) and Gradient Boosting (GB) (Friedman, 2000). RF is an
ensemble learning method combining several classification trees. Each decision tree is
fitted to a set of subsamples randomly selected through a bootstrapping procedure and
using randomly selected subsets of the predictor variables. The global prediction is then
obtained as the majority vote across all the predictions from all trees. GB builds a series
of weak decision trees, where each subsequent tree corrects the errors made by the
previous ones. The final prediction is a combination of all the weak trees. On the other
hand, SVM is a supervised learning algorithm, that aims to find the hyperplane that best
separates different classes in the feature space. More information about these classifiers
can be found in the literature cited above.

For each classifier, a nested resampling (Figure 3) was implemented to obtain reliable
performance estimates. This procedure consists of two nested resampling loops. In the
outer resampling loop, a Leave-One-Animal Out Cross-Validation (LOAOCV) was
carried out. In LOAOCV, the dataset is divided into n subsets, where n is the number of
animals. For each iteration of the outer loop, data points corresponding to one animal
are held out as the testing dataset, and the model is trained on the remaining data points,
ensuring that all the data points are used for prediction. The models were thus tested
with different animals than those used for model training, preventing overfitting and
over-optimistic results. This approach allowed us to evaluate the predictive power of the model while considering the variability inherent in individual animals.

<figure><img src="image_4.png" /><figcaption>Figure 3. Nested k-fold cross-validation diagram.</figcaption></figure>

In each outer training set, feature selection was carried out by selecting subsets of the most informative features using RF. The best features (i.e. the ones that contribute the most to the classification of the animal's state corresponding to every window period) were selected based on their Gini importance scores, which quantify the reduction in impurity achieved by each feature across all the decision trees. For each subset of an increasing range of the most important features (from 5 to 25, in steps of 5), a 3-fold CV was implemented in each outer training set, where one fold was used as a validation set and the remaining folds were used as an inner training set. The evaluation of this inner CV is used in a grid-search procedure to find the optimum hyperparameters of the machine learning classifiers. Each model is built and evaluated with every combination (discrete grid) of the manually specified subset of values for each hyperparameter. The discrete grid applied for each classifier is presented in Table 4. We refer to the scikit-learn library for details about hyperparameters and values (Fabian Pedregosa Gaël
Varoquaux, 2011). Once, the optimal hyperparameters were found, the model was fitted to all training data. The output of the model is the probability that the time window belongs to a given class. The optimal threshold for which a window is classified as inactive was calculated from the Receiver Operating Characteristics (ROC) curve directly. This curve represents the true positive rate (TPR) or recall versus the false positive rate (FPR) at each threshold setting.

$$TPR \text{ or recall} = \frac{TP}{TP + FN}$$

$$FPR = \frac{FP}{FP + TN}$$

The geometric mean or G-mean is a metric for imbalanced classification that, if optimized, will seek a balance between the TPR and the specificity, which is 1-FPR. Then, when the ROC curve is calculated, the G-mean can be calculated for each threshold:

$$G - mean = \sqrt{TPR * (1 - FPR)}$$

The optimal threshold is determined by the probability corresponding to the largest G-mean.

The same scheme and the same data split were used to compare prediction performance in the same conditions for the different window sizes and the three classifiers.
<table><caption>Table 4. Hyperparameters tuned for each classifier</caption><thead><tr><th>Classifier</th><th>Hyperparameter</th><th>Discrete grid</th></tr></thead><tbody><tr><td rowspan="4">Random Forest</td><td><strong>Number of estimators:</strong> number of trees in the forest</td><td>100, 250, 500, 800</td></tr><tr><td><strong>Max depth:</strong> maximum depth of the tree</td><td>2, 4</td></tr><tr><td><strong>Min samples split:</strong> the minimum number of samples required to split an internal node</td><td>2, 4</td></tr><tr><td><strong>Min samples leaf:</strong> the minimum number of samples required to be a leaf node</td><td>4, 8</td></tr><tr><td rowspan="3">Gradient Boosting</td><td><strong>Number of estimators:</strong> the number of trees to perform</td><td>100, 250, 500, 800</td></tr><tr><td><strong>Learning rate:</strong> shrinks the contribution of each tree</td><td>0.01, 0.1</td></tr><tr><td><strong>Max depth:</strong> maximum depth of the individual trees</td><td>2, 4</td></tr><tr><td rowspan="3">Support Vector Machine</td><td><strong>C:</strong> regularization parameter</td><td>1, 3</td></tr><tr><td><strong>Kernel</strong></td><td>Linear, RBF</td></tr><tr><td><strong>Gamma:</strong> kernel coefficient</td><td>0.1, 0.4</td></tr></tbody></table>

## Evaluation of the models

The performance was evaluated in each of the test datasets using different metrics: recall, precision, F1 score and accuracy. The confusion matrix was also evaluated. Recall measures how often the models correctly identify inactive windows (true positive) from all the actual positive windows in the dataset. Precision measures how often the model correctly predicts inactive windows. It is defined as follows:

$$Precision = \frac{TP}{TP + FP}$$
The F1 score was computed to assess the overall performance of a classification model.

This metric provides a single value that balances the recall and the precision:

$$F1 \text{ Score} = \frac{2 \times \text{Precision} \times \text{Recall}}{\text{Precision} + \text{Recall}}$$

The accuracy is the proportion of correct predictions made by the model out of the total predictions made:

$$Accuracy = \frac{TP+TN}{TP+FN+TN+FP}$$

# Results

## Model performance

In this section, the performance of each classifier for each window size and each feature subset size is evaluated. It is important to note that a LOAOCV procedure was conducted in a combination of the learner, the window size and the feature subset size.

Therefore, there were 16 prediction performances (one for each animal) for each combination.

For the same window size, similar results were obtained regardless of the number of most important features (see figures in supplementary material, Figure S1, S2, S3, S4, and S5). Therefore, here, we present the performance of the simplest and fastest model to train, which corresponds to the model trained using the top 5 features according to RF. The model performance of each classifier for each window size with this subset of the most important features is presented in this section.

The distribution of precision, recall and F1 score with the top 5 features depending on the window size for each machine learning model is presented in Figure 4. The median of the precision, recall and F1 score increased as the window size increased, regardless of the machine learning model. However, the differences were not substantial.
Similarly, no differences were observed among the three classifiers for the same window size. From now on, we will focus on the results obtained for each machine learning model with a window size of 9 seconds and the 5 top RF features. In that configuration, a median F1 score of 0.96, ranging from 0.88 to 0.99, was obtained with RF. The median (Q1, Q3) of F1 scores for the classifiers SVM and GB were 0.95 (0.90, 0.98) and 0.95 (0.93, 0.97), respectively. Regarding the precision, the median (Q1, Q3) was 1 (0.99, 1) for RF, SVM and GB. This means that 100% of the time when a window was predicted as the positive class (inactive), it truly belonged to this class. In addition, the median (Q1, Q3) recall for RF was 0.93 (0.89, 0.97). That means that 93% of the windows corresponding to inactive periods were detected by the model. The recall median (Q1, Q3) for SVM and GB was 0.91 (0.84, 0.97) and 0.92 (0.87, 0.95), respectively.

<figure><img src="image_5.png" /><figcaption>Figure 4. Distribution of precision, recall and F1 score for each model for each window size with the top 5 features. The green dot represents the mean across the 16 outer loops.</figcaption></figure>
Regarding the accuracy of the model, with a window size of 9 seconds and the 5 top best features the median accuracy (Q1, Q3) for RF was 0.93 (0.89, 0.96), similar to the other classifiers (results not shown).

Since there is no substantial difference between the classifiers, only the confusion matrix for RF is presented (Figure 5), showing the median values, as well as the Q1 and Q3 of the 16 folds. Regarding the positive class, i.e., inactive, 92 windows were classified as positive, all of them TP. Only, 8 out of 100 inactive windows were misclassified as active windows (FN). Focusing on the negative class, out of the total of the 19 windows classified as active 42% of them belonged to the inactive class. If the active state were considered as the positive class, the median recall would be 100% ($\frac{11}{11+0}$) and the median precision of 58% ($\frac{11}{11+8}$). The most important features were the motion variation across the x, y, z and magnitude axes.

<figure><img src="image_6.png" /><figcaption>Figure 5. Confusion matrix for random forest at a window size of 9 seconds with the top 5 more important features. The median values (Q1, Q3) of the 16 folds are depicted.</figcaption></figure>
Inference of active/inactive states

<figure><img src="image_7.png" /><figcaption>Figure 6. Daily pattern activity of three individuals.</figcaption></figure>

The best RF model based on the F1 score was used to perform inference on the activity
level of three randomly selected rabbits throughout a day. The model's input consisted
of raw accelerometer signals segmented into equal-sized windows of 9 seconds each.
The daily pattern activity of these rabbits is presented in Figure 6. In this figure, it can
be observed that the most significant activity patterns occurred during the night. This is
particularly evident in individuals 1 and 3, where intense activity concludes around 5/6h
in the morning and resumes around 18h.

Discussion

Our analysis aimed to train a model capable of classifying two general states of growing rabbits, active and inactive, based on accelerometer data. To find the best possible classification performance, multiple machine learning algorithms have been tested, with their respective hyperparameter tuning, on top of a variety of window sizes for the accelerometer signals.
Firstly, our study showed that accelerometers attached to the back of rabbits in cages can be used to reliably classify inactive states. With a window size of 9 s and the top 5 features, the RF model reaches a median precision of 100% and a median recall of 93%. In addition, the models were validated in a configuration where the rabbits used for model training have not been used for model testing, suggesting that the model also has a good genericity (Riaboff et al., 2022). Furthermore, it is noteworthy to point out that the rabbits did not struggle to wear the sensor. It did not affect their behaviour or that of their cage mates, no fights or attempts to remove the device were appreciated. At the end of the experiment, the accelerometers were retrieved in perfect condition, with no hardware damage, making it a viable option to measure the activity of growing rabbits. To the best of our knowledge, this is the first attempt where wearable accelerometers have been used to monitor the behaviours of growing rabbits, thus highlighting the potential of such technologies in that field.

Even if the models' performance are really good, several improvements could be proposed. First, it was not possible to simultaneously test different accelerometer configurations due to the limited number of sensors at our disposal. Based on results obtained from other species and following the device instructions, the sampling rate was set up to 25 Hz and the sensitivity to ±8g. However, for future analyses, it would be advisable to test multiple configurations and assess which is the best one for the case study.

As for the placement, in rabbits, the most feasible option was to attach it to their backs, at the level of the rib cage, using an elastic band Figure 2. This arrangement enables the sensor to move with the general movement of the rabbit but may fail to catch activities such as eating when there is only head movement. Thus, the signal between the animal lying down and eating can be hardly distinguished. In the case of the drinking activity,
since the position of the nipple is on top of the cage, the rabbit had to stand up, which
should be reflected on the accelerometer data. The decision of where to place the sensor
is therefore of high relevance as it will determine which behaviours will be measured
with higher precision (Chapa et al., 2020). In the literature, some work can be found
where more than one accelerometer was employed, demonstrating an improvement in
predicting behaviours *versus* the only one sensor approach (Ringgenberg et al., 2010;
Thompson et al., 2019). However, in growing rabbits, this option seems difficult to
achieve.

In the process of synchronization, an average gap between the camera clock and
accelerometer clock was observed in each continuous sequence due to the time drift.
Thus, the impact that it might have on the correspondence between the accelerometer
signal and the annotated behaviours can be significant if not corrected. In this study,
each continuous sequence was manually corrected to ensure a perfect match between
the signal and the annotations but this is time-consuming and labour-intensive, which
may make this type of study difficult to achieve. One solution to this problem of
accelerometer clock drift is to equip the animals and film them for several hours (~8
hours), then reset the cameras and sensors, and repeat the test the next day, since drift
accumulates over time.

In the context of model training, the number of samples is also highly important. It
depends on the amount of data available for each behaviour but also of the chosen
window size; bigger window sizes result in smaller sample sizes and *vice versa*.
Furthermore, for large window sizes, there is a greater likelihood of having several
behaviours in the window and therefore, of excluding it from the dataset for the
analysis. If these windows are not removed but instead the most likely class is assigned,
the signal corresponding to different behaviours would be present in the same window,
leading to noise. With a window size equal to 9 seconds, 1,941 windows were generated, 86% of them belonging to the inactive class, resulting in a class imbalance problem. For that purpose, techniques for over-sampling and under-sampling could be applied (Turner et al., 2022). In the present study, multiple Synthetic Minority Over-sampling Technique (SMOTE) variants were tested (results not shown), nevertheless, they did not enhance the performance of the overall model. Results could be improved with additional data annotations and with a better representation of all the classes.

Multiple features were extracted from the segmented accelerometer signal, as typically done in the field to predict a variety of behaviours from accelerometer data (Shahriar et al., 2016; Lush et al., 2018; Pandey et al., 2021). A parallel approach can be to apply neural networks, as done by Turner et al. (2022), to the accelerometer time series, thus avoiding knowledge-based feature extraction. They reported that neural networks outperformed classical machine learning algorithms. However, this kind of approach requires a substantial dataset size.

In the present study, the model accuracy was greater than that of the majority class proportion. Regarding the trade-off between precision and recall, with RF and a window size of 9 seconds, we can predict inactive behaviours with a median precision of 1 (Q1=0.99, Q3=1) and a median recall of 0.93 (Q1=0.89, Q3=0.97). As already explained, precision refers to the proportion of TP among all positive predictions and recall refers to the proportion of TP among all the actual positive cases. In this case, the model is highly reliable in correctly classifying positive instances and it is capable of detecting 93% of the positive instances. The main limitation to achieving higher recall values is that the signal in some periods classified as inactive is similar to that obtained in some periods classified as active. This may be a consequence of multiple factors, such as having mixed data in the inactive class (the sensor might move when the animal
is drinking or eating), the placement and strapping of the sensor or possible light interactions between the rabbits (the sensor is slightly hit by another rabbit). On the other hand, if the active class were considered as the positive class, we would obtain a perfect recall but a median precision of 58% due to confusion between inactive instances and active ones.

A potential use of the activity patterns obtained from accelerometers in growing rabbits would be the detection of sick animals (González et al., 2008; Dittrich et al., 2019). These daily patterns, as shown in Figure 6, could be useful for implementing alarm systems for intervention if a behaviour change is observed. Moreover, understanding daily activity patterns can also assist in optimizing management strategies and identifying potential stressors or environmental factors affecting animal behaviour. On the other hand, the activity pattern has been found to be related to feed efficiency in beef steers (Haskell et al., 2019). This opens the possibility of defining new or additional phenotypes that could be included in a breeding program to select for feed efficiency.

Nevertheless, some drawbacks need to be considered regarding the use of this kind of device. The accelerometer used in this study is required to be connected to the computer to download the data. That means, that the device must be removed from the animals every time this action is needed. In rabbits, this is not a significant problem because they are small animals and easy to handle. Similarly, the anchoring system was an elastic band, which is easy to put on and take off but it involves handling the animal in a way that can be stressful for it. On top of that, a long-lasting battery and Bluetooth connection that ensures storage of data on an external database are important characteristics to be included in the device without compromising its price, size and weight.
The greatest advantage of these devices compared to other systems is that they allow the individualized monitoring of animals without the need for tracking. This makes accelerometers especially useful for animals in outdoor production systems. Furthermore, the data collected by this device could be complemented with data available from other types of sensors, such as radio frequency identification tags, cameras, or microphones to improve the capabilities of the models.

## Conclusions

This is the first study where the aim was to automate the detection of active and inactive states in rabbits. The results show that, with the device configuration, algorithms and hyperparameters tested, the models presented a high level of precision, signifying that the model is highly reliable in correctly classifying positive instances. Additionally, achieving a recall of 0.93 emphasizes the model's effectiveness in capturing a substantial portion of positive instances. The results could be improved if more data were gathered to have a better representation of the classes, which would also allow distinguishing between classes. Therefore, it appears to be a valuable tool for obtaining insights into the behaviour of rabbits and the factors that influence their welfare and productive efficiency.

## Acknowledgements

We would like to thank Oscar Perucho for their contribution to data recording and animal care during the experiment. We would like to express our gratitude to Padraig Cunningham for his valuable grammar review contributions.

## Conflict of interest statement

The authors declare that they have no known competing financial interests or personal relationships that could have appeared to influence the work reported in this paper.
## Author Contributions

Individual author contributions to this research article are as follows: Conceptualization and design: MM, MP, ID, methodology: MM, MP and LR, formal analysis: MM and LR, writing the original draft: MM, writing-review editing: MP, ID, LR, supervision: MP, LR and funding acquisition: MP, JPS.

## Data and model availability statement

The data that support the findings of this study are available from the corresponding author upon reasonable request.

## References

Benjamin, M., and S. Yik. 2019. Precision Livestock Farming in Swine Welfare: A Review for Swine Practitioners. Animals 9. https://doi.org/doi:10.3390/ani9040133

Berckmans, D. 2017. General introduction to precision livestock farming. Animal Frontiers 7, 6-11. https://doi.org/doi: 10.2527/af.2017.0102

Breiman, L. 2001. Random Forests. Machine Learning 45, 5-32.

Chapa, J. M., K. Maschat, M. Iwersen, J. Baumgartner, and M. Drillich. 2020. Accelerometer systems as tools for health and welfare assessment in cattle and pigs - A review. Behav Processes 181:104262. https://doi.org/doi: 10.1016/j.beproc.2020.104262

Cornou, C., and S. Lundbye-Christensen. 2010. Classification of sows' activity types from acceleration patterns using univariate and multivariate models. Computers and Electronics in Agriculture 72, 53-60. https://doi.org/doi: 10.1016/j.compag.2010.01.006
Cristianini, N., and E. Ricci. 2008. Support Vector Machines. In: M.-Y. Kao, editor, *Encyclopedia of Algorithms*. Springer US, Boston, MA. p. 928-932.

Dittrich, I., M. Gertz, and J. Krieter. 2019. Alterations in sick dairy cows' daily behavioural patterns. *Heliyon* 5, e02902. doi: https://doi.org/10.1016/j.heliyon.2019.e02902

Fabian Pedregosa Gaël Varoquaux, A. G. a. V. M., Bertrand Thirion and Olivier Grisel and Mathieu Blondel, Peter Prettenhofer, Ron Weiss and Vincent Dubourg, Jake Vanderplas and Alexandre Passos, David Cournapeau and Matthieu Brucher, Matthieu Perrot, Édouard Duchesnay. 2011. Scikit-learn: Machine Learning in Python. Journal of Machine Learning Research 12, 2825-2830.

Friard, O., and M. Gamba. 2016. BORIS: a free, versatile open-source event-logging software for video/audio coding and live observations. Methods in Ecology and Evolution 7, :1325-1330. doi: https://doi.org/10.1111/2041-210X.12584

Friedman, J. 2000. Greedy Function Approximation: A Gradient Boosting Machine. *The Annals of Statistics* 29. https://doi.org/doi: 10.1214/aos/1013203451

González, L. A., B. J. Tolkamp, M. P. Coffey, A. Ferret, and I. Kyriazakis. 2008. Changes in Feeding Behavior as Possible Indicators for the Automatic Monitoring of Health Disorders in Dairy Cows. Journal of dairy science 91, 1017-1028. https://doi.org/doi: https://doi.org/10.3168/jds.2007-0530

Haskell, M. J., J. A. Rooke, R. Roehe, S. P. Turner, J. J. Hyslop, A. Waterhouse, and C.-A. Duthie. 2019. Relationships between feeding behaviour, activity, dominance and feed efficiency in finishing beef steers. Applied Animal Behaviour Science 210, 9-15. https://doi.org/10.1016/j.applanim.2018.10.012

Jones, E., T. Oliphant, and P. Peterson. 2001. SciPy: Open Source Scientific Tools for Python.
Lush, L., R. P. Wilson, M. D. Holton, P. Hopkins, K. A. Marsden, D. R. Chadwick, and A. J. King. 2018. Classification of sheep urination events using accelerometers to aid improved measurements of livestock contributions to nitrous oxide emissions. Computers and Electronics in Agriculture 150:170-177. https://doi.org/10.1016/j.compag.2018.04.018

Martiskainen, P., M. Järvinen, J.-P. Skön, J. Tiirikainen, M. Kolehmainen, and J. Mononen. 2009. Cow behaviour pattern recognition using a three-dimensional accelerometer and support vector machines. Applied Animal Behaviour Science - APPL ANIM BEHAV SCI 119, 32-38. https://doi.org/10.1016/j.applanim.2009.03.005

Pandey, S., U. Kalwa, T. Kong, B. Guo, P. C. Gauger, D. J. Peters, and K. J. Yoon. 2021. Behavioral Monitoring Tool for Pig Farmers: Ear Tag Sensors, Machine Intelligence, and Technology Adoption Roadmap. Animals (Basel) 11. https://doi.org/10.3390/ani11092665

Rautiainen, H., M. Alam, P. G. Blackwell, and A. Skarin. 2022. Identification of reindeer fine-scale foraging behaviour using tri-axial accelerometer data. Movement Ecology 10, 40. https://doi.org/10.1186/s40462-022-00339-0

Rayas-Amor, A. A., E. Morales-Almaráz, G. Licona-Velázquez, R. Vieyra-Alberto, A. García-Martínez, C. G. Martínez-García, R. G. Cruz-Monterrosa, and G. C. Miranda-de la Lama. 2017. Triaxial accelerometers for recording grazing and ruminating time in dairy cows: An alternative to visual observations. Journal of Veterinary Behavior 20, 102-108. https://doi.org/https://doi.org/10.1016/j.jveb.2017.04.003

Riaboff, L., S. Poggi, A. Madouasse, S. Couvreur, S. Aubin, N. Bédère, E. Goumand, A. Chauvin, and G. Plantier. 2020. Development of a methodological framework
for a robust prediction of the main behaviours of dairy cows using a combination
of machine learning algorithms on accelerometer data. Computers and
Electronics in Agriculture 169, 105179.
https://doi.org/10.1016/j.compag.2019.105179

Riaboff, L., L. Shalloo, A. F. Smeaton, S. Couvreur, A. Madouasse, and M. T. Keane.
2022. Predicting livestock behaviour using accelerometers: A systematic review
of processing techniques for ruminant behaviour prediction from raw
accelerometer data. Computers and Electronics in Agriculture 192:106610.
https://doi.org/10.1016/j.compag.2021.106610

Ringgenberg, N., R. Bergeron, and N. Devillers. 2010. Validation of accelerometers to automatically record sow postures and stepping behaviour. Applied Animal Behaviour Science 128, 37-44. https://doi.org/10.1016/j.applanim.2010.09.018

Rodriguez-Baena, D. S., F. A. Gomez-Vela, M. García-Torres, F. Divina, C. D. Barranco, N. Daz-Diaz, M. Jimenez, and G. Montalvo. 2020. Identifying livestock behavior patterns based on accelerometer dataset. Journal of Computational Science 41, 101076. https://doi.org/10.1016/j.jocs.2020.101076

Shahriar, M. S., D. Smith, A. Rahman, M. Freeman, J. Hills, R. Rawnsley, D. Henry, and G. Bishop-Hurley. 2016. Detecting heat events in dairy cows using accelerometers and unsupervised learning. Computers and Electronics in Agriculture 128, 20-26. https://doi.org/10.1016/j.compag.2016.08.009

Smith, D., A. Rahman, G. J. Bishop-Hurley, J. Hills, S. Shahriar, D. Henry, and R.
Rawnsley. 2016. Behavior classification of cows fitted with motion collars:
Decomposing multi-class classification into a set of binary problems. Computers
and Electronics in Agriculture 131, 40-50.
https://doi.org/10.1016/j.compag.2016.10.006
Thompson, R. J., S. Matthews, T. Plötz, and I. Kyriazakis. 2019. Freedom to lie: How farrowing environment affects sow lying behaviour assessment using inertial sensors. Computers and Electronics in Agriculture 157, 549-557. https://doi.org/10.1016/j.compag.2019.01.035

Turner, K. E., A. Thompson, I. Harris, M. Ferguson, and F. Sohel. 2022. Deep learning based classification of sheep behaviour from accelerometer data with imbalance. Information Processing in Agriculture https://doi.org/10.1016/j.inpa.2022.04.001

Vázquez Diosdado, J. A., Z. E. Barker, H. R. Hodges, J. R. Amory, D. P. Croft, N. J. Bell, and E. A. Codling. 2015. Classification of behaviour in housed dairy cows using an accelerometer-based activity monitoring system. Animal Biotelemetry 3, 15. https://doi.org/10.1186/s40317-015-0045-8
Supplementary Material

<figure><img src="image_8.png" /><figcaption>Figure S1. Distribution of precision, recall and F1 score for each model for each subset of the most important features with a window size of 1 second. The green dot represents the mean across the 16 outer loops.</figcaption></figure>

<figure><img src="image_9.png" /><figcaption>Figure S2. Distribution of precision, recall and F1 score for each model for each subset of the most important features with a window size of 3 seconds. The green dot represents the mean across the 16 outer loops.</figcaption></figure>
<figure><img src="image_10.png" /><figcaption>Figure S3. Distribution of precision, recall and F1 score for each model for each subset of the most important features with a window size of 5 seconds. The green dot represents the mean across the 16 outer loops.</figcaption></figure>

<figure><img src="image_11.png" /><figcaption>Figure S4. Distribution of precision, recall and F1 score for each model for each subset of the most important features with a window size of 7 seconds. The green dot represents the mean across the 16 outer loops.</figcaption></figure>
Window size: 9 seconds

<figure><img src="image_12.png" /><figcaption>Figure S5. Distribution of precision, recall and F1 score for each model for each subset of the most important features with a window size of 9 seconds. The green dot represents the mean across the 16 outer loops.</figcaption></figure>