0% found this document useful (0 votes)
66 views30 pages

Project

The document outlines a project aimed at developing a machine learning-driven Crop Management System to enhance agricultural productivity through data-driven crop recommendations, fertilizer suggestions, and yield predictions. It addresses the limitations of traditional farming methods by utilizing real-time environmental data and advanced algorithms to optimize resource usage and improve decision-making for farmers. The project emphasizes the integration of various machine learning models and aims to support sustainable agriculture practices while being accessible to small and marginal farmers.

Uploaded by

Avinash Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views30 pages

Project

The document outlines a project aimed at developing a machine learning-driven Crop Management System to enhance agricultural productivity through data-driven crop recommendations, fertilizer suggestions, and yield predictions. It addresses the limitations of traditional farming methods by utilizing real-time environmental data and advanced algorithms to optimize resource usage and improve decision-making for farmers. The project emphasizes the integration of various machine learning models and aims to support sustainable agriculture practices while being accessible to small and marginal farmers.

Uploaded by

Avinash Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

CHAPTER 1

INTRODUCTION

Agriculture remains the foundation of the worldwide economy, maintaining billions


through the arrangement of fundamental food supplies. In any case, the segment faces
numerous challenges that affect viability, maintainability, and benefit. Unusual climate
patterns, unacceptable crop choices, wasteful asset administration, and declining soil
wellbeing posture leading to the decline in agricultural productivity. Traditionally , farmers
depend on instinct, picked up information, and prior encounters to choose which crops to
cultivate. Indeed in spite of the fact that these strategies have been the establishment of
cultivating for a long time, they frequently lead to imperfect crop choices, wasteful utilization
of assets, and reduced efficiency. Much obliged to the fast progressions in innovation,
especially in machine learning and data analysis, agriculture has experienced a critical change
toward exactness cultivation. Machine learning calculations are competent in analyzing
tremendous sums of information to uncover designs and relationships that are difficult to
distinguish with ordinary strategies[1]. These insights enable agriculturists to create educated
choices, make strides asset allotment, and boost crop yields. Leveraging these innovations
can essentially boost agricultural efficiency, decreasing wasteful utilization and cultivating
with the most profitable yield.

This project contains the module Crop Recommendation , Fertilizer Recommendation


, Yield Prediction , Crop possibility prediction system that utilizes machine learning strategies
to help agriculturists in making educated, data-driven choices. The paper points to prescribing
the foremost reasonable crops for agriculture by looking at different natural and soil factors,
counting temperature, moisture of soil , pH levels, and supplement substance. Also, it
predicts anticipated crop yields, permitting agriculturists to organize their agricultural
exercises more successfully. Through the integration of distinctive machine learning models,
assessing their adequacy, and utilizing the best-performing demonstration, the project
upgrades the in general decision-making handle in cultivation. Through the examination of
natural components such as temperature, moisture, pH levels, soil supplements, and
dampness substance, the paper proposes the most suitable crops for a particular region
whereas determining conceivable yields. Decision Trees define decision rules, Random
Forest improves expectation accuracy by joining various trees[2]. Logistic regression

1
analyzes the likelihood of crop compatibility, and naive Bayes assesses the chances of perfect
crop yield. This cohesive methodology helps farmers in optimizing resources, reducing
dangers, and upgrading yield, advancing productive and maintainable agricultural practices.

Agricultural efficiency is essential for food security, but agriculturists regularly


experience challenges in choosing the most excellent crops and determining conceivable
yields due to natural and soil factors. Conventional agricultural choices depend on encounter
rather than data-based experiences, coming about in less-than-ideal crop determinations and
incapable asset utilization. This activity looks to form a machine learning-driven crop
recommendation system ,fertilizer recommendation system , yield prediction system and crop
possibility prediction system to assist farmers make taught choices, upgrade efficiency, and
advance economical cultivating. In outline, The Crop Recommendation , Fertilizer
Recommendation , Yield Prediction , Crop possibility prediction system serves as an
imperative asset for progressing agriculture. Utilizing information and machine learning, it
helps farmers in making learned choices that result in expanded efficiency, made strides in
resource administration, and a more maintainable agricultural future.

1.2 Aim of the Project

The aim of this project is to develop an intelligent Crop Management System that
leverages machine learning techniques to provide accurate crop recommendations, improve
soil health analysis, and assist farmers in making data-driven decisions for sustainable
agriculture. This system is designed to enhance productivity, reduce resource wastage, and
support precision agriculture practices through user-friendly interfaces and real-time insights.

1.3 Project Domain

This project lies in the intersection of the Agriculture and Artificial Intelligence (AI)
domains, with a focus on Machine Learning (ML). It integrates data science techniques to
solve real-world agricultural problems, contributing to the field of AgriTech. The system
aims to support Precision Agriculture, which utilizes technology and data analysis to
optimize crop yield and farming efficiency.

2
1.4 Scope of the Project

●​ Provides crop recommendations based on soil parameters (nitrogen, phosphorus,


potassium), pH level, temperature, humidity, and rainfall.
●​ Predicts the most suitable crop to be grown in a given condition using trained ML
models.
●​ Can be extended to include fertilizer recommendations, pest detection, and yield
prediction.
●​ Supports farmers in making evidence-based decisions, reducing dependency on
traditional methods.
●​ Offers potential integration with IoT sensors for real-time data collection in future
versions.

1.5 Methodology

1. Data Collection: A comprehensive dataset containing soil nutrients, weather conditions,


