Chapter 4 Use cases for machine learning methods
As described before in section 2.2, the first implementations of sensor technologies in apiculture were often using simple decision rules to support the beekeepers. Examples for these simple rules are:
- Temperature increases inside the hive by more than 1°C compared to 30 minutes ago over multiple consecutive minutes: the colony is swarming (Zacepins et al. (2016)).
- Lowest temperature inside the hive < 5°C or highest temperature > 36°C: unfavorable climate – alert sent to the beekeeper (Markovic et al. (2016)) (Edwards Murphy, Magno, O’Leary, et al. (2015)).
These studies were, however, conducted at rather small scale (e.g. four hives for Bayir and Albayrak (2016), one hive over limited time for Edwards Murphy, Magno, O’Leary, et al. (2015)) and under close supervision of the researchers to maintain a good data quality. While according to the project design of Bee Observer all hives in the project should have the same sensor setup and thus the same variables available, the data quality analysis in section 3.1 has shown that data availability is fluctuating over time, and due to the lack of control by the project team, some beekeepers have not even installed all three sensor components in their hives. Further, as shown earlier in figure 3.13, the center of the brood nest may move over longer periods, thus making it difficult to deduct the bee health state from the same temperature sensor. Lastly, previous research was based on data from hives in broadly the same geographical area, whereas in Bee Observer the data are sent from hives across Germany and even some other countries. Thus, colonies might be affected by different environmental influences in their regions which may affect their behavior, requiring adjustments to static rules. Instead of programming alert systems based on static rules it would be rather preferable to use flexible methods of machine learning to learn relationships between the variables that influence or are influenced by the behavior of the bees inside the hive.
4.1 Supervised swarm detection
One of the most obvious use cases of machine learning in beekeeping is to detect swarm events: If a swarm goes unnoticed, the part of the colony that left may either abandon the apiary or even die, and even if caught in time, both halves of the former colony are now weakened and are producing less honey over the remainder of the year. A mechanical tool to allow the beekeeper to quickly react, catch the swarm and give it a new hive will thus be of economic value.
Between April and June 2020, 13 swarm events were recorded in the beekeeping apps. Unfortunately, in only six cases were the sensor kits also active during the event. Thus, for the training of a classification model that could detect swarm events and warn the beekeeper in time, the sample size is still quite limited. Nonetheless, also in this limited sample12, we can make similar observations as Anand et al. (2018), who could only observe one event, see figure 4.1. Starting around half an hour before departure until the point when the swarming is concluded, a steady and significant increase in temperature is recorded in the center of the hive (but also at the other temperature sensors) as well as, albeit to a smaller degree, an increase in relative humidity. This happens as the part of the colony that is about to leave the hive is warming up their muscles for flying. Using the rough patterns observed in terms of changes in weight, temperature and humidity as well as the level of temperature, I was able to identify three more swarming events in the sensor data, which were not at all or not correctly entered in the dataset on inspections, raising the sample of sensor keys with swarms to eight. These three swarms were confirmed by the project colleagues as they contacted the respective beekeepers.
Figure 4.1: Characteristics of a swarm event
The observed drops in weight also help us estimate the total weight of a bee colony: assuming around half the colony leaves the hive during the swarming, a full colony will weigh between 7kg and 10kg. Further, these observations also teach us about the length of the process and consequently at what maximum frequency we should analyze the data, at least for the detection of swarms: leaving the hive took between five and eight minutes for the five colonies observed, thus if one would aggregate the data too much, say into five-minute medians, the distinct temperature and humidity increases may be masked, and the steep, but nonetheless gradual, weight decreases would appear too abrupt. At least for the use case of swarm detection, a sampling rate of 1 minute seems appropriate.
4.1.1 Training a classification model
With the previous observations we learned that swarm events are characterized by a sequence of developments: temperature and humidity increase first, then, when the bees start departing and the weight measured on the scale starts decreasing, also humidity begins decreasing again. Given that warm air rises, the peak in temperature is only reached when the departure of the bees has been concluded, before it decreases again with some delay. Thus, to classify a swarm, it makes sense to not only consider level and growth rates of the variables at a given time, but also what happened in the minutes before. To this end we calculate 10-minute differences for humidity, weight and the three inner temperature sensors and the upper temperature sensor as well as the first ten lags for each of the growth rates. Following Ziegler, Dettli, and Thommen (2019), who reported that swarming typically occurs during the day, we also add as predictor the time of day in seconds13. The analysis in section 3.1.1.2 showed that the central temperature sensors characterize well the developments in the brood nest, but across beehives and over time the center of the nest with the highest temperatures may be located closer to different sensors. Thus, instead of considering each thermometer reading inside the hive, I aggregate the information to the maximum of the three sensors, reducing the number of variables. As some of the sequences do not have complete observations on all temperature sensors and model training requires complete observations, this transformation will also improve the size the dataset. Also, due to the higher volatility of humidity compared to the other variables, its level and growth rates are less useful as swarm predictors. Thus, instead of the raw humidity data, a centered five-minute moving average is chosen for the training dataset. Finally, it is clear that the many lagged growth rates will be very closely related to one another and may likely not carry a lot of additional predictive power for a model. I thus apply an additional high correlation filter (removing variables correlated with others by more than \(\rho = 0.9\)), which reduces the set of predictors to 13, namely the four sensor series, their 10-minute differences and their 10-minute differences lagged by ten minutes, as well as the time of day.
Using additional predictors such as weather data as presented in section 3.3.2 could additionally be considered, but as the geocoordinates are not available for all beehives, this might result in a further reduction of the training dataset. Further, in the analyzed period it is likely that environmental conditions outside should in most cases be supportive of a swarm event as it should be sufficiently warm during the day and less likely to rain between April and July compared with the rest of the year. This should however be investigated next year with more and better data available.
For the labels, we define as TRUE for the binary variable swarm the observations five minutes before and after the observation at the beginning of the departure (T=0 in figure 4.1) and all other observations as FALSE. As one of the eight sensor kits has none of the temperature sensors reporting during the event, in the training dataset we include only seven swarm sequences plus the twenty minutes before and after, respectively. Further, to train the model not to mislabel quick weight drops during inspections as swarms, we include one hour of data during inspections and another hour of normal daily behavior. Excluding observations with missing values (in one case of a swarm the sensors were switched back on just shortly before) we end up with a quite imbalanced training dataset of 518 observations, of which 77 are labelled as swarms. Given the class imbalance of the dataset, I add as a final pre-processing step an up-sampling using the SMOTE algorithm (Chawla et al. (2002)) which creates synthetic observations for swarms using the k-nearest neighbors of actual swarm observations.
A first attempt of modelling a classifier using logistic regression fails to converge even on the significantly reduced set of variables. After reducing dimensionality further to ten predictors using the greedy Wilks algorithm for feature selection, the model yields acceptable results on the training dataset, but fails on new data: For the other observations in the sample, which likely do not exhibit swarms, the predicted probabilities of a swarm occurring often reach very high levels, in particular during inspections. As a logistic model implies that the log odds increase in a linear relation to the predictors, the model interprets any strong decrease in weight as a sign of a swarm occurring, while in reality the weight decrease is bound to be the weight of around half a bee colony (i.e. something in the range of 4-5kg) and the temperature does not increase endlessly. Thus, a model allowing for non-linearities is likely a better option. I estimate a Random Forest model with the ranger package (Wright and Ziegler (2017)) using the default hyper-parameters (1000 trees, number of variables used for splitting mtry = 3 ≈ sqrt(13), minimum node size of 10) and test its accuracy in ten-fold cross-validation in folds with similar class relations. The accuracy in training is high with above 97% and an area under the ROC curve of over 99%. Given the high frequency of the data at one-minute intervals, a low relative false positive rate may still mean thousands of wrong notifications to the beekeeper, which we would want to avoid.
Figure 4.2: Swarm probabilities in training set
The visualization of the predicted swarm probabilities in the training set in figure 4.2 shows when the random forest and the logistic regression models react to actual swarm events.
To check the usefulness of our models, I also apply the trained models on the remaining unlabeled observations from the time period between April and July 2020. As no other swarms were entered in the dataset on inspections, one should not expect too many swarms to have occurred, and thus the models should classify the vast majority of observations as not belonging to swarm events. Otherwise we might end up with a model that could send notifications based on false positives, which should be avoided, as beekeepers may lose interest in participating in the project if the app causes them unnecessary trips to the apiary. For the Random Forest model this condition is met, as probabilities remain generally low for the new data. Only in very few cases - likely due to sensor failure - the model (falsely) predicts a swarm with high probability of around 75%, which still is a considerable improvement compared with the logistic regression model, which reacts very strongly very often, see the example shown in figure 4.3.
Figure 4.3: Applying trained models on new data
An issue of the trained Random Forest model is its dependence on complete observations. As our data is often incomplete, either due to the sensors not sending data or sending erroneous data that are then removed by the cleaning algorithm, there are many observations where the full model would not produce predictions at all. Based on the analysis of missingness shown in figure 19, the most frequent cause of incomplete data is one sensor component failing completely. Indeed, in training the logistic regression and random forest models before, one case of a swarming event was actually not included, as it had no records from the thermometer unit during the event. Thus, to complement the above model using data from all three sensor components, we further train three more Random Forest models with default hyperparameters for cases where only two of the three components are active and three more with only one component active. All models are estimated using the same complete observations as the full model. Figure 4.4 shows that reducing the number of predictors does not have a significant negative effect on model performance: in fact, the model without variables based on weight achieves a higher accuracy and specificity than the model with data from all sensor components. Overall, the accuracy is quite high across models and in a rather narrow range between 96% and 98%.
Figure 4.4: Model performance depending on number of used sensor components
For specificity, the metric explaining the share of non-swarm observations that are correctly predicted, the variation is somewhat wider: while the models with the highest overall accuracy also have higher specificities between 84% and 88%, which is also achieved by the model using only thermometer data, the models using only the scale, the humidity sensor or both achieve an average specificity between 74% and 80%. All estimated models could still be improved using hyper-parameter tuning. Also, other model types such as Boosted Trees could be explored. However, given the small training dataset and the overall low data quality, a too extensive modelling approach appears premature at this stage and should be targeted for late 2021, when hopefully data quality has improved and more swarms were recorded.
4.1.2 Importance of swarm prevention
One reason behind the overall low count of swarms in the data so far is that the beekeepers actively try to prevent swarming. One popular method of swarm prevention is introducing a new queen annually, or at least every two years, to make sure that enough pheromones are emitted to keep the worker bees from developing queen cells. Other measures include clipping the queen’s wings or destroying new queen cells once discovered. It may thus be of merit to also look not only into hives where swarms have happened to provide timely alerts to the beekeeper to catch the swarm and provide a new home, but also analyze those hives in which the beekeepers observe the first signs of the colony’s urge to swarm, namely by developing queen cells or at least building the required structure, a “fake” queen cell (“Spielnäpfchen” in German).
In the case of the eight sensor kits with recorded swarm events, only two had recorded observations of building of queen cells before the swarming event. In one case, however, the beekeeper cut out the queen cells (mentioned in the qualitative notes) and in the last inspection value for this variable before the swarming event, around one month earlier, the value was set to FALSE, thus the beekeeper likely assumed to have successfully suppressed the bees’ urge to swarm. While in the currently available data there are not enough observations for useful analysis, looking ahead it may be useful to include in the set of predictors of any detection model a dummy on whether building of queen cells was observed during inspections in the recent time and on types of swarm prevention methods applied, if any, but this depends on the completeness and accuracy on the side of the beekeepers.
4.2 Other use cases for supervised methods
At the current stage, the dataset on inspections is quite small not allowing for sound analysis combining sensor and inspection data, but going forward a number of other use cases come to mind:
- Estimate risk of colony loss: do the sensor data for colonies lost over the winter differ from those that survive? Can dangerous levels or trends be detected early enough for the beekeeper to intervene before the hibernation? An application of a supervised approach using boosted decision trees was presented by (Dineva und Atanasova, 2018). In the current dataset only one reported colony loss fell within a period with recorded sensor data which is not enough for statistical inference.
- Detection of Varroa mite pests or other diseases: can sensor data show a significant effect of a Varroa mite infestation or a spread of the Deformed Wing Virus? E.g., would less bees leave the hive for foraging, leading to a smaller weight fluctuation and less pollen and honey inflow or would the bees inside have more difficulties maintaining the microclimate within the hive? An early detection of diseases and thus an early treatment may improve the health of the colony. In the currently available data, only six hives with sensor data recorded 22 cases of Varroa infestation, while ten more hives with sensor data recorded negative observations on this issue.
- Estimation of colony size and food reserves: based on the weight and its daily fluctuation during the foraging period one could estimate the number of bees in the colony and thus their food demand. Regression methods could help suggest an ideal amount of honey to be harvested and/or the right amount of supplement feeding that would not lead to starvation of the colony.
4.3 Unsupervised anomaly detection
Given the rare occurrence of inspections and the generally low size of the inspection dataset compared to the millions of sensor observations it may also be useful to gain insights from unsupervised methods, classifying the data into normal and anomalous. The approach chosen by Davidson et al. (2020) was to use a method of Deep Learning, namely Recurrent Auto-Encoders, to classify 60-minute sequences of consecutive data from beehives with heterogenous sensor set-ups, and were able to detect anomalies that were due to beekeeper inspections, but also swarms. The training of Neural Networks, however, requires complete sequences of data, which can rarely be achieved in the currently available dataset.
Within Bee Observer, the project team also worked on a methods of anomaly detection, to be presented at an upcoming conference (Senger et al. (2020)): on the simpler side. the distance of the observed values to the moving median of the last five minutes for one or multiple variables of interest are classified using a statistical test for outliers. More advanced methods exploit the stationarity and seasonality of the variables: the variables are modelled using uni- or multivariate Autoregressive Integrated Moving Average (ARIMA) models and the outlier test is then applied to the model residuals. Tested on a number of selected, mostly complete sequences of data, the moving median as well as some advanced methods are able to identify a substantial share of observations as anomalies that are within a close distance of an inspection recorded in the beekeeper app. Afterwards the anomalous observations are clustered together based on their timestamps (acknowledging the longer duration of inspections), and an agent-based model assesses the likelihood that the anomaly could be due to an inspection based on the variables such as the time since the last inspection or the weather conditions.
The anomalies detected by the unsupervised models would afterwards provide a good starting point for further analysis using supervised methods.
One more swarm was registered, which was however not used in the later dataset to train the model: in this case the beekeeper was present when the colony started swarming and initiated a full inspection at the time of departure. Thus, effects of the swarm and the external intervention overlap and may likely affected the predictive power of a model negatively.↩︎
As this analysis was limited to the normal swarming season between April and July, a further predictor for the time in the year was not deemed necessary. When more swarm data becomes available in future data collections, allowing for more balanced training sets, it may be useful to include (non-swarm) observations outside the swarming season and also include the day in the year as a predictor.↩︎