Crop Yield Prediction Using Machine
Learning
Introduction
Agriculture plays a major role in the economy of many countries, especially in India. Farmers
depend on environmental conditions such as rainfall, temperature, and pesticide usage to achieve
better crop production. Predicting crop yield helps farmers and agricultural industries make
better decisions regarding cultivation, irrigation, and resource management.
This project focuses on predicting crop yield using Machine Learning algorithms. The project
compares three different regression models:
• Linear Regression
• Random Forest Regressor
• Decision Tree Regressor
The dataset used in the project contains agricultural factors such as:
• Average rainfall per year Pesticide usage in tonnes
• Average temperature
These features are used to predict the crop yield measured in hg/ha_yield (hectograms per
hectare yield).
The project is implemented using Python and libraries such as:
• Pandas
• Matplotlib
• Scikit-learn
The main objective is to identify which Machine Learning model provides the best prediction
accuracy for crop yield.
Objectives of the Project
The important objectives of this project are:
1. To analyze agricultural data for crop yield prediction.
2. To apply Machine Learning regression algorithms.
3. To compare the performance of different models.
4. To identify the most accurate prediction model.
5. To visualize model accuracy using graphs.
This project helps in understanding how data science and machine learning can improve
agricultural productivity.
Dataset Description
The dataset used in this project is loaded from the file:
yield_df.csv
The dataset contains the following important columns:
Feature Name Description average_rain_fall_mm_per_year Average
annual rainfall
pesticides_tonnes Amount of pesticides used
avg_temp Average temperature hg/ha_yield Crop yield
output
The first three columns are used as input features, while the crop yield column is used as the
target output.
Working of the Project
Step 1: Importing Libraries
The project begins by importing required Python libraries.
import pandas as pd import
[Link] as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from [Link] import RandomForestRegressor
from [Link] import DecisionTreeRegressor
Purpose of Libraries
Pandas is used for reading and handling datasets.
Matplotlib is used for data visualization.
Scikit-learn provides machine learning algorithms and utilities.
Step 2: Loading the Dataset
The dataset is loaded using the Pandas library.
df = pd.read_csv("yield_df.csv")
This statement reads the CSV file and stores it in a dataframe named df.
Step 3: Selecting Input and Output
Input features and output values are separated.
X = df[['average_rain_fall_mm_per_year',
'pesticides_tonnes',
'avg_temp']]
y =
df['hg/ha_yield']
Input Features
• Rainfall
• Pesticides
• Temperature
Output
Crop Yield
The model learns the relationship between these environmental factors and crop production.
Step 4: Splitting the Dataset
The dataset is divided into training and testing data.
x_train,x_test,y_train,y_test = train_test_split(X,y,test_size=0.2)
Explanation
80% data is used for training. 20%
data is used for testing.
Training data helps the model learn patterns, while testing data checks the model performance.
Machine Learning Models Used
1. Linear Regression
Linear Regression is one of the simplest regression algorithms. It finds a linear relationship
between input variables and output.
lr = LinearRegression() [Link](x_train,y_train)
Advantages
• Simple and fast
• Easy to understand
• Works well for linear relationships
Disadvantages
Cannot handle complex nonlinear data effectively
2. Random Forest Regressor
Random Forest is an ensemble learning algorithm that uses multiple decision trees.
rf = RandomForestRegressor() [Link](x_train,y_train)
Advantages
• High accuracy
• Handles large datasets
• Reduces overfitting
Disadvantages
More computationally expensive
Slower compared to Linear Regression
Random Forest usually performs better because it combines predictions from multiple trees.
3. Decision Tree Regressor
Decision Tree creates a tree structure for prediction.
dt = DecisionTreeRegressor() [Link](x_train,y_train)
Advantages
• Easy to visualize
• Handles nonlinear relationships
Disadvantages
• Can overfit the data
• Less stable compared to Random Forest
Accuracy Calculation
The accuracy of each model is calculated using the .score() function.
lr_score = [Link](x_test,y_test) * 100 rf_score
= [Link](x_test,y_test) * 100 dt_score =
[Link](x_test,y_test) * 100
The score represents how well the model predicts crop yield.
Higher percentage means better prediction performance.
Displaying Results
The program prints the accuracy of all models.
print("Linear Regression Accuracy: ",round(lr_score,2),"%")
print("Random Forest Accuracy: ",round(rf_score,2),"%")
print("Decision Tree Accuracy: ",round(dt_score,2),"%")
The best model is selected using: best =
max(lr_score,rf_score,dt_score)
Conditional statements identify the highest scoring model.
Graph Visualization
A bar graph is used to compare model performance.
models = ['Linear Regression','Random Forest','Decision Tree'] scores
= [lr_score,rf_score,dt_score]
[Link](models,scores)
[Link]("Accuracy Percentage")
[Link]("Crop Yield Prediction Model Comparison")
[Link]()
Purpose of Graph
• Easy comparison of model accuracy
• Better understanding of performance
• Visual representation of results
The graph clearly shows which algorithm performs best.
Advantages of the Project
1. Helps farmers estimate crop production.
2. Improves agricultural planning.
3. Reduces uncertainty in farming.
4. Uses environmental data effectively.
5. Provides comparison between multiple algorithms.
Applications of Crop Yield Prediction
This project can be used in:
• Smart agriculture systems
• Government agricultural planning
• Weather-based crop analysis
• Farm management systems
• Agricultural research
Conclusion
The Crop Yield Prediction project demonstrates how Machine Learning can be used in
agriculture to improve prediction accuracy and decision-making. The project uses rainfall,
pesticide usage, and temperature data to predict crop yield.
Three regression algorithms were implemented:
• Linear Regression
• Random Forest Regressor
• Decision Tree Regressor
The models were trained and tested successfully, and their accuracies were compared using
graphical visualization. Among the three models, the one with the highest accuracy is selected as
the best model for prediction.
This project shows that Machine Learning can help modern agriculture by providing better
insights and improving productivity. Future improvements can include larger datasets, additional
environmental features, and advanced deep learning techniques for even more accurate
predictions.