A Predictive Approach to Improving Agricultural Productivity in Morocco through Crop Recommendations

—Agricultural productivity is a critical component of sustainable economic growth, particularly in developing countries. Morocco, with its vast agricultural potential, is in need of advanced technologies to optimize crop productivity. Precision farming is one such technology, which incorporates the use of artificial intelligence and machine learning to analyze data from various sources and make informed decisions about crop management. In this study, we propose a web-based crop recommendation system that leverages ML algorithms to predict the most suitable crop to harvest based on environmental factors such as soil nutrient levels, temperature, and precipitations. We evaluated the performance of five ML algorithms (Decision Tree, Naïve Bayes, Random Forest, Logistic Regression, and Support Vector Machine) and identified Random Forest as the best-performing algorithm. Despite the promising results, we faced several challenges, including limited availability of data and the need for field validation of the results. Nonetheless, our platform aims to provide free and open-source precision farming solutions to Moroccan farmers to improve agricultural productivity and contribute to sustainable economic growth in the country.


INTRODUCTION
Agriculture is a crucial sector in Morocco, accounting for a significant portion of the country's GDP and employing a large percentage of the population. However, the sector faces several challenges, including water scarcity, unpredictable weather patterns, and a lack of access to information and resources [1]. Recently, an increasing interest has been observed for developing crop recommendation systems to address these challenges and improve agricultural productivity in the country [2].
Crop recommendation systems use predictive techniques to suggest the most suitable crops for a given location and set of conditions. These systems rely on data from various sources, such as satellite imagery, weather forecasts, soil analyses, and historical crop yields, to make accurate predictions [3]. By providing farmers with personalized recommendations, crop recommendation systems can help them make informed decisions about crop selection and improve their yields and profits [4].
The objective of this paper is to present a predictive approach to improving agricultural productivity in Morocco through crop recommendations. Specifically, we will develop a crop recommendation system that utilizes prediction techniques to suggest the most suitable crops for a given location and set of conditions.
In order to achieve this objective, we will initially examine the current body of literature related to crop recommendation systems as well as the difficulties encountered by the agricultural sector in Morocco. After this, we will outline the approach we employed to construct our system, which including the dataset, prediction techniques, and evaluation metrics. Following this, we will detail the outcomes of our study, including the precision of our forecasts and the efficacy of our crop recommendation system. Lastly, we will analyze the implications of our research on enhancing agricultural productivity in Morocco and suggest potential avenues for future research.
The structure of the paper is as follows. Firstly, an introduction is provided, followed by a succinct AI in precision agriculture summary, focusing primarily on Machine Learning (ML) as a component of Artificial Intelligence (AI). The paper also includes a concise literature review that highlights recent developments in the field. The research methodology is then presented, which involves an experimental evaluation of our research using various ML algorithms such as Decision Tree, Naïve Bayes, Random Forest, Logistic Regression, and Support Vector Machine. A discussion comes after this section. Finally, the key findings of the study are summed up as a conclusion of this paper.

II. PRECISION FARMING OVERVIEW
Precision farming is an agricultural management approach that uses technology to optimize crop yields and reduce waste. Its objective is to provide farmers with real-time data and information on their farms and livestock, in order to take accurate actions that can result in maximized crop yields and limited losses. AI helps in analyzing data from various sources and making informed decisions about crop management [5]. ML, a subfield of AI, has proven to be particularly useful in precision farming due to its ability to automatically learn patterns from The data collected by these sensors is transmitted to the technical staff. Various data analytic methods are then applied to interpret and derive useful insights from the collected data. The resulting information is exploited to take accurate and timely actions. To provide a better understanding, Fig. 2 illustrates the various stages involved, including the automated collection of data and the processing operations by agribots according to the insights derived from the processed data.
One area where ML has been applied in precision farming is crop yield prediction. ML algorithms can analyze data from sensors, such as satellite imagery, weather stations, and soil sensors, to make accurate predictions about crop yields [9]. For example, a study [10] used ML to predict winter wheat yields in China based on satellite imagery and weather data.
Another application of ML in precision farming is crop disease detection. By analyzing images of crops, ML algorithms can identify signs of disease or stress and alert farmers to take action [11]. For example, a study [12] used ML to identify cassava disease in Tanzania based on images captured by drones. The authors found that their ML model was able to accurately identify diseased plants, even in cases where the symptoms were not visible to the human eye.  ML can also be used to optimize crop management decisions, such as irrigation and fertilization. By analyzing data on soil moisture, nutrient levels, and weather patterns, ML algorithms can suggest the optimal amount of water to apply to a crop [13]. For example, a study by [14] demonstrates that the integration of active canopy sensing and machine learning improves the prediction accuracy of the corn nitrogen nutrition index by accounting for genetic, environmental, and management factors.
In conclusion, ML has significant potential in precision farming due to its ability to analyze large datasets and make accurate predictions. By applying ML to tasks such as crop yield prediction, disease detection, and crop management optimization, farmers can improve their yields and reduce waste.

