Introduction
Literature Review
Materials and Methodology
Dataset Overview
Machine Learning Workflow
Machine Learning Models
Performance Metrics
Results and Discussion
The results of the crop recommendation
The results of the Fertilizer Recommendation
Comparison with the Present State of Art
Conclusion and Future Scope
Introduction
Machine learning (ML), as a core component of Artificial Intelligence (AI), has gained significant importance across various domains, particularly in the development of intelligent and sustainable built environments. The rapid advancement of Internet of Things (IoT) technologies, combined with AI, has enabled the transformation of conventional buildings into smart, data-driven systems that enhance efficiency and sustainability. These developments are driven by global challenges such as increasing energy demand, climate change, and the need for environmentally responsible urban infrastructure. The built environment plays a critical role in global energy consumption and environmental impact, necessitating the adoption of intelligent technologies to optimise performance. IoT- enabled devices including environmental sensors, smart meters, and occupancy detectors facilitate continuous monitoring of key building parameters such as temperature, humidity, air quality, lighting conditions, and energy usage. The data collected from these systems supports real-time decision-making and predictive analytics, enabling efficient resource utilization and improved indoor environmental quality [1]. AI-driven models, including Decision Tree, Random Forest, and XGBoost, further enhance the capability of these systems by predicting optimal operational conditions and supporting automated control strategies. The integration of IoT sensing and ML techniques represents a significant step toward sustainable building management, enabling adaptive, scalable, and intelligent solutions for smart buildings and urban environments. Figure 1 illustrates key applications of IoT in smart building systems and highlights their role in advancing sustainable and resilient infrastructure.
The ML algorithm works with nominal human intervention. These algorithms are capable of mining knowledge from data, detecting and reading patterns and generating logical inferences. In this field, various models work on heterogeneous datasets to increase predictive accuracy and decision-making. Various devices are used for data collection, such as drones, images obtained from vines, and the readings of smart devices installed on the ground [2]. In this study, the IoT datasets were used for the execution of ML algorithms. Traditional farming practices are being redefined by AI and ML [3, 4, 5, 6] algorithms, which are at the core of this change.
Innovative levels of intelligence in agricultural operations are enabled by these systems’ ability to interpret and process large amounts of data. These developments improve crop yield and productivity, maintain soil fertility, reduce dependency on labor, and reduce pesticide waste and water. A crop and fertilizer recommendation-based AI system enables farmers to make more precise decisions by automating decision-making, predicting crop and fertilizer in advance [7]. Consequently, farming is becoming progressively more data-driven, which improves agricultural production results and optimizes resource use. Technology is becoming an essential tool in modern agriculture, and another key innovation of this digital transformation is the Internet of Things. An IoT [8] system uses sensors to collect real-time data using a network and smart devices. The ongoing stream of information and data processing enables farmers to respond with speed and efficiency to changes in their fields. Figure 2 shows an application where machine learning is applied for agricultural purposes.
The usage of AI in agriculture is still restricted due to its high prices, and the lack of knowledge on how to use technology and handle the large amount of data accuracy and security is also a big issue in using technology in agriculture [9, 10]. Although agricultural automation and emerging technologies such as robotic systems, precision agriculture and other automated solutions have driven the shift toward smart farming, a few challenges remain unaddressed. The smart machines, like drones, are being used for data collection, crop monitoring and spraying water and medicines. This study contributes to how AI, combined with IoT sensor technologies, can suggest or predict the right crop and fertilizer. The key contributions are:
∙Development of an agricultural smart system combining two agricultural datasets to make crop recommendation and fertilizer prediction using machine learning models.
∙The use of multiple machine learning models such as Decision Tree, Random Forest and XGBoost for their comparative evaluation to determine which one is best suited to achieve accurate prediction and recommendation tasks.
∙Preprocessing data and analysing the features to optimize the model and increase the accuracy of the recommendations and evaluating with metrics like accuracy, precision, recall, and F1 score the effectiveness of various machine learning models.
∙Development of an integrated AI-driven Agricultural Decision Support Pipeline to help farmers choose appropriate crops and fertilizers for their land, based on the soil and environmental conditions, to minimize labor and enhance agricultural output.
The organization of research is as follows: Section 2, literature review, describes related works to this domain. Section 3 explains the materials and methodology, including the dataset details with tables, graphs and the used algorithms. Section 4 discusses findings and their analysis with graphs and figures. Section 5, concludes the entire study and also suggests and proposes some future research directions.
Literature Review
The agricultural sector is currently challenged with various structural and operational difficulties, including insufficient post-harvest storage infrastructure, the production of crop diseases, persistent pest and weed infestations, and inefficient irrigation methods. The global population reflect persistent development, the demand for food is rising just as quickly. Conventional agriculture methods are struggling to keep up with these increasing pressures. Under these circumstances, precision and smart farming approaches are becoming insufficient to maintain productivity and guarantee food security so new technologies like IoT and ML offer disruptive possibilities to improve resource efficiency and crop yield forecasting, and to enable data- driven farming, thus creating more sustainable and scalable farming systems. Akhter, R et al. studied the use of IoT, ML, and data analytics for precision farming, and the key motive of this article is to predict scab disease on apples in Kashmir. How real-time sensor data is effective in crop health monitoring and shows practical benefits. The study explains the smart farming technology over the problem of high cost, low awareness, and limited technical skill among traditional farmers and give the solution to improve the both crop yield and quality [11]. Gosai et al. proposed a smart crop decision-driven system that operates on IoT sensor data and ML algorithms to enhance the production of food. By analyzing key soil factors like rainfall, NPK levels, pH, temperature, and humidity, the system predicts the most appropriate crops using algorithms like Decision Tree, SVM, and XGBoost, where XGBoost give the highest accuracy of 99.31% [12]. Bakthavatchalam et al. studied a precision farming model based on IoT that uses ML and sensor data to build a crop recommendations system on the various environmental factors like rainfall, temperature, pH, NPK, and humidity. Using a dataset of 2,200 records covering 22 crops, the study achieved 98.2% accuracy with multilayer perceptron, JRip, and decision table algorithms in WEKA. Real-time sensor data was stored in the cloud and analyzed to optimize yield and resource use [13]. Rezk et al. studied a smart farming system that is based on IoT and uses the WPART technique, which combines wrapper feature selection with the PART algorithms to predict the drought conditions and crop yield. The system collected required environmental data using sensors, performed preprocessing, and selected the most important features before applying machine learning methods for prediction, achieving up to 98.15% accuracy across five datasets and excelling beyond existing models in precision, F1-score and accuracy. For the future prospective author, advice is to use the improvements, such as incorporating time-series analysis, soil parameters, and computer vision techniques to enhance the system performance [14]. Patil studied the fusion of both IoT and AI techniques in machine learning for advanced smart agriculture. IoT-based sensors are used to gather data and make data-driven decisions for better crop management, productivity, and water conservation. Machine learning, AI techniques analyzed this data for prediction and gave the results for optimal planting times, estimated yields, and assessed fertilizer requirements, and IoT devices ensured real- time monitoring, promoting efficient use of resources and reducing wastage [15]. Sundaresan et al. introduced a smart farming system integrating IoT and ML to boost crop yield and reduce labor. The system provided fertilizer management, automatic irrigation, and crop selection. It used algorithms like KNN to recommend appropriate crops based on soil data (NPK, pH, and moisture) and cloud-based weather inputs. While fertilizer recommendations were customized based on crop type and soil nutrients, irrigation was automated based on current weather and soil moisture. The technology provides a sustainable, AI-driven solution for precision farming and has been tested on crops like maize, rice, and apples [16]. Rajak et al. explored CRS (crop recommendation system) designed to increase and boost agricultural productivity by analyzing soil data obtained from testing laboratories. It uses Support Vector Machine (SVM) and Neural Networks (NN) algorithms that combines to form an ensemble approach to enhance prediction accuracy. It supports the farmers to take data-driven decisions by offering location-specific crop suggestions based on soil characteristics. This approach aims to give a solution to the problems associated with unsuitable crop choice and soil management practices [17]. Zhang, R et al. presented bibliometric analysis of 650 and above publications of the period of 2000 to 2024 to map artificial intelligence advanced technologies in agricultural information identification have significantly evolved, especially with the combination of deep learning and remote sensing platforms such as UAVs and satellite systems. The findings indicate that Convolutional Neural Networks (CNNs) have developed as a leading approach for real-time crop monitoring due to their high capability in image-based feature extraction and analysis [18]. Sudha, S.P. et al. focuses on the rising need for reliable, scalable, and secure integration of ML and IoT systems to help decision- making on real-time and promote sustainable farming practices. It deliberates how combining ML methods with IoT-based precision farming systems can improve key farming activities like crop health monitoring, soil assessment, irrigation control, and yield prediction. Different ML algorithms are highlighted for their role in detecting plant diseases, optimizing nutrient usage, and analyzing the impact of climate conditions. This paper explains how IoT sensors collect data (temperature, soil moisture, and humidity), that helps farmers take more accurate and timely decisions for efficient crop management [19]. Afzal, H. et al. proposed an ensemble model, RFXG, joining Random Forest and XGBoost to recommend the best crop among 22 crops and applying hyperparameter tuning and K-fold cross-validation, and achieves 98% accuracy. The system gives fast, reliable recommendations to support agricultural decisions at the right time [20, 21, 22, 23, 24]. Singla, D. et al. applied transfer learning to classify basil leaf diseases using 2 datasets and 7 pre-trained CNN models were fine-tuned to differentiate the healthy and diseased leaves. For Dataset 1, EfficientNetB3 delivered the best performance, achieving 94% accuracy along with 99% validation accuracy, and 94% precision and recall. For Dataset 2, all models showed outstanding results with 99% across evaluation metrics, though EfficientNetB3 still slightly outperformed the others. Overall, EfficientNetB3 proved to be the most effective model on both datasets [25]. R. Kumar, et al. (2020). have conducted a comprehensive study demonstrating how a combination of a CNN model pre-trained on ImageNet (namely, GoggleNet, MobileNetV2, and Xception) with a lightweight recurrent classifier (single- layer LSTM), can be used to create a highly accurate and reproducible method for automatically detecting Vigna mungo leaf disease. The key to the proposed solution is to treat the convolutional feature maps as spatial sequences, thereby allowing the application of a single-layer LSTM to learn the relationships between pixels on the leaf, which enhances the detection of non-uniform lesion patterns. To works with limited dataset of 660 images, the approach used gradient clipping, frozen backbones, real-time data augmentation, dropout, and early stopping and evaluation was performed using stratified 5-fold cross-validation, and results showed that the Xception-LSTM model attains the best result, with a mean accuracy of 98.34% [26]. Sharma, S et al. study discussed the growing role of AI-driven automation in agriculture to address increasing food demand and labor challenges. It also explained the different applications of agriculture, such as irrigation, weeding, and spraying using sensors, robots, and drones, which improved efficiency while conserving resources. The work also emphasized the combination of AI with corresponding technologies to introduce modern agricultural challenges and improve productivity [27]. Pandey, A. et al. discussed the fast growth of the global population and the resulting difficulty of food insecurity that predictable farming systems failed to address. It discussed the role of SDG 2, SDG 12, and SDG 15, in guiding the transformation of agricultural practices. In this work, sustainable agriculture is defined in terms of an agro-ecological systems approach that enables the production of food and fibre while enhancing environmental, resource and economic sustainability. It also outlines future sustainability targets in relation to current needs, ensuring a strategic alignment with current and future goals [28]. Motwani, A. et al. pointed out the Random Forest and Crop recommendation using CNN and models were suggested by based on the major factors - place, soil and price- and also mentioned India as the largest producer of different crops, with the issues faced by farmers in choosing the right and lucrative crop depending on soil diversity. The CNN model was evaluated and found to have a higher accuracy of 95.21% than 75% for the Random Forest (RF) model, showing its ability to crop prediction [29, 30, 31, 32]. Thalyari, J. et al. presented AI-effective solutions, problems in agriculture, including increasing crop losses, climate change, soil degradation, and market fluctuations. The proposed approach increases productivity, efficiency and sustainability by better decision-making and resource allocation and its adoption is limited by issues such as data availability, infrastructure and ethical issues [33]. Gupta, S. et al. looked at the importance of technologies such as IoT, sensor networks, and UAVs, and machine learning, deep learning, and computer vision, in transforming traditional farming into sustainable practices. These technologies can be applied to areas such as smart irrigation, greenhouse monitoring, crop monitoring, quality, yield estimation, crop phenotyping, and disease detection [34]. Varshitha, D. N et al studied that agriculture is one of the best part of major industries in India, where technology is required to overcome the challenges faced by traditional farming practices. The authors emphasize the need to have information on soil conditions and crop suitability to enhance productivity and profits and suggested a combined approach of deep learning and IoT features for smart farming applications. This research uses different soil properties, to predict soil fertility and suitable crop. A deep neural network (DNN) model was trained to predict the best crop fit for the parameters and various classifiers, including Gaussian Naïve Bayes, K-Nearest Neighbors (KNN), Decision Tree, and Linear Discriminant Analysis (LDA), Support Vector Machine (SVM), were used for a comparative study. The results shows that the proposed DNN model has the best accuracy of 87%, compared to other classifiers which showed relatively lower accuracies. The results propose that DL models for better prediction and robustness accuracy, and make deep learning a promising technique for systems and decision support systems [35]. P. Bandara et al. recommended an automated crop system to resolve problems faced in today’s agriculture, especially in an area where the lands, like Sri Lanka. This system combines IoT data collection (Arduino microcontrollers) and machine learning methods to study environmental data. Critical factors such as temperature, water and soil conditions are monitored to inform crop selection. The method uses both supervised, such as NB, SVM and K-Means clustering, and Natural Language clustering and Natural Language Processing (NLP) techniques are making. The system determines appropriate crops for the specific conditions, and gives real-time advice to feedback mechanism, to farmers as they grow the crop, and a feedback loop, enabling the model to continually update learn and enhance its performance. Experimental outcomes demonstrate an accuracy of 95% or more after 4-6 months of implementation. The proposed approach eliminates the need for expert opinion and maintenance costs [36]. Akkem, Y. et al. given a detailed overview of the impacts of AI in smart agriculture development, presenting insights on challenges of farm sustainability. The study discusses why machine learning, time series and deep learning analysis in optimizing several agricultural processes. Machine learning methods are widely used to select crops, farm management and classify soil compatibility. Deep learning methods are applied for crop prediction and yield forecasting due to their ability to their capacity to deal with complex and massive data. Besides, time series analysis is highlighted in estimating crop production, demand, and commodity prices. The integration of these techniques provides better information for agriculture. The paper also explores how agricultural data can be used for assessing soil fertility and crop recommendation systems. With an increasing population and scarcity, forecasting crop yield is a crucial task. The authors review many time series models to solve forecasting problems, and the research proposes that fusion of ML, deep learning and time series techniques can substantially improve food production and mitigate future food insecurity [37]. Hasan, M et al. talked about the role of farm in attaining food security, especially for the developing world, such as Bangladesh and the need to maximise crop yield with scarce land and other resources, is requiring reliable crop prediction techniques. To address data deficiency, the new data set is built using agricultural institutions and weather data. Several ensemble and ML algorithms such as SVM, NB, Ridge Regression, Forest and CatBoost, are tested. Subsequently, a new ensemble model, K-NN, Random Forest Ridge Regression (KRR), is proposed for crop and yield production prediction. The performance of the model is evaluated using as MAE, MSE, RMSE, and R². These show that KRR achieves better than other models, with high accuracy and minimal or less error. The model’s accuracy is also is confirmed by Diebold-Mariano test. Furthermore, the research notes that rice and potato production are increasing, while wheat production is declining. A crop recommendation system is also constructed to recommend crops for cultivation [38, 39, 40, 41, 42, 43]. Turgut, Ö. et al. discussed crop as a major issue in agriculture due by limited resources and climate variability. To tackle this problem, the authors use state-of-the-art technologies including IoT, machine learning and explainable AI (XAI). An edge computing system, AgroXAI, to suggest recommendations based on weather and soil factors. The study uses explainability tools such as ELI5, LIME, and SHAP to increase model explainability local and global explanations to enhance user trust and understanding. Also, counterfactual explanations are used to recommend other crop options in a region. And the proposed framework can help to inform and sustain the diversification of the farming system [44]. Vanitha, V. et al. described the traditional farming practices and their dependence and issues in India. The author also explains that the key issues, such as improper crop selection, leaf disease identification, and soil health assessment, are identified as major factors affecting productivity. To overcome these issues, researchers proposed an integrated system combining crop recommendation, leaf disease detection and fertilizer suggestion. Ensemble learning methods are employed for disease detection and crop recommendation tasks. Fertilizer prediction is performed using decision tree models optimized through grid search. An IoT-based module is developed for real-time data collection and analysis. The system also includes user-friendly web, mobile, and chatbot interfaces, achieving 98% accuracy in disease detection and 92% accuracy in crop recommendation [45]. Venkateswara, S., et al. studied the important role of AI and IoT in modern agriculture rather than traditional agriculture methods. The author used the Tabnet deep learning model that works on tabular data to improve the prediction accuracy with the SMOTE technique for data imbalance handling and the explainable AI procedure SHAP for enhance the model transparency [46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62]. Sehrish Munawar Cheema et al. utilized parameters such as pH level, Nitrogen (N), Phosphorus (P), Potassium (K), humidity, temperature, and rainfall for smart agriculture prediction. The study compared Decision Tree with AdaBoost, KNN, DT, RF, and SVM models, where the Decision Tree with AdaBoost achieved the highest accuracy of 98% [63]. Khaliq, A. et al. proposed advanced transformer-based models using nutrient levels, moisture, and temperature data for irrigation, soil, crop, and fertilizer recommendation. Their TTL model achieved 99.13% accuracy for irrigation advice, the SwiFT model obtained 98.75% accuracy for crop recommendation, while the TabNet classifier achieved 99.3% accuracy for fertilizer recommendation with improved interpretability using explainable AI techniques [64]. Bülbül, H et al. purposed dual-module agricultural decision support system for crop and fertilizer recommendation using machine learning techniques and using Random Forest, SVM, XGBoost, and KNN were evaluated on agricultural datasets containing 2,200 crop and 3,100 fertilizer samples. Random Forest achieved the best performance with 99.32% accuracy for crop recommendation and 98.75% for fertilizer recommendation. The system also integrates SMOTE for class balancing, GridSearchCV for hyperparameter tuning, and SHAP analysis for explainable AI, providing an efficient and sustainable solution for smart agriculture [65, 66, 67]. Based on the literature studied, the following gaps have been identified.
∙Many AI systems cannot yet process and analyse crop health in real time, and there is a requirement to design AI models capable of processing large datasets of varying farm size, geographic regions, and crop varieties in real time to allow farmers to make quick decisions about changing conditions.
∙The limited sample size affects the AI model’s reliability and generalization. With a smaller sample size, the model prediction is biased, and accuracy is also reduced [26].
∙ AI has demonstrated promising and encouraging outcomes in agricultural applications like disease detection and crop monitoring despite a limited sample size. Exploring other deep learning architectures like GAN, etc, could potentially improve accuracy and offer new insights by integrating environmental and agronomic data [45].
Materials and Methodology
Supervised learning (SL) is the process of learning patterns from labeled training data, where the correct outputs are already known to the machine. The algorithm studies these examples to recognize relationships and patterns between the given data and their corresponding results. This stage is called as the training phase. In this phase, data is given to the model so it can learn to make predictions.
Algorithms like decision trees, random forests, are known for their efficiency in classification tasks, are commonly used to help the system interpret and classify data. The subsequent stage is testing, in this stage, the trained model is given new, unseen and unknown problems to solve. The model uses previously learned patterns to forecast the most suitable outcome. The performance of these predictions is dependent on various factors like the size and quality of the training dataset, the chosen algorithm, and the existence of noise or outliers. The two key steps in supervised learning are training on labelled data and generating accurate predictions from that knowledge.
Dataset Overview
The data set applied for this study was attained from Kaggle, named the Crop Recommendation dataset [47]. It consists of 2,200 rows and includes eight agricultural related environmental features. These features include levels of macro-nutrients like Nitrogen, Phosphorus and Potassium (in parts per million), weather-based features such as Rainfall (mm), Humidity (%), and Temperature (°C), along with soil-level pH reading. The target variable has been labelled Crop, indicating the most suitable crop based on environmental and soil features. Figure 3 indicates the crop distribution.
and the second dataset is Fertilizer Recommendation from Kaggle contain 3,100 rows with the parameters Temperature, Moisture, Rainfall, PH, Nitrogen, Phosphorous, Potassium, Carbon, Soil, Crop, Fertilizer, Remark [61]. Table 1. shows the existing parameter values and a sample of the dataset, in which individual data entries are independent pairings of soil and weather types with one recommended crop and fertilizer that can be produced. The datasets cover many other crop types, from staples such as rice and maize to cash crops and vegetables. With machine learning, complete datasets and diverse input scenarios, these datasets offer a strong foundation for developing smart farming solutions.
Table 1.
Dataset details with feature, samples and use cases
| Dataset | Features | Sample Data | Purpose |
| Crop Recommendation Dataset [47] | N, P, K, Temperature, Humidity, pH, Rainfall, Label | ![]() | Recommend a suitable crop |
| Fertilizer Recommendation Dataset [61] | Temperature, Moisture, Rainfall, pH, Nitrogen, Phosphorous, Potassium, Carbon, Soil, Crop, Fertilizer, Remark | ![]() | Recommend a suitable Fertilizer |
Machine Learning Workflow
Machine learning, along with algorithms such as Decision Trees, Random Forests and XGBoost, is a key component for the design and development of robust and efficient prediction models. The splitting of the dataset into testing and training data is done in the ratio of 70-30% and is a popular approach, allowing for efficient model validation and generalization on new data. This allows us to achieve a fair assessment of the performance while avoiding biases. Through the careful implementation of these techniques, experts can build accurate and efficient machine learning models. This work can be effectively extended to address domain-specific problems and improve the prediction performance, to ultimately assist with data- driven decision-making processes in practice. Figure 4 is the flow of the machine learning technique for crop suggestion and fertilizer recommendation.
Data Pre-Processing
This is done after data collection to clean and improve the inputs and model accuracy. There are two parts in this process. During the first stage, noise and inconsistencies are eliminated. In the second phase, data cleaning and handling missing values.
Feature Extraction
Feature extraction is a data mining process that helps us reduce the dimensions of the data while maintaining the information. It enables the compact representation of big and complex data. This is critical in high-dimensional data, where many variables can make the analysis difficult and cause problems in model performance and preventing the anticipated results.
Feature Selection
The next step involves feature selection, which continues to enhance the dataset by preserving and identifying only the important features.
This step eliminates data redundancy, boosts classification accuracy, reduces computational load and boosts overall efficiency of the model. By removing irrelevant or redundant features overfitting is avoided and model interpretability is improved.
Classification
The classification, which typically contains of two main phases, such as training and testing. During training, the model learns patterns from the dataset, while in testing, its performance is evaluated on unseen data.
Training and Testing
In this study, 70% of the data is used for training model, while 30% is reserved for testing to assess its predictive performance and generalization capability for both tasks.
Fine-Tuning
All the models were tested with hyperparameter tuning to achieve optimal performance. Hyperparameters are values set before training and can have a significant impact on the model’s performance, e.g., its accuracy, generalisation, and computation time. Table 2 represented the Hyperparameter used by the machine learning models.For the Random Forest model, the number of decision trees estimators, maximum depth, feature selection strategy and minimum sample split values were tuned. The parameters were used to increase the stability of the model, decrease the variance and improve the accuracy of the prediction using the ensemble learning. The XGBoost model was tuned by adjusting its important hyperparameters: learning rate, maximum tree depth, subsampling ratio, column sampling ratio and evaluation metric.
Table 2.
Hyperparameters selected for machine learning model
This optimization procedure made gradient boosting more efficient, led to less classification errors, and better generalisation on unseen data.
Machine Learning Models
The ML models are deployed on a cloud platform, where various classification algorithms are executed. These algorithms gathered data through the IoT sensors. Once the data is collected or received, the machine learning models analyze it and give the best results.
1.Random Forest - This machine learning technique, which is based on supervised learning, uses ensemble learning to create a powerful classifier from several weaker models. By training many decision trees at once using the bagging technique. It improves overall performance and decreases the chances of overfitting. A collection of decision trees, each acting as a weak learner, makes up a Random Forest. The outputs of these distinct trees are joined to provide the final results and forecast, usually through majority voting in classification problems. Accurate and effective model results are provided by this parallel structure [46, 48, 49, 50, 52].
Here, shows the prediction from the -th decision tree, and is the total no. of trees in the forest. For classification tasks, the final output is typically determined by majority voting among all trees, while for regression, the average of predictions is taken [49, 58, 59]. The equation 1 shows the mathematical formula of random forest.
2.Decision Tree – It is a supervised learning algorithm that is apply on both classification and regression functions, but in the article, it is used as a classifier. Its core concept includes outlining all possible decision outcomes in a hierarchical tree structure. With each inner node representing a condition on an attribute, each branch displaying the test’s result, and the leaf nodes holding the final class labels, this arrangement resembles a flowchart. When a new case is evaluated, its features follow the same and specific path through the tree, with its core important to a predicted class at a leaf node. Decision trees are commonly used for classification problems across various agricultural datasets and can handle both complete and incomplete datasets with effortlessness [46, 47, 48, 49, 50, 52]. One of the most commonly used formulations is based on information gain using entropy [50].
The equation 2 and 3 used by the decision tree while working on classification task.
Here, is the information gain of attribute , is the entropy of the dataset, and represents subsets after splitting on attribute . The entropy is defined as:
where is the probability of class .
The algorithm selects the feature with the highest information gain at each step to split the data, recursively forming a tree structure. This process continues until a stopping condition is met, such as maximum depth or pure leaf nodes.
3.XGBoost - Extreme Gradient Boosting (XGBoost) is a reliable and effective form of gradient-boosted decision trees, improved for both speed and performance. As an ML approach based on a supervised learning algorithm, it constructs models sequentially, and with each new tree, it aims to fix the errors of the previous one. The inclusion of L1 and L2 regularization, parallel execution, and enhanced tree pruning in XGBoost contributes to higher accuracy and reduces overfitting. Its ability to scale and handle missing values makes it ideal for working with large and complex datasets. [46, 47, 48, 49, 50, 51, 52, 53, 54]. Its objective function associates a loss function and a regularization term:
Here, is the loss function (e.g., logistic or squared error), and is the regularization term for the -th tree, defined as:
where is the number of leaves, represents leaf weights, and 𝛾 and 𝜆 are regularization parameters (39-45). The equation 5 and 6 shows the mathematical formula of XGboost.
Performance Metrics
In classification, the primary goal is to predict a target variable that takes on discrete values [46, 47, 48, 60]. These metrics show how well the model performs. Various commonly used performance metrics are:
Accuracy - The accuracy parameter is mostly apply to assess a model’s performance. By evaluating the percentage of correctly predicted cases from the total number, it provides a rapid indicator of the model’s performance. The number of accurate predictions divided by the total number of input samples is the precise way to calculate accuracy. This metric is used to determine how reliably the model can classify new data based on what it has learned [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60].
Here, TP (True Positives) and TN (True Negatives) mean correct predictions, while FP (False Positives) and FN (False Negatives) mean incorrect predictions.
Precision – The metric evaluates a model’s performance, especially when reducing false positives is essential. Across all the cases the model classified as positive, it shows how accurate its positive predictions are and how many of those were actually true [36, 45].
At this point, TP mean correctly predicted positive cases, and FP mean incorrectly predicted positive cases.
Recall - This performance metric indicates how well a model identifies all actual positive instances. It is executed as the number of true positive cases divided by the total no. of real positive cases.
Here, represents correctly predicted positive cases, and represents actual positive cases that were incorrectly predicted as negative.
F1-Score - In classification problems, the F1-score is a performance metric that totals recall and precision into a single score. F1-score is helpful for unbalanced datasets because it balances recall and precision by taking the harmonic mean of the two metrics [48, 60].
It integrated both false positives and false negatives into a single metric, making it useful when you need a trade-off between precision and recall.
Support - Support helps in determining how well each class is represented during evaluation in situations where the data is unbalanced, since low support can significantly affect performance measures.
Here, and together represent the total actual instances of a particular class.
Results and Discussion
The authors assessed the performance of the Random Forest, XGBoost and Decision Tree classifiers using measures including recall, F1-score, accuracy and precision for both crop recommendation and fertilizer recommendation work.
The results of the crop recommendation
Performance of the Decision Tree classifier for crop recommendation
The results of the decision tree classifier were evaluated using various key classification metrics. The model achieves exceptional performance across all 22 crop classes, with an overall accuracy of 98.79%.
Precision and recall values were reliably high for most classes, with many categories achieving 1.00 scores across all three-parameter metrics. The macro-average of all metrics is approximately 0.99, showing balanced and reliable performance across all crop categories.
The classification report further decomposes to check performance for each crop. The more crops, such as Banana, Coffee, Mango, and Pomogranate, achieve perfect scores (1.00), indicates good classification.
A crops, including Jute, Rice, Blackgram, and Mothbeans, show lower scores, suggesting minor misclassifications. Overall, the model maintains high consistency and robustness. Figure 5 represents the decision tree classifier results.
The weighted average and macro average F1-scores were both 0.99 and 1.00, indicating robust classification performance across both frequent and less frequent classes.
Figure 6 shows the confusion matrix of the decision tree. According to Figure 7, the most important feature Humidity.
Performance of the Random Forest classifier for crop recommendation
The results of the random forest classifier were evaluated using several key classification metrics. The model illustrates excellent performance across all 22 crop classes, achieving an overall accuracy of 99.55% indicating that the model predicts crop types with near-perfect correctness. The classification report further breaks down performance for each crop.
Most crops including Apple, Banana, Coffee, Mango, and Papaya achieve perfect scores of 1.00 in precision, recall, and F1-score, reflecting flawless classification. In general, the figure indicates that the model achieves a high level of accuracy, well-balanced, and effective for crop prediction tasks across diverse crop types.
Precision and recall values were constantly excessive for most classes, with many categories exceeding 1.00 scores in all three-parameter metrics. Figure 8 represents the random forest classifier results.
The weighted average and macro average F1-scores were both 1.00, indicating strong classification performance across both frequent and less frequent classes.
Figure 9 shows the confusion matrix of RF, Figure 10 shows the feature importance where rainfall is indicated as the important feature.
Performance of the XGBoost classifier for crop recommendation
The results of the XGBoost classifier were evaluated using various key classification. The model demonstrated exceptional performance across all 22 crop classes, achieving an overall accuracy of 99.24%, indicating that the model correctly classifies most crops.
In the classification report, many crops, such as Chickpea, Coconut, Coffee, Grapes, Mango, and Papaya achieve perfect or near-perfect scores, reflecting highly accurate predictions. However, a few crops including Jute, Rice, and moth beans show relatively lower recall or F1-scores, indicating occasional misclassification or difficulty in distinguishing these classes.
The report is robust and effective for predicting crop types, while also identifying specific crops that may require further model improvement.
Precision and recall values were consistently excessive for most classes, with many categories achieving scores near 1.00 in all three metrics.
Figure 11, shows the results of the XGBoost classifier. The weighted average and macro average F1-scores were both 0.99, indicating good classification performance across both frequent and less frequent classes.
Figure 12 represents confusion matrix of the XGBoost Classifier and Figure 13 shows the feature importance where Potassium is shown as the important feature. Table 3 compares the performance of random forest, decision tree and XGBoost classifiers.
Table 3.
Result Analysis of crop recommendation
| Metrics / Models | Decision Tree | Random Forest | XGBoost |
| Accuracy | 98.79% | 99.55% | 99.24% |
| Precision | 98.86% | 99.56% | 99.29% |
| Recall | 98.79% | 99.55% | 99.24% |
| F1-Score | 98.78% | 99.55% | 99.24% |
The performance indicators showed that the Random Forest model had the highest accuracy of 99.55%, the highest precision of 99.56%, the highest recall of 99.55%, and the highest F1 score of 99.55%. Thus, these results have shown the excellent classification performance and high consistency among all the crop classes. The third model, XGBoost, also performed extremely well with an accuracy of 99.24%, precision of 99.29%, recall of 99.24% and an F1 score of 99.24%. It is slightly less accurate than Random Forest, but is still very accurate and has good overall generalizability. The Decision Tree model has also performed well, with an accuracy of 98.79%, precision of 98.86%, recall of 98.79%, and F1-score of 98.78%. The performance, however, was slightly lower than that of the ensemble-based approaches, due to slight misclassifications in certain crop categories. In general, all three machine learning algorithms gave high accuracy in classification and good results for the recommendation of crops. In these, Random Forest model provided the best accuracy and precision, followed by XGBoost and Decision Tree model had comparatively lower but still good predictive performance.
In Figure 14, it is shown that the Random Forest model has better results than the Decision Tree and XGBoost in all of the evaluation measures, including 99.55% accuracy, 99.56% precision, 99.55% recall and 99.55% F1-score.
The XGBoost is reasonably good, whereas Decision Tree reaches slightly lower values, which points to relatively poor results of classification efficiency.
The results of the Fertilizer Recommendation
Performance of the Decision Tree Classifier for Fertilizer Recommendation
The performances of the Decision Tree classifier were measured with some significant classification measures. Overall accuracy of the model was 99.25% which shows that the model performed well for the fertilizer classification. The macro precision, recall, and F1-score were 97.36%, 98.40%, and 97.84%, respectively, showing a balance prediction for most classes of fertilizer. The classification report indicates that several fertilizer categories, such as the Compost, DAP, Muriate of Potash, and Water Retaining Fertilizer, had near perfect or perfect precision, recall, and F1- score values. The precision and recall values were slightly less in categories of Minor (General Purpose Fertilizer), Gypsum, and Urea as compared to other classes. The performance of the Decision Tree model was also good for generalization and high level of prediction accuracy overall, and was able to classify the fertilizer types with reliable and consistent performance and were appropriate for fertilizer recommendation tasks. The Figure 15 shown the classification report of decision tree.
The confusion matrix of the Decision Tree classifier demonstrates that the classifier has good classification performance, and the predictions are mainly concentrated on the diagonal. The best classification result was for DAP 316 followed by Water Retaining Fertilizer 202 and Compost 111. Other fertilizers like Lime, Urea, Gypsum and Organic Fertilizer were also classified accurately with slight errors. There are only a few small off diagonal terms which represent negligible misclassification rates between classes in Figure 16. In general, the results demonstrate the high accuracy and reliability of the fertilizer classification performance of the Decision Tree model.
The result of the feature importance analysis of Decision Tree model indicates that among the most important features that affects fertilizer recommendation is Phosphorous, followed by Potassium and Carbon as shown in Figure 17. Other parameters like pH, Nitrogen and Moisture also played a moderate role in the prediction process. However, temperature, rainfall and crop type had little influence on the decision making of the model. In conclusion, the nutrient related parameters were an important factor in the accurate prediction of fertilizers.
Performance of the Random Forest Classifier for Fertilizer Recommendation
In terms of fertilizer classification, the overall accuracy of the Random Forest classifier was 99.25% as equal as the Decision Tree. The model achieved high performance in terms of macro-average precision 98.62%, recall 96.61%, and F1-score 97.30%, showing its robustness and evenness of performance in predicting various fertilizer categories. The results of class-wise evaluation revealed that DAP, Compost, General Purpose Fertilizer, Lime, Muriate of Potash and Water Retaining Fertilizer showed F1-score of 1.00 with perfect precision and recall scores, indicating that they classified classes very well and reliably. Figure 18 illustrates the classification report of Random Forest.
The performance of the Random Forest model was assessed by the use of a confusion matrix as shown in Figure 19. Results show that the classifier had a good prediction ability on most of the fertilizer categories. The classification accuracy of the model was very good for the different fertilizer classes such as DAP, Compost, Muriate of Potash, Water Retaining Fertilizer and Lime. Most importantly, there was very little misclassification for 316 DAP samples, 132 Compost samples, 98 Muriate of Potash samples, 202 Water Retaining Fertilizer samples and 54 Lime samples. There is an indication that the Random Forest model was able to learn the distinctive features of these fertilizers.
There were a few categories that were found to have minor classification errors. For instance, the Gypsum class exhibited some confusion with other fertilizers with a small number of samples misclassified as Balanced NPK Fertilizer, Compost, Organic Fertilizer and Water Retaining Fertilizer. The confusion matrix also indicates that the model had a good inter-class separability, implying that the soil and environmental features selected contained enough discrimination information for fertilizer recommendation. The small off-diagonal values show that there was a good minimization of over fitting and class overlap.
To find the contribution of each input parameter towards the prediction of fertilizers, the feature importance analysis was performed. The relative importance scores obtained from the Random Forest model are presented in Figure 20. Phosphorous was the most important parameter (with an importance score of about 0.31 among all the features, which is related to the concentration of phosphorus. Phosphorous was the most important feature (with an importance score of approximately 0.31 among all the features, which is related to the concentration of phosphorus and the concentration of phosphorus plays the dominant role in the fertilizer recommendation. This was then followed by Potassium and pH with scores of almost 0.15 and 0.14, separately.
The results indicate that the nutrient composition of the soil and its acidity play important roles when deciding on fertilizer choice. The feature ranking also shows that the data set has valuable and relevant features which can be used for a machine learning- based fertilizer recommendation system. Phosphorus and potassium were the highly influential parameters, which could be used to assess the smart farming decision support systems.
Performance of the XGBoost Classifier for Fertilizer Recommendation
The XGBoost model has been tested in terms of accuracy, precision, recall, F1-score and confusion matrix analysis. Results obtained show that the classification of fertilizer using multi-class is very well predicted. The model had an overall highest accuracy of 99.46% and a macro precision of 98.99%, a macro recall of 98.60% and a macro F1 score of 98.74%. The results show that the proposed framework based on the XGBoost is effective in classifying various types of fertilizers with very high reliability. The detailed classification report indicates that performance was almost perfect for most of the fertilizer classes. Precision, Recall and F1 scores were 1.00 for classes like General Purpose Fertilizer, Lime, Muriate of Potash, and Water Retaining Fertilizer, which shows perfect classification.
Likewise, DAP also attained a precision of 1.00, recall of 0.99 and F1 score of 1.00, which indicates extremely precise predictions. The organic fertilizer and urea had an F1-score of 0.98 and the Balanced NPK fertilizer had an F1-score of 0.99, respectively. The performance of Gypsum was comparatively poor, with recall of only 0.88 and F1-score of 0.93, suggesting that there is subtle confusion of this class with other fertilizers. However, the classification performance of all the categories was still very high. Figure 21 represents the classification report of XGBoost classifier.
The confusion matrix analysis is used to illustrate the accuracy of the fertilizer classification for the XGBoost classifier, as it has a very few misclassified fertilizers in all categories. The majority of predictions were focused on the diagonal elements of the matrix, suggesting correct classification of fertilizer samples. The model correctly predicted 47 samples of Balanced NPK Fertilizer samples, 111 Compost samples, 314 DAP samples, 9 General Purpose Fertilizer samples, 14 Gypsum samples, 54 Lime samples, 98 Muriate of Potash samples, 29 Organic Fertilizer samples, 46 Urea samples, and 203 Water Retaining Fertilizer samples. There were only a few off-diagonal errors observed as illustrate in Figure 22.
In particular, one Compost sample was incorrectly identified as Balanced NPK Fertilizer and two DAP samples were identified as Urea. Furthermore, for the Gypsum category one sample was predicted as Organic Fertilizer and another sample was predicted as Water Retaining Fertilizer. Even though of the minor errors in the confusion matrix, the XGBoost model has proven to be a good model for the distinction of fertilizer classes and it has shown good consistency in the classification. The results show that the model proposed for intelligent fertilizer recommendation systems in precision agriculture is robust and reliable, with only a few misclassifications.
Feature importance analysis results show that Phosphorous is the most predominant feature as the greatest importance score of about 0.29, which is significantly higher than all other attributes as shown in Figure 23.
This result is indicative of the importance of the concentration of phosphorus in making appropriate fertilizer recommendations. Carbon was the second most influential feature and then Potassium. Soil type, Nitrogen, pH and Moisture contributed moderately to the prediction process. Crop type, Rainfall, and Temperature exhibited relatively low importance score indicating lesser importance in the considered data set to classify fertilizer.
The nutrient-related parameters dominate, thus demonstrating that the chemical composition of the soil is the most important consideration in making fertilizer recommendation decisions. The feature ranking derived from XGBoost is comparable to agronomic principles and the macronutrients needed for crop productivity are phosphorus, potassium, and nitrogen.
The performance comparison of the three machine learning models for fertilizer recommendation is presented in Table 4. Among the evaluated models, the XGBoost classifier achieved the best overall performance with an accuracy of 99.46%, precision of 98.99%, recall of 98.60%, and F1-score of 98.74%.
Table 4.
Result Analysis of Fertilizer Recommendation
| Metric\Models | Decision Tree | Random Forest | XGBoost |
| Accuracy | 99.25% | 99.25% | 99.46% |
| Precision | 97.36% | 98.62% | 98.99% |
| Recall | 98.40% | 96.61% | 98.60% |
| F1-Score | 97.84% | 97.30% | 98.74% |
The findings show that XGBoost achieved the best performance in terms of achieving a balance and consistency between the rate of over- and under- prediction for fertilizer recommendations, effectively managing the complex relationships within the agricultural dataset. The Decision Tree model also performed well with an accuracy of 99.25% and an F1 score of 97.84%. In particular, it showed a higher recall 98.40% compared to the Random Forest model, indicating its effectiveness in correctly identifying fertilizer classes. It had a lower precision, however, which indicated that there was a slightly higher rate of misclassification. The Random Forest model performed with a high accuracy of 99.25%, precision of 98.62%, recall of 96.61% and F1 score of 97.30%. While Random Forest was able to achieve fairly good results with high precision, it failed to balance false positives and false negatives as well as XGBoost did with lower recall and F1-score.
In general, the experimental results showed that the model based on XGBoost was more efficient in making a fertilizer recommendation compared to the model based on the Decision Tree model and Random Forest model, as represented in the performance comparison Figure 24. The high performance of XGBoost could be attributed to its boosting mechanism, which has the advantage of combining multiple weak learners to further improve the accuracy of prediction and reduce the classification error. The results showed the effectiveness of XGBoost in creating intelligent and accurate fertilizer recommendation systems in precision agriculture.
Comparison with the Present State of Art
The present state-of-the-art in smart agriculture highlights the integration of AI, IoT, and deep learning techniques for intelligent crop and fertilizer recommendation system.
Advanced models are capable of analyzing soil nutrients, environmental parameters and climatic conditions for better prediction results. Table 5 shows the latest methods of deep learning and machine learning approaches with accuracy used by the different authors for precision farming.
Table 5.
Comparative Analysis of Existing State-of-the-Art Machine Learning Approaches for Crop and Fertilizer Recommendation Systems
| Datasets | Ref/ Year | Author | Parameters | Method | Accuracy |
| Crop Recommendation | [62]/2025 | Stella Mary Venkateswara et al. | Soil nutrients (N, P, K), temperature, humidity, climatic conditions | TabNet with SHAP, Iterative Imputation, and SMOTE |
95.24% (Fertilizer), 96.21% (Crop Recommendation) |
| [63]/2025 | Sehrish Munawar Cheema a, et al. | pH level, macro nutrients (NPK) and humidity (h), temperature (t) and average rainfall | Decision Tree with AdaBoost, K-Nearest Neighbor (KNN), Decision Tree (DT), Random Forest (RF) and Support Vector Machine (SVM) |
Decision Tree with AdaBoost achieve highest Accuracy (AC: 98%) | |
| [64]/2025 | Khaliq, A et al. | nutrient levels, moisture, and temperature | Transformer-based tabular learning (TTL). Sparse Weighted fusion transformer (SwiFT). TabNet with explainable AI (XAI): | TTL model 99.13% accuracy for irrigation advice, the TabNet regressor obtained RMSE of 1.51 and R² score of 98.7% for soil analysis, the SwiFT model achieved 98.75% accuracy for crop recommendation, and the TabNet classifier reached 99.3% accuracy for fertilizer recommendation. | |
| [65]/2026 | Hatice Bülbül1, et al. | pH level, macro nutrients (NPK) and humidity (h), temperature (t) and average rainfall | Random Forest, SVM, XGBoost, KNN, SMOTE, GridSearchCV, SHAP | Random forest highe st accuracy for Crop Recommendation: 99.32%. | |
| Present Study | pH level, macro nutrients (NPK) and humidity (h), temperature (t) and average rainfall | Decision Tree, Random Forest, XG Boost | Random Forest achieves the highest accuracy of 99.55% | ||
| Fertilizer Recommendation | [65]/2026 | Hatice Bülbül1, et al. |
Temperature (°C) Moisture Rainfall (mm) pH, macro nutrients (NPK), Carbon (C) Soil, Crop Fertilizer | Random Forest, SVM, XGBoost, KNN, SMOTE, GridSearchCV, SHAP | Random forest highest accuracy for Fertilizer Recommendation: 98.75% |
| Present Study |
Temperature (°C) Moisture, Rainfall (mm), pH, macro nutrients (NPK),Carbon (C), Soil, Crop Fertilizer |
Decision Tree Random Forest XGBoost | XGBoost obtained highest accuracy 99.46% | ||
Conclusion and Future Scope
This study examines the integration of IoT sensor networks and machine learning algorithms in developing an intelligent framework for sustainable building performance optimization. The proposed system utilizes environmental and operational data such as temperature, humidity, NPK and type of soil to enable accurate prediction. Among the evaluated models the performance of the Decision Tree, Random Forest, and XGBoost models in terms of crop and fertilizer recommendation has been compared with the evaluation metrics: Accuracy, Precision, Recall, and F1-score. Experimental results showed that ensemble learning techniques performed better than the traditional Decision Tree Classifier. The overall best performance was obtained by the Random Forest model, which has approximately 99.55 per cent accuracy, 99.56 per cent precision, 99.55 per cent recall and 99.55 per cent F1-score for crop recommendation. The model XGBoost also performed very well with the values of the metrics around 99.23%, whereas for the Decision Tree model the value of the metrics was comparatively low and around 98.80%. The results showed that the Random Forest model showed the highest level of reliability and stability in predicting the crop recommendation because of its good generalization ability and less overfitting.
XGBoost had the best performance in terms of the evaluation metrics across all the models with around 99.46% accuracy, 98.99% precision, 98.60% recall, and 98.74% F1-score for fertilizer recommendation. The Decision Tree model effectively reached the accuracy of almost 99.25% and the other metrics also came close to acceptable results with moderate values, whereas Random Forest had relatively lower values in recall and F1-score. The results prove the power of XGBoost in modeling complex relationships between key soil nutrients and environmental parameters for accurate fertilizer predictions. Results indicate that machine learning-based suggestion systems are capable of supporting precision agriculture applications. Random Forest was found to be the most appropriate model for crop recommendation while XGBoost was found to be the best model for fertilizer recommendation. The predictive accuracies obtained in this study indicate the potential application of these models to enhance agricultural productivity, optimize fertilizer use and promote sustainable farming practices.
Future research directions include the use of larger and more diverse real-time datasets across different building typologies and climatic conditions to improve model generalization. The integration of advanced deep learning and hybrid models may further enhance predictive performance and robustness. Additionally, incorporating lifecycle cost analysis, environmental impact metrics can strengthen the applicability of the system for sustainable urban development and long-term asset management.




























