Full text
i Machine learning approaches for tomato crop yield prediction in precision agriculture María Fernanda Restrepo Suescún Internship report presented as partial requirement for obtaining the Master’s degree in Advanced Analytics
ii NOVA Information Management School Instituto Superior de Estatística e Gestão de Informação Universidade Nova de Lisboa MACHINE LEARNING APPROACHES FOR TOMATO CROP YIELD PREDICTION IN PRECISION AGRICULTURE by María Fernanda Restrepo Suescún Internship report presented as partial requirement for obtaining the Master’s degree in Advanced Analytics Advisor: Prof Doutor Flávio Luis Portas Pinheiro August 2021
iii DEDICATION Dedicated to my family and my beloved partner for their unconditional support.
iv ACKNOWLEDGEMENTS A special thanks to the company for letting me participate in such an interesting and innovative project. The experience was very enriching for me and contributed a lot to my growth as a Data Scientist. I also want to express my gratitude to my advisor Flávio Pinheiro who allowed me to work on this project. Through his classes, he gave me the knowledge and valuable tools that I applied in this work, and that will be useful throughout my professional career.
v ABSTRACT The objective of this project was to apply ML techniques to predict processing tomato crop yield given information on soil properties, weather conditions, and applied fertilizers. Besides being robust enough for predicting tomato productivity, the model needed to be interpretable and transparent for the business. The models assessed were Decision Trees Regression, ensemble bagging models like Random Forest Regression, and boosting techniques like Gradient Boosting Regression, and Support Vector Regression. Overall, Gradient Boosting and Support Vector models presented the best performance. For improving the predictive power, we combined the predictions of our two best models into a stacked approach with a Ridge Regression as the final model. The generalization error of the final chosen model on new data was 9.02 ton/ha for the MAE metric, 9.5% for the MAPE, and 13.5 ton/ha for the RMSE. This means that our model can predict tomato crop yield with an approximate error of 9 ton/ha. Even though our final model was complex and not intrinsically interpretable, we were able to apply model-agnostic interpretation methods like the SHAP summary plot to better understand the feature importance and feature effects, and the Accumulated Local Effects (ALE) plot, to explain how features influence the outcome of the model on average. In general, the objectives of the project were accomplished and the company was satisfied with the result of the model and its interpretation. KEYWORDS Yield prediction; tomato; agriculture; machine learning; ensemble learning.
vi INDEX 1. INTRODUCTION ............................................................................................................ 1 1.1. PROJECT DESCRIPTION .......................................................................................... 1 2. THEORETICAL FRAMEWORK ......................................................................................... 2 2.1. PROCESSING TOMATO .......................................................................................... 2 2.1.1. GROWING CONDITIONS ................................................................................. 2 2.1.2. AGRICULTURAL CYCLE .................................................................................... 2 2.2. AGRICULTURAL BACKGROUND ............................................................................. 3 2.2.1. SOIL PROPERTIES ............................................................................................ 3 2.2.2. SOIL FERTILIZATION ........................................................................................ 5 2.2.3. WEATHER CONDITIONS .................................................................................. 6 2.3. ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING ........................................... 7 2.3.1. OVERVIEW OF MACHINE LEARNING .............................................................. 7 2.3.2. DECISION TREES.............................................................................................. 9 2.3.3. RANDOM FOREST ......................................................................................... 11 2.3.4. GRADIENT BOOSTING ................................................................................... 11 2.3.5. SUPPORT VECTOR MACHINES ...................................................................... 12 2.3.6. STACKED MODELS ........................................................................................ 14 3. METHODOLOGY .......................................................................................................... 17 3.1. BUSINESS UNDERSTANDING ............................................................................... 18 3.2. DATA UNDERSTANDING ...................................................................................... 19 3.2.1. LAND PARCEL INFORMATION ....................................................................... 19 3.2.2. SOIL PROPERTIES INFORMATION ................................................................. 19 3.2.3. WHEATHER INFORMATION .......................................................................... 23 3.2.4. FERTILIZATION INFORMATION ..................................................................... 23 3.2.5. PRODUCTIVITY INFORMATION ..................................................................... 24 3.3. DATA PREPARATION ............................................................................................ 24 3.4. MODELING ........................................................................................................... 25 3.4.1. MODELS ........................................................................................................ 26 3.4.2. TEST DESIGN ................................................................................................. 26 3.4.3. HYPERPARAMETER TUNING AND FEATURE SELECTION .............................. 27 3.5. EVALUATION ........................................................................................................ 28 3.6. DEPLOYMENT ...................................................................................................... 28 4. RESULTS AND DISCUSSION ......................................................................................... 29
vii 5. CONCLUSIONS ............................................................................................................ 36 6. LIMITATIONS AND RECOMMENDATIONS FOR FUTURE WORKS ................................ 37 7. BIBLIOGRAPHY ............................................................................................................ 38 8. ANNEXES ..................................................................................................................... 40
viii LIST OF FIGURES Figure 1. Texture classification according to USDA (Source: Queensland Government, 2016) 3 Figure 2. Range of pH found in soils (Source: Queensland Government, 2016) ....................... 4 Figure 3. Typical train - validation - test split ............................................................................. 7 Figure 4. K-folds cross-validation process .................................................................................. 8 Figure 5. Scenario in the bias-variance trade-off (Source: IBM Cloud Education, 2020) .......... 8 Figure 6. "Sweet point" between underfitting and overfitting (Source: IBM Cloud Education, 2020)................................................................................................................................... 9 Figure 7. Structure of a Decision Tree ...................................................................................... 10 Figure 8. Maximal margin hyperplane (Source: James et al., 2013) ........................................ 12 Figure 9. SVM with a polynomial and a radial kernel (Source: James et al., 2013) ................. 13 Figure 10. Trade-off between flexibility and interpretability .................................................. 14 Figure 11. CRISP-DM methodology (Source: Data Science Project Management) .................. 17 Figure 12. Soil texture classification of parcels ........................................................................ 21 Figure 13. Correlation between soil parameters ..................................................................... 22 Figure 14. Average fertilizers applied by zone ......................................................................... 24 Figure 15. Summary of data sources and final dataset ............................................................ 25 Figure 16. Cross-validation strategy used ................................................................................ 26 Figure 17. Top 15 features ranked by Gini Importance ........................................................... 29 Figure 18. SHAP summary plot ................................................................................................. 33 Figure 19. Accumulated Local Effects plot ............................................................................... 34
ix LIST OF TABLES Table 1. Functions of macro and micronutriens in plants (Source: Food and Agriculture Organization of the United Nations, 1984) ........................................................................ 5 Table 2. Distribution of zones and parcels ............................................................................... 19 Table 3. Soil properties parameters ......................................................................................... 20 Table 4. Distribution of pH classification per zone .................................................................. 21 Table 5. Weather parameters measured at the stations ......................................................... 23 Table 6. Hyperparameter tuning results .................................................................................. 30 Table 7. Results of the prediction error for model selection. .................................................. 31 Table 8. Result of the prediction error for the stacked model ................................................ 31 Table 9. Generalization error of the final chosen model ......................................................... 32
6 productive soil should contain all the essential plant nutrients in sufficient quantity and in balanced proportions to allow plants to grow and develop to their full potential. However, from the macronutrients there are three elements that plants need in larger quantities and are prioritized in the fertilization plans: Nitrogen, Phosphorus and Potassium. These nutrients are applied to the soil as fertilizers, depending on the soil tests results and if required by the plant during the campaign. These products are commonly known as NPK fertilizers, because of the chemical symbols of the macronutrients that compose them (Food and Agriculture Organization of the United Nations, 1984). 2.2.3. WEATHER CONDITIONS Weather conditions have a significant impact on the tomato crop cycle. As these are factors that cannot be controlled by the farmers, it is interesting to understand their effect on the tomato crop yield to anticipate scenarios. Following, we briefly explain the climate parameters that are mentioned throughout the project. Precipitation: refers to all aqueous particles in a liquid or solid state that originate in the atmosphere and fall to the earth's surface by the action of gravity. The usual unit of measurement of precipitation is millimeters (mm) of liquid water depth collected at a given point over a specified period. Solar radiation: is the amount of electromagnetic radiation released by the sun and received at the earth's surface per unit area. It is measured in watts per square meter (W/m2). Wind speed: refers to the ratio of the distance covered by moving air to the time taken to cover it. This air movement is caused by fluctuations in temperature. Wins speed is measured in meters per second (m/s) or kilometers per hour (Km/h). Leaf wetness duration: refers to the time of continual contact of the leaves with liquid moisture, on both their top and bottom sides. This measure is key for fungus and disease control. The unit of measurement is usually minutes. Temperature: is the quantity measured by a thermometer and that expresses hotness or coldness. Temperature can be measured in the Celsius scale (ºC), Fahrenheit scale (ºF), or Kelvin scale (K). Relative humidity: refers to the quantity of actual water vapor that is in the air in comparison with the maximum possible. The relative humidity is generally reported as a percentage. Dew point: is the temperature to which air needs to lose heat to become condensed with water vapor. As it is a temperature, the dew point can be measured in ºC, ºF, or K. Evapotranspiration: is the amount of water transferred from the earth to the atmosphere by evaporation from the soil, and by transpiration from the leaves of the plants growing on it. Evapotranspiration is measured in mm. (American Metereological Society, 2020) (Encyclopedia Britannica, 2021)
7 2.3. ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING In this subsection, we will briefly introduce the methods and techniques applied in this project, specifically, a short description of Machine Learning concepts and techniques. 2.3.1. OVERVIEW OF MACHINE LEARNING Machine Learning can be defined as the process of solving a practical problem by gathering a dataset, and then algorithmically building a statistical model based on that dataset (Burkov, 2019). Machine Learning models divide into two groups which aim at solving different problems, these groups are the models based on Supervised Learning (SL) and those that are based on Unsupervised Learning (UL). Supervised Learning models use labeled datasets to train algorithms to learn a specific task. Such a task could be either to classify data in categories (Classification) or predict outcomes accurately (Regression). The training datasets include inputs and correct outputs allowing the algorithm to learn over time. On the other hand, the principal objective of Unsupervised Learning is to discover hidden patterns or clustered unlabeled datasets through algorithms. Unsupervised Learning models are used for three main tasks – clustering, association, and dimensionality reduction (IBM Cloud Education, 2020). For this project, the focus will be on the Supervised Learning techniques for Regression. Two main goals are key on Supervised Learning: model selection and model assessment. In model selection, we estimate the performance of different models to choose the best one, and in model assessment, having chosen a final model, we estimate its prediction or generalization error on new data. Generalization of a model is key on Supervised Learning and is related to the ability of a model to make accurate predictions on unseen data. The general approach for both model selection and model assessment tasks is to randomly divide the dataset into three parts: a training set, a validation set, and a test set. The training set is used to fit the models, the validation set is used to estimate prediction error for model selection, and the test set is used for assessment of the generalization error of the final chosen model (Hastie, Tibshirani, & Friedman, 2017). Figure 3 shows a typical split configuration where 50% of the dataset is used for training and 25% each for validation and testing. Figure 3. Typical train - validation - test split However, in some situations, the amount of data for training and testing will be limited, and to build proficient models it is necessary to use as much of the available data as possible for training. This is the case of this project where we don’t have enough data to split it in a typical train - validation - test split. One approach for cope with this situation, it to use k-folds cross-validation where the dataset is split into k equally sized subsets or folds. One of the k-folds will act as the test set and the remaining folds will be used for training the model. This process is repeated for all k possible choices for the test set and the performance score from the k runs is then averaged (IBM Cloud Education, 2020). Figure 4 illustrates the k-fold cross-validation process for a case of five folds.
8 Figure 4. K-folds cross-validation process One of the most important concepts in machine learning is the bias-variance trade-off. The bias of a model refers to the error introduced by the inability of the algorithm to capture the true relationship of the data. A model with no bias will never make any errors in prediction while one with high bias will fail to accurately predict the target variable. On the other hand, the variance of a model represents its sensibility to changes in the training set. A model with low variance has few fluctuations when built with new data while a model with high variance is very sensitive to the training data. The bias-variance trade-off represents how it is easy to decrease bias at the expense of increasing variance, and vice versa. In machine learning, the ideal algorithm has low bias by accurately modeling the true relationship, and has low variability by producing consistent predictions across different datasets. Figure 5, illustrates three situations in the bias-variance trade-off. The leftmost scenario represents a very simple model that does a bad job classifying the target variable and presents high bias. This situation where the model is unable to capture the relationship between the input and output variable accurately is called underfitting. In opposition, the rightmost scenario shows a complicated model that passes through all the data points. This model is memorizing the noise instead of capturing the approximate relationship and will probably fail to generalize on new data. This situation in which the model fits exactly against its training data is called overfitting (Fischetti, 2018). Figure 5. Scenario in the bias-variance trade-off (Source: IBM Cloud Education, 2020)
9 In contrast, the middle graph in Figure 5, represents an optimum situation and the goal when fitting a model: the “sweet spot” between underfitting and overfitting. Figure 6, illustrates better this ideal point in this bias-variance trade-off. As a model becomes more complicated, its bias or error in the training set continues to decrease. As the fitting process continues to iterate and the model begins to fit the data better and better the error in the validation set decreases as well. At some point, the model becomes very flexible and begins to memorize the noise in the training set or overfit, while the error in the validation set goes up. The sweet spot is the point when this validation error is minimized (Fischetti, 2018). Figure 6. "Sweet point" between underfitting and overfitting (Source: IBM Cloud Education, 2020) Following, we briefly described some popular ML models that will be used later in this project. 2.3.2. DECISION TREES Decision trees (DT) are one of the most easily interpretable and popular models used for classification and regression purposes. This approach is very useful in situations where decisions should be transparent and easily understood and explained. This situation is common in the agricultural context. A decision tree looks like an upside-down tree with the trunk on top and the leaves on the bottom. The very top of the tree is called root node, the next ones are internal nodes or branches, and the last ones are called leaf nodes. A decision tree can be defined as a collection of decision nodes, connected by branches, extending downward from the root node until ending in leaf nodes. Starting at the root node, a series of splitting rules are applied to the attributes, with each possible outcome resulting in a branch. Each branch then leads either to another decision node or to a terminal leaf node. Each split point on the decision tree is chosen carefully to result in the most informative split (Larose & Larose, 2014) (Fischetti, 2018). Figure 7 illustrates the structure of simple decision tree.
10 Figure 7. Structure of a Decision Tree The recursive splitting process of building a tree can be summarized in the following steps: 1. Select a variable and split point that results in the best outcome. The first iteration will be for choosing the variable on the root node. For the case of classification, the idea is to choose the variable that more contributes to the decrease in impurity on the subsequent leaves. This is measured through Gini impurity and entropy reduction or information gain. For the case of regression, a reduction in the sum of squared residuals is measured. 2. For each of the resulting branches, check to see if some stopping criteria are met. For example, if a node pure is reached, there is no reason to continue splitting to reduce impurity and we will have arrived at a leaf node. Other stopping criteria that can be defined by us, is either a certain depth that the tree can’t exceed or a minimum number of observations required by a leaf node. 3. Repeat the steps below on the branches that do not meet the stopping criteria. One critical disadvantage of decision trees is that if there are not stopping criteria, as mentioned in step 2, the model will be prone to build complicated and large trees with leave nodes containing only one observation. In other words, the decision trees are prone to overfit the training data and not to generalize well on unseen data. These big and complex decision trees are models with low bias and high variance. A smaller tree with fewer splits will probably have lower variance and will generalize better at the cost of a little bias. One approach to reach such a simpler yet powerful tree is through a technique called pruning where complex branches that contribute little, are cut down and removed (Fischetti, 2018). In summary, decision trees are simple and useful for interpretation. However, due to their high variance condition, their predictive performance is not competitive with other unsupervised learning techniques. One of the approaches for dealing with the poor performance of decision trees is ensemble learning. That is a technique based on the idea of the “wisdom of crowds” which suggests that the decisionmaking of a larger group of people is usually better than the one of a single expert. This way, ensemble
11 models aggregate a group of single models to achieve a better final prediction. These single models, also known as weak learners, work together to form a strong learner and reduce bias or variance. Bagging and Boosting, are two main types of ensemble methods. The former is commonly used for variance reduction, while the latter is typically used for decreasing bias. In bagging (acronym of bootstrap aggregation), a random sample of data in a training set is selected with replacement. That process is known as bootstrapping. After several bootstrapped datasets are generated, weak models are trained in parallel, and their outcomes are combined to reduce variance. For regression, we fit independent regression trees for the bootstrapped datasets and then average the results. For classification, we select the majority vote of the group of trees as the predicted class. One extension of the bagging method is the random forest algorithm, which uses bagging and feature randomness to create an uncorrelated forest of decision trees. We will talk about it in more detail later. Boosting, on the other hand, combines a group of weak models into a stronger one to minimize training errors or reduce bias. Unlike bagging where the weak learners are trained in parallel, in boosting they learn sequentially, this means that each model tries to reduce the errors of its predecessor. Gradient boosting, an example of boosting algorithms is explained later (IBM Cloud Education, 2020). 2.3.3. RANDOM FOREST As mentioned above, Random Forest (RF) model belongs to the ensemble methods that use the bagging technique. The process for building a RF is the following (Hastie, Tibshirani, & Friedman, 2017): 1. Create a bootstrapped dataset, that is, to randomly select samples from the original dataset with the possibility of picking the same sample more than once. 2. Grow a decision tree using the bootstrapped data set, but instead of using all the features, select a random subset of variables. 3. Repeat steps 1 and 2 until the number of desired individual decision trees is reached. 4. Aggregate the results of the ensemble of trees. For regression average the result of each one, and for classification calculate the majority vote of the group. Random forest has played a relevant role in ML lately due to key advantages like reducing the risk of overfitting, and its convenience at evaluating variable importance or contribution to the model. However, the algorithm also presents some challenges like high time consumption when training and the resource requirements. Additionally, the interpretability of a random forest output is more challenging than the one of a single decision tree (IBM Cloud Education, 2020). 2.3.4. GRADIENT BOOSTING As for bagging models, boosting has the objective of combining many weak learners to produce a more powerful model. However, unlike bagging methods like random forest, which rely on a simple average of the individual learners, the idea of boosting is to sequentially improve the ensemble. Gradient boosting belongs to these types of models, and its name is because it combines the gradient descent algorithm and the boosting method (IBM Cloud Education, 2020). Gradient boosting models starts with a weak model that can be a single leaf or a decision tree with only a few splits. The algorithm sequentially boots the performance by fitting new trees to the residuals
12 of the previous ones. The new tree on the sequence will focus on the observations where the previous tree had the largest prediction error trying to fix them up. Gradient boosting is recognized as a gradient descent algorithm. This algorithm tries to adjust parameters iteratively to minimize a cost function. An important parameter in gradient descent is the size of the step to find the minimum which is controlled by a learning rate, and that also deals with overfitting. 2.3.5. SUPPORT VECTOR MACHINES Support Vector Machines (SVM), is a technique used for both classifications and regression problems, developed in the ‘90s. This approach is considered one of the best “out of the box” models for showing good performance in many scenarios, including the scenario of small datasets as in our case. The SVM is a generalization of a simple and intuitive classifier called the maximal margin classifier, which is the optimal hyperplane selected in the case where two classes are linearly separable. In a pdimensional space, a hyperplane is a flat subspace with dimension p-1. For example, in two dimensions a hyperplane is a straight line, and in three dimensions, a plane. If the data can be perfectly separated using a hyperplane, then there will be an infinite number of them and it will be necessary to choose one. A reasonable way of choosing this hyperplane is to calculate the distance from each training observation to a given separating hyperplane and compute the margin, that is the minimal distance from the observations to the hyperplane. The selected classifier will be based on the maximal margin hyperplane, the separating hyperplane for which the margin is largest. Figure 8 shows in solid line the maximal margin hyperplane that separates two classes represented by the blue and purple points. The margin, represented by the arrows, is the distance from the solid line to the dashes lines. The points that lie on the dashed lines are called support vectors which are data points that are closer to the hyperplane and support it in the sense of influencing its position and orientation. Figure 8. Maximal margin hyperplane (Source: James et al., 2013) Although the maximal margin classifier is simple and sometimes successful, it is not realistic and can’t be applied to most datasets as it requires the classes to be separable by a linear boundary. Besides,
13 this approach can sometimes lead to overfitting since the maximal hyperplane is extremely sensitive to a change in a single observation. A more robust alternative to the maximal margin classifier is the support vector classifier, also known as soft margin classifier since the margin is soft and allows some misclassification in the interest of greater robustness to individual observations and better classification of most of the training observations. The support vector classifier is a powerful approach for non-separable cases. However, it has the shortcoming of relying exclusively on linear decision boundaries. A further extension of the support vector classifier that deals with nonlinear relationships is the support vector machine (SVM). SVM works by enlarging the feature space using quadratic, cubic, and even higher-order polynomial functions of the predictors called kernels. In other words, SVM uses a kernel to implicitly transform the original space into a higher dimensional space during the training process. The word “implicitly” is key because the task of the kernel is to calculate the high-dimensional relationships without doing this transformation explicitly. This property of the kernels known as the kernel trick reduces the amount of computation required. Specifically, a kernel is a function that quantifies the similarity of two observations. For instance, a linear kernel uses Pearson correlation to quantify such similarity. There are also polynomial kernels that lead to a more flexible decision boundary by fitting a support vector classifier in a high dimensional space involving polynomials. Another example of a nonlinear kernel and a popular choice is the radial kernel. Figure 9 shows two different kernels applied to nonlinearly separable data; in the left, a polynomial of degree 3, and in the right a radial kernel. Both kernels can capture the decision boundary (James, Witten, Tibshirani, & Hastie, 2013) (Burkov, 2019). Figure 9. SVM with a polynomial and a radial kernel (Source: James et al., 2013) The SVM concepts can be generalized to regression problems with the support vector regression (SVR). This model find the optimal regression hyperplane so that most training samples lie within a certain margin around it, and uses a symmetrical loss function, which equally penalizes high and low misestimates. As in classification, SVR uses kernels for the non-linear approach and is not computationally expensive. SVR has been proven to be an effective tool for estimation with prediction accuracy and generalization capabilities (Awad & Khanna, 2015).
14 2.3.6. STACKED MODELS Stacking is a technique used for both classifications and regression problems that combines the prediction of several base learners. Unlike ensemble models that aggregate a group of weak learners to achieve a better final prediction, stacking is designed to ensemble a group of strong learners. First, the base learners are trained individually, then a final model called the super learner computes the final prediction based on the predictions of the base learners. Such staked models tend to perform as well or better than any of the individual learners in the staking. A common approach for training a staking model is as follows: 1. Select and train a set of individual base learners, and find the optimal hyperparameters that provide the best predictions. Collect the predictions from each base learner which will be the input values for the stacking model. For these models to be part of the stacking they all must be trained on the same dataset and with the same distribution of cross-validation folds. 2. Specify and train the final model that will learn from all the individual predictions and generate predictions on new data. Stacking presents better results when the individual base learners have different predictions. If the individual models generate similar predictions, the benefit of combining them will be lower (Boehmke & Greenwell, 2020). 2.3.7. INTERPRETABILITY IN MACHINE LEARNING Machine learning has been gaining popularity in business due to its predictive power in certain tasks. However, there are situations in which besides the predictions themselves, the reasons behind such predictions are also important for the business. Interpretability can be defined as the degree to which a human can understand the cause of a decision. Some models are intrinsically interpretable and transparent, for instance, linear regression. However, these interpretable models tend to be simple and relatively inflexible. Typically, as the complexity of a model increases, interpretability is lost. Figure 10. Trade-off between flexibility and interpretability
15 Figure 10 shows this trade-off between flexibility and interpretability of the models that we have previously described. As mentioned above, decision trees are simple and useful for interpretation but their predictive power is not competitive with other unsupervised learning techniques. On the other hand, approaches like the ensembles and SVM are powerful but not interpretable. Fortunately, there are model-agnostic interpretation methods that can be applied to any model and can especially help to explain these kinds of “black-box” approaches. One popular method for interpretation of ML models is the Partial Dependence Plot (PDP) which indicates the marginal effect that the variables have on the predictions of a model and the kind of relationship between the outcome and the variables. This method is intuitive and easy to interpret but has a big disadvantage of assuming that the variables are not correlated, which is non-realistic in some scenarios. If the features of a model are correlated, then the partial dependence plot can’t be trusted. Luckily there is an unbiased alternative to PDP, the Accumulated Local Effects (ALE) plot, which describes how variables influence the outcome of a model on average (Molnar, 2021). To manage correlated features, the Accumulated Local Effects plot makes use of the conditional distribution to separate the effect of the feature of interest. To do so, it creates augmented data based on the conditional distribution (Oracle, 2021). To estimate the local effects, the variable is separated into several intervals, and then differences in the predictions over the augmented data are calculated, lastly, those differences are averaged. In an ALE plot, each line is interpreted as the change in the model prediction when the selected feature has a given value compared to the average prediction (Molnar, 2021). Alternatively, there is another interesting model-agnostic method for interpretability called Shapley Values. This method is based on cooperative game theory and tries to assign payouts to players depending on their contributions to the total gain. When applied to the ML scenario, the players are the feature values that collaborated to predict a certain value. The Shapley value is the average of the marginal contributions of a variable value among all the possible combinations of features (Molnar, 2021) (Oracle, 2021). For a better understanding of the concept of Shapley value in the context of Machine Learning, let’s give an example. Let’s imagine we have trained a model to predict car prices. For a certain car, the model predicts a price of 30,000 euros and we want to explain this prediction. The car is five-year-old, is electric, and its color is black. If the average price prediction for all cars is 25,000 euros it would be of interest to know the amount contributed by each variable to a certain prediction compared to the average prediction. In our example, the gain would be the difference between the prediction for that car and the average prediction of all cars, in this case, 5,000 euros. The players would be the variables that cooperated to obtain the gain, in this case, the fact that the car is five-year-old, is electric, and its color is black. If we were to calculate the Shapley value for the feature car_color = black, we would need to calculate all possible coalitions or combinations among the rest of the variables. The coalitions would be the following four: 1. No feature values, 2. car_age = 5 years, 3. car_motor = electric, 4. car_age = 5 years + car_motor = electric. For each combination, we would need to calculate the predicted price with and without the feature car_color = black and compute the difference to get the marginal contribution. When averaging those differences, we will have calculated the Shapley value.
22 magnesium carbonate that work increasing the soil’s pH. On the other hand, alkalinity is usually treated by incorporating organic matter into the soil, given the acidic reaction produced by decomposition that helps reduce pH levels. • Correlation between soil properties Figure 13 presents a heat map of the linear correlation between the parameters measured on the soil. The stronger the red color of the square, the higher the positive correlation between both parameters, and the stronger the blue color, the higher the negative correlation. Figure 13. Correlation between soil parameters From the figure are derived some interesting facts. For instance, the percentage of sand in the soil is negatively related to most of the nutrients. On the contrary, the percentage of clay is positively correlated with a higher presence of nutrients. This matches with the fact that sandy soils tend to be well aerated but do not hold much water and are low in nutrients. By contrast, clay soils, in general, hold more water and are better at supplying nutrients.
23 3.2.3. WHEATHER INFORMATION For measuring weather information, the company owns meteorological stations at each one of its five zones. These stations capture climate parameters daily. Although the stations belong to the company, an external supplier operates and captures the information. To integrate the information into our database system, the supplier made available a Web Service with the historical and current data. Later we created a process through Azure Data Factory resource to integrate all the information in our database into a table called Weather_Parameters at zone level. Table 5 shows the parameters that were measured at the weather stations. Parameter Unit of Measure Data type Precipitation (total) mm Numeric Solar radiation (average) W/m2 Numeric Wind speed (average) Km/h Numeric Wind speed (minimum) Km/h Numeric Wind speed (maximum) Km/h Numeric Leaf wetness minutes Numeric Air temperature (average) ºC Numeric Air temperature (minimum) ºC Numeric Air temperature (maximum) ºC Numeric Relative humidity (average) % Numeric Relative humidity (minimum) % Numeric Relative humidity (maximum) % Numeric Dew point (average) ºC Numeric Dew point (minimum) ºC Numeric Dew point (maximum) ºC Numeric Evapotranspiration mm Numeric Table 5. Weather parameters measured at the stations 3.2.4. FERTILIZATION INFORMATION This information refers to the total amount of fertilizer applied during the plantation campaign on each one of the parcels. As mentioned in the theoretical framework, there are three macronutrients of primary importance for the plants: Nitrogen, Phosphorus, and Potassium. These nutrients are applied to the soil as fertilizers, depending on the soil tests results and if are required by the plant during the campaign. These products are commonly known as NPK fertilizers, because of the chemical symbols of the macronutrients that compose them. The amounts of fertilizers applied are daily registered in a farm management software owned by the company that structured the data in a relational database system. The information was made available through views that later were easily integrated into our system in a table called Fertilization, which registered the total dose of fertilizers applied in Kg per one hectare on each parcel. Figure 14 shows the average amount of fertilizers applied by zone in kg/ha. From the chart, it can be inferred that, in general, Nitrogen (N) is the most applied macronutrient and Phosphorus (P) is the less applied. Sandy soils as the ones present in Zone B are more prone to
24 Potassium (K) deficiency, and it can be confirmed in the chart that this zone received the largest amount of Potassium. Zone C, got the largest rate of Nitrogen and the lowest amount of Phosphorus. In general, clay and loamy soils benefit the most from high Nitrogen supply. Figure 14. Average fertilizers applied by zone 3.2.5. PRODUCTIVITY INFORMATION As previously described, when the tomato has reached its maturity stage, it is harvested and send to the factory to be processed. At the factory, only tomatoes that achieve quality standards are accepted. At each delivery, an estimated weight of tomato accepted is calculated. Once deliveries have finished, the productivity of each parcel is calculated as the total weight of accepted tomato in tons over the planted area in hectares (ton/ha). In some cases, more than one tomato variety is planted in the same parcel, and the productivity is calculated at the variety level, considering the weight of the accepted tomato and the planted area for each variety. At our relational database productivity information was integrated into a table called Productivity at parcel and tomato variety level. The productivity or yield of tomato crop is our target variable to predict at the modeling stage. 3.3. DATA PREPARATION After having collected, integrated, and first explored the data sources, this stage had the objective of preparing the final dataset for modeling. For that purpose, each of the data sources was inspected in detail for evaluating its quality and identifying possible erroneous values. This process was under the supervision of business experts who gave feedback when atypical values were found. Fortunately, most of the data sources were in an optimal state. There were only found a couple of anomaly values in the Precipitation field of the Weather_Parameters table, due to errors in the data collection at the weather stations. As there were few values, they were manually replaced by searching open information of the nearest public weather stations. As the Weather_Parameters table had daily values of several climate variables, it was necessary to transform and derive new features from the existing ones. It is important to notice that it was considered only the climate during the planting period. This planting period consists of 90 to 120 days
25 between the plantation and harvesting periods that can be between April and August. Each one of the parcels had different dates of plantation and harvesting so the influence of the climate factors was different. For each climate parameter, it was calculated the mean, standard deviation, minimum and maximum value during the plantation campaign at each parcel. For the Precipitation, it was also calculated the accumulated sum. Additionally, there were derived some features like the longest dry spell, the longest_wet_spell, and the number of days with temperatures above 27ºC. After having verified the quality of the data, corrected erroneous values and derived new features, all the data sources were joined into a final dataset for modeling at parcel and tomato variety level. Figure 15 summarizes all data sources that were used for creating the final dataset. We ended up with 440 observations and 61 features from four agricultural campaigns (from 2017 to 2020). Figure 15. Summary of data sources and final dataset 3.4. MODELING After having defined and obtained the final dataset, this stage had the objective of training and assessing different ML models in an iterative process. This phase required selecting the modeling techniques, generating the test design, building and evaluating the models. As mentioned before, our target variable was the Productivity in (ton/ha) for each pair of parcel and tomato variety. This variable was then set aside from the final data set and stored in a separated vector called y, which represented our output variable. The rest of the features were put into a matrix called X, serving as our input variables. The modelling process was performed with Scikit-learn, the free machine learning library for the Python programming language.
26 3.4.1. MODELS Considering that our task in this project was to predict a continuous outcome, the approach we should use was Supervised Learning techniques for Regression. Since we were looking for a highly interpretable model and we were short in data samples, our initial options were simple approaches like linear models and decision trees. However, we quickly discarded linear models as our variables were highly correlated and the assumption of no or little multicollinearity was violated. Additionally, the relationship between some features and the target variables was not expected to be linear. This way we opted for tree-based models which are more robust to correlated data and nonlinear relationships. Besides the simple Decision Trees Regression, we included into our options ensemble bagging models like Random Forest Regression and boosting techniques like Gradient Boosting Regression. Finally, we included a final approach that had shown good performance in scenarios of small datasets and capturing nonlinear relationships, the Support Vector Regression. These last three models are in general more robust and complex but also more difficult to interpret. Fortunately, there are some techniques for interpreting these “black-box” types of models. 3.4.2. TEST DESIGN Since we were in a scenario of a small dataset and we needed to make the most of the data in the training stage, we used the k-folds cross-validation approach for the training and validation process. As shown in Figure 16, we split all the data into two groups, a training set (80% of the total data) in which we performed the k-folds cross-validation, and a test set (20% of the total data) that was held out for final evaluation. As explained earlier, in k-folds cross-validation the dataset is split into k equally sized subsets or folds. One of the k-folds will act as the validation set and the remaining folds will be used for training the model. The procedure is repeated for all k possible choices, and the performance score from the k runs is then averaged. Throughout the process of cross-validation, we fit the models and estimate the prediction error for model selection. Additionally, in this stage, we choose a set of optimal hyperparameters through the process of hyperparameter tuning. The test set was used for the assessment of the generalization error of the final chosen model. Figure 16. Cross-validation strategy used
27 3.4.3. HYPERPARAMETER TUNING AND FEATURE SELECTION Hyperparameter tuning is an important task for the training process that deals with the selection of an optimal set of hyperparameters that optimize the outcome of a model. While the parameters of a model are derived via training, hyperparameters are the ones that define the model architecture and must be tuned before the training stage. In other words, hyperparameters are part of the input to the ML algorithm and parameters are part of the output of the fitting process. A good choice of hyperparameters can optimize the training process and make a model more accurate. Instead of using methods like the grid or random search for performing the hyperparameter tuning, we opted for a Bayesian optimization approach which works faster and better than the previous ones. In Bayesian optimization, at every iteration, the algorithm detects which regions in the hyperparameter space are more interesting to explore and which are not. This approach typically requires fewer iterations to get to the optimal set of hyperparameter values. The tool that we used for this hyperparameter tuning was Optuna, an automatic hyperparameter optimization framework, particularly designed for machine learning and available as a Python library. The process of feature selection is another important task before training to reduce the computational cost and improve the performance of the model. In our case, we had a considerable number of features and needed to select the best ones. As we didn’t have a large volume of data and it was computational feasible, we decided to combine the process of feature selection with hyperparameter tuning. For that purpose, we followed the next methodology: 1. As most of the candidate models were tree-based (except for the SVR), we decided to run an initial random forest regression with the default hyperparameters and with all the features. We then capture the Gini Importance and created a set of features ranked according to their importance. 2. For each model, we performed hyperparameter optimization with Optuna. The sets of features calculated in the previous step were treated as an additional hyperparameter. Besides the feature selection, we also treated the data scaling as a hyperparameter. The algorithm had to select between no transforming the data, or applying standardization (equation 1) or min-max normalization (equation 2): 𝑋𝑠𝑐𝑎𝑙𝑒𝑑 =𝑥−μ 𝜎 (1) 𝑋𝑠𝑐𝑎𝑙𝑒𝑑 =𝑥−min(𝑥) max(𝑥)−min(𝑥) (2) 2.4.4. PERFORMANCE METRICS FOR MODEL EVALUATION For evaluating the performance of the model, we selected metrics that were intuitive for interpretation and relatively easy to explain as our model needed to be very transparent for the business. For that purpose, we choose the Mean Absolute Error – MAE (equation 3) the Mean Absolute Percentage Error – MAPE (equation 4) and the Root Mean Squared Error – RMSE (equation 5).
28 𝑀𝐴𝐸= 1 𝑛∑|𝑦𝑖−𝑦𝑖| 𝑖 (3) 𝑀𝐴𝑃𝐸= 100 𝑛∑|𝑦𝑖−𝑦𝑖 𝑦𝑖 | 𝑖 (4) 𝑅𝑀𝑆𝐸= √1 𝑛∑(𝑦𝑖−𝑦𝑖)2 𝑖 (5) The results of the hyperparameter tuning, the feature selection, the model selection, and the assessment and interpretation of the final model are described in the later section of Results. 3.5. EVALUATION In this stage, our final model was tested and verified to evaluate if it met the business objectives and requirements defined in the first step. As mentioned earlier, the principal objective was to create a model to predict the processing tomato productivity given some factors like the soil properties, the weather conditions, and the fertilization applied. Besides being robust enough for predicting tomato crop yield, this model had to be highly interpretable as the “black-box” types of models were not a good idea in industries like agriculture, where people tend to be a little skeptical about these kinds of approaches. From this perspective, we could meet the requirement of creating a robust model for predicting productivity. Although our final model was not simple and not intrinsically interpretable, we were able to use some interpretability techniques that helped us to explain the prediction of the model to the business. To share the results of this project, we had meetings with people in different positions in the company from growers, to field managers. Even though some people were very skeptical about the benefits of using ML approaches, in general, most of them liked the work and got interested on continue iterating the process. 3.6. DEPLOYMENT Since it was the first time that a project involving Machine Learning was carried out in the company, the objective was to have a first approach to this kind of technique rather than to have a model to put into production. Although the model had a good performance and its interpretation was well-received, it was still too early to base the business decision on it. The model established a good starting point for the implementation of ML approaches, but it is still necessary to capture more data and to refine and test the model further. On this first iteration, the deployment stage consisted more in sharing the results and familiarizing the people with this kind of approach. The idea is to continue feeding, improving, and assessing the model with the result of each campaign. Hopefully, over time, the model will help farmers make better decisions and optimize productivity.
29 4. RESULTS AND DISCUSSION The first step in the training process was to tune the hyperparameters of all the models with Optuna. As mentioned earlier, this step also included the feature and scaling selection. For the feature selection, we trained an initial Random Forest Regressor with all the features and the default hyperparameters. Then we captured the Gini importance for each feature and rank all according to their importance. Figure 17 shows the Top 15 of these ranked features that represented 91% of all Gini Importance. The set of features ranked by Gini Importance were treated as an additional hyperparameter for tuning. The feature in the first place was the total amount of Potassium (K) in kg/ha applied as fertilizer to the soil. There were also five weather parameters and seven soil properties present in this set. The tomato varieties T10 and T13 are two of the most widely used varieties in the tomato culture due to their pest and disease resistance and their ability to adapt. The names of the varieties were changed by request of the company. Figure 17. Top 15 features ranked by Gini Importance Table 6 shows the results of the hyperparameter tuning process for the four models specifying the search space for each hyperparameter, the selected value, the time for optimization and the best score. For each of the models, we run 100 trials optimizing the MAE metric. SVR was the model that obtained the best MAE (11.06) in one of the trials. The second-best score was achieved by the Gradient Boosting model (11.86). Random Forest and Gradient Boosting presented the highest optimization times as expected since ensemble models typically present high time consumption. SVR required the shortest optimization time, although it could be because it was trained only with scaled data. Scaling data is a good practice before training Support Vector Machines otherwise, not scaling the data can make the model less accurate and produce high computational costs. The Optimization History Plot of the hyperparameter tuning process for the four models, can be found in the Annexes.
30 Model Hyperparameter Search space Selected value Time to Optimize Best MAE Decision Tree Criterion MSE, Friedman MSE, MAE MSE 4.0 seconds 12.43 Maximum depth [1, 20] 4 Minimum samples leaf [2, 20] 4 Maximum lead nodes [2, 20] 15 Prunning parameter (alpha) [0, 0.1] (step=0.001) 0.024 Best features [1, 15] Top 9 Best scaling No scaling, Std., MinMax No scaling Random Forest Number of estimators [10, 100] (step=10) 20 30.99 seconds 12.15 Criterion MSE, MAE MAE Maximum depth [1, 20] 7 Minimum samples split [2, 20] 4 Minimum samples leaf [1, 10] 12 Prunning parameter (alpha) [0.6, 1.0] (step=0.01) 0.61 Maximum samples [45, 65] 46 Best features [1, 15] Top 6 Best scaling No scaling, Std., MinMax No scaling Gradient Boosting Loss LS, LAD, Huber, Quantile LAD 55.82 seconds 11.86 Learning rate [0.1, 0.5] (step=0.05) 0.15 Number of estimators [10, 200] (step=10) 80 Subsample [0.1, 1.0] (step=0.1) 0.5 Criterion MSE, Friedman MSE, MAE MSE Best features [1, 15] Top 12 Best scaling No scaling, std., MinMax MinMaxScaler Support Vector Kernel Linear, Polynomial, RBF Polynomial 3.11 seconds 11.06 Degree [1,5] 4 Gamma Scale, auto Scale Coeficient [0.0, 2.0] (step=0.05) 0.90 Regularization parameter [0.0, 2.0] (step=0.05) 1.18 Epsilon [0, 1] (step=0.001) 0.614 Best features [1, 15] Top 7 Best scaling Std., min-max StdScaler Table 6. Hyperparameter tuning results
31 After having tuned the hyperparameters, and selected the best values, we then continued with the model selection and model assessment. As described in the theoretical framework section, in model selection, we estimate the performance of different models to choose the best one, and in model assessment, having chosen a final model, we estimate its prediction or generalization error on new data. For the model selection, we performed a k-fold cross-validation process on the train set as presented in Figure 16. Table 7 shows the results of the average prediction error measured in three different metrics for each model. Model MAE (ton/ha) MAPE (%) RMSE (ton/ha) Decision Tree 13.3 16.1% 16.2 Random Forest 12.2 14.8% 15.9 Gradient Boosting 10.9 12.6% 13.7 Support Vector 10.6 12.3% 13.6 Stacking 9.4 10.5% 12.4 Table 7. Results of the prediction error for model selection. The current solution for the company for predicting productivity relies on the intuition of business experts and the average results of past campaigns. Considering that this baseline solution presents an average error of 15 ton/ha from campaign to campaign, most of the models above, show a better result than the current scenario. The Decision Tree model presented the worst performance in the three metrics. This result was expected since DT is a simple model whose predictive performance is not competitive with other unsupervised learning techniques. However, its metrics were not so far away from those of the Random Forest which was expected to perform better. Gradient Boosting and Support Vector models had the best and very similar performance. To have a better performance, we decided to combine the predictions of some of our models into a stacked model. As mentioned earlier, stacking is designed to ensemble a group of strong learners, and such models tend to perform as well or better than any of the individual learners in the staking. For deciding which models to combine, which features to include, and the scaling method to apply, we used again Optuna to optimize the choice. The selected strategy for the stacking was to combine our two best models Gradient Boosting and Support Vector as base learners and to have a Ridge Regression as our final model or super learner. Figure 18 shows the structure of the stacking solution. Figure 18. Structure of the stacking solution
38 7. BIBLIOGRAPHY American Metereological Society. (2020). Glossary of Meteorology. Retrieved from American Metereological Society: https://glossary.ametsoc.org/wiki/Welcome Awad, M., & Khanna, R. (2015). Support Vector Regression. In Efficient Learning Machines. Springer Nature. Bishop, C. M. (2006). Pattern Recognition and Machine Learning . Springer. Boehmke, B., & Greenwell, B. (2020). Hands-On Machine Learning with R. Taylor & Francis Group. Burkov, A. (2019). The Hundred-Page Machine Learning Book. Data Science Project Management. (n.d.). What is CRISP DM? Retrieved from Data Science Project Management: https://www.datascience-pm.com/crisp-dm-2/ Encyclopedia Britannica. (2021). Encyclopedia Britannica. Retrieved from Encyclopedia Britannica: https://www.britannica.com/ Fischetti, T. (2018). Data Analysis with R - Second Edition. Packt. Food and Agriculture Organization of the United Nations. (1984). Fertilizer and plant nutrition guide. Retrieved from Food and Agriculture Organization of the United Nations: http://www.fao.org/3/aq355e/aq355e.pdf Food and Agriculture Organization of the United Nations. (2009, 10 12). How to feed the world in 2050. Retrieved from Food and Agriculture Organization of the United Nations: http://www.fao.org/fileadmin/templates/wsfs/docs/expert_paper/How_to_Feed_the_Worl d_in_2050.pdf Forbes. (2021, 01 07). Forbes Technology Council. Retrieved from Forbes: https://www.forbes.com/sites/forbestechcouncil/2021/01/07/artificial-intelligence-and- precision-farming-the-dawn-of-the-next-agricultural-revolution/?sh=6bfa74751dbe Hastie, T., Tibshirani, R., & Friedman, J. (2017). The Elements of Statistical Learning. Springer. IBM Cloud Education. (2020, 07 15). IBM Cloud Education. Retrieved from IBM: https://www.ibm.com/cloud/learn/education James, G., Witten, D., Tibshirani, R., & Hastie, T. (2013). An Introduction to Statistical Learning with Applications in R. Kumar Srivastava, A., Safaei, N., Khaki, S., Lopez, G., Zeng , W., Ewert, F., . . . Rahimi, J. (2021, 05 04). Comparison of Machine Learning Methods for Predicting Winter Wheat Yield in Germany. Larose, D., & Larose, C. (2014). Discovering Knowledge in Data: An Introduction to Data Mining, 2nd Edition. Wiley.
39 Meroni, M., Waldner, F., Seguinia, L., Kerdiles, H., & Rembold, F. (2021, 04 27). Yield forecasting with machine learning and small data: what gains for grains? Agricultural and Forest Meteorology. Molnar, C. (2021). Interpretable Machine Learning. A Guide for Making Black Box Models Explainable. Oracle. (2021). Accumulated Local Effects. Retrieved from Oracle Accelerated Data Science: https://docs.oracle.com/en-us/iaas/tools/adssdk/latest/user_guide/mlx/accumulated_local_effects.html Queensland Government. (2016). Soil Properties. Retrieved from Queensland Government: https://www.qld.gov.au/environment/land/management/soil/soil-properties Shahhosseini, M., Hu, G., & Archontoulis, S. (2020). Forecasting Corn Yield With Machine Learning Ensembles. Frontiers in Plant Science. Srinivasan, A. (2006). Handbook of Precision Agriculture Principles and Applications. Stirrup, J., & Oliva Ramos, R. (2017). Advanced Analytics with R and Tableau. The Economist. (2016, 06 09). The future of Agriculture. Retrieved from The Economist: https://www.economist.com/technology-quarterly/2016-06-09/factory-fresh United States Department of Agriculture. (n.d.). United States Department of Agriculture. Retrieved from Soil Quality Kit: https://www.nrcs.usda.gov University of Georgia. (2017, 01 30). Commercial Tomato Production Handbook. Retrieved from University of Georgia Extension: https://extension.uga.edu/publications/detail.html?number=B1312&title=Commercial%20T omato%20Production%20Handbook#:~:text=Soil%20Requirements%20and%20Site%20Prepa ration,that%20tend%20to%20stay%20wet. Yara. (2021). Crop Nutrition Tomato. Retrieved from Yara United States: https://www.yara.us/cropnutrition/tomato/managing-tomato-taste/
40 8. ANNEXES Figure 21. Optimization history plot Decision Tree Figure 22. Optimization history plot Random Forest
41 Figure 23. Optimization history plot Gradient Boosting Figure 24. Optimization history plot Support Vector
Page | i