and crop types is sourced from open agricultural datasets.
2. Data Preprocessing: The dataset is cleaned, normalized, and encoded to ensure quality
input for the model.
3. Model Selection: Various classification algorithms (Random Forest, Decision Tree, KNN,
SVM) are evaluated for accuracy.
4. Model Training and Testing: The best-performing model is trained on the dataset and
tested for precision and recall.
5. Model Deployment: The trained model is converted to a deployable format (e.g.,
TensorFlow Lite) and integrated into a web/mobile interface.
6. System Integration: A simple GUI or web app allows users (farmers) to input soil and
environmental data to receive crop recommendations instantly.

3
CHAPTER 2

LITERATURE REVIEW

Ajay Agarwal et al.[1] A Comprehensive Analysis, the advancements highlighted


the significance of joining soil properties. Different considers utilized machine learning
calculations to analyze soil information and predict the appropriate crops for individual
lands.the master plans are also investigated, giving farmers with required proposals based on
soil conditions. Siva Ramakrishna Sani et al.[2] Crop Recommendation System using
Decision tree Algorithm in Machine Learning explains about in agricultural industries
illustrated the usability of machine learning calculations in progressing trim suggestions.
Different calculations like SVM, were investigated for predicting appropriate crops based on
soil properties. The significance of soil quality and supplement substance in improving is
controlled. Shunmuga Lakshmi P et al.[3]A Recommendation System for Crop Prediction
Under Diverse Weather Conditions, The significance of early and exact generations
estimating to make steps forward agricultural results.

Meet Mehta et al.[4] An Innovative Model For Soil Testing With Crop
Recommendation System,The soil testing labs regularly sustain that from insufficient
foundation and over workloads, causing delays that will prepare farmers from planting crops
at the correct time. Whereas private labs offer faster management,but their high costs make
them too expensive for several farmers.Dr Gayathri B et al.[5] Machine Learning based Crop
Suitability Prediction and Fertiliser Recommendation System, Researchers previously
explored traditional methods relying on farmers experience, which often led to inaccurate
predictions. With advancements in technology, machine learning algorithms have been
applied to analyze historical yield data and soil properties to improve estimated accuracy.
Studies have shown that Random Forest exceeded other models in crop prediction due to its
strength in handling large datasets. Similarly, K-means clustering has been effectively used to
classify soil nutrients and recommend suitable fertilizers. D.N.V.S.L.S. Indira et al.[6] A
Machine Learning based Recommendation System to the Farmer A few examinations have
been conducted to progress agricultural efficiency utilizing machine learning methods.
Analysts already depended on routine strategies, but these approaches frequently led to
wrong expectations and wasteful aspects. Machine learning models such as XGBoost, and

4
K-means clustering were utilized to predict cut reasonableness, prescribe fertilizers, and
differentiate plant illnesses.

Mahalakshmi B et al.[7] Agricultural Crop and Fertilizer Recommendations based on


Various Parameters ,Researchers have highlighted the affect of unusual climatic conditions
shows on rural efficiency. Analysts distinguished soil quality, water accessibility, and regular
varieties as their key components affecting cut of yield. Information of harvesting approaches
have been utilized to analyze genuine rural information and give beneficial proposals to
agriculturists. Considers have illustrated that sharp cultivating advances move forward for
decision-making and benefit administration in agriculture. Jaichandran R et al.[8] Light GBM
Algorithm based Crop Advisory by Weather Detection and Soil Nutrients ,Based on the
previous considerations they have emphasized the significance of crop production in
supporting national economies and making steps for food security.

Dr. J. Avanija et al.[9] Crop Advisory System using Ant Lion Optimization and
Decision Tree Algorithm, Analysts have utilized decision tree calculations, support vector
machines to analyze soil properties, climatic conditions, and asset accessibility for exact crop
determination. Nature-inspired calculations, such as Antlion Optimization (ALO), have been
broadly considered for their efficiency in improving complicated rural parameters. CH.
Rakesh et al.[10] Crop Advisory and Prediction System,some of the considerations have
examined the role of machine learning and agriculture in improving crop choice and making
developments in rural efficiency. Analysts have utilized calculations such as k-Nearest
Neighbors (KNN), choice trees, and profound learning models to analyze soil conditions,
climate designs, and resource accessibility.

5
CHAPTER 3

PROJECT DESCRIPTION

3.1 Existing System

In the traditional agricultural setup, farmers often rely on their experience, regional
knowledge, and advice from local agricultural officers to make decisions about crop selection
and cultivation practices. While this approach may work in certain cases, it lacks scientific
accuracy and is not scalable for modern precision farming. Furthermore, existing systems that
offer crop recommendations are usually rule-based or static, providing generic suggestions
without analyzing real-time soil or environmental data. These systems are not adaptive and
cannot handle complex interactions among various parameters such as soil nutrients,
temperature, rainfall, and pH. Additionally, many of them are inaccessible to small and
marginal farmers due to language barriers, lack of digital literacy, or the absence of
region-specific recommendations.

3.2 Proposed System

The proposed Crop Management System is a machine learning-driven solution that