III. LITERATURE REVIEW
Nowadays, as ML has been increasingly employed in precision agriculture, numerous studies have been conducted across various areas of farming. Therefore, to provide a clearer picture and distinguish this work from others, we present a summary of recent research in Table I.  Table I displays that numerous scientists have created Artificial Intelligence AI-based solutions suitable for different agriculture areas including crop selection and cultivation techniques. These solutions are often presented in the form of predictive systems and recommendation platforms, using stateof-the-art techniques. While these approaches have potential, they do not necessarily address the need for real solutions that can be implemented in the field at low cost and can help farmers and decision-makers optimize their resources and maximize profits.
It is interesting to note that few studies have focused on this issue in recent years, with most studies providing only theoretical overviews and practical implementations. The challenge is to find a way to make these solutions available for all, and make them more visible to a larger audience, such as farmers. Our study provides a step-by-step explanation of how to address these problems and offers examples of how to make these technologies available for free.

A. System Conception
To design our crop recommendation system, we initiated the first step by preparing a crop recommendation dataset. We used Moroccan climate, fertilizer and precipitations data [30] then preprocessed it in order to make extensive explorations. We worked with a dataset consisting of 1800 entries and eight variables. Next, we conducted an exploration of the data to understand its nature. Finally, we used ML techniques counting NB, DT, RF, SVM, and LR to extract the best features and build our ML models. After completing the models building step, we proceeded to evaluate their performance. Once the evaluation was complete, we then moved on to deploy the model with highest performance as a web application, which forms a basis of our crop recommendation system.
After completing the evaluation, the next step was to deploy the best selected model as a web application, which serves as the foundation for our crop recommendation system.

B. Dataset Preparation and Feature Selection
The crop recommendation dataset we selected comprised several features, including content in soil of Phosphorus (P), Potassium (K) and Nitrogen (N), as well as soil pH value and moisture, precipitations, temperature and plant variety. The data collection consisted of 1800 entries, and an overview of the dataset statistics is presented in Table II.
In terms of the relationship between the input parameters and target, we observed that certain parameters, such as Potassium, phosphorus and Nitrogen exhibit strong correlations of 0.6. This is a promising sign prior to the commencement of the prediction. There were also some phew negative correlation values between the indicators. This shows that the dataset is rich in information.
From a biological perspective, the P K N levels play a vital role as important macro-nutrients that support plant growth. Potassium, is responsible for the plant's natural functioning, while phosphorus aids in the maturation of fruits. Nitrogen contributes mainly to the growth of leaves.
Fertilizer containing elements such as P K N and can be tailored to different crops based on their concentrations. These nutrients are essential for the growth and productivity of crops, and using fertilizer can make up for any deficiencies in the soil. By understanding the PKN ratios required for optimal plant development, farmers can manage fertilization and achieve better yields [31].
Other parameters in our data, including temperature, soil moisture and pH, and precipitations play important roles in crop selection. The pH value affects the existence of vital substances, while precipitations level is crucial in plant survival. Air temperature impacts photosynthesis, and soil moisture is essential for growth, but too much or too little can be detrimental. Our dataset includes several crop categories, such as apples, dates, corn, grape, pepper, orange, peach, potatoes, onions, tomatoes, olives, and watermelon, that can be predicted based on these features. The prediction of these crops yields is dependent on the parameters mentioned.

C. Predictive Models Development
To develop our predictive ML models, we utilized the Python programming language. The data preprocessing stage involved importing the necessary libraries, including NumPy, Pandas, Scikit-learn, and Matplotlib.
To train and test the models, we split the dataset into training and testing datasets, with a ratio of 70:30. We then employed five ML models (DT, NB, LR, RF, and SVM).
To evaluate the accuracy of the models, we used precision, recall, F1 and accuracy metrics, which were calculated using the following formulas: Additionally, we used k-fold cross-validation scores to evaluate the effectiveness of the different algorithms used in the predictive analysis, which provided a more robust assessment of the models' performance [32].
These scores helped us evaluate the effectiveness of the different algorithms used in the predictive analysis.

A. Results of Prediction
This section presents a discussion of the experimental results obtained for the performance of the ML algorithms used in our study. Table III provides a detailed summary of the precision, recall, accuracy, and k-fold cross-validation score results.
Based on our results, the ML algorithms employed in our study exhibit varying levels of predictive capabilities in determining profitable crop based on inputs. Our analysis shows that RF has the highest performance in terms of accuracy, with a score of 97.18%. In comparison, other algorithms such as NB (96.36%), LR (95.62%), SVM (87.38%), and DT (86.64%) have lower accuracy scores. Fig. 4 illustrates a comparison of the accuracy for all ML models adopted in our analysis.
The precision value assesses the ratio of accurate positive label predictions, indicates that NB and RF exhibit excellent performance. Conversely, DT has the lowest performance in this category. Regarding recall value, which assesses the ability of the ML models to correctly predict actual positives, RF once again outperforms the other models, while SVM and DT have the lowest scores.
Regarding the F1 score, which is the harmonic mean of precision and recall, RF attains the highest score of 97%, followed by NB at 96%, LR at 96%, SVM at 87%, and DT at 83%.
To estimate the overall performance of the models, we used K-fold cross-validation with a value of K=10. The results indicate that RF has the highest 10-fold cross-validation vale, while DT has the lowest performance. Although accuracy alone is not a reliable performance metric, considering other evaluation measures, it is apparent that RF surpasses the used ML techniques in forecasting the most appropriate crop.