addresses the shortcomings of the existing system by providing intelligent and dynamic crop
recommendations. This system analyzes critical agricultural parameters such as nitrogen (N),
phosphorus (P), potassium (K), temperature, humidity, soil pH, and rainfall to predict the
most suitable crop for cultivation in a particular region. Using trained classification
algorithms, the system learns from historical data and predicts outcomes with high accuracy.
The proposed system offers a user-friendly interface—either through a web application or a
mobile app—where users can input real-time values and instantly receive recommendations.
This approach not only reduces guesswork but also optimizes input usage, thus enhancing
productivity, profitability, and environmental sustainability. The system also holds potential
for future expansion, including modules for fertilizer suggestions, pest detection, yield
prediction, and integration with IoT-based sensors for real-time monitoring.

6
3.2.1 Advantages

The proposed system offers several advantages over the existing methods. It ensures
high accuracy in crop recommendation by leveraging supervised machine learning models
that can generalize well across varied input conditions. It enhances resource optimization by
advising crops that are well-suited for the current soil and weather conditions, thereby
reducing fertilizer misuse and water consumption. The intuitive interface makes it accessible
to farmers, agricultural officers, and students alike. Moreover, the system is scalable and
flexible, allowing additional functionalities such as pest and disease detection, fertilizer
prediction, and region-specific advisories in the future. Most importantly, it shifts the farming
paradigm from experience-based to data-driven decision-making, ensuring long-term
sustainability and food security.

3.3 Feasibility Study

3.3.1 Economic Feasibility

The development and implementation of the system are economically feasible as it


relies on open-source technologies and publicly available datasets. The cost of training and
deploying the model is minimal, and the infrastructure required for hosting the web or mobile
application is affordable, especially with cloud platforms offering free-tier services. Once
deployed, the system significantly reduces long-term operational costs by helping farmers
choose appropriate crops, thereby minimizing input wastage and improving yields. This
makes it a highly cost-effective solution, especially for developing countries where
agriculture is a major economic sector.

3.3.2 Technical Feasibility

From a technical standpoint, the project is highly feasible. The machine learning
models can be efficiently trained using standard Python libraries such as Scikit-learn,
TensorFlow, and Pandas. The dataset is preprocessed and cleaned to ensure high-quality
inputs to the model. The final trained model is converted to a lightweight format using
TensorFlow Lite for easy deployment on Android platforms or embedded systems.
Integration with a Flask-based backend allows for a smooth and responsive user experience.
The technologies used are well-documented and supported by active developer communities,
ensuring ease of maintenance and updates.

7
3.3.3 Social Feasibility

The project has strong social feasibility, especially in agrarian societies where small
and marginal farmers face challenges in accessing expert agricultural advice. By providing
localized, personalized crop suggestions, the system empowers farmers with scientific
knowledge, bridging the gap between traditional practices and modern technology.
Additionally, the simplicity of the interface ensures that users with limited technical
knowledge can still benefit from the system. It supports regional language integration in
future iterations, making it even more socially inclusive. Overall, the system promotes
sustainable agriculture, enhances livelihood opportunities, and supports national food security
goals.

3.4 System Specification

3.4.1 Hardware Specification

To run and test the system efficiently, a computer or laptop with a minimum Intel i5
processor, 4 GB RAM, and at least 100 GB of storage is required. A basic display screen (13
inches or more) is sufficient for the web interface. For mobile deployment, a standard
Android smartphone with an internet connection and basic processing capabilities is enough
to run the application. The lightweight model ensures that the system can function even on
low-end devices, making it accessible to a wide range of users.

3.4.2 Software Specification

The software requirements include a modern operating system such as Windows,


Linux, or Android. The backend is developed using Python with frameworks like Flask or
Django. For machine learning, libraries such as Pandas, NumPy, Scikit-learn, Matplotlib, and
TensorFlow are used. The model is converted using TensorFlow Lite for mobile app
integration. For web deployment, HTML, CSS, Bootstrap, and JavaScript may be used for
front-end development. An SQLite or CSV-based storage can be used for lightweight local
storage of results.

8
3.4.3 Standards and Policies

The system is designed following best practices in software development and ethical
use of artificial intelligence. It complies with data privacy standards and avoids storing
personally identifiable information (PII). The system encourages open-source development,
allowing others to contribute and improve the tool over time. It also aligns with sustainable
agriculture standards promoted by organizations such as the Food and Agriculture
Organization (FAO) of the United Nations. By adhering to these policies, the project ensures
ethical deployment and responsible AI use in agriculture.

9
CHAPTER 4

PROPOSED METHODOLOGY

4.1 General Architecture:


A precise approach is pivotal for the effective execution of a solid and compelling
framework in our Crop management project using Machine learning. This approach
comprises of three primary stages:Gathering dataset from Kaggle, Training models with
Pickel, and creating an Web application in Visual Studio Code.The structure of the project
shown in Fig. 4.1.

Fig. 4.1: System Architecture

10
4.2 Module Description
4.2.1. Dataset Collection:
The favorable outcome of a machine learning project is based on the data's quality
and amount. For this project, we utilize multiple datasets relevant to agriculture and crop
prediction taken from open source Kaggle, each containing essential attributes for effective
recommendations and predictions. The Crop Recommendation Dataset consists of soil
nutrients like Nitrogen (N), Phosphorous (P), Potassium (K) and environmental factors like
temperature, humidity, pH, and rainfall and the crop name which helps in recommending the
most suitable crop for a given condition. The Fertilizer Recommendation Dataset includes
temperature, humidity, soil moisture, soil type, crop type, nitrogen, phosphorus, potassium
levels and fertilizer name which helps in recommendation of the most suitable fertilizer for
the given conditions . The Yield Prediction Dataset contains state name, district name, crop
year, season, crop type, area, and production, which is crucial for predicting crop yields for
the given conditions . The Crop Prediction Dataset includes state, district, season, and crop
type, assisting in identifying the likely crops grown in a specific region. The dataset
undergoes preprocessing to handle missing values, normalize features, and standardize labels,
ensuring high accuracy in model predictions.

4.2.2 Model Training:


This project contains four modules: Crop Recommendation Module, Fertilizer
Recommendation Module, Yield Prediction Module and Crop Possibility Prediction Module,
each module has a separate trained model for their predictions and recommendations for
precision agriculture. Choosing the algorithm for precision results we go with an ensemble
learning approach, ensemble learning approach chooses the best model for the given dataset
to produce precision results.
Comparing the Decision tree algorithm, Random forest algorithm, Logistic regression
algorithm, Naive Bayes algorithm,K Nearest Neighbours and Random forest is more accurate
for the given dataset, as shown in fig. 4.2.

11
Fig. 4.2: Model selection
​ The Crop recommendation model is trained with the algorithm Random forest
classifier, an ensemble learning algorithm to recommend the crop based on the soil properties
like Nitrogen (N), Phosphorous (P), Potassium (K), Temperature(TEMP), Humidity(HUM),
pH level (pH), Rainfall(RF). It operates in two modes: training and predictions. In the
training phase , it reads soil properties and weather conditions from the dataset given, the
model trains a Random forest model with 10 decision trees and saves it as ‘crop_model.pkl’
using pickle. In the prediction phase the user provides input values, which are processed and
fed into a trained model to recommend the most suitable crop.
𝐶𝑀𝑡​(𝑥) = 𝑓(𝑁, 𝑃, 𝐾, 𝑇𝐸𝑀𝑃, 𝐻𝑈𝑀, 𝑝𝐻, 𝑅𝐹) 𝐸𝑞𝑛(1)

Substituting the values in the equation 1, N as 90, P as 48, K as 52, TEMP as 22, HUM as 85,
pH as 6.5 and RF as 225.

𝐶𝑀𝑡(90, 48, 52, 22, 85, 6. 5, 225) = 𝐶𝑟𝑜𝑝 𝑟𝑒𝑐𝑜𝑚𝑚𝑒𝑛𝑑𝑒𝑑(𝑦)

The solution of Decision trees are:


Decision tree 1, 𝐶𝑀
​ 1(x)= Rice

Decision tree 2,𝐶𝑀2(x)= Rice

Decision tree 3, 𝐶𝑀3​(x)= Maize

Decision tree 4, 𝐶𝑀4(x)= Wheat

Decision tree 5, 𝐶𝑀5(𝑥)= Rice

12
𝑦 = 𝑚𝑜𝑑𝑒{𝐶𝑀1​(𝑥), 𝐶𝑀2​(𝑥), 𝐶𝑀3​(𝑥), 𝐶𝑀4​(𝑥), 𝐶𝑀5​(𝑥)} 𝐸𝑞𝑛(2)

Rice appears 3 times; Maize appears 1 time; Wheat appears 1 time. Now using the Ensemble
learning approach the most repeated outcome from the decision trees will be a recommended
crop. Equation 3 is a recommended crop.

𝑦 = 𝑅𝑖𝑐𝑒 𝐸𝑞𝑛(3)

Where: 𝐶𝑀𝑡(𝑥) is the predicted crop from the t-th decision tree

The Fertilizer recommendation model is trained with the algorithm Random forest
classifier, an ensemble learning algorithm to recommend the Fertilizer based on the soil
properties. It trains a model using data Nitrogen (N), Phosphorous (P), Potassium (K),
Temperature(TEMP), Soil type(ST), Soil moisture(SM), Crop(C) and Humidity(HUM) where
Categorical values are encoded using label encoding. The dataset is split into training and
testing. the model trains a Random forest model with 10 decision trees and saves it as
‘crop_model.pkl’ using pickle the trained model is saved for future use if the model or
encoders are missing, it automatically retrains the model. When a user gives input values, the
python script validates and encodes them, then predicts the ideal fertilizer utilizing the trained
model. In the prediction phase the user provides eight input values, which are processed and
fed into by a trained model to predict the most suitable fertilizer.

𝐶𝑀𝑡​(𝑥) = 𝑓(𝑁, 𝑃, 𝐾, 𝑇𝐸𝑀𝑃, 𝐻𝑈𝑀, 𝑆𝑀, 𝑆𝑇, 𝐶𝑇) 𝐸𝑞𝑛(4)

Substituting the values in the Equation 4, N as 30, P as 5, K as 6, TEMP as 28, HUM as 54,
SM as 41, ST as Loamy and CT as paddy.

𝐶𝑀𝑡(30, 5, 6, 28, 54, 41, 𝐿𝑜𝑎𝑚𝑦, 𝑃𝑎𝑑𝑑𝑦) = 𝐹𝑒𝑟𝑡𝑖𝑙𝑖𝑧𝑒𝑟(𝑦)

Decision tree 1, 𝐶𝑀1(𝑥)=Urea

Decision tree 2, 𝐶𝑀2(𝑥)=Urea

Decision tree 3, 𝐶𝑀3(𝑥)=DAP

Decision tree 4, 𝐶𝑀4(𝑥)=Urea

Decision tree 5, 𝐶𝑀5(𝑥)=MOPh