B. Crop Recommendation Solution
In our opinion, the market for precision agriculture solutions that are available at no cost and released under an open-source license is continuing to evolve, and considerable progress is needed for these solutions to compete with closedsource solutions. However, the involvement of a network of IT specialists and interested parties, including farmers, has aided expansion of open-source alternatives. These communities can address any issues or doubts related to technology integration with ease [33][34][35]. Bearing this in mind, our main objective was to propose and design a crop recommendation system.
Relying on the performance metrics mentioned earlier, RF demonstrated superior performance in comparison to the other ML models we used. Therefore, we plan to employ RF to predict the optimal crop based on the user's input parameters, such as P K N, soil moisture and pH, temperature, and precipitations. After selecting the best-performing model, we serialized/saved it Python's built-in persistence model, namely pickle, for developing of the crop recommendation system. The various steps involved in designing and deploying the crop recommendation system are outlined in Fig. 5. To create the system, we utilized Flask as a Python micro framework used in applications development, which enables programmers to conveniently build Application Programming Interfaces (APIs) in Python language. To create interactive web pages for users, we used HTML (Hypertext Markup Language) and designed them using CSS. After that, we implemented the platform Flask micro web framework. Fig. 6 depicts the fully functional recommendation platform hosted locally.
The working system along with the development environment are available on an uploaded directory online [36]. It consists of all code files used for the training and prediction, as well as the app code of the recommendation system and the frontend source code.
In Fig. 6(a), the collected field data is entered manually at the Front end.
In Fig. 6(b), the Result is displayed after processing the given data through the trained M.L Model.

VI. DISCUSSION
After evaluating the performance results of the ML model training, we found that RF has the best performance among all the models. Despite the small training dataset of only 1800 entries, RF still outperforms other models in terms of recall, precision, and other performance criteria, apart from accuracy. Therefore, we chose RF as the ML technique to use in building the recommendation system.
Once the required inputs are submitted, the platform verifies for missing values and if the entries fall within acceptable thresholds before proceeding. The system then predicts the most appropriate crop to plant based on the input parameters. This enables farmers to make informed decisions for higher returns on investment and reduced wastage. This enables farmers to opt for knowledgeable choices that lead to increased profits and reduced waste.
During the development of our crop recommendation system, we postulated that users would utilize pre-existing (IJACSA) International Journal of Advanced Computer Science and Applications, Vol. 14, No. 3, 2023 204 | P a g e www.ijacsa.thesai.org meteorological data and the abundant IoT farming tools that are already deployed to obtain necessary information for submitting parameters to our platform. Since our platform is web-based, it is accessible from anywhere and from any device, providing a high level of convenience for the users.
However, we acknowledge that the dataset we used for developing the system is constituted of Moroccan data, and crop growth can vary based on the context and circumstances of different territories. To provide our system to farmers globally, more data from various geographic locations may be required. As our system continues to develop, it can have the capability to compile information from various geographical territories, allowing users to enter their position along with the relevant data to predict suitable crops for planting. This paper displays the potential of using ML to design smart techniques at the service of agriculture, and it may set the stage for emerging studies to develop predictive platforms in conjunction with robotic technology.
Investing in farming is critical for any economy, and selecting profitable crops is an important task that can guarantee the best production. Our proposed solution aims to help farmers select the best crop for their land and environmental context. With further improvements, like integrating IoT in automated data collection and using more parameters and key indicators from different locations, we can offer this technology to more farmers, especially those who want to implement technology-driven precision farming.
While many organizations and startups are designing precision farming solutions, most of them are subscriptionbased with high prices, free and open-source alternatives can be accessible for farmers to. It is crucial for farmers to be knowledgeable about these alternatives that can enable them to utilize technology at no cost, instead of making significant upfront investments.

VII. CONCLUSION AND PERSPECTIVES
Agriculture is a vital industry that feeds billions of people worldwide, and the use of technology has transformed traditional farming practices, resulting in improved yields and a higher quality harvest while reducing manual labor. Precision farming, powered by AI, is becoming increasingly popular due to its ability to collect field data and to assist farmers in taking informed actions to manage their cultivated lands.
This study presents a web-based ML-driven crop recommendation system to assist users choose the most suitable crops to plant based on local environmental conditions. Although there are many commercial solutions available, alternatives also exist at freely and at no coast.
The study demonstrates the combination of ML and precision agriculture and outlines the architecture of a webbased platform. The platform could be improved by adding real-time monitoring capabilities by interfacing with existing data aggregation platforms from sensors and IoT. This would result in a more accurate and suitable prediction framework, making precision farming more accessible to farmers worldwide, ultimately helping to address the challenges of feeding the global population.