13
𝑦 = 𝑚𝑜𝑑𝑒{𝐶𝑀1(𝑥), 𝐶𝑀2(𝑥), 𝐶𝑀3(𝑥), 𝐶𝑀4(𝑥), 𝐶𝑀5(𝑥)}

𝐸𝑞𝑛(5)

Urea appears 3 times; DAP appears 1 time; MOP appears 1 time, Now using the Ensemble
learning approach the most repeated outcome from the decision trees will be a recommended
crop. Equation 6 is a recommended fertilizer.

𝑦 = 𝑈𝑟𝑒𝑎 𝐸𝑞𝑛(6)

Where: 𝐶𝑀𝑡(𝑥) is the recommended fertilizer from the t-th decision tree

​ The Yield Prediction model is trained with a random forest regression algorithm to
predict the crop yield (production) using various input features. It begins by loading the
dataset and recognizing categorical columns like State name, District name, Season, Crop
name, and Crop year. These categorical features are changed over into numerical values
utilizing One Hot Encoding, ensuring the model can process them. The dataset is splitted
into two parts, training (X) and testing (y), where production is the target variable. The
dataset is divided into 80% training and 20% testing sets utilizing train_test_split(). A random
forest regression model with 100 decision trees (n_estimators=100) is trained on the training
data (X_train, y_train), learning the relationship between input features and edit crop
production. After training, the trained model is saved as crop_production_model.pkl and one
hot encoder is saved as label_encoders_yield.pkl are saved using joblib.dump() for future
predictions. For prediction, the script takes six command-line inputs: state, district, crop year,
season, crop and area. It verifies the input count and loads the trained model and One Hot
Encoder. The categorical inputs are transformed using One Hot Encoding and the numerical
feature (Area) is added. The script ensures the input features align with those used during
training by reindexing the DataFrame. Finally, the trained model predicts the crop yield and
the yield is shown as the anticipated surrender in quintal. This structured approach guarantees
precise data encoding and dependable yield prediction for different input conditions.

𝐶𝑀𝑡(𝑥) = 𝑓(𝑆𝑡𝑎𝑡𝑒, 𝐷𝑖𝑠𝑡𝑟𝑖𝑐𝑡, 𝐶𝑟𝑜𝑝 𝑌𝑒𝑎𝑟, 𝑆𝑒𝑎𝑠𝑜𝑛, 𝐶𝑟𝑜𝑝, 𝐴𝑟𝑒𝑎)

𝐸𝑞𝑛(7)

14
Substituting the values in the Equation 7, State as Andhra Pradesh, District as GUNTUR,
year as 2026, season as Rabi, Crop as Rice, Area as 250.

𝐶𝑀𝑡("𝐴𝑛𝑑ℎ𝑟𝑎𝑃𝑟𝑎𝑑𝑒𝑠ℎ", "𝐺𝑈𝑁𝑇𝑈𝑅", 2026, "𝑅𝑎𝑏𝑖", "𝑅𝑖𝑐𝑒", 250) = 𝑃𝑟𝑒𝑑𝑖𝑐𝑡𝑒𝑑 𝑌𝑖𝑒𝑙𝑑 (𝑦)

= 𝑦𝑖𝑒𝑙𝑑 𝑝𝑟𝑒𝑑𝑖𝑐𝑡𝑖𝑜𝑛(𝑦)
Decision tree 1, 𝐶𝑀1(𝑥)=220.1 quintal

Decision tree 2, 𝐶𝑀2(𝑥)=228.4 quintal

Decision tree 3, 𝐶𝑀3(𝑥)=225.6 quintal

Decision tree 4, 𝐶𝑀4(𝑥)=230.2 quintal

Decision tree 5, 𝐶𝑀5(𝑥)=228.4 quintal

𝑦 = 𝑚𝑜𝑑𝑒{𝐶𝑀1(𝑥), 𝐶𝑀2(𝑥), 𝐶𝑀3(𝑥), 𝐶𝑀4(𝑥), 𝐶𝑀5(𝑥)} 𝐸𝑞𝑛(8)

228.4 appear twice, 220.1 appear once, 230.4 appear once,225.6 appear once Now using the
Ensemble learning approach the most repeated outcome from the decision trees will be a
recommended crop. Equation 9 is the predicted yield of the crop in quintals

𝑦 = 228. 4 𝑞𝑢𝑖𝑛𝑡𝑎𝑙𝑠 𝐸𝑞𝑛(9)

Where: 𝐶𝑀𝑡(𝑥) is the predicted yield from the t-th decision tree

The crop prediction model is trained using the decision tree classifier to give
information about the crop growth in the specific region and season , The decision Tree
Classifier for crop prediction employing the preprocessed dataset ‘preprocessed2.csv’. The
dataset is split into training data (80%) and testing data (20%). Function like unique_vals(),
class_counts(), parcel(), gini(), and info_gain() analyze data and determine the most excellent
split using find_best_split(). The decision Tree structure is defined usind the question, leaf
and decision node class and build_tree() recursively develops the tree. The trained model is
saved as ‘filetest2.pkl’. The prediction of the model takes the input values state, district and
season as command-line inputs. It classifies the crop using classify(), retrieves prediction
probabilities using print_leaf(), and prints the predicted list of crops in that specific region
and season. The decision tree model helps in data-driven decision-making by classifying
crops based on patterns in the dataset, enhancing agricultural productivity.

𝐶𝑀 (𝑥) = 𝑓(𝑥1​, 𝑥2,..., 𝑥𝑛​) 𝐸𝑞𝑛(10)

15
In Equation 10 the 𝑥1, 𝑥2,..., 𝑥𝑛 are feature values given by the user like state, district and

season for getting the possibility crop prediction shown in Equation 11.

𝐶𝑀 (𝑥) = 𝑦 𝐸𝑞𝑛(11)

4.2.3. Front End Development:


To provide an user-friendly interface, we developed the frontend using PHP. The
process began with designing a structured layout using HTML and CSS to ensure a clean and
responsive user interface. Bootstrap was incorporated to enhance responsiveness across
different devices. The primary focus was on creating a seamless user experience by
structuring multiple pages for input and output display. User inputs were captured through
well-designed forms using PHP, which validated and processed the data before passing it to
the backend model for predictions. JavaScript and AJAX were utilized to improve
interactivity, allowing dynamic content updates without requiring page reloads. The results
from the machine learning model were formatted and displayed effectively using PHP,
ensuring clarity in presenting recommendations or predictions. Error handling mechanisms
were implemented to manage invalid inputs gracefully. CSS styling and JavaScript
animations were used to enhance user engagement, providing a smooth and visually
appealing experience.

16
CHAPTER 5
IMPLEMENTATION
5.1 Crop Recommendation System
import pandas as pd
import numpy as np
import pickle
import sys
from sklearn.ensemble import RandomForestClassifier
# Check if script is running for training or prediction
if len(sys.argv) == 2 and sys.argv[1] == "--train":
# Load the dataset
dataset = pd.read_csv("Crop_recommendation.csv")
# Separate features (X) and target labels (y)
X = dataset.iloc[:, :-1].values # All columns except the last one
y = dataset.iloc[:, -1].values # Last column (crop type)
# Train the model
classifier = RandomForestClassifier(n_estimators=10, criterion="entropy",
random_state=42)
classifier.fit(X, y)
# Save the trained model
with open("crop_model.pkl", "wb") as model_file:
pickle.dump(classifier, model_file)
print(" Model training complete! The trained model is saved as 'crop_model.pkl'.")
else:
# Ensure correct number of arguments
if len(sys.argv) != 9:
print(" Incorrect number of arguments. Usage:")
print('python recommendcrop.py N P K temperature humidity pH rainfall model_path')
sys.exit(1)
# Parse user inputs (convert to appropriate types)
try:
N = float(sys.argv[1])
P = float(sys.argv[2])

17
K = float(sys.argv[3])
temperature = float(sys.argv[4])
humidity = float(sys.argv[5])
pH = float(sys.argv[6])
rainfall = float(sys.argv[7])
model_path = sys.argv[8]
except ValueError:
print(" Invalid input: Please enter numeric values for N, P, K, temperature, humidity, pH,
and rainfall.")
sys.exit(1)
# Load the trained model
try:
with open(model_path, "rb") as model_file:
model = pickle.load(model_file)
except FileNotFoundError:
print(f" Model file not found: {model_path}")
sys.exit(1)
# Prepare input data
user_input = np.array([[N, P, K, temperature, humidity, pH, rainfall]])
# Predict the crop
predicted_crop = model.predict(user_input)[0]
print(f"{predicted_crop}")
5.2 Fertilizer Recommendation System
import sys
import pickle
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.ensemble import RandomForestClassifier
import os
import warnings
warnings.filterwarnings("ignore") # Suppress all warnings

18
# Paths for model & encoders
model_path =
r"C:\Users\hball\Downloads\crop-management-system-main\fertilizer_model.pkl"
encoders_path =
r"C:\Users\hball\Downloads\crop-management-system-main\label_encoders.pkl"
dataset_path =
r"C:\Users\hball\Downloads\crop-management-system-main\crop-management-system-main\
fertilizer_recommendation.csv"
# Function to train model if not available
def train_model():
df = pd.read_csv(dataset_path)
df.rename(columns=lambda x: x.strip(), inplace=True)
# Encode categorical variables
le_soil = LabelEncoder()
le_crop = LabelEncoder()
le_fertilizer = LabelEncoder()
#df["Soil Type"] = le_soil.fit_transform(df["Soil Type"])
#df["Crop Type"] = le_crop.fit_transform(df["Crop Type"])
df["Fertilizer Name"] = le_fertilizer.fit_transform(df["Fertilizer Name"])
# Define features & target
X = df[['Temparature', 'Humidity', 'Soil Moisture', 'Soil Type', 'Crop Type', 'Nitrogen',
'Potassium', 'Phosphorous']]
y = df["Fertilizer Name"]
# Train the model
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
# Save model & encoders
with open(model_path, "wb") as f:
pickle.dump(model, f)
with open(encoders_path, "wb") as f:
pickle.dump({"soil": le_soil, "crop": le_crop, "fertilizer": le_fertilizer}, f)
print(" Model trained and saved successfully!")

19
# Train if model doesn't exist
if not os.path.exists(model_path) or not os.path.exists(encoders_path):
print(" Model or encoders not found. Training the model now...")
train_model()
# Load trained model & encoders
try:
with open(model_path, "rb") as f:
model = pickle.load(f)
with open(encoders_path, "rb") as f:
encoders = pickle.load(f)
# Verify encoders loaded correctly
if not isinstance(encoders, dict) or "soil" not in encoders or "crop" not in encoders or
"fertilizer" not in encoders:
raise ValueError(" Encoders dictionary structure is incorrect. Re-training the model.")
except Exception as e:
print(f" Error loading model or encoders: {e}")
print(" Re-training the model...")
train_model()
def predict_fertilizer(n, p, k, t, h, sm, soil, crop):
try:
if soil not in encoders["soil"].classes_:
return f" Error: '{soil}' is not a recognized Soil Type. Available:
{list(encoders['soil'].classes_)}"
if crop not in encoders["crop"].classes_:
return f" Error: '{crop}' is not a recognized Crop Type. Available:
{list(encoders['crop'].classes_)}
soil_encoded = encoders["soil"].transform([soil])[0]
crop_encoded = encoders["crop"].transform([crop])[0]
# Prepare input array
input_data = np.array([[t, h, sm, soil_encoded, crop_encoded, n, k, p]])
# Make prediction
pred = model.predict(input_data)
# Decode prediction
fertilizer_name = encoders["fertilizer"].inverse_transform(pred)[0]

20
return f" {fertilizer_name}"
except Exception as e:
return f" Error: {str(e)}"
# Run from command-line with inputs
if __name__ == "__main__":
if len(sys.argv) != 9:
print(f" Error: Invalid number of inputs. Expected 8 parameters, received
{len(sys.argv)-1}.")
print(" Received parameters:", sys.argv[1:])
n = float(sys.argv[1]) # Nitrogen
p = float(sys.argv[2]) # Phosphorus
k = float(sys.argv[3]) # Potassium
t = float(sys.argv[4]) # Temperature
h = float(sys.argv[5]) # Humidity
sm = float(sys.argv[6]) # Soil Moisture
soil = sys.argv[7] # Soil Type
crop = sys.argv[8] # Crop Type
# Get prediction & print result
result = predict_fertilizer(n, p, k, t, h, sm, soil, crop)
print(result)
5.3 Yield Prediction System
import joblib
import pandas as pd
import sys
if len(sys.argv) != 7:
print(" Error: Incorrect number of arguments.")
#print("Usage: python yield_prediction.py <State_Name> <District_Name> <Crop_Year>
<Season> <Crop> <Area>")
sys.exit(1) =
joblib.load(r"C:\Users\hball\Downloads\crop-management-system-main\crop_production_mo
del.pkl")
ohe =
joblib.load(r"C:\Users\hball\Downloads\crop-management-system-\one_hot_encoder.pkl")

21
state = sys.argv[1]
district = sys.argv[2]
year = int(sys.argv[3])
season = sys.argv[4]
crop = sys.argv[5]
area = float(sys.argv[6])
# Prepare input dictionary
user_input = {
'State_Name': state,
'District_Name': district,
'Season': season,
'Crop': crop,
'Crop_Year': year,
'Area': area
}
# Convert input to DataFrame
user_df = pd.DataFrame([user_input])
# Apply OneHotEncoding
X_encoded = ohe.transform(user_df[['State_Name', 'District_Name', 'Season', 'Crop',
'Crop_Year']])
X_encoded_df = pd.DataFrame(X_encoded, columns=ohe.get_feature_names_out())
# Add numerical feature 'Area'
X_final = pd.concat([X_encoded_df, user_df[['Area']].reset_index(drop=True)], axis=1)
# Ensure features match the trained model
trained_features = model.feature_names_in_
X_final = X_final.reindex(columns=trained_features, fill_value=0)
# Make prediction
prediction = model.predict(X_final)
print(f"{prediction[0]}")
5.4 Crop Possibility Prediction
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.ensemble import RandomForestClassifier

22
import joblib
pd.read_csv(r"C:\Users\hball\Downloads\crop-management-system-main\crop-management-
system-main\preprocessed2.csv")
# Select input features (X) and target (y)
X = df[['State_Name', 'District_Name', 'Season']] # Only 3 columns
y = df['Crop']
# Encode categorical data
label_encoders = {}
for column in X.columns:
label_encoders[column] = LabelEncoder()
X[column] = label_encoders[column].fit_transform(X[column])
crop_encoder = LabelEncoder()
y = crop_encoder.fit_transform(y)
# Train model
model = RandomForestClassifier()
model.fit(X, y)
# Save model and encoders
joblib.dump(model, "crop_suggestion_model.pkl")
joblib.dump(label_encoders, "label_encoders_suggest.pkl")
joblib.dump(crop_encoder, "crop_encoder.pkl")
print(“ Model retrained successfully!")

23
CHAPTER 6

RESULT AND DISCUSSION

Fig. 6.1: Home page for crop management system

In fig. 6.1 we can see the interactive user home page to access the all the 4 modules given in
the navigation bar in left side

Fig. 6.2: Crop recommendation page

Fig. 6.3: Recommendation of crops in crop recommendation system

24
In fig. 6.2 we can see the crop recommendation system webpage, in provided text box user
can give inputs that are asked in the provided text field, for example we can see in fig.6.3 :
Nitrogen value is given as 90, Phosphorus value is given as 48 ,Potassium value is given as
52 ,Temperature is given as 22,Humidity is given as 85,pH value is given as 6.5 and Avg
Rainfall as 225 mm, Here the recommended crop is “rice”.

Fig. 6.4: Fertilizer recommendation page

Fig. 6.5: Recommendation of fertilizer in fertilizer recommendation system


In fig. 6.4 we can see the fertilizer recommendation system webpage, in provided text box
user can give inputs that are asked in the provided text field, for example we can see in
fig.6.5 : Nitrogen value is given as 30, Phosphorus value is given as 5 ,Potassium value is
given as 6 ,Temperature is given as 28,Humidity is given as 54, Soil Moisture is given as 41
and Soil type given as loamy,Crop type given as paddy, Here the recommended crop is
“Urea”.

25
Fig. 6.6: Yield prediction page

Fig. 6.7: Prediction of yield in yield Prediction system


In fig. 6.6 we can see the yield Prediction system webpage, in provided text box user can give
inputs that are asked in the provided text field, for example we can see in fig.6.7 : State name
is entered as Andhra Pradesh, District name is entered as Guntur, Crop year is entered as
2026, Season is entered as Rabi, Crop is entered as Rice and Area(Hectors) is entered as 250,
Here the predicted crop yield is “228.4 Quintal”.

Fig. 6.8: Crop Possibility Prediction page

26
Fig. 6.9: Possibility Predicted Crops in Crop Possibility Prediction system
In fig. 6.8 we can see the yield Prediction system webpage, in provided text box user
can give inputs that are asked in the provided text field, for example we can see in fig.6.9 :
State name is entered as Andhra Pradesh, District name is entered as Guntur, Season is
entered as Rabi, Here the predicted crops list of crops are “Arhar, Dry Chillies, Gram,
Groundnut, Jowar, Maize, Moong, Rice, sesamum and so on as shown in fig.6.9”.

27
CHAPTER 7

CONCLUSION

The project effectively created a real-time crop management system using random forest and
decision tree algorithms, emphasizing accessibility and practical use for the farmers. The
system effectively recommends and predicts according to the given input from the user as we
can see the recommended crop is rice for the given inputs shown in fig. 5, we can see the
recommended fertilizer is urea for the given inputs shown in fig. 7, we can see the predicted
yield of the crop is 228.4 quintal for the given inputs shown in fig. 9, we can see the possible
crops grown in particular region are Arhar, Dry Chillies, Gram, Groundnut, Jowar, Maize,
Moong, Rice, sesamum and so on for the given user input as shown in fig.11. Future
enhancements could concentrate on improving the model to ensure quicker and more precise
processing, enhancing its functionality in various real-world settings.

28
REFERENCES
[1]​Ajay Agarwal, Sartaj Ahmad,Adesh Pandey, “ Crop Recommendation Based on Soil
Properties: A Comprehensive Analysis” 2023 14th International Conference on
Computing Communication and Networking Technologies (ICCCNT) IEEE
[2]​Siva Ramakrishna Sani ,Surya Venkata Sekhar Ummadi ,SriRajarajeswari Thota , Nikitha
Muthineni,Varun Sai Srinivas Swargam,Teja Sree Ravella , “Crop Recommendation
System using Random Forest Algorithm in Machine Learning “2023 2nd International
Conference on Applied Artificial Intelligence and Computing (ICAAIC) IEEE
[3]​Shunmuga Lakshmi P,Ram Kishore V ,PillaiPrathaRamachandran,Santhi,Kalaiselvi S , “
A Recommendation System for Crop Prediction Under Diverse Weather Conditions”
2023 9th International Conference on Advanced Computing and Communication Systems
(ICACCS) IEEE
[4]​Meet Mehta, Abhijit Saha, Siddharth Fulia, Tushar Jain, Dr. Narendra Shekokar ,“An
Innovative Model For Soil Testing With Intelligent Crop Recommendation System”,2023
14th International Conference on Computing Communication and Networking
Technologies (ICCCNT) IEEE
[5]​Dr Gayathiri ,Brindha P,Karthika I,Saranya E,Dr Rajeshkumar G,Dr Rajesh Kanna P, “
Machine Learning based Crop Suitability Prediction and Fertiliser Recommendation
System”,2023 4th International Conference on Electronics and Sustainable
Communication Systems (ICESC) IEEE
[6]​ D.N.V.S.L.S. Indira,M. Sobhana,A.H.L.Swaroop,Phani Kumar V, “ KRISHI RAKSHAN
- A Machine Learning based New Recommendation System to the Farmer “, 2022 6th
International Conference on Intelligent Computing and Control Systems (ICICCS) IEEE
[7]​Mahalakshmi B,Sakthivel V, Sumitha Devi B, Swetha S, “ Agricultural Crop and
Fertilizer Recommendations based on Various Parameters “, 2023 International
Conference on Sustainable Computing and Smart Systems (ICSCSS) IEEE
[8]​ Jaichandran R, T.Murali Krishna,Sri Harsha Arigela, Ramakrishnan Raman,Dharani N,
Ashok Kumar, “Light GBM Algorithm based Crop Recommendation by Weather
Detection and Acquired Soil Nutrients “,2022 International Conference on Power,
Energy, Control and Transmission Systems (ICPECTS) IEEE
[9]​Dr. J. Avanija ,Keerthi Ambati ,Likitheswari Naraganti, Sai Sahith Derangula,Tanujasree
Nashina, “ Crop Recommendation System using Antlion Optimization and Decision Tree
Algorithm”,2024 3rd International Conference on Applied Artificial Intelligence and
Computing (ICAAIC) IEEE
[10]​ CH. Rakesh D. Vishnu Vardhan, Babu Bhavani Vasantha, G. Sai Krishna “Crop
Recommendation and Prediction System “,2023 9th International Conference on
Advanced Computing and Communication Systems (ICACCS) IEEE

29

You might